@platforma-sdk/bootstrap 2.4.0 → 2.4.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.
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- "use strict";var Xe=Object.defineProperty;var Ze=(a,e,r)=>e in a?Xe(a,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[e]=r;var y=(a,e,r)=>Ze(a,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@oclif/core"),_=require("node:os"),l=require("node:fs"),f=require("node:path"),F=require("node:child_process"),W=require("winston"),er=require("node:crypto"),K=require("readline-sync"),rr=require("node:stream"),z=require("zod"),tr=require("decompress"),xe=require("yaml"),ar=require("node:https"),sr=require("tar");function ir(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const r in a)if(r!=="default"){const t=Object.getOwnPropertyDescriptor(a,r);Object.defineProperty(e,r,t.get?t:{enumerable:!0,get:()=>a[r]})}}return e.default=a,Object.freeze(e)}const cr=ir(sr),$={"log-level":d.Flags.string({description:"logging level",default:"info",options:["error","warn","info","debug"],required:!1})},Be={image:d.Flags.string({description:"use custom docker image to run platforma"})},V={version:d.Flags.string({description:"use custom platforma release (official docker image or binary package)"})},Q={license:d.Flags.string({description:'pass a license code. The license can be got from "https://licensing.milaboratories.com".'}),"license-file":d.Flags.file({exists:!0,description:"specify a path to the file with a license. The license can be got from 'https://licensing.milaboratories.com'."})},X={"grpc-port":d.Flags.integer({description:"port for Platforma Backend gRPC API. Default is 6345",env:"PLATFORMA_GRPC_PORT"}),"grpc-listen":d.Flags.string({description:"full listen addr for Platforma Backend gRPC API. Default is 127.0.0.1:6345",env:"PLATFORMA_GRPC_LISTEN"}),"monitoring-port":d.Flags.integer({description:"port for Platforma Backend monitoring API. Default is 9090",env:"PLATFORMA_MONITORING_PORT"}),"monitoring-listen":d.Flags.string({description:"full listen addr for Platforma Backend monitoring API. Default is 127.0.0.1:9090",env:"PLATFORMA_MONITORING_LISTEN"}),"debug-port":d.Flags.integer({description:"port for Platforma Backend debug API. Default is 9091",env:"PLATFORMA_DEBUG_PORT"}),"debug-listen":d.Flags.string({description:"full listen addr for Platforma Backend debug API. Default is 127.0.0.1:9091",env:"PLATFORMA_DEBUG_LISTEN"})},nr={"s3-address-port":d.Flags.integer({description:"port that S3 will listen, default is 9000",default:9e3,env:"PLATFORMA_S3_PORT"}),"s3-console-address-port":d.Flags.integer({description:"port that a console of S3 will listen, default is 9001",default:9001,env:"PLATFORMA_S3_CONSOLE_PORT"})},Z={storage:d.Flags.string({description:"specify path on host to be used as storage for all Platforma Backend data"})},Ge={"pl-log-file":d.Flags.file({description:"specify path for Platforma Backend log file"})},Ue={"pl-workdir":d.Flags.file({description:"specify working directory for Platforma Backend process"})},je={"pl-binary":d.Flags.file({description:"start given Platforma Backend binary instead of automatically downloaded version"})},We={"pl-sources":d.Flags.file({description:"path to pl repository root: build Platforma Backend from sources and start the resulting binary"})},qe={config:d.Flags.string({description:"use custom Platforma Backend config"})};d.Flags.file({description:"specify path on host to be used as 'primary' storage"});const ue={"storage-work":d.Flags.file({description:"specify path on host to be used as 'work' storage"})};d.Flags.file({description:"specify path on host to be used as 'library' storage"});const fe={"storage-primary":d.Flags.string({description:`specify 'primary' storage destination URL.
1
+ "use strict";var Ve=Object.defineProperty;var Qe=(a,e,r)=>e in a?Ve(a,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[e]=r;var y=(a,e,r)=>Qe(a,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@oclif/core"),_=require("node:os"),l=require("node:fs"),f=require("node:path"),F=require("node:child_process"),W=require("winston"),Xe=require("node:crypto"),K=require("readline-sync"),Ze=require("node:stream"),z=require("zod"),er=require("decompress"),Ie=require("yaml"),V=require("@milaboratories/pl-config"),rr=require("node:https"),tr=require("tar");function ar(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const r in a)if(r!=="default"){const t=Object.getOwnPropertyDescriptor(a,r);Object.defineProperty(e,r,t.get?t:{enumerable:!0,get:()=>a[r]})}}return e.default=a,Object.freeze(e)}const ir=ar(tr),$={"log-level":d.Flags.string({description:"logging level",default:"info",options:["error","warn","info","debug"],required:!1})},Ce={image:d.Flags.string({description:"use custom docker image to run platforma"})},Q={version:d.Flags.string({description:"use custom platforma release (official docker image or binary package)"})},X={license:d.Flags.string({description:'pass a license code. The license can be got from "https://licensing.milaboratories.com".'}),"license-file":d.Flags.file({exists:!0,description:"specify a path to the file with a license. The license can be got from 'https://licensing.milaboratories.com'."})},Z={"grpc-port":d.Flags.integer({description:"port for Platforma Backend gRPC API. Default is 6345",env:"PLATFORMA_GRPC_PORT"}),"grpc-listen":d.Flags.string({description:"full listen addr for Platforma Backend gRPC API. Default is 127.0.0.1:6345",env:"PLATFORMA_GRPC_LISTEN"}),"monitoring-port":d.Flags.integer({description:"port for Platforma Backend monitoring API. Default is 9090",env:"PLATFORMA_MONITORING_PORT"}),"monitoring-listen":d.Flags.string({description:"full listen addr for Platforma Backend monitoring API. Default is 127.0.0.1:9090",env:"PLATFORMA_MONITORING_LISTEN"}),"debug-port":d.Flags.integer({description:"port for Platforma Backend debug API. Default is 9091",env:"PLATFORMA_DEBUG_PORT"}),"debug-listen":d.Flags.string({description:"full listen addr for Platforma Backend debug API. Default is 127.0.0.1:9091",env:"PLATFORMA_DEBUG_LISTEN"})},sr={"s3-address-port":d.Flags.integer({description:"port that S3 will listen, default is 9000",default:9e3,env:"PLATFORMA_S3_PORT"}),"s3-console-address-port":d.Flags.integer({description:"port that a console of S3 will listen, default is 9001",default:9001,env:"PLATFORMA_S3_CONSOLE_PORT"})},ee={storage:d.Flags.string({description:"specify path on host to be used as storage for all Platforma Backend data"})},Be={"pl-log-file":d.Flags.file({description:"specify path for Platforma Backend log file"})},Ge={"pl-workdir":d.Flags.file({description:"specify working directory for Platforma Backend process"})},Ue={"pl-binary":d.Flags.file({description:"start given Platforma Backend binary instead of automatically downloaded version"})},je={"pl-sources":d.Flags.file({description:"path to pl repository root: build Platforma Backend from sources and start the resulting binary"})},We={config:d.Flags.string({description:"use custom Platforma Backend config"})};d.Flags.file({description:"specify path on host to be used as 'primary' storage"});const ge={"storage-work":d.Flags.file({description:"specify path on host to be used as 'work' storage"})};d.Flags.file({description:"specify path on host to be used as 'library' storage"});const ue={"storage-primary":d.Flags.string({description:`specify 'primary' storage destination URL.
2
2
  file:/path/to/dir for directory on local FS
3
3
  s3://<bucket>/?region=<name> for real AWS bucket
4
4
  s3e://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via http
5
- s3es://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via https`})},he={"storage-library":d.Flags.string({description:`specify 'library' storage destination URL.
5
+ s3es://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via https`})},fe={"storage-library":d.Flags.string({description:`specify 'library' storage destination URL.
6
6
  file:/path/to/dir for directory on local FS
7
7
  s3://<bucket>/?region=<name> for real AWS bucket
8
8
  s3e://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via http
9
- s3es://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via https`})},lr={"auth-enabled":d.Flags.boolean({description:"enable authorization"})},or={"auth-htpasswd-file":d.Flags.file({description:"path to .htpasswd file with Platforma users (static user DB auth source)"})},dr={"auth-ldap-server":d.Flags.string({description:"address of LDAP server to use for auth in Platforma (auth source)"})},gr={"auth-ldap-default-dn":d.Flags.string({description:"DN to use when checking user with LDAP bind operation: e.g. cn=%u,ou=users,dc=example,dc=com"})},ee={...lr,...or,...dr,...gr};function ur(a){return K.question(`${a} [y/N] `).toLowerCase()==="y"}function J(a){throw new Error("this should never happen")}function T(a="debug"){return W.createLogger({level:a,format:W.format.combine(W.format.printf(({level:e,message:r})=>{const t=" ".repeat(e.length+2),s=r.split(`
9
+ s3es://<endpoint>/<bucket>/?region=<name> for bucket behind custom endpoint via https`})},cr={"auth-enabled":d.Flags.boolean({description:"enable authorization"})},nr={"auth-htpasswd-file":d.Flags.file({description:"path to .htpasswd file with Platforma users (static user DB auth source)"})},lr={"auth-ldap-server":d.Flags.string({description:"address of LDAP server to use for auth in Platforma (auth source)"})},or={"auth-ldap-default-dn":d.Flags.string({description:"DN to use when checking user with LDAP bind operation: e.g. cn=%u,ou=users,dc=example,dc=com"})},re={...cr,...nr,...lr,...or};function dr(a){return K.question(`${a} [y/N] `).toLowerCase()==="y"}function H(a){throw new Error("this should never happen")}function T(a="debug"){return W.createLogger({level:a,format:W.format.combine(W.format.printf(({level:e,message:r})=>{const t=" ".repeat(e.length+2),i=r.split(`
10
10
  `).map((c,n)=>n===0?c:t+c).join(`
11
- `);return`${(c=>W.format.colorize().colorize(c,c))(e)}: ${s}`})),transports:[new W.transports.Console({stderrLevels:["error","warn","info","debug"],handleExceptions:!0})]})}function fr(a){return er.randomBytes(Math.ceil(a/2)).toString("hex").slice(0,a)}function hr(a){return a.startsWith("~")?f.join(_.homedir(),a.slice(1)):a}function Y(a,e){l.existsSync(a)||(l.mkdirSync(a,{recursive:!0}),e!=null&&e.mode&&l.chmodSync(a,e.mode))}function mr(a){try{if(_.platform()!=="win32")return F.execSync(`ps -p ${a} -o comm=`,{encoding:"utf8"}).trim();const e=`wmic process where processid=${a} get Caption`,r=F.execSync(e,{encoding:"utf8"}).split(`
12
- `);return r.length<=1?"":r[1].trim()}catch{return""}}const yr=z.z.object({npmOrgName:z.z.string().min(1),orgName:z.z.string().min(1),blockName:z.z.string().min(1)});async function br(a){const e=Pr(),r=f.join(process.cwd(),e.blockName);a.info("Downloading boilerplate code..."),await vr("https://github.com/milaboratory/platforma-block-boilerplate/archive/refs/heads/main.zip","platforma-block-boilerplate-main",r),a.info("Replace everything in the template with provided options..."),wr(r,[{from:/platforma-open/g,to:e.npmOrgName},{from:/my-org/g,to:e.orgName},{from:/block-boilerplate/g,to:e.blockName}]),a.info("Remove github actions directory"),l.rmSync(f.join(r,".github"),{recursive:!0,force:!0})}function Pr(){let a=K.question('Write an organization name for npm. Default is "platforma-open": ');a===""&&(a="platforma-open");const e=K.question('Write an organization name, e.g. "my-org": '),r=K.question('Write a name of the block, e.g. "hello-world": ');return yr.parse({npmOrgName:a,orgName:e,blockName:r})}async function vr(a,e,r){const s=await(await fetch(a)).blob(),i=l.mkdtempSync(f.join(_.tmpdir(),"create-repo")),c=f.join(i,"packed-repo.zip"),n=rr.Writable.toWeb(l.createWriteStream(c));await s.stream().pipeTo(n);const m=f.join(i,"unpacked-repo");l.mkdirSync(m),await tr(c,m),l.cpSync(f.join(m,e),r,{recursive:!0})}function wr(a,e){const r=kr(a);e.forEach(({from:t,to:s})=>{r.forEach(i=>Sr(i,t,s))})}function kr(a){return l.readdirSync(a,{withFileTypes:!0,recursive:!0}).filter(r=>r.isFile()).map(r=>f.join(r.parentPath,r.name))}function Sr(a,e,r){const s=l.readFileSync(a).toString().replaceAll(e,r);l.writeFileSync(a,s)}const I=class I extends d.Command{async run(){const{flags:e}=await this.parse(I),r=T(e["log-level"]);await br(r)}};y(I,"description","Helps to create a new block by downloading a block's template."),y(I,"examples",["<%= name %>"]),y(I,"flags",{...$});let se=I;function Je(...a){return f.resolve(__dirname,"..",...a)}function O(...a){return Je("assets",...a)}function Ar(){return l.readdirSync(O()).filter(e=>e.startsWith("compose-")&&e.endsWith(".yaml")).map(e=>O(e))}function He(...a){return l.readFileSync(Je(...a))}var te;function re(){return te||(te=JSON.parse(He("package.json").toString())),te}function ae(a){return a||(a=re()["pl-version"]),`quay.io/milaboratories/platforma:${a}`}const E=class E{constructor(e){y(this,"state",{lastRun:void 0,isActive:!1});y(this,"filePath");y(this,"dirPath");e=e??f.resolve(_.homedir(),".config","pl-bootstrap");const r=f.join(e,"state.json");this.dirPath=e,this.filePath=r,l.existsSync(e)||l.mkdirSync(e,{recursive:!0}),l.existsSync(r)&&(this.state=JSON.parse(He(r).toString()))}static getInstance(){return E.instance||(E.instance=new E),E.instance}path(...e){return f.join(this.dirPath,...e)}data(...e){return this.path("data",...e)}binaries(...e){return this.path("binaries",...e)}writeState(){l.writeFileSync(this.filePath,JSON.stringify(this.state))}get isActive(){var e,r;return this.state.isActive?this.state.isActive:(r=(e=this.state.lastRun)==null?void 0:e.process)!=null&&r.pid?this.isValidPID:!1}get isValidPID(){var r,t;if(!((t=(r=this.state.lastRun)==null?void 0:r.process)!=null&&t.pid))return!1;const e=mr(this.state.lastRun.process.pid);return e==="platforma"||e.endsWith("/platforma")||e.endsWith("\\platforma")}set isActive(e){this.state.isActive=e,this.writeState()}get lastRun(){return this.state.lastRun}set lastRun(e){this.state.lastRun=e,this.writeState()}};y(E,"instance");let ie=E;const o=ie.getInstance();function Me(a,e,r,t){var s;return o.lastRun={...o.lastRun,mode:"docker",cmd:"docker",args:e,workdir:r.cwd,envs:r.env,docker:{...(s=o.lastRun)==null?void 0:s.docker,...t}},ze(a,"docker",e,r)}function Lr(a,e,r,t,s){var c;o.lastRun={...o.lastRun,mode:"process",cmd:e,args:r,workdir:t.cwd,envs:t.env,process:{...(c=o.lastRun)==null?void 0:c.process,...s}};const i=_r(a,e,r,t);return o.lastRun.process={...o.lastRun.process,pid:i.pid},i}function Rr(a,e){if(!o.lastRun)throw new Error("no previous run info found: this is the first run after package installation");return e={cwd:o.lastRun.workdir,env:{...o.lastRun.envs,...e.env},...e},ze(a,o.lastRun.cmd,o.lastRun.args,e)}function _r(a,e,r,t){a.debug(`Running:
11
+ `);return`${(c=>W.format.colorize().colorize(c,c))(e)}: ${i}`})),transports:[new W.transports.Console({stderrLevels:["error","warn","info","debug"],handleExceptions:!0})]})}function gr(a){return Xe.randomBytes(Math.ceil(a/2)).toString("hex").slice(0,a)}function ur(a){return a.startsWith("~")?f.join(_.homedir(),a.slice(1)):a}function Y(a,e){l.existsSync(a)||(l.mkdirSync(a,{recursive:!0}),e!=null&&e.mode&&l.chmodSync(a,e.mode))}function fr(a){try{if(_.platform()!=="win32")return F.execSync(`ps -p ${a} -o comm=`,{encoding:"utf8"}).trim();const e=`wmic process where processid=${a} get Caption`,r=F.execSync(e,{encoding:"utf8"}).split(`
12
+ `);return r.length<=1?"":r[1].trim()}catch{return""}}const hr=z.z.object({npmOrgName:z.z.string().min(1),orgName:z.z.string().min(1),blockName:z.z.string().min(1)});async function mr(a){const e=yr(),r=f.join(process.cwd(),e.blockName);a.info("Downloading boilerplate code..."),await Pr("https://github.com/milaboratory/platforma-block-boilerplate/archive/refs/heads/main.zip","platforma-block-boilerplate-main",r),a.info("Replace everything in the template with provided options..."),br(r,[{from:/platforma-open/g,to:e.npmOrgName},{from:/my-org/g,to:e.orgName},{from:/block-boilerplate/g,to:e.blockName}]),a.info("Remove github actions directory"),l.rmSync(f.join(r,".github"),{recursive:!0,force:!0})}function yr(){let a=K.question('Write an organization name for npm. Default is "platforma-open": ');a===""&&(a="platforma-open");const e=K.question('Write an organization name, e.g. "my-org": '),r=K.question('Write a name of the block, e.g. "hello-world": ');return hr.parse({npmOrgName:a,orgName:e,blockName:r})}async function Pr(a,e,r){const i=await(await fetch(a)).blob(),s=l.mkdtempSync(f.join(_.tmpdir(),"create-repo")),c=f.join(s,"packed-repo.zip"),n=Ze.Writable.toWeb(l.createWriteStream(c));await i.stream().pipeTo(n);const m=f.join(s,"unpacked-repo");l.mkdirSync(m),await er(c,m),l.cpSync(f.join(m,e),r,{recursive:!0})}function br(a,e){const r=vr(a);e.forEach(({from:t,to:i})=>{r.forEach(s=>wr(s,t,i))})}function vr(a){return l.readdirSync(a,{withFileTypes:!0,recursive:!0}).filter(r=>r.isFile()).map(r=>f.join(r.parentPath,r.name))}function wr(a,e,r){const i=l.readFileSync(a).toString().replaceAll(e,r);l.writeFileSync(a,i)}const I=class I extends d.Command{async run(){const{flags:e}=await this.parse(I),r=T(e["log-level"]);await mr(r)}};y(I,"description","Helps to create a new block by downloading a block's template."),y(I,"examples",["<%= name %>"]),y(I,"flags",{...$});let ae=I;function qe(...a){return f.resolve(__dirname,"..",...a)}function p(...a){return qe("assets",...a)}function kr(){return l.readdirSync(p()).filter(e=>e.startsWith("compose-")&&e.endsWith(".yaml")).map(e=>p(e))}function Sr(...a){return l.readFileSync(qe(...a))}function te(a){return a||(a=V.getPlVersion()),`quay.io/milaboratories/platforma:${a}`}const E=class E{constructor(e){y(this,"state",{lastRun:void 0,isActive:!1});y(this,"filePath");y(this,"dirPath");e=e??f.resolve(_.homedir(),".config","pl-bootstrap");const r=f.join(e,"state.json");this.dirPath=e,this.filePath=r,l.existsSync(e)||l.mkdirSync(e,{recursive:!0}),l.existsSync(r)&&(this.state=JSON.parse(Sr(r).toString()))}static getInstance(){return E.instance||(E.instance=new E),E.instance}path(...e){return f.join(this.dirPath,...e)}data(...e){return this.path("data",...e)}binaries(...e){return this.path("binaries",...e)}writeState(){l.writeFileSync(this.filePath,JSON.stringify(this.state))}get isActive(){var e,r;return this.state.isActive?this.state.isActive:(r=(e=this.state.lastRun)==null?void 0:e.process)!=null&&r.pid?this.isValidPID:!1}get isValidPID(){var r,t;if(!((t=(r=this.state.lastRun)==null?void 0:r.process)!=null&&t.pid))return!1;const e=fr(this.state.lastRun.process.pid);return e==="platforma"||e.endsWith("/platforma")||e.endsWith("\\platforma")}set isActive(e){this.state.isActive=e,this.writeState()}get lastRun(){return this.state.lastRun}set lastRun(e){this.state.lastRun=e,this.writeState()}};y(E,"instance");let ie=E;const o=ie.getInstance();function xe(a,e,r,t){var i;return o.lastRun={...o.lastRun,mode:"docker",cmd:"docker",args:e,workdir:r.cwd,envs:r.env,docker:{...(i=o.lastRun)==null?void 0:i.docker,...t}},He(a,"docker",e,r)}function Ar(a,e,r,t,i){var c;o.lastRun={...o.lastRun,mode:"process",cmd:e,args:r,workdir:t.cwd,envs:t.env,process:{...(c=o.lastRun)==null?void 0:c.process,...i}};const s=Rr(a,e,r,t);return o.lastRun.process={...o.lastRun.process,pid:s.pid},s}function Lr(a,e){if(!o.lastRun)throw new Error("no previous run info found: this is the first run after package installation");return e={cwd:o.lastRun.workdir,env:{...o.lastRun.envs,...e.env},...e},He(a,o.lastRun.cmd,o.lastRun.args,e)}function Rr(a,e,r,t){a.debug(`Running:
13
13
  env: ${JSON.stringify(t.env)}
14
14
  cmd: ${JSON.stringify([e,...r])}
15
- wd: ${t.cwd}`),t.env={...process.env,...t.env},a.debug(" spawning child process");const s=F.spawn(e,r,t);var i=!1;const c=()=>{s.kill("SIGINT"),i=!0};return a.debug(" setting up signal handler"),process.on("SIGINT",c),s.on("close",n=>{process.removeListener("SIGINT",c),i&&process.exit(n)}),s}function ze(a,e,r,t){return a.debug(`Running:
15
+ wd: ${t.cwd}`),t.env={...process.env,...t.env},a.debug(" spawning child process");const i=F.spawn(e,r,t);var s=!1;const c=()=>{i.kill("SIGINT"),s=!0};return a.debug(" setting up signal handler"),process.on("SIGINT",c),i.on("close",n=>{process.removeListener("SIGINT",c),s&&process.exit(n)}),i}function He(a,e,r,t){return a.debug(`Running:
16
16
  env: ${JSON.stringify(t.env)}
17
17
  cmd: ${JSON.stringify([e,...r])}
18
- wd: ${t.cwd}`),t.env={...process.env,...t.env},F.spawnSync(e,r,t)}function pr(a){return{id:a,type:"S3",indexCachePeriod:"0s",endpoint:"",region:"",presignEndpoint:"",bucketName:"",createBucket:!1,forcePathStyle:!1,key:"",secret:"",keyPrefix:"",accessPrefixes:[],uploadKeyPrefix:""}}function Ye(a){return{id:a,type:"FS",indexCachePeriod:"0s",rootPath:""}}function N(a,e,r){a=hr(a);const t=new URL(a,`file:${e}`);switch(t.protocol){case"s3:":var c=t.hostname,s=t.searchParams.get("region");return{...r,type:"S3",bucketName:c,region:s};case"s3e:":var i=t.pathname.split("/").slice(1),c=i[0],n=i.length>1?i[1]:"";return{...r,type:"S3",endpoint:`http://${t.host}/`,bucketName:c,keyPrefix:n,region:t.searchParams.get("region"),key:t.username?`static:${t.username}`:"",secret:t.password?`static:${t.password}`:""};case"s3es:":var i=t.pathname.split("/").slice(1),c=i[0],n=i.length>1?i[1]:"";return{...r,type:"S3",endpoint:`https://${t.host}/`,bucketName:c,keyPrefix:n,region:t.searchParams.get("region"),key:t.username?`static:${t.username}`:"",secret:t.password?`static:${t.password}`:""};case"file:":return{type:"FS",rootPath:t.pathname};default:throw new Error(`storage protocol '${t.protocol}' is not supported`)}}function Or(a,e){var g,P,w,S,L,k,p,j,A,me,ye,be,Pe,ve,we,ke,Se,Ae,Le,Re,_e,pe,Oe,Fe,$e,Te,Ee,De,Ne,Ie;const r=(e==null?void 0:e.localRoot)??o.data("local-custom"),t={level:((g=e==null?void 0:e.log)==null?void 0:g.level)??"info",path:((P=e==null?void 0:e.log)==null?void 0:P.path)??`${r}/platforma.log`},s={listen:((w=e==null?void 0:e.grpc)==null?void 0:w.listen)??"localhost:6345",tls:{enable:H((L=(S=e==null?void 0:e.grpc)==null?void 0:S.tls)==null?void 0:L.enable,!1),clientAuthMode:((p=(k=e==null?void 0:e.grpc)==null?void 0:k.tls)==null?void 0:p.clientAuthMode)??"NoAuth",certFile:((A=(j=e==null?void 0:e.grpc)==null?void 0:j.tls)==null?void 0:A.certFile)??`${r}/certs/tls.cert`,keyFile:((ye=(me=e==null?void 0:e.grpc)==null?void 0:me.tls)==null?void 0:ye.keyFile)??`${r}/certs/tls.key`,...(be=e==null?void 0:e.grpc)==null?void 0:be.tls}},i={auth:{enabled:((ve=(Pe=e==null?void 0:e.core)==null?void 0:Pe.auth)==null?void 0:ve.enabled)??!1,drivers:((ke=(we=e==null?void 0:e.core)==null?void 0:we.auth)==null?void 0:ke.drivers)??[{driver:"jwt",key:a},{driver:"htpasswd",path:`${r}/users.htpasswd`}]},db:{path:`${r}/db`}},c=Ce("main",`${r}/storages/main`,"main-bucket",(Se=e==null?void 0:e.storages)==null?void 0:Se.primary);var n;switch((Le=(Ae=e==null?void 0:e.storages)==null?void 0:Ae.work)==null?void 0:Le.type){case void 0:case"FS":n=Ye("work"),n.rootPath=((_e=(Re=e==null?void 0:e.storages)==null?void 0:Re.work)==null?void 0:_e.rootPath)??`${r}/storages/work`,n.indexCachePeriod=((Oe=(pe=e==null?void 0:e.storages)==null?void 0:pe.work)==null?void 0:Oe.indexCachePeriod)??"1m";break;default:throw new Error("work storage MUST have 'FS' type as it is used for working directories management")}const h=Ce("library",`${r}/storages/library`,"library-bucket",(Fe=e==null?void 0:e.storages)==null?void 0:Fe.library),u={enabled:H(($e=e==null?void 0:e.monitoring)==null?void 0:$e.enabled,!0),listen:((Te=e==null?void 0:e.monitoring)==null?void 0:Te.listen)??"127.0.0.1:9090"},v={enabled:H((Ee=e==null?void 0:e.debug)==null?void 0:Ee.enabled,!0),listen:((De=e==null?void 0:e.debug)==null?void 0:De.listen)??"127.0.0.1:9091"},b={value:((Ne=e==null?void 0:e.license)==null?void 0:Ne.value)??"",file:((Ie=e==null?void 0:e.license)==null?void 0:Ie.file)??""};return{localRoot:r,license:b,log:t,grpc:s,core:i,monitoring:u,debug:v,storages:{primary:c,work:n,library:h},hacks:{libraryDownloadable:!0}}}function Ce(a,e,r,t){var s;switch(t==null?void 0:t.type){case void 0:case"FS":s=Ye(a),s.rootPath=(t==null?void 0:t.rootPath)??e;break;case"S3":s=pr(a),s.endpoint=(t==null?void 0:t.endpoint)??"http://localhost:9000",s.presignEndpoint=(t==null?void 0:t.presignEndpoint)??"http://localhost:9000",s.bucketName=(t==null?void 0:t.bucketName)??r,s.createBucket=H(t==null?void 0:t.createBucket,!0),s.forcePathStyle=H(t==null?void 0:t.forcePathStyle,!0),s.key=(t==null?void 0:t.key)??"",s.secret=(t==null?void 0:t.secret)??"",s.keyPrefix=(t==null?void 0:t.keyPrefix)??"",s.accessPrefixes=(t==null?void 0:t.accessPrefixes)??[""],s.uploadKeyPrefix=(t==null?void 0:t.uploadKeyPrefix)??"";break;default:throw J(),new Error("unknown storage type")}return s}function Fr(a){const e=a.monitoring.enabled?"":" disabled",r=a.debug.enabled?"":" disabled",t=a.hacks.libraryDownloadable?"true":"false";var s=a.license.value;return a.license.file!=""&&(s=l.readFileSync(a.license.file).toString().trimEnd()),`
18
+ wd: ${t.cwd}`),t.env={...process.env,...t.env},F.spawnSync(e,r,t)}function _r(a){return{id:a,type:"S3",indexCachePeriod:"0s",endpoint:"",region:"",presignEndpoint:"",bucketName:"",createBucket:!1,forcePathStyle:!1,key:"",secret:"",keyPrefix:"",accessPrefixes:[],uploadKeyPrefix:""}}function Je(a){return{id:a,type:"FS",indexCachePeriod:"0s",rootPath:""}}function N(a,e,r){a=ur(a);const t=new URL(a,`file:${e}`);switch(t.protocol){case"s3:":var c=t.hostname,i=t.searchParams.get("region");return{...r,type:"S3",bucketName:c,region:i};case"s3e:":var s=t.pathname.split("/").slice(1),c=s[0],n=s.length>1?s[1]:"";return{...r,type:"S3",endpoint:`http://${t.host}/`,bucketName:c,keyPrefix:n,region:t.searchParams.get("region"),key:t.username?`static:${t.username}`:"",secret:t.password?`static:${t.password}`:""};case"s3es:":var s=t.pathname.split("/").slice(1),c=s[0],n=s.length>1?s[1]:"";return{...r,type:"S3",endpoint:`https://${t.host}/`,bucketName:c,keyPrefix:n,region:t.searchParams.get("region"),key:t.username?`static:${t.username}`:"",secret:t.password?`static:${t.password}`:""};case"file:":return{type:"FS",rootPath:t.pathname};default:throw new Error(`storage protocol '${t.protocol}' is not supported`)}}function Or(a,e){var g,b,w,S,L,k,O,j,A,he,me,ye,Pe,be,ve,we,ke,Se,Ae,Le,Re,_e,Oe,pe,Fe,$e,Te,Ee,De,Ne;const r=(e==null?void 0:e.localRoot)??o.data("local-custom"),t={level:((g=e==null?void 0:e.log)==null?void 0:g.level)??"info",path:((b=e==null?void 0:e.log)==null?void 0:b.path)??`${r}/platforma.log`},i={listen:((w=e==null?void 0:e.grpc)==null?void 0:w.listen)??"localhost:6345",tls:{enable:J((L=(S=e==null?void 0:e.grpc)==null?void 0:S.tls)==null?void 0:L.enable,!1),clientAuthMode:((O=(k=e==null?void 0:e.grpc)==null?void 0:k.tls)==null?void 0:O.clientAuthMode)??"NoAuth",certFile:((A=(j=e==null?void 0:e.grpc)==null?void 0:j.tls)==null?void 0:A.certFile)??`${r}/certs/tls.cert`,keyFile:((me=(he=e==null?void 0:e.grpc)==null?void 0:he.tls)==null?void 0:me.keyFile)??`${r}/certs/tls.key`,...(ye=e==null?void 0:e.grpc)==null?void 0:ye.tls}},s={auth:{enabled:((be=(Pe=e==null?void 0:e.core)==null?void 0:Pe.auth)==null?void 0:be.enabled)??!1,drivers:((we=(ve=e==null?void 0:e.core)==null?void 0:ve.auth)==null?void 0:we.drivers)??[{driver:"jwt",key:a},{driver:"htpasswd",path:`${r}/users.htpasswd`}]},db:{path:`${r}/db`}},c=Me("main",`${r}/storages/main`,"main-bucket",(ke=e==null?void 0:e.storages)==null?void 0:ke.primary);var n;switch((Ae=(Se=e==null?void 0:e.storages)==null?void 0:Se.work)==null?void 0:Ae.type){case void 0:case"FS":n=Je("work"),n.rootPath=((Re=(Le=e==null?void 0:e.storages)==null?void 0:Le.work)==null?void 0:Re.rootPath)??`${r}/storages/work`,n.indexCachePeriod=((Oe=(_e=e==null?void 0:e.storages)==null?void 0:_e.work)==null?void 0:Oe.indexCachePeriod)??"1m";break;default:throw new Error("work storage MUST have 'FS' type as it is used for working directories management")}const h=Me("library",`${r}/storages/library`,"library-bucket",(pe=e==null?void 0:e.storages)==null?void 0:pe.library),u={enabled:J((Fe=e==null?void 0:e.monitoring)==null?void 0:Fe.enabled,!0),listen:(($e=e==null?void 0:e.monitoring)==null?void 0:$e.listen)??"127.0.0.1:9090"},v={enabled:J((Te=e==null?void 0:e.debug)==null?void 0:Te.enabled,!0),listen:((Ee=e==null?void 0:e.debug)==null?void 0:Ee.listen)??"127.0.0.1:9091"},P={value:((De=e==null?void 0:e.license)==null?void 0:De.value)??"",file:((Ne=e==null?void 0:e.license)==null?void 0:Ne.file)??""};return{localRoot:r,license:P,log:t,grpc:i,core:s,monitoring:u,debug:v,storages:{primary:c,work:n,library:h},hacks:{libraryDownloadable:!0}}}function Me(a,e,r,t){var i;switch(t==null?void 0:t.type){case void 0:case"FS":i=Je(a),i.rootPath=(t==null?void 0:t.rootPath)??e;break;case"S3":i=_r(a),i.endpoint=(t==null?void 0:t.endpoint)??"http://localhost:9000",i.presignEndpoint=(t==null?void 0:t.presignEndpoint)??"http://localhost:9000",i.bucketName=(t==null?void 0:t.bucketName)??r,i.createBucket=J(t==null?void 0:t.createBucket,!0),i.forcePathStyle=J(t==null?void 0:t.forcePathStyle,!0),i.key=(t==null?void 0:t.key)??"",i.secret=(t==null?void 0:t.secret)??"",i.keyPrefix=(t==null?void 0:t.keyPrefix)??"",i.accessPrefixes=(t==null?void 0:t.accessPrefixes)??[""],i.uploadKeyPrefix=(t==null?void 0:t.uploadKeyPrefix)??"";break;default:throw H(),new Error("unknown storage type")}return i}function pr(a){const e=a.monitoring.enabled?"":" disabled",r=a.debug.enabled?"":" disabled",t=a.hacks.libraryDownloadable?"true":"false";var i=a.license.value;return a.license.file!=""&&(i=l.readFileSync(a.license.file).toString().trimEnd()),`
19
19
  license:
20
20
  value: '${a.license.value}'
21
21
  file: '${a.license.file}'
@@ -79,30 +79,30 @@ controllers:
79
79
  workdirCacheOnFailure: 1h
80
80
  secrets:
81
81
  - map:
82
- MI_LICENSE: ${JSON.stringify(s)}
82
+ MI_LICENSE: ${JSON.stringify(i)}
83
83
 
84
84
  packageLoader:
85
85
  packagesRoot: '${a.localRoot}/packages'
86
86
 
87
87
  workflows: {}
88
- `}function H(a,e){return a===void 0?e:a}const $r=["linux","macos","windows"];function Tr(a){const e=_.platform();switch(e){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:throw new Error(`operating system '${e}' is not currently supported by Platforma ecosystem. The list of OSes supported: `+JSON.stringify($r))}}const Er=["amd64","arm64"];function Ke(a){const e=_.arch();switch(e){case"arm64":return"arm64";case"x64":return"amd64";default:throw new Error(`processor architecture '${e}' is not currently supported by Platforma ecosystem. The list of architectures supported: `+JSON.stringify(Er))}}function Dr(a,e){const r=(e==null?void 0:e.version)??re()["pl-version"],t=(e==null?void 0:e.showProgress)??process.stdout.isTTY,s=`pl-${r}-${Ke()}.tgz`,i=(e==null?void 0:e.downloadURL)??`https://cdn.platforma.bio/software/pl/${Tr()}/${s}`,c=(e==null?void 0:e.saveTo)??o.binaries(s);if(l.existsSync(c))return a.info(`Platforma Backend archive download skipped: '${c}' already exists`),Promise.resolve(c);l.mkdirSync(f.dirname(c),{recursive:!0}),a.info(`Downloading Platforma Backend archive:
89
- URL: ${i}
90
- Save to: ${c}`);const n=ar.get(i);return new Promise((m,h)=>{n.on("response",u=>{if(!u.statusCode){const P=new Error("failed to download archive: no HTTP status code in response from server");n.destroy(),h(P);return}if(u.statusCode!==200){const P=new Error(`failed to download archive: ${u.statusCode} ${u.statusMessage}`);n.destroy(),h(P);return}const v=parseInt(u.headers["content-length"]||"0",10);let b=0;const g=l.createWriteStream(c);u.pipe(g),u.on("data",P=>{b+=P.length;const w=b/v*100;t&&process.stdout.write(` downloading: ${w.toFixed(2)}%\r`)}),u.on("error",P=>{l.unlinkSync(c),a.error(`Failed to download Platforma Binary: ${P.message}`),n.destroy(),h(P)}),g.on("finish",()=>{g.close(),a.info(" ... download done."),n.destroy(),m(c)})})})}function Nr(a,e){a.debug("extracting archive...");const r=(e==null?void 0:e.version)??re()["pl-version"];a.debug(` version: '${r}'`);const t=`${Qe({version:r})}.tgz`,s=(e==null?void 0:e.archivePath)??o.binaries(t);a.debug(` archive path: '${s}'`);const i=(e==null?void 0:e.extractTo)??xr(s);if(a.debug(` target dir: '${i}'`),l.existsSync(i))return a.info(`Platforma Backend binaries unpack skipped: '${i}' exists`),i;if(!l.existsSync(s)){const c=`Platforma Backend binary archive not found at '${s}'`;throw a.error(c),new Error(c)}return l.existsSync(i)||(a.debug(` creating target dir '${i}'`),l.mkdirSync(i,{recursive:!0})),a.info(`Unpacking Platforma Backend archive:
91
- Archive: ${s}
92
- Target dir: ${i}`),cr.x({file:s,cwd:i,gzip:!0,sync:!0}),a.info(" ... unpack done."),i}function Ve(a,e){return Dr(a,e).then(r=>Nr(a,{archivePath:r}))}function Qe(a){return`pl-${(a==null?void 0:a.version)??re()["pl-version"]}-${Ke()}`}function Ir(a,...e){return o.binaries(Qe({version:a}),...e)}function xr(a){const e=a.lastIndexOf(".");return e===-1?a:a.slice(0,e)}class D{constructor(e){this.logger=e}startLast(){const e=Rr(this.logger,{stdio:"inherit"});q(e,"failed to bring back Platforma Backend in the last started configuration")}startLocal(e){var m,h,u,v,b,g,P,w,S,L;const r=(e==null?void 0:e.binaryPath)??Ir(e==null?void 0:e.version,"binaries","platforma");var t=e==null?void 0:e.configPath;const s=(e==null?void 0:e.workdir)??(t?process.cwd():o.path());e!=null&&e.primaryURL&&(e.configOptions={...e.configOptions,storages:{...(m=e.configOptions)==null?void 0:m.storages,primary:N(e.primaryURL,s,(u=(h=e.configOptions)==null?void 0:h.storages)==null?void 0:u.primary)}}),e!=null&&e.libraryURL&&(e.configOptions={...e.configOptions,storages:{...(v=e.configOptions)==null?void 0:v.storages,library:N(e.libraryURL,s,(g=(b=e.configOptions)==null?void 0:b.storages)==null?void 0:g.library)}});const i=Or(this.getLastJwt(),e==null?void 0:e.configOptions);this.logger.debug(" checking license..."),this.checkLicense((w=(P=e==null?void 0:e.configOptions)==null?void 0:P.license)==null?void 0:w.value,(L=(S=e==null?void 0:e.configOptions)==null?void 0:S.license)==null?void 0:L.file);const c=[`${i.localRoot}/packages`,`${i.localRoot}/packages-local`,`${i.localRoot}/blocks-local`];i.storages.primary.type==="FS"&&c.push(i.storages.primary.rootPath),i.storages.library.type==="FS"&&(c.push(i.storages.library.rootPath),i.hacks.libraryDownloadable=!1),i.storages.work.type==="FS"&&c.push(i.storages.work.rootPath),this.logger.debug(" creating pl state directories...");for(const k of c)l.existsSync(k)||(this.logger.debug(` '${k}'`),l.mkdirSync(k,{recursive:!0}));for(const k of i.core.auth.drivers)k.driver==="htpasswd"&&(l.existsSync(k.path)||(this.logger.debug(` installing default 'users.htpasswd' to ${k.path}...`),l.copyFileSync(O("users.htpasswd"),k.path)));t||(t=f.join(i.localRoot,"config.yaml"),this.logger.debug(` rendering configuration '${t}'...`),l.writeFileSync(t,Fr(i)));const n=this.renderRunInfo({configPath:t,dbPath:i.core.db.path,apiAddr:i.grpc.listen,logPath:i.log.path,primary:i.storages.primary,work:i.storages.work,library:i.storages.library});return this.logger.info(`Starting platforma:
93
- ${n}`),Lr(this.logger,r,["-config",t],{cwd:s,stdio:"inherit"},{storagePath:i.localRoot})}startLocalS3(e){var s;this.logger.debug("starting platforma in 'local s3' mode...");const r=(e==null?void 0:e.minioPort)??9e3,t=(s=e==null?void 0:e.configOptions)==null?void 0:s.localRoot;return this.startMinio({minioPort:r,minioConsolePort:e==null?void 0:e.minioConsolePort,storage:t?f.join(t,"minio"):void 0}),this.startLocal({...e,primaryURL:(e==null?void 0:e.primaryURL)??`s3e://testuser:testpassword@localhost:${r}/main-bucket/?region=no-region`,libraryURL:(e==null?void 0:e.libraryURL)??`s3e://testuser:testpassword@localhost:${r}/library-bucket/?region=no-region`})}startMinio(e){this.logger.debug(" starting minio...");var r=O("compose-backend.yaml");const t=e!=null&&e.version?`:${e.version}`:"";this.logger.debug(` minio version: ${t}`);const s=(e==null?void 0:e.image)??`quay.io/minio/minio${t}`;this.logger.debug(` minio image: ${s}`);const i=(e==null?void 0:e.storage)??o.data("minio");Y(i,{mode:"0775"});const c=o.data("stub");Y(c);const n=(e==null?void 0:e.minioPort)??9e3,m=(e==null?void 0:e.minioConsolePort)??9001,h={MINIO_IMAGE:s,MINIO_STORAGE:f.resolve(i),MINIO_PORT:n.toString(),MINIO_CONSOLE_PORT:m.toString(),PL_DATA_DB_ROOT:c,PL_DATA_PRIMARY_ROOT:c,PL_DATA_LIBRARY_ROOT:c,PL_DATA_WORKDIR_ROOT:c,PL_DATA_PACKAGE_ROOT:c,PL_IMAGE:"scratch"};this.logger.debug(" spawning child 'docker' process...");const u=F.spawnSync("docker",["compose",`--file=${r}`,"up","--detach","--remove-orphans","--pull=missing","minio"],{env:{...process.env,...h},stdio:"inherit"});q(u,"failed to start MinIO service in docker")}buildPlatforma(e){const r=f.resolve(e.repoRoot,"cmd","platforma"),t=e.binPath??f.join(_.tmpdir(),"platforma-local-build");this.logger.info("Building Platforma Backend binary from sources"),this.logger.info(` sources path: ${e.repoRoot}`),this.logger.info(` binary path: ${t}`);const s=F.spawnSync("go",["build","-o",t,"."],{cwd:r,stdio:"inherit"});return q(s,"failed to build platforma binary from sources using 'go build' command"),t}startDockerS3(e,r){const t=O("compose-backend.yaml"),s=(r==null?void 0:r.image)??ae(r==null?void 0:r.version);this.checkLicense(r==null?void 0:r.license,r==null?void 0:r.licenseFile);const i=S=>f.join(e,S),c=S=>{const L=i(S);return Y(L,{mode:"0775"}),L},n=i("platforma.log");l.existsSync(n)||(l.mkdirSync(f.dirname(n),{recursive:!0}),l.writeFileSync(n,""));const m=N("s3e://testuser:testpassword@minio:9000/main-bucket");if(m.type!=="S3")throw new Error("primary storage must have 'S3' type in 'docker s3' configuration");m.presignEndpoint="http://localhost:9000";const h=N("s3e://testuser:testpassword@minio:9000/library-bucket");if(h.type!=="S3")throw new Error(`${h.type} storage type is not supported for library storage`);h.presignEndpoint="http://localhost:9000";const u=c("db"),v=c("work"),b=i("users.htpasswd");l.existsSync(b)||l.copyFileSync(O("users.htpasswd"),b);const g={MINIO_IMAGE:"quay.io/minio/minio",MINIO_STORAGE:c("minio"),PL_IMAGE:s,PL_AUTH_HTPASSWD_PATH:b,PL_LICENSE:r==null?void 0:r.license,PL_LICENSE_FILE:r==null?void 0:r.licenseFile,PL_LOG_LEVEL:(r==null?void 0:r.logLevel)??"info",PL_LOG_FILE:n,PL_DATA_DB_ROOT:u,PL_DATA_PRIMARY_ROOT:c("primary"),PL_DATA_LIBRARY_ROOT:c("library"),PL_DATA_WORKDIR_ROOT:v,PL_DATA_PACKAGE_ROOT:c("packages"),...this.configureDockerStorage("primary",m),...this.configureDockerStorage("library",h)};if(r!=null&&r.grpcAddr&&(g.PL_GRPC_ADDR=r.grpcAddr),r!=null&&r.grpcPort&&(g.PL_GRPC_PORT=r.grpcPort.toString()),r!=null&&r.monitoringAddr&&(g.PL_MONITORING_ADDR=r.monitoringAddr),r!=null&&r.monitoringPort&&(g.PL_MONITORING_PORT=r.monitoringPort.toString()),r!=null&&r.debugAddr&&(g.PL_DEBUG_ADDR=r.debugAddr),r!=null&&r.debugPort&&(g.PL_DEBUG_PORT=r.debugPort.toString()),r!=null&&r.auth&&(r.auth.enabled&&(g.PL_AUTH_ENABLED="true"),r.auth.drivers)){for(const S of r.auth.drivers)S.driver==="htpasswd"&&(g.PL_AUTH_HTPASSWD_PATH=f.resolve(S.path),S.path="/etc/platforma/users.htpasswd");g.PL_AUTH_DRIVERS=JSON.stringify(r.auth.drivers)}const P=Me(this.logger,["compose",`--file=${t}`,"up","--detach","--remove-orphans","--pull=missing","minio","backend"],{env:g,stdio:"inherit"},{plImage:s,composePath:t});q(P,"failed to start Platforma Backend in Docker"),o.isActive=!0;const w=this.renderRunInfo({apiPort:r==null?void 0:r.grpcPort,apiAddr:r==null?void 0:r.grpcAddr,logPath:n,primary:m,work:{type:"FS",rootPath:v},library:h,dbPath:u});this.logger.info(`Started platforma:
94
- ${w}`)}startDocker(e,r){var t=O("compose-backend.yaml");const s=(r==null?void 0:r.image)??ae(r==null?void 0:r.version);this.checkLicense(r==null?void 0:r.license,r==null?void 0:r.licenseFile);const i=k=>f.join(e,k),c=k=>{const p=i(k);return Y(p,{mode:"0775"}),p},n=i("platforma.log");l.existsSync(n)||(l.mkdirSync(f.dirname(n),{recursive:!0}),l.writeFileSync(n,""));const m=c("db"),h=c("primary"),u=c("library"),v=c("work"),b=i("users.htpasswd");l.existsSync(b)||l.copyFileSync(O("users.htpasswd"),b);const g=N((r==null?void 0:r.primaryStorageURL)??`file:${h}`,"."),P=N((r==null?void 0:r.libraryStorageURL)??`file:${u}`,"."),w={MINIO_IMAGE:"quay.io/minio/minio",MINIO_STORAGE:c("minio"),PL_IMAGE:s,PL_AUTH_HTPASSWD_PATH:b,PL_LICENSE:r==null?void 0:r.license,PL_LICENSE_FILE:r==null?void 0:r.licenseFile,PL_LOG_LEVEL:"info",PL_LOG_FILE:n,PL_DATA_DB_ROOT:m,PL_DATA_PRIMARY_ROOT:h,PL_DATA_LIBRARY_ROOT:u,PL_DATA_WORKDIR_ROOT:v,PL_DATA_PACKAGE_ROOT:c("packages"),...this.configureDockerStorage("primary",g),...this.configureDockerStorage("library",P)};if(r!=null&&r.grpcAddr&&(w.PL_GRPC_ADDR=r.grpcAddr),r!=null&&r.grpcPort&&(w.PL_GRPC_PORT=r.grpcPort.toString()),r!=null&&r.monitoringAddr&&(w.PL_MONITORING_ADDR=r.monitoringAddr),r!=null&&r.monitoringPort&&(w.PL_MONITORING_PORT=r.monitoringPort.toString()),r!=null&&r.debugAddr&&(w.PL_DEBUG_ADDR=r.debugAddr),r!=null&&r.debugPort&&(w.PL_DEBUG_PORT=r.debugPort.toString()),r!=null&&r.auth&&(r.auth.enabled&&(w.PL_AUTH_ENABLED="true"),r.auth.drivers)){for(const k of r.auth.drivers)k.driver==="htpasswd"&&(w.PL_AUTH_HTPASSWD_PATH=f.resolve(k.path),k.path="/etc/platforma/users.htpasswd");w.PL_AUTH_DRIVERS=JSON.stringify(r.auth.drivers)}const S=Me(this.logger,["compose",`--file=${t}`,"up","--detach","--remove-orphans","--pull=missing","backend"],{env:w,stdio:"inherit"},{plImage:s,composePath:t,primaryPath:h,workPath:v,libraryPath:u});q(S,"failed to start Platforma Backend in Docker"),o.isActive=!0;const L=this.renderRunInfo({apiPort:r==null?void 0:r.grpcPort,apiAddr:r==null?void 0:r.grpcAddr,logPath:n,primary:g,work:{type:"FS",rootPath:v},library:P,dbPath:m});this.logger.info(`Started platforma:
95
- ${L}`)}stop(){if(!o.isActive){console.log("no running service detected");return}const e=o.lastRun;switch(e.mode){case"docker":const r=F.spawnSync("docker",["compose","--file",e.docker.composePath,"down"],{env:{...process.env,...e.envs},stdio:"inherit"});o.isActive=!1,r.status!==0&&process.exit(r.status);return;case"process":o.isValidPID&&process.kill(e.process.pid),o.isActive=!1;return;default:J(e.mode)}}cleanup(){var n,m,h,u,v,b,g,P,w,S,L,k,p,j;const e=["last command run cache ('pl-service start' shorthand will stop working until next full start command call)","'platforma' docker compose service containers and volumes"],r=o.data(),t=[r];if((m=(n=o.lastRun)==null?void 0:n.docker)!=null&&m.primaryPath){const A=(u=(h=o.lastRun)==null?void 0:h.docker)==null?void 0:u.primaryPath;A.startsWith(r)||t.push(A)}if((b=(v=o.lastRun)==null?void 0:v.docker)!=null&&b.workPath){const A=(P=(g=o.lastRun)==null?void 0:g.docker)==null?void 0:P.workPath;A.startsWith(r)||t.push(A)}if((S=(w=o.lastRun)==null?void 0:w.process)!=null&&S.storagePath){const A=(k=(L=o.lastRun)==null?void 0:L.process)==null?void 0:k.storagePath;A.startsWith(r)||t.push(A)}const s=t.length>0?` - storages (you'll loose all projects and calculation results stored in service instances):
88
+ `}function J(a,e){return a===void 0?e:a}const Fr=["linux","macos","windows"];function $r(a){const e=_.platform();switch(e){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:throw new Error(`operating system '${e}' is not currently supported by Platforma ecosystem. The list of OSes supported: `+JSON.stringify(Fr))}}const Tr=["amd64","arm64"];function ze(a){const e=_.arch();switch(e){case"arm64":return"arm64";case"x64":return"amd64";default:throw new Error(`processor architecture '${e}' is not currently supported by Platforma ecosystem. The list of architectures supported: `+JSON.stringify(Tr))}}function Er(a,e){const r=(e==null?void 0:e.version)??V.getPlVersion(),t=(e==null?void 0:e.showProgress)??process.stdout.isTTY,i=`pl-${r}-${ze()}.tgz`,s=(e==null?void 0:e.downloadURL)??`https://cdn.platforma.bio/software/pl/${$r()}/${i}`,c=(e==null?void 0:e.saveTo)??o.binaries(i);if(l.existsSync(c))return a.info(`Platforma Backend archive download skipped: '${c}' already exists`),Promise.resolve(c);l.mkdirSync(f.dirname(c),{recursive:!0}),a.info(`Downloading Platforma Backend archive:
89
+ URL: ${s}
90
+ Save to: ${c}`);const n=rr.get(s);return new Promise((m,h)=>{n.on("response",u=>{if(!u.statusCode){const b=new Error("failed to download archive: no HTTP status code in response from server");n.destroy(),h(b);return}if(u.statusCode!==200){const b=new Error(`failed to download archive: ${u.statusCode} ${u.statusMessage}`);n.destroy(),h(b);return}const v=parseInt(u.headers["content-length"]||"0",10);let P=0;const g=l.createWriteStream(c);u.pipe(g),u.on("data",b=>{P+=b.length;const w=P/v*100;t&&process.stdout.write(` downloading: ${w.toFixed(2)}%\r`)}),u.on("error",b=>{l.unlinkSync(c),a.error(`Failed to download Platforma Binary: ${b.message}`),n.destroy(),h(b)}),g.on("finish",()=>{g.close(),a.info(" ... download done."),n.destroy(),m(c)})})})}function Dr(a,e){a.debug("extracting archive...");const r=(e==null?void 0:e.version)??V.getPlVersion();a.debug(` version: '${r}'`);const t=`${Ke({version:r})}.tgz`,i=(e==null?void 0:e.archivePath)??o.binaries(t);a.debug(` archive path: '${i}'`);const s=(e==null?void 0:e.extractTo)??Ir(i);if(a.debug(` target dir: '${s}'`),l.existsSync(s))return a.info(`Platforma Backend binaries unpack skipped: '${s}' exists`),s;if(!l.existsSync(i)){const c=`Platforma Backend binary archive not found at '${i}'`;throw a.error(c),new Error(c)}return l.existsSync(s)||(a.debug(` creating target dir '${s}'`),l.mkdirSync(s,{recursive:!0})),a.info(`Unpacking Platforma Backend archive:
91
+ Archive: ${i}
92
+ Target dir: ${s}`),ir.x({file:i,cwd:s,gzip:!0,sync:!0}),a.info(" ... unpack done."),s}function Ye(a,e){return Er(a,e).then(r=>Dr(a,{archivePath:r}))}function Ke(a){return`pl-${(a==null?void 0:a.version)??V.getPlVersion()}-${ze()}`}function Nr(a,...e){return o.binaries(Ke({version:a}),...e)}function Ir(a){const e=a.lastIndexOf(".");return e===-1?a:a.slice(0,e)}class D{constructor(e){this.logger=e}startLast(){const e=Lr(this.logger,{stdio:"inherit"});q(e,"failed to bring back Platforma Backend in the last started configuration")}startLocal(e){var m,h,u,v,P,g,b,w,S,L;const r=(e==null?void 0:e.binaryPath)??Nr(e==null?void 0:e.version,"binaries","platforma");var t=e==null?void 0:e.configPath;const i=(e==null?void 0:e.workdir)??(t?process.cwd():o.path());e!=null&&e.primaryURL&&(e.configOptions={...e.configOptions,storages:{...(m=e.configOptions)==null?void 0:m.storages,primary:N(e.primaryURL,i,(u=(h=e.configOptions)==null?void 0:h.storages)==null?void 0:u.primary)}}),e!=null&&e.libraryURL&&(e.configOptions={...e.configOptions,storages:{...(v=e.configOptions)==null?void 0:v.storages,library:N(e.libraryURL,i,(g=(P=e.configOptions)==null?void 0:P.storages)==null?void 0:g.library)}});const s=Or(this.getLastJwt(),e==null?void 0:e.configOptions);this.logger.debug(" checking license..."),this.checkLicense((w=(b=e==null?void 0:e.configOptions)==null?void 0:b.license)==null?void 0:w.value,(L=(S=e==null?void 0:e.configOptions)==null?void 0:S.license)==null?void 0:L.file);const c=[`${s.localRoot}/packages`,`${s.localRoot}/packages-local`,`${s.localRoot}/blocks-local`];s.storages.primary.type==="FS"&&c.push(s.storages.primary.rootPath),s.storages.library.type==="FS"&&(c.push(s.storages.library.rootPath),s.hacks.libraryDownloadable=!1),s.storages.work.type==="FS"&&c.push(s.storages.work.rootPath),this.logger.debug(" creating pl state directories...");for(const k of c)l.existsSync(k)||(this.logger.debug(` '${k}'`),l.mkdirSync(k,{recursive:!0}));for(const k of s.core.auth.drivers)k.driver==="htpasswd"&&(l.existsSync(k.path)||(this.logger.debug(` installing default 'users.htpasswd' to ${k.path}...`),l.copyFileSync(p("users.htpasswd"),k.path)));t||(t=f.join(s.localRoot,"config.yaml"),this.logger.debug(` rendering configuration '${t}'...`),l.writeFileSync(t,pr(s)));const n=this.renderRunInfo({configPath:t,dbPath:s.core.db.path,apiAddr:s.grpc.listen,logPath:s.log.path,primary:s.storages.primary,work:s.storages.work,library:s.storages.library});return this.logger.info(`Starting platforma:
93
+ ${n}`),Ar(this.logger,r,["-config",t],{cwd:i,stdio:"inherit"},{storagePath:s.localRoot})}startLocalS3(e){var i;this.logger.debug("starting platforma in 'local s3' mode...");const r=(e==null?void 0:e.minioPort)??9e3,t=(i=e==null?void 0:e.configOptions)==null?void 0:i.localRoot;return this.startMinio({minioPort:r,minioConsolePort:e==null?void 0:e.minioConsolePort,storage:t?f.join(t,"minio"):void 0}),this.startLocal({...e,primaryURL:(e==null?void 0:e.primaryURL)??`s3e://testuser:testpassword@localhost:${r}/main-bucket/?region=no-region`,libraryURL:(e==null?void 0:e.libraryURL)??`s3e://testuser:testpassword@localhost:${r}/library-bucket/?region=no-region`})}startMinio(e){this.logger.debug(" starting minio...");var r=p("compose-backend.yaml");const t=e!=null&&e.version?`:${e.version}`:"";this.logger.debug(` minio version: ${t}`);const i=(e==null?void 0:e.image)??`quay.io/minio/minio${t}`;this.logger.debug(` minio image: ${i}`);const s=(e==null?void 0:e.storage)??o.data("minio");Y(s,{mode:"0775"});const c=o.data("stub");Y(c);const n=(e==null?void 0:e.minioPort)??9e3,m=(e==null?void 0:e.minioConsolePort)??9001,h={MINIO_IMAGE:i,MINIO_STORAGE:f.resolve(s),MINIO_PORT:n.toString(),MINIO_CONSOLE_PORT:m.toString(),PL_DATA_DB_ROOT:c,PL_DATA_PRIMARY_ROOT:c,PL_DATA_LIBRARY_ROOT:c,PL_DATA_WORKDIR_ROOT:c,PL_DATA_PACKAGE_ROOT:c,PL_IMAGE:"scratch"};this.logger.debug(" spawning child 'docker' process...");const u=F.spawnSync("docker",["compose",`--file=${r}`,"up","--detach","--remove-orphans","--pull=missing","minio"],{env:{...process.env,...h},stdio:"inherit"});q(u,"failed to start MinIO service in docker")}buildPlatforma(e){const r=f.resolve(e.repoRoot,"cmd","platforma"),t=e.binPath??f.join(_.tmpdir(),"platforma-local-build");this.logger.info("Building Platforma Backend binary from sources"),this.logger.info(` sources path: ${e.repoRoot}`),this.logger.info(` binary path: ${t}`);const i=F.spawnSync("go",["build","-o",t,"."],{cwd:r,stdio:"inherit"});return q(i,"failed to build platforma binary from sources using 'go build' command"),t}startDockerS3(e,r){const t=p("compose-backend.yaml"),i=(r==null?void 0:r.image)??te(r==null?void 0:r.version);this.checkLicense(r==null?void 0:r.license,r==null?void 0:r.licenseFile);const s=S=>f.join(e,S),c=S=>{const L=s(S);return Y(L,{mode:"0775"}),L},n=s("platforma.log");l.existsSync(n)||(l.mkdirSync(f.dirname(n),{recursive:!0}),l.writeFileSync(n,""));const m=N("s3e://testuser:testpassword@minio:9000/main-bucket");if(m.type!=="S3")throw new Error("primary storage must have 'S3' type in 'docker s3' configuration");m.presignEndpoint="http://localhost:9000";const h=N("s3e://testuser:testpassword@minio:9000/library-bucket");if(h.type!=="S3")throw new Error(`${h.type} storage type is not supported for library storage`);h.presignEndpoint="http://localhost:9000";const u=c("db"),v=c("work"),P=s("users.htpasswd");l.existsSync(P)||l.copyFileSync(p("users.htpasswd"),P);const g={MINIO_IMAGE:"quay.io/minio/minio",MINIO_STORAGE:c("minio"),PL_IMAGE:i,PL_AUTH_HTPASSWD_PATH:P,PL_LICENSE:r==null?void 0:r.license,PL_LICENSE_FILE:r==null?void 0:r.licenseFile,PL_LOG_LEVEL:(r==null?void 0:r.logLevel)??"info",PL_LOG_FILE:n,PL_DATA_DB_ROOT:u,PL_DATA_PRIMARY_ROOT:c("primary"),PL_DATA_LIBRARY_ROOT:c("library"),PL_DATA_WORKDIR_ROOT:v,PL_DATA_PACKAGE_ROOT:c("packages"),...this.configureDockerStorage("primary",m),...this.configureDockerStorage("library",h)};if(r!=null&&r.grpcAddr&&(g.PL_GRPC_ADDR=r.grpcAddr),r!=null&&r.grpcPort&&(g.PL_GRPC_PORT=r.grpcPort.toString()),r!=null&&r.monitoringAddr&&(g.PL_MONITORING_ADDR=r.monitoringAddr),r!=null&&r.monitoringPort&&(g.PL_MONITORING_PORT=r.monitoringPort.toString()),r!=null&&r.debugAddr&&(g.PL_DEBUG_ADDR=r.debugAddr),r!=null&&r.debugPort&&(g.PL_DEBUG_PORT=r.debugPort.toString()),r!=null&&r.auth&&(r.auth.enabled&&(g.PL_AUTH_ENABLED="true"),r.auth.drivers)){for(const S of r.auth.drivers)S.driver==="htpasswd"&&(g.PL_AUTH_HTPASSWD_PATH=f.resolve(S.path),S.path="/etc/platforma/users.htpasswd");g.PL_AUTH_DRIVERS=JSON.stringify(r.auth.drivers)}const b=xe(this.logger,["compose",`--file=${t}`,"up","--detach","--remove-orphans","--pull=missing","minio","backend"],{env:g,stdio:"inherit"},{plImage:i,composePath:t});q(b,"failed to start Platforma Backend in Docker"),o.isActive=!0;const w=this.renderRunInfo({apiPort:r==null?void 0:r.grpcPort,apiAddr:r==null?void 0:r.grpcAddr,logPath:n,primary:m,work:{type:"FS",rootPath:v},library:h,dbPath:u});this.logger.info(`Started platforma:
94
+ ${w}`)}startDocker(e,r){var t=p("compose-backend.yaml");const i=(r==null?void 0:r.image)??te(r==null?void 0:r.version);this.checkLicense(r==null?void 0:r.license,r==null?void 0:r.licenseFile);const s=k=>f.join(e,k),c=k=>{const O=s(k);return Y(O,{mode:"0775"}),O},n=s("platforma.log");l.existsSync(n)||(l.mkdirSync(f.dirname(n),{recursive:!0}),l.writeFileSync(n,""));const m=c("db"),h=c("primary"),u=c("library"),v=c("work"),P=s("users.htpasswd");l.existsSync(P)||l.copyFileSync(p("users.htpasswd"),P);const g=N((r==null?void 0:r.primaryStorageURL)??`file:${h}`,"."),b=N((r==null?void 0:r.libraryStorageURL)??`file:${u}`,"."),w={MINIO_IMAGE:"quay.io/minio/minio",MINIO_STORAGE:c("minio"),PL_IMAGE:i,PL_AUTH_HTPASSWD_PATH:P,PL_LICENSE:r==null?void 0:r.license,PL_LICENSE_FILE:r==null?void 0:r.licenseFile,PL_LOG_LEVEL:"info",PL_LOG_FILE:n,PL_DATA_DB_ROOT:m,PL_DATA_PRIMARY_ROOT:h,PL_DATA_LIBRARY_ROOT:u,PL_DATA_WORKDIR_ROOT:v,PL_DATA_PACKAGE_ROOT:c("packages"),...this.configureDockerStorage("primary",g),...this.configureDockerStorage("library",b)};if(r!=null&&r.grpcAddr&&(w.PL_GRPC_ADDR=r.grpcAddr),r!=null&&r.grpcPort&&(w.PL_GRPC_PORT=r.grpcPort.toString()),r!=null&&r.monitoringAddr&&(w.PL_MONITORING_ADDR=r.monitoringAddr),r!=null&&r.monitoringPort&&(w.PL_MONITORING_PORT=r.monitoringPort.toString()),r!=null&&r.debugAddr&&(w.PL_DEBUG_ADDR=r.debugAddr),r!=null&&r.debugPort&&(w.PL_DEBUG_PORT=r.debugPort.toString()),r!=null&&r.auth&&(r.auth.enabled&&(w.PL_AUTH_ENABLED="true"),r.auth.drivers)){for(const k of r.auth.drivers)k.driver==="htpasswd"&&(w.PL_AUTH_HTPASSWD_PATH=f.resolve(k.path),k.path="/etc/platforma/users.htpasswd");w.PL_AUTH_DRIVERS=JSON.stringify(r.auth.drivers)}const S=xe(this.logger,["compose",`--file=${t}`,"up","--detach","--remove-orphans","--pull=missing","backend"],{env:w,stdio:"inherit"},{plImage:i,composePath:t,primaryPath:h,workPath:v,libraryPath:u});q(S,"failed to start Platforma Backend in Docker"),o.isActive=!0;const L=this.renderRunInfo({apiPort:r==null?void 0:r.grpcPort,apiAddr:r==null?void 0:r.grpcAddr,logPath:n,primary:g,work:{type:"FS",rootPath:v},library:b,dbPath:m});this.logger.info(`Started platforma:
95
+ ${L}`)}stop(){if(!o.isActive){console.log("no running service detected");return}const e=o.lastRun;switch(e.mode){case"docker":const r=F.spawnSync("docker",["compose","--file",e.docker.composePath,"down"],{env:{...process.env,...e.envs},stdio:"inherit"});o.isActive=!1,r.status!==0&&process.exit(r.status);return;case"process":o.isValidPID&&process.kill(e.process.pid),o.isActive=!1;return;default:H(e.mode)}}cleanup(){var n,m,h,u,v,P,g,b,w,S,L,k,O,j;const e=["last command run cache ('pl-service start' shorthand will stop working until next full start command call)","'platforma' docker compose service containers and volumes"],r=o.data(),t=[r];if((m=(n=o.lastRun)==null?void 0:n.docker)!=null&&m.primaryPath){const A=(u=(h=o.lastRun)==null?void 0:h.docker)==null?void 0:u.primaryPath;A.startsWith(r)||t.push(A)}if((P=(v=o.lastRun)==null?void 0:v.docker)!=null&&P.workPath){const A=(b=(g=o.lastRun)==null?void 0:g.docker)==null?void 0:b.workPath;A.startsWith(r)||t.push(A)}if((S=(w=o.lastRun)==null?void 0:w.process)!=null&&S.storagePath){const A=(k=(L=o.lastRun)==null?void 0:L.process)==null?void 0:k.storagePath;A.startsWith(r)||t.push(A)}const i=t.length>0?` - storages (you'll loose all projects and calculation results stored in service instances):
96
96
  - ${t.join(`
97
- - `)}`:"";var i=`
97
+ - `)}`:"";var s=`
98
98
  You are going to reset the state of platforma service
99
99
  Things to be removed:
100
100
  - ${e.join(`
101
101
  - `)}
102
- ${s}
103
- `;if(this.logger.warn(i),!ur("Are you sure?")){this.logger.info("Reset action was canceled");return}const c=new Set(Ar());(j=(p=o.lastRun)==null?void 0:p.docker)!=null&&j.composePath&&c.add(o.lastRun.docker.composePath);for(const A of c)this.logger.info(`Destroying docker compose '${A}'`),this.destroyDocker(A,ae());for(const A of t)this.logger.info(`Destroying '${A}'`),l.rmSync(A,{recursive:!0,force:!0});this.logger.info(`Destroying state dir '${o.path()}'`),l.rmSync(o.path(),{recursive:!0,force:!0}),this.logger.info(`
102
+ ${i}
103
+ `;if(this.logger.warn(s),!dr("Are you sure?")){this.logger.info("Reset action was canceled");return}const c=new Set(kr());(j=(O=o.lastRun)==null?void 0:O.docker)!=null&&j.composePath&&c.add(o.lastRun.docker.composePath);for(const A of c)this.logger.info(`Destroying docker compose '${A}'`),this.destroyDocker(A,te());for(const A of t)this.logger.info(`Destroying '${A}'`),l.rmSync(A,{recursive:!0,force:!0});this.logger.info(`Destroying state dir '${o.path()}'`),l.rmSync(o.path(),{recursive:!0,force:!0}),this.logger.info(`
104
104
  If you want to remove all downloaded platforma binaries, delete '${o.binaries()}' dir manually
105
- `)}mergeLicenseEnvs(e){e.license===void 0&&((process.env.MI_LICENSE??"")!=""?e.license=process.env.MI_LICENSE:(process.env.PL_LICENSE??"")!=""&&(e.license=process.env.PL_LICENSE)),e["license-file"]===void 0&&e.license===void 0&&((process.env.MI_LICENSE_FILE??"")!=""?e["license-file"]=process.env.MI_LICENSE_FILE:(process.env.PL_LICENSE_FILE??"")!=""?e["license-file"]=process.env.PL_LICENSE_FILE:l.existsSync(f.resolve(_.homedir(),".pl.license"))&&(e["license-file"]=f.resolve(_.homedir(),".pl.license")))}initAuthDriversList(e,r){var t=[];if(e["auth-htpasswd-file"]&&t.push({driver:"htpasswd",path:f.resolve(r,e["auth-htpasswd-file"])}),!!e["auth-ldap-server"]!=!!e["auth-ldap-default-dn"])throw new Error("LDAP auth settings require both 'server' and 'default DN' options to be set");if(e["auth-ldap-server"]&&t.push({driver:"ldap",serverUrl:e["auth-ldap-server"],defaultDN:e["auth-ldap-default-dn"]}),t.length!==0)return[{driver:"jwt",key:this.getLastJwt()},...t]}getLastJwt(){const e=o.path("auth.jwt"),r="utf-8";let t="";try{t=l.readFileSync(e,{encoding:r})}catch{}return t==""&&(t=fr(64),l.writeFileSync(e,t,{encoding:r})),t}destroyDocker(e,r){const t=o.data("stub"),s=F.spawnSync("docker",["compose","--file",e,"down","--volumes","--remove-orphans"],{env:{...process.env,PL_IMAGE:"scratch",PL_DATA_DB_ROOT:t,PL_DATA_PRIMARY_ROOT:t,PL_DATA_LIBRARY_ROOT:t,PL_DATA_WORKDIR_ROOT:t,PL_DATA_PACKAGE_ROOT:t,MINIO_IMAGE:"scratch",MINIO_STORAGE:t},stdio:"inherit"});s.status!==0&&process.exit(s.status)}checkLicense(e,r){if(!(e!==void 0&&e!="")&&!(r!==void 0&&r!=""))throw this.logger.error(`A license for Platforma Backend must be set.
105
+ `)}mergeLicenseEnvs(e){e.license===void 0&&((process.env.MI_LICENSE??"")!=""?e.license=process.env.MI_LICENSE:(process.env.PL_LICENSE??"")!=""&&(e.license=process.env.PL_LICENSE)),e["license-file"]===void 0&&e.license===void 0&&((process.env.MI_LICENSE_FILE??"")!=""?e["license-file"]=process.env.MI_LICENSE_FILE:(process.env.PL_LICENSE_FILE??"")!=""?e["license-file"]=process.env.PL_LICENSE_FILE:l.existsSync(f.resolve(_.homedir(),".pl.license"))&&(e["license-file"]=f.resolve(_.homedir(),".pl.license")))}initAuthDriversList(e,r){var t=[];if(e["auth-htpasswd-file"]&&t.push({driver:"htpasswd",path:f.resolve(r,e["auth-htpasswd-file"])}),!!e["auth-ldap-server"]!=!!e["auth-ldap-default-dn"])throw new Error("LDAP auth settings require both 'server' and 'default DN' options to be set");if(e["auth-ldap-server"]&&t.push({driver:"ldap",serverUrl:e["auth-ldap-server"],defaultDN:e["auth-ldap-default-dn"]}),t.length!==0)return[{driver:"jwt",key:this.getLastJwt()},...t]}getLastJwt(){const e=o.path("auth.jwt"),r="utf-8";let t="";try{t=l.readFileSync(e,{encoding:r})}catch{}return t==""&&(t=gr(64),l.writeFileSync(e,t,{encoding:r})),t}destroyDocker(e,r){const t=o.data("stub"),i=F.spawnSync("docker",["compose","--file",e,"down","--volumes","--remove-orphans"],{env:{...process.env,PL_IMAGE:"scratch",PL_DATA_DB_ROOT:t,PL_DATA_PRIMARY_ROOT:t,PL_DATA_LIBRARY_ROOT:t,PL_DATA_WORKDIR_ROOT:t,PL_DATA_PACKAGE_ROOT:t,MINIO_IMAGE:"scratch",MINIO_STORAGE:t},stdio:"inherit"});i.status!==0&&process.exit(i.status)}checkLicense(e,r){if(!(e!==void 0&&e!="")&&!(r!==void 0&&r!=""))throw this.logger.error(`A license for Platforma Backend must be set.
106
106
 
107
107
  You can provide the license directly using the '--license' flag
108
108
  or use the '--license-file' flag if the license is stored in a file.
@@ -112,6 +112,6 @@ Alternatively, you can set it via the environment variables 'MI_LICENSE' or 'PL_
112
112
  The license file can also be set with the variables 'MI_LICENSE_FILE' or 'PL_LICENSE_FILE',
113
113
  or stored in '$HOME/.pl.license'.
114
114
 
115
- You can obtain the license from "https://licensing.milaboratories.com".`),new Error("The license was not provided.")}configureDockerStorage(e,r){const t={},s=r.type;switch(e=e.toUpperCase(),s){case"S3":return t[`PL_DATA_${e}_TYPE`]="S3",t[`PL_DATA_${e}_S3_BUCKET`]=r.bucketName,r.endpoint&&(t[`PL_DATA_${e}_S3_ENDPOINT`]=r.endpoint),r.presignEndpoint&&(t[`PL_DATA_${e}_S3_PRESIGN_ENDPOINT`]=r.presignEndpoint),r.region&&(t[`PL_DATA_${e}_S3_REGION`]=r.region),r.key&&(t[`PL_DATA_${e}_S3_KEY`]=r.key),r.secret&&(t[`PL_DATA_${e}_S3_SECRET`]=r.secret),t;case"FS":return t[`PL_DATA_${e}_TYPE`]="FS",t;default:J()}return{}}renderRunInfo(e,r=10){var n,m;const t=[],s=h=>h.padStart(r," ");switch(e.configPath&&t.push(`${s("config")}: ${e.configPath}`),e.apiAddr?t.push(`${s("API")}: ${e.apiAddr}`):e.apiPort?t.push(`${s("API")}: 127.0.0.1:${e.apiPort.toString()}`):t.push(`${s("API")}: 127.0.0.1:6345`),e.logPath&&t.push(`${s("log")}: ${e.logPath}`),(n=e.primary)==null?void 0:n.type){case void 0:break;case"FS":t.push(`${s("primary")}: ${e.primary.rootPath}`);break;case"S3":t.push(`${s("primary")}: S3 at '${e.primary.endpoint??"AWS"}', bucket '${e.primary.bucketName}', prefix: '${e.primary.keyPrefix??""}'`);break;default:J()}switch((m=e.library)==null?void 0:m.type){case void 0:break;case"FS":t.push(`${s("library")}: ${e.library.rootPath}`);break;case"S3":t.push(`${s("library")}: S3 at '${e.library.endpoint??"AWS"}', bucket '${e.library.bucketName}', prefix: '${e.library.keyPrefix??""}'`);break;default:J()}return e.work&&t.push(`${s("workdirs")}: ${e.work.rootPath}`),e.dbPath&&t.push(`${s("db")}: ${e.dbPath}`),t.join(`
116
- `)}readComposeFile(e){const r=l.readFileSync(e);return xe.parse(r.toString())}writeComposeFile(e,r){l.writeFileSync(e,xe.stringify(r))}}function q(a,e){if(a.error)throw a.error;const r=e??"failed to run command";if(a.status!==0)throw new Error(`${r}, process exited with code '${a.status}'`)}const x=class x extends d.Command{async run(){const{flags:e}=await this.parse(x),r=T(e["log-level"]);new D(r).cleanup()}};y(x,"description","Clear service state (forget last run command, destroy docker services, volumes and so on)"),y(x,"examples",["<%= config.bin %> <%= command.id %>"]),y(x,"flags",{...$});let ce=x;const M=class M extends d.Command{async run(){const{flags:e}=await this.parse(M),r=T(e["log-level"]);new D(r).startLast()}};y(M,"description","Start last run service configuraiton"),y(M,"examples",["<%= config.bin %> <%= command.id %>"]),y(M,"flags",{...$});let ne=M;const C=class C extends d.Command{async run(){const{flags:e}=await this.parse(C),r=T(e["log-level"]);new D(r).stop()}};y(C,"description","Stop platforma service"),y(C,"examples",["<%= config.bin %> <%= command.id %>"]),y(C,"flags",{...$});let le=C;const B=class B extends d.Command{async run(){const{flags:e}=await this.parse(B),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const s=e["auth-enabled"],i=s?{enabled:s,drivers:t.initAuthDriversList(e,".")}:void 0,c=e.storage?f.join(".",e.storage):o.data("docker");t.startDocker(c,{primaryStorageURL:e["storage-primary"],workStoragePath:e["storage-work"],libraryStorageURL:e["storage-library"],image:e.image,version:e.version,license:e.license,licenseFile:e["license-file"],auth:i,grpcAddr:e["grpc-listen"],grpcPort:e["grpc-port"],monitoringAddr:e["monitoring-listen"],monitoringPort:e["monitoring-port"],debugAddr:e["debug-listen"],debugPort:e["debug-port"]})}};y(B,"description","Run platforma backend service with 'FS' primary storage type"),y(B,"examples",["<%= config.bin %> <%= command.id %>"]),y(B,"flags",{...$,...X,...Be,...V,...ee,...Q,...Z,...fe,...ue,...he});let oe=B;const G=class G extends d.Command{async run(){const{flags:e}=await this.parse(G),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const s=e["pl-workdir"]??".",i=e.storage?f.join(s,e.storage):o.data("local"),c=e["pl-log-file"]?f.join(s,e["pl-log-file"]):void 0,n=t.initAuthDriversList(e,s),m=e["auth-enabled"]??n!==void 0;var h=e["pl-binary"];e["pl-sources"]&&(h=t.buildPlatforma({repoRoot:e["pl-sources"]}));var u="127.0.0.1:6345";e["grpc-listen"]?u=e["grpc-listen"]:e["grpc-port"]&&(u=`127.0.0.1:${e["grpc-port"]}`);var v="127.0.0.1:9090";e["monitoring-listen"]?v=e["monitoring-listen"]:e["monitoring-port"]&&(v=`127.0.0.1:${e["monitoring-port"]}`);var b="127.0.0.1:9091";e["debug-listen"]?b=e["debug-listen"]:e["debug-port"]&&(b=`127.0.0.1:${e["debug-port"]}`);const g={binaryPath:h,version:e.version,configPath:e.config,workdir:e["pl-workdir"],primaryURL:e["storage-primary"],libraryURL:e["storage-library"],configOptions:{grpc:{listen:u},monitoring:{listen:v},debug:{listen:b},license:{value:e.license,file:e["license-file"]},log:{path:c},localRoot:i,core:{auth:{enabled:m,drivers:n}},storages:{work:{type:"FS",rootPath:e["storage-work"]}}}};g.binaryPath?t.startLocal(g):Ve(r,{version:e.version}).then(()=>t.startLocal(g)).catch(function(P){r.error(P.message)})}};y(G,"description","Run Platforma Backend service as local process on current host (no docker container)"),y(G,"examples",["<%= config.bin %> <%= command.id %>"]),y(G,"flags",{...$,...V,...X,...je,...We,...qe,...Q,...Z,...fe,...ue,...he,...Ge,...Ue,...ee});let de=G;var R;let Mr=(R=class extends d.Command{async run(){const{flags:e}=await this.parse(R),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const s=e["auth-enabled"],i=s?{enabled:s,drivers:t.initAuthDriversList(e,".")}:void 0,c=e.storage?f.join(".",e.storage):o.data("docker-s3");t.startDockerS3(c,{image:e.image,version:e.version,license:e.license,licenseFile:e["license-file"],auth:i,grpcAddr:e["grpc-listen"],grpcPort:e["grpc-port"],monitoringAddr:e["monitoring-listen"],monitoringPort:e["monitoring-port"],debugAddr:e["debug-listen"],debugPort:e["debug-port"]})}},y(R,"description","Run platforma backend service with 'S3' primary storage type"),y(R,"examples",["<%= config.bin %> <%= command.id %>"]),y(R,"flags",{...$,...X,...Be,...V,...Z,...Q,...ee}),R);const U=class U extends d.Command{async run(){const{flags:e}=await this.parse(U),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const s=e["pl-workdir"]??".",i=e.storage?f.join(s,e.storage):o.data("local-s3"),c=e["pl-log-file"]?f.join(s,e["pl-log-file"]):void 0,n=t.initAuthDriversList(e,s),m=e["auth-enabled"]??n!==void 0;var h=e["pl-binary"];e["pl-sources"]&&(h=t.buildPlatforma({repoRoot:e["pl-sources"]}));var u="127.0.0.1:6345";e["grpc-listen"]?u=e["grpc-listen"]:e["grpc-port"]&&(u=`127.0.0.1:${e["grpc-port"]}`);var v="127.0.0.1:9090";e["monitoring-listen"]?v=e["monitoring-listen"]:e["monitoring-port"]&&(v=`127.0.0.1:${e["monitoring-port"]}`);var b="127.0.0.1:9091";e["debug-listen"]?b=e["debug-listen"]:e["debug-port"]&&(b=`127.0.0.1:${e["debug-port"]}`);const g={binaryPath:h,version:e.version,configPath:e.config,workdir:e["pl-workdir"],primaryURL:e["storage-primary"],libraryURL:e["storage-library"],minioPort:e["s3-address-port"],minioConsolePort:e["s3-console-address-port"],configOptions:{grpc:{listen:u},monitoring:{listen:v},debug:{listen:b},license:{value:e.license,file:e["license-file"]},log:{path:c},localRoot:i,core:{auth:{enabled:m,drivers:n}},storages:{work:{type:"FS",rootPath:e["storage-work"]}}}};g.binaryPath?t.startLocalS3(g):Ve(r,{version:e.version}).then(()=>t.startLocalS3(g)).catch(function(P){r.error(P.message)})}};y(U,"description","Run Platforma Backend service as local process on current host (no docker container)"),y(U,"examples",["<%= config.bin %> <%= command.id %>"]),y(U,"flags",{...$,...V,...X,...nr,...je,...We,...qe,...Q,...Z,...fe,...ue,...he,...Ge,...Ue,...ee});let ge=U;const Cr={"create-block":se,reset:ce,start:ne,stop:le,"start:docker":oe,"start:local":de,"start:docker:s3":Mr,"start:local:s3":ge};exports.COMMANDS=Cr;
115
+ You can obtain the license from "https://licensing.milaboratories.com".`),new Error("The license was not provided.")}configureDockerStorage(e,r){const t={},i=r.type;switch(e=e.toUpperCase(),i){case"S3":return t[`PL_DATA_${e}_TYPE`]="S3",t[`PL_DATA_${e}_S3_BUCKET`]=r.bucketName,r.endpoint&&(t[`PL_DATA_${e}_S3_ENDPOINT`]=r.endpoint),r.presignEndpoint&&(t[`PL_DATA_${e}_S3_PRESIGN_ENDPOINT`]=r.presignEndpoint),r.region&&(t[`PL_DATA_${e}_S3_REGION`]=r.region),r.key&&(t[`PL_DATA_${e}_S3_KEY`]=r.key),r.secret&&(t[`PL_DATA_${e}_S3_SECRET`]=r.secret),t;case"FS":return t[`PL_DATA_${e}_TYPE`]="FS",t;default:H()}return{}}renderRunInfo(e,r=10){var n,m;const t=[],i=h=>h.padStart(r," ");switch(e.configPath&&t.push(`${i("config")}: ${e.configPath}`),e.apiAddr?t.push(`${i("API")}: ${e.apiAddr}`):e.apiPort?t.push(`${i("API")}: 127.0.0.1:${e.apiPort.toString()}`):t.push(`${i("API")}: 127.0.0.1:6345`),e.logPath&&t.push(`${i("log")}: ${e.logPath}`),(n=e.primary)==null?void 0:n.type){case void 0:break;case"FS":t.push(`${i("primary")}: ${e.primary.rootPath}`);break;case"S3":t.push(`${i("primary")}: S3 at '${e.primary.endpoint??"AWS"}', bucket '${e.primary.bucketName}', prefix: '${e.primary.keyPrefix??""}'`);break;default:H()}switch((m=e.library)==null?void 0:m.type){case void 0:break;case"FS":t.push(`${i("library")}: ${e.library.rootPath}`);break;case"S3":t.push(`${i("library")}: S3 at '${e.library.endpoint??"AWS"}', bucket '${e.library.bucketName}', prefix: '${e.library.keyPrefix??""}'`);break;default:H()}return e.work&&t.push(`${i("workdirs")}: ${e.work.rootPath}`),e.dbPath&&t.push(`${i("db")}: ${e.dbPath}`),t.join(`
116
+ `)}readComposeFile(e){const r=l.readFileSync(e);return Ie.parse(r.toString())}writeComposeFile(e,r){l.writeFileSync(e,Ie.stringify(r))}}function q(a,e){if(a.error)throw a.error;const r=e??"failed to run command";if(a.status!==0)throw new Error(`${r}, process exited with code '${a.status}'`)}const x=class x extends d.Command{async run(){const{flags:e}=await this.parse(x),r=T(e["log-level"]);new D(r).cleanup()}};y(x,"description","Clear service state (forget last run command, destroy docker services, volumes and so on)"),y(x,"examples",["<%= config.bin %> <%= command.id %>"]),y(x,"flags",{...$});let se=x;const M=class M extends d.Command{async run(){const{flags:e}=await this.parse(M),r=T(e["log-level"]);new D(r).startLast()}};y(M,"description","Start last run service configuraiton"),y(M,"examples",["<%= config.bin %> <%= command.id %>"]),y(M,"flags",{...$});let ce=M;const C=class C extends d.Command{async run(){const{flags:e}=await this.parse(C),r=T(e["log-level"]);new D(r).stop()}};y(C,"description","Stop platforma service"),y(C,"examples",["<%= config.bin %> <%= command.id %>"]),y(C,"flags",{...$});let ne=C;const B=class B extends d.Command{async run(){const{flags:e}=await this.parse(B),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const i=e["auth-enabled"],s=i?{enabled:i,drivers:t.initAuthDriversList(e,".")}:void 0,c=e.storage?f.join(".",e.storage):o.data("docker");t.startDocker(c,{primaryStorageURL:e["storage-primary"],workStoragePath:e["storage-work"],libraryStorageURL:e["storage-library"],image:e.image,version:e.version,license:e.license,licenseFile:e["license-file"],auth:s,grpcAddr:e["grpc-listen"],grpcPort:e["grpc-port"],monitoringAddr:e["monitoring-listen"],monitoringPort:e["monitoring-port"],debugAddr:e["debug-listen"],debugPort:e["debug-port"]})}};y(B,"description","Run platforma backend service with 'FS' primary storage type"),y(B,"examples",["<%= config.bin %> <%= command.id %>"]),y(B,"flags",{...$,...Z,...Ce,...Q,...re,...X,...ee,...ue,...ge,...fe});let le=B;const G=class G extends d.Command{async run(){const{flags:e}=await this.parse(G),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const i=e["pl-workdir"]??".",s=e.storage?f.join(i,e.storage):o.data("local"),c=e["pl-log-file"]?f.join(i,e["pl-log-file"]):void 0,n=t.initAuthDriversList(e,i),m=e["auth-enabled"]??n!==void 0;var h=e["pl-binary"];e["pl-sources"]&&(h=t.buildPlatforma({repoRoot:e["pl-sources"]}));var u="127.0.0.1:6345";e["grpc-listen"]?u=e["grpc-listen"]:e["grpc-port"]&&(u=`127.0.0.1:${e["grpc-port"]}`);var v="127.0.0.1:9090";e["monitoring-listen"]?v=e["monitoring-listen"]:e["monitoring-port"]&&(v=`127.0.0.1:${e["monitoring-port"]}`);var P="127.0.0.1:9091";e["debug-listen"]?P=e["debug-listen"]:e["debug-port"]&&(P=`127.0.0.1:${e["debug-port"]}`);const g={binaryPath:h,version:e.version,configPath:e.config,workdir:e["pl-workdir"],primaryURL:e["storage-primary"],libraryURL:e["storage-library"],configOptions:{grpc:{listen:u},monitoring:{listen:v},debug:{listen:P},license:{value:e.license,file:e["license-file"]},log:{path:c},localRoot:s,core:{auth:{enabled:m,drivers:n}},storages:{work:{type:"FS",rootPath:e["storage-work"]}}}};g.binaryPath?t.startLocal(g):Ye(r,{version:e.version}).then(()=>t.startLocal(g)).catch(function(b){r.error(b.message)})}};y(G,"description","Run Platforma Backend service as local process on current host (no docker container)"),y(G,"examples",["<%= config.bin %> <%= command.id %>"]),y(G,"flags",{...$,...Q,...Z,...Ue,...je,...We,...X,...ee,...ue,...ge,...fe,...Be,...Ge,...re});let oe=G;var R;let xr=(R=class extends d.Command{async run(){const{flags:e}=await this.parse(R),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const i=e["auth-enabled"],s=i?{enabled:i,drivers:t.initAuthDriversList(e,".")}:void 0,c=e.storage?f.join(".",e.storage):o.data("docker-s3");t.startDockerS3(c,{image:e.image,version:e.version,license:e.license,licenseFile:e["license-file"],auth:s,grpcAddr:e["grpc-listen"],grpcPort:e["grpc-port"],monitoringAddr:e["monitoring-listen"],monitoringPort:e["monitoring-port"],debugAddr:e["debug-listen"],debugPort:e["debug-port"]})}},y(R,"description","Run platforma backend service with 'S3' primary storage type"),y(R,"examples",["<%= config.bin %> <%= command.id %>"]),y(R,"flags",{...$,...Z,...Ce,...Q,...ee,...X,...re}),R);const U=class U extends d.Command{async run(){const{flags:e}=await this.parse(U),r=T(e["log-level"]),t=new D(r);t.mergeLicenseEnvs(e);const i=e["pl-workdir"]??".",s=e.storage?f.join(i,e.storage):o.data("local-s3"),c=e["pl-log-file"]?f.join(i,e["pl-log-file"]):void 0,n=t.initAuthDriversList(e,i),m=e["auth-enabled"]??n!==void 0;var h=e["pl-binary"];e["pl-sources"]&&(h=t.buildPlatforma({repoRoot:e["pl-sources"]}));var u="127.0.0.1:6345";e["grpc-listen"]?u=e["grpc-listen"]:e["grpc-port"]&&(u=`127.0.0.1:${e["grpc-port"]}`);var v="127.0.0.1:9090";e["monitoring-listen"]?v=e["monitoring-listen"]:e["monitoring-port"]&&(v=`127.0.0.1:${e["monitoring-port"]}`);var P="127.0.0.1:9091";e["debug-listen"]?P=e["debug-listen"]:e["debug-port"]&&(P=`127.0.0.1:${e["debug-port"]}`);const g={binaryPath:h,version:e.version,configPath:e.config,workdir:e["pl-workdir"],primaryURL:e["storage-primary"],libraryURL:e["storage-library"],minioPort:e["s3-address-port"],minioConsolePort:e["s3-console-address-port"],configOptions:{grpc:{listen:u},monitoring:{listen:v},debug:{listen:P},license:{value:e.license,file:e["license-file"]},log:{path:c},localRoot:s,core:{auth:{enabled:m,drivers:n}},storages:{work:{type:"FS",rootPath:e["storage-work"]}}}};g.binaryPath?t.startLocalS3(g):Ye(r,{version:e.version}).then(()=>t.startLocalS3(g)).catch(function(b){r.error(b.message)})}};y(U,"description","Run Platforma Backend service as local process on current host (no docker container)"),y(U,"examples",["<%= config.bin %> <%= command.id %>"]),y(U,"flags",{...$,...Q,...Z,...sr,...Ue,...je,...We,...X,...ee,...ue,...ge,...fe,...Be,...Ge,...re});let de=U;const Mr={"create-block":ae,reset:se,start:ce,stop:ne,"start:docker":le,"start:local":oe,"start:docker:s3":xr,"start:local:s3":de};exports.COMMANDS=Mr;
117
117
  //# sourceMappingURL=index.js.map