@overlayed/cli 0.3.0 → 0.4.0
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/cli.js +11 -11
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Builtins as e,Cli as t,Command as n,UsageError as r}from"clipanion";import{scope as i,type as a}from"arktype";import o,{createWriteStream as ee,existsSync as s,mkdirSync as c,readdirSync as l,unlinkSync as u,writeFileSync as te}from"fs";import{ensureFileSync as ne}from"fs-extra";import d,{join as f}from"path";import p from"node:path";import m from"chalk";import{createReadStream as h}from"node:fs";import{glob as g}from"glob";import _,{fileURLToPath as re}from"node:url";import{createJiti as ie}from"jiti";import ae from"jszip";import v,{isXiorError as y}from"xior";import{checkbox as oe,password as se}from"@inquirer/prompts";import{Listr as b}from"listr2";import{ListrInquirerPromptAdapter as ce}from"@listr2/prompt-adapter-inquirer";import{exec as le}from"child_process";import{promisify as ue}from"util";const x={deployment:`deployment`};function S(e){throw e}function C(e){return Object.prototype.toString.call(e)===`[object Object]`}function w(e){return e?Array.isArray(e)?e:[e]:[]}var T=class{data=[];constructor(){}get size(){return this.data.length}add(e){this.data.push(e)}next(){return this.data.shift()}clear(){this.data.length=0}*flush(){for(;this.size>0;){let e=this.next();e&&(yield e)}}};function E(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var D=class{emitter;constructor(){this.emitter=E()}on(e,t){w(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){w(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){w(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}};function O(e,...t){let n=class extends e{static _instance;static getInstance(){return this._instance||(this._instance=new e(...t)),this._instance}static clearInstance(){this._instance=void 0}};return n}var k=class extends D{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}};const A=O(k);var j=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){let t=this.get();return t[e]}save(e){let t=this.onBeforeSave(e);try{ne(this.getFilePath()),o.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return this.data=e,e}try{let e=o.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=a(`string.json.parse`).to(`object`),n=t(e);if(n instanceof a.errors)return this._defaultValue;let r=this._schema[`~standard`].validate(n);if(r instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return r.issues?this.migrate(n,this._defaultValue):this.migrate(r.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return o.accessSync(e,o.constants.R_OK|o.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return o.accessSync(e,o.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]}return n}reportInvalidConfigFile(e){A.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}},M=class e extends D{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(new Date),this.ensureLogDirectory(),this.ensureLogFile(),this.stream=this.createStream(),this.rotationCheckInterval=this.startRotationCheck(),this.cleanupOldLogs()}static scope(t,n){return new e(t,n)}log(...e){this.write(`log`,...e)}error(...e){this.write(`error`,...e)}warn(...e){this.write(`warn`,...e)}info(...e){this.write(`info`,...e)}debug(...e){this.write(`debug`,...e)}async close(){clearInterval(this.rotationCheckInterval),await new Promise(e=>{this.stream.end(()=>e())})}getCurrentFileName(){return this.getFileName(this.currentDate)}static getMessageElements(e,...t){let n=new Date,r=n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getMilliseconds().toString().padStart(3,`0`)}`,i=t.map(e=>typeof e==`object`?JSON.stringify(e,void 0,2):String(e)).join(` `);return{timestamp:r,level:e,message:i}}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{c(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=f(this.logPath,this.getFileName(this.currentDate));if(!s(e))try{te(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return e.toISOString().split(`T`)[0]}createStream(){let e=f(this.logPath,this.getFileName(this.currentDate));return ee(e,{flags:`a`,encoding:`utf8`})}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e,this.stream=this.createStream(),this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e=l(this.logPath),t=new Date;t.setDate(t.getDate()-7);let n=e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let n=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``),r=new Date(n);return r<t});n.forEach(e=>{try{u(f(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}write(t,...n){let{timestamp:r,message:i}=e.getMessageElements(t,...n),a=`[${r}] [${t}] ${i}\n`;this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}};const N=()=>p.join(process.env.APPDATA??``,`overlayed`),P=e=>p.join(N(),`apps`,e),F=e=>p.join(P(e),`logs`);var I=class{fileLogger;path;appId;messageQueue=new T;fileName;_debug=!1;silent=!1;constructor(e){this.fileName=e}init(e,t=!1,n=!1){this.appId=e,this._debug=t,this.silent=n,this.path=F(e),this.fileLogger=new M(this.path,this.fileName),this.messageQueue.flush().forEach(e=>{this.fileLogger?.[e.type](...e.args)})}scope(e){if(!this.appId||!this.path)throw Error(`Logger not initialized`);let t=`[${e}]`;return{scope:e=>this.scope(e),error:(...e)=>this.error(t,...e),warn:(...e)=>this.warn(t,...e),info:(...e)=>this.info(t,...e),log:(...e)=>this.log(t,...e),debug:(...e)=>this.debug(t,...e)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this._debug&&this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){this.logToConsole(e,...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}logToConsole(e,...t){let n={error:m.red,warn:m.yellow,debug:m.blue,log:m.white};if(this.silent&&!this._debug)return;let{timestamp:r,message:i}=M.getMessageElements(e,...t),a=console[e],o=n[e];a(`${m.gray(r)} ${o(i)}`)}};O(I,`overlayed.log`);const L=`**/overlayed.config.{js,ts,mts}`;async function R(){let e=B(),t=ie(import.meta.url),n=await Promise.all(e.map(async e=>{if(e.endsWith(`.ts`)){let n=await t.import(e,{default:!0});return[n,e]}else{let t=await import(_.pathToFileURL(e).toString());return[t.default,e]}}));return n.filter(([e])=>z(e)).map(([e,t])=>[e,t])}function z(e){return C(e)&&`app`in e}function B(){let e=g.globSync(L,{absolute:!0,cwd:process.cwd()});return e}var V=class{pattern;options;constructor(e,t){this.pattern=e,this.options=t}},H=class{defaultIgnore=[`overlayed.config.ts`];patterns=[];addGlobPattern(e,t){let n=this.resolveOptions(t),r=w(e);this.patterns.push(new V(r,n))}async bundle(){let e=new ae;for(let t of this.patterns){let n={...t.options},r;r=n.cwd?typeof n.cwd==`string`?n.cwd:re(n.cwd):process.cwd(),p.isAbsolute(r)||(r=p.resolve(r)),n.absolute=!0,n.cwd=r;let i=await g(t.pattern,n);await Promise.all(i.map(async t=>{let n=p.relative(r,t),i=h(t,`binary`);e.file(n,i,{compression:`DEFLATE`})}))}return e}resolveOptions(e){return{...e,ignore:[...w(e?.ignore),...this.defaultIgnore]}}},U=class extends Error{constructor(){super(`package.json not found in bundle`),this.name=`PackageJsonNotFoundError`}},de=class extends H{defaultIgnore=[`overlayed.config.ts`,`**/installer/**`];constructor(){super(),this.addGlobPattern(`package.json`)}async bundle(){let e=await super.bundle(),t=e.file(`package.json`);if(!t)throw new U;return e}};const fe=v.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});fe.interceptors.request.use(e=>e);const W=v.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let G;function K(e){G=e}W.interceptors.request.use(e=>{let t=G?.();return e.headers??={},t&&(e.headers[`X-Api-Key`]=t),e});function pe(e){return e}function q(e){return e?t=>(e(t),t):pe}q(),q();function me(e,t){return W.post(`/v1/applications/${e}/bundles/upload`,t)}function he(e,t){return W.post(`/v1/applications/${e}/bundles/queue`,{name:t})}function ge(e,t){return W.put(e,t,{headers:{"Content-Type":`application/zip`,"Content-Length":t.length}})}q();const _e=q();q();function J(){return W.get(`/v1/auth/me`)}q();const ve=d.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),ye=i({Account:a({email:`string`,apiKey:`string`})}),be=ye.type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`),Y=new j({path:ve,default:void 0,schema:be});async function X(){let e=Y.get();if(!e?.currentAccount)throw new r(`Not authenticated. Run 'overlayed login' to authenticate.`);try{let e=await J(),t=e.data.email;return t}catch(e){if(!y(e))throw e;let t=e.response?.status;switch(t){case 401:case 403:throw new r(`Authentication failed. Your API key may be invalid or expired. Run 'overlayed login' to re-authenticate.`);default:throw Error(`API error occurred. Please try again later.`)}}}async function xe(e){let t=await R();if(t.length===0)throw new r(`No config file found matching `+L);return t.length>1&&e.stdout.write(m.yellow(`
|
|
3
|
-
Multiple config files found matching ${
|
|
4
|
-
`)),t.at(0)}var
|
|
2
|
+
import{Builtins as e,Cli as t,Command as n,UsageError as r}from"clipanion";import{scope as i,type as a}from"arktype";import o,{createWriteStream as s,existsSync as ee,mkdirSync as te,readdirSync as c,unlinkSync as l,writeFileSync as u}from"fs";import{ensureDirSync as ne,ensureFileSync as re}from"fs-extra";import d,{join as f}from"path";import p from"node:path";import m from"chalk";import{createReadStream as h,existsSync as g,lstatSync as _}from"node:fs";import{glob as v}from"glob";import ie,{fileURLToPath as ae}from"node:url";import{createJiti as oe}from"jiti";import{readdir as se}from"node:fs/promises";import ce from"jszip";import y,{isXiorError as b}from"xior";import{checkbox as le,password as ue}from"@inquirer/prompts";import{Listr as x}from"listr2";import{ListrInquirerPromptAdapter as de}from"@listr2/prompt-adapter-inquirer";import{exec as S}from"child_process";import{promisify as C}from"util";const w={deployment:`deployment`};function T(e){throw e}function E(e){return Object.prototype.toString.call(e)===`[object Object]`}function D(e){return e?Array.isArray(e)?e:[e]:[]}var O=class{data=[];constructor(){}get size(){return this.data.length}add(e){this.data.push(e)}next(){return this.data.shift()}clear(){this.data.length=0}*flush(){for(;this.size>0;){let e=this.next();e&&(yield e)}}};function k(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var A=class{emitter;constructor(){this.emitter=k()}on(e,t){D(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){D(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){D(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}};function j(e,...t){let n=class extends e{static _instance;static getInstance(){return this._instance||(this._instance=new e(...t)),this._instance}static clearInstance(){this._instance=void 0}};return n}var M=class extends A{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}};const N=j(M);var P=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){let t=this.get();return t[e]}save(e){let t=this.onBeforeSave(e);try{re(this.getFilePath()),o.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return this.data=e,e}try{let e=o.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=a(`string.json.parse`).to(`object`),n=t(e);if(n instanceof a.errors)return this._defaultValue;let r=this._schema[`~standard`].validate(n);if(r instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return r.issues?this.migrate(n,this._defaultValue):this.migrate(r.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return o.accessSync(e,o.constants.R_OK|o.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return o.accessSync(e,o.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]}return n}reportInvalidConfigFile(e){N.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}},F=class e extends A{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(new Date),this.ensureLogDirectory(),this.ensureLogFile(),this.stream=this.createStream(),this.rotationCheckInterval=this.startRotationCheck(),this.cleanupOldLogs()}static scope(t,n){return new e(t,n)}log(...e){this.write(`log`,...e)}error(...e){this.write(`error`,...e)}warn(...e){this.write(`warn`,...e)}info(...e){this.write(`info`,...e)}debug(...e){this.write(`debug`,...e)}async close(){clearInterval(this.rotationCheckInterval),await new Promise(e=>{this.stream.end(()=>e())})}getCurrentFileName(){return this.getFileName(this.currentDate)}static getMessageElements(e,...t){let n=new Date,r=n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getMilliseconds().toString().padStart(3,`0`)}`,i=t.map(e=>typeof e==`object`?JSON.stringify(e,void 0,2):String(e)).join(` `);return{timestamp:r,level:e,message:i}}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{te(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=f(this.logPath,this.getFileName(this.currentDate));if(!ee(e))try{u(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return e.toISOString().split(`T`)[0]}createStream(){let e=f(this.logPath,this.getFileName(this.currentDate));return s(e,{flags:`a`,encoding:`utf8`})}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e,this.stream=this.createStream(),this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e=c(this.logPath),t=new Date;t.setDate(t.getDate()-7);let n=e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let n=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``),r=new Date(n);return r<t});n.forEach(e=>{try{l(f(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}write(t,...n){let{timestamp:r,message:i}=e.getMessageElements(t,...n),a=`[${r}] [${t}] ${i}\n`;this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}};const I=()=>p.join(process.env.APPDATA??``,`overlayed`),L=e=>p.join(I(),`apps`,e),R=e=>p.join(L(e),`logs`);var z=class{fileLogger;path;appId;messageQueue=new O;fileName;_debug=!1;silent=!1;constructor(e){this.fileName=e}init(e,t=!1,n=!1){this.appId=e,this._debug=t,this.silent=n,this.path=R(e),this.fileLogger=new F(this.path,this.fileName),this.messageQueue.flush().forEach(e=>{this.fileLogger?.[e.type](...e.args)})}scope(e){if(!this.appId||!this.path)throw Error(`Logger not initialized`);let t=`[${e}]`;return{scope:e=>this.scope(e),error:(...e)=>this.error(t,...e),warn:(...e)=>this.warn(t,...e),info:(...e)=>this.info(t,...e),log:(...e)=>this.log(t,...e),debug:(...e)=>this.debug(t,...e)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this._debug&&this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){this.logToConsole(e,...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}logToConsole(e,...t){let n={error:m.red,warn:m.yellow,debug:m.blue,log:m.white};if(this.silent&&!this._debug)return;let{timestamp:r,message:i}=F.getMessageElements(e,...t),a=console[e],o=n[e];a(`${m.gray(r)} ${o(i)}`)}};j(z,`overlayed.log`);const B=`**/overlayed.config.{js,ts,mts}`;async function V(){let e=fe(),t=oe(import.meta.url),n=await Promise.all(e.map(async e=>{if(e.endsWith(`.ts`)){let n=await t.import(e,{default:!0});return[n,e]}else{let t=await import(ie.pathToFileURL(e).toString());return[t.default,e]}}));return n.filter(([e])=>H(e)).map(([e,t])=>[e,t])}function H(e){return E(e)&&`app`in e}function fe(){let e=v.globSync(B,{absolute:!0,cwd:process.cwd()});return e}var pe=class{pattern;options;constructor(e,t){this.pattern=e,this.options=t}},U=class{defaultIgnore=[`overlayed.config.ts`];patterns=[];constructor(e){this.config=e}addGlobPattern(e,t){let n=this.resolveOptions(t),r=D(e);this.patterns.push(new pe(r,n))}async bundle(){let e=new ce;for(let t of this.patterns){let n={...t.options},r;r=n.cwd?typeof n.cwd==`string`?n.cwd:ae(n.cwd):process.cwd(),p.isAbsolute(r)||(r=p.resolve(r)),n.absolute=!0,n.cwd=r;let i=await v(t.pattern,n),a=await this.getFilesPathsFromPaths(i);await Promise.all(a.map(async t=>{this.zipFile(r,e,t)}))}return e}zipFile(e,t,n){let r=p.relative(e,n);if(r=r.replace(/^(\.\.\\|\.\.\/)+/,``),!g(n)){t.file(r,``,{compression:`DEFLATE`});return}let i=h(n,`binary`);t.file(r,i,{compression:`DEFLATE`})}resolveOptions(e){return{...e,ignore:[...D(e?.ignore),...this.defaultIgnore]}}async getFilesPathsFromPaths(e){return Promise.all(e.map(async e=>await this.getFilePathsFromPathRecursive(e))).then(e=>e.flat())}async getFilePathsFromPathRecursive(e){if(!g(e)||!_(e).isDirectory())return[e];let t=await se(e,{withFileTypes:!0}),n=await Promise.all(t.map(async t=>{let n=p.join(e,t.name);return t.isDirectory()?await this.getFilePathsFromPathRecursive(n):[n]}));return n.flat()}},me=class extends Error{constructor(){super(`package.json not found in bundle`),this.name=`PackageJsonNotFoundError`}},he=class extends U{defaultIgnore=[`overlayed.config.ts`,`**/installer/**`];constructor(e){super(e),this.addGlobPattern(`package.json`)}async bundle(){let e=await super.bundle(),t=e.file(`package.json`);if(!t)throw new me;return e}};const ge=y.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});ge.interceptors.request.use(e=>e);const W=y.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let G;function K(e){G=e}W.interceptors.request.use(e=>{let t=G?.();return e.headers??={},t&&(e.headers[`X-Api-Key`]=t),e});function _e(e){return e}function q(e){return e?t=>(e(t),t):_e}q(),q();function ve(e,t){return W.post(`/v1/applications/${e}/bundles/upload`,t)}function ye(e,t){return W.post(`/v1/applications/${e}/bundles/queue`,{name:t})}function be(e,t){return W.put(e,t,{headers:{"Content-Type":`application/zip`,"Content-Length":t.length}})}q();const xe=q();q();function J(){return W.get(`/v1/auth/me`)}q();const Se=d.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),Ce=i({Account:a({email:`string`,apiKey:`string`})}),we=Ce.type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`),Y=new P({path:Se,default:void 0,schema:we});async function X(){let e=Y.get();if(!e?.currentAccount)throw new r(`Not authenticated. Run 'overlayed login' to authenticate.`);try{let e=await J(),t=e.data.email;return t}catch(e){if(!b(e))throw e;let t=e.response?.status;switch(t){case 401:case 403:throw new r(`Authentication failed. Your API key may be invalid or expired. Run 'overlayed login' to re-authenticate.`);default:throw Error(`API error occurred. Please try again later.`)}}}async function Te(e){let t=await V();if(t.length===0)throw new r(`No config file found matching `+B);return t.length>1&&e.stdout.write(m.yellow(`
|
|
3
|
+
Multiple config files found matching ${B}, using the first one.
|
|
4
|
+
`)),t.at(0)}var Ee=class extends n{static paths=[[`bundle`]];static usage=n.Usage({category:w.deployment,description:`Bundle the app and site for deployment.`,details:`
|
|
5
5
|
Bundle the app and site for deployment.
|
|
6
6
|
|
|
7
7
|
[Docs](http://docs.overlayed.gg/cli/bundle)
|
|
8
|
-
`,examples:[[`Basic usage`,`$0 bundle`]]});async execute(){await X();let e=new
|
|
8
|
+
`,examples:[[`Basic usage`,`$0 bundle`]]});async execute(){await X();let e=new x([{title:`Authenticating`,task:X},{title:`Locating overlayed.config.ts`,task:async e=>e.config=await this.resolveConfig()},{task:async(e,t)=>{let n=await t.prompt(de).run(...this.getTargetBundles(e.config));e.targetBundles=n,this.context.stdout.write(m.green(`Selected bundles: `)+m.bold(n.join(`, `)))}}]),t=await e.run(),n=new x([{title:`Uploading bundles`,task:e=>new x(e.targetBundles.map((e,t)=>({title:`Uploading ${e} bundle`,task:async n=>{n.taskIds??=[];let r=await this.uploadBundle(n.config,e);r&&(n.taskIds[t]=r)}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})},{title:`Waiting for bundles to be processed`,task:e=>new x(e.taskIds.map((t,n)=>({title:`Waiting for ${m.bold(e.targetBundles[n])} bundle to be processed. This may take some time - you can wait for the bundle to appear in the dashboard here: ${m.blue(`https://dashboard.overlayed.gg/applications/${e.config.applicationId}/bundles?taskId=${t}`)}`,task:async()=>{await new Promise(e=>setTimeout(e,3e3))}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})}]);await n.run(t)}async uploadBundle(e,t){let n=await ve(e.applicationId,{type:t}),r=await e[t]?.bundle()??T(Error(`No bundle found for `+t));e.debug&&r.forEach(e=>{console.log(`Zipping: `,e)});let i=await r.generateAsync({type:`nodebuffer`});if(e.debug){let e=`.overlayed/tmp`;ne(e),u(`${e}/debug-${t}.zip`,i);return}await be(n.data.upload_url,i);let a=await ye(e.applicationId,n.data.asset_bundle_name);return a.data.task_id}getTargetBundles(e){let t=e=>`(Disabled: No config found for "${e}" in overlayed.config.ts)`;return[le,{message:`Select your desired bundles to create and upload.`,shortcuts:{all:`a`,invert:`i`},choices:[{name:`App`,value:`app`,disabled:e.app?void 0:t(`app`)},{name:`Site`,value:`site`,disabled:e.site?void 0:t(`site`)}]}]}async resolveConfig(){let[e,t]=await Te(this.context);return{...e,applicationId:xe(e.applicationId),app:this.getAppBundler(e,t),site:this.getSiteBundler(e,t)}}getAppBundler(e,t){let n=new he(e);return n.addGlobPattern(e.app.include,{ignore:e.app.exclude,cwd:d.dirname(t)}),n}getSiteBundler(e,t){if(!e.site)return;let n=new U(e);return n.addGlobPattern(e.site.include,{ignore:e.site.exclude,cwd:d.dirname(t)}),n}async catch(e){if(b(e)){let t=e.response?.status,n=(e.config?.baseURL??``)+(e.config?.url??``);throw Error(`Request to ${n} failed with status ${t}. ${e.response?.data}`)}throw e}};function De(e){return`https://dashboard.overlayed.gg${e}`}const Z={normal:Oe,success:Q,error:ke,warning:Ae,info:je};function Oe(...e){return m.gray(e,`
|
|
9
9
|
`)}function Q(...e){return[m.green(`✔`),...e,`
|
|
10
|
-
`].join(` `)}function
|
|
11
|
-
`].join(` `)}function
|
|
12
|
-
`].join(` `)}function
|
|
13
|
-
`].join(` `)}const
|
|
10
|
+
`].join(` `)}function ke(...e){return[m.red(`✘`),...e,`
|
|
11
|
+
`].join(` `)}function Ae(...e){return[m.yellow(`⚠`),...e,`
|
|
12
|
+
`].join(` `)}function je(...e){return[m.blue(`ℹ`),...e,`
|
|
13
|
+
`].join(` `)}const Me=C(S);var Ne=class extends n{static paths=[[`login`]];static usage=n.Usage({description:`Authenticate with the Overlayed platform.`,details:`
|
|
14
14
|
Authenticate with the Overlayed platform.
|
|
15
|
-
`,examples:[[`Basic usage`,`$0 login`]]});async execute(){let e=
|
|
15
|
+
`,examples:[[`Basic usage`,`$0 login`]]});async execute(){let e=De(`/settings/api-keys`);await this.openUrl(e);let t=await ue({message:`To authenticate, you'll need an API Key. We've opened the page to create one in your browser.\n\n${Z.info(e)}\n\nOnce you have it, enter it here:`,async validate(e){K(()=>e);try{let t=await J(),n=t.data.email,r={email:n,apiKey:e},i=Y.get();Y.set({...i,currentAccount:r,accounts:i?.accounts.concat(r)??[r]})}catch(e){if(!b(e))return`Unknown error has occurred: ${e}`;let t=e.response?.status;switch(t){case 401:case 403:return`Invalid API key, please try again.`;default:return`API error, please try again later.`}}return K(()=>Y.get()?.currentAccount?.apiKey),!0}});if(!t)throw Error(`Login unknown error - this should never happen`);let n=Y.get();if(!n?.currentAccount)throw Error(`Could not get config after login`);let r=n.currentAccount.email;this.context.stdout.write(Z.success(`Authentication Complete - Logged in as ${r}`))}async openUrl(e){let t=process.platform,n;switch(t){case`darwin`:n=`open "${e}"`;break;case`win32`:n=`start "" "${e}"`;break;default:n=`xdg-open "${e}"`;break}try{await Me(n)}catch{}}},Pe=class extends n{static paths=[[`logout`]];static usage=n.Usage({description:`Log out of the currently authenticated account.`,details:`
|
|
16
16
|
Log out of the currently authenticated account.
|
|
17
|
-
`,examples:[[`Basic usage`,`$0 logout`]]});async execute(){let e=await X(),t=Y.get();if(!t){this.context.stdout.write(Z.normal(`Not currently logged in.`));return}let n=t.accounts.filter(t=>t.email!==e);Y.set({...t,currentAccount:void 0,accounts:n}),this.context.stdout.write(Z.normal(`Logged out from ${e}`))}},
|
|
17
|
+
`,examples:[[`Basic usage`,`$0 logout`]]});async execute(){let e=await X(),t=Y.get();if(!t){this.context.stdout.write(Z.normal(`Not currently logged in.`));return}let n=t.accounts.filter(t=>t.email!==e);Y.set({...t,currentAccount:void 0,accounts:n}),this.context.stdout.write(Z.normal(`Logged out from ${e}`))}},Fe=class extends n{static paths=[[`whoami`]];static usage=n.Usage({description:`Display information about the currently authenticated user.`,details:`
|
|
18
18
|
Display information about the currently authenticated user.
|
|
19
19
|
|
|
20
20
|
[Docs](http://docs.overlayed.gg/cli/whoami)
|
|
21
|
-
`,examples:[[`Basic usage`,`$0 whoami`]]});async execute(){let e=await X();this.context.stdout.write(Z.normal(`Logged in as ${e}`))}};const
|
|
21
|
+
`,examples:[[`Basic usage`,`$0 whoami`]]});async execute(){let e=await X();this.context.stdout.write(Z.normal(`Logged in as ${e}`))}};const Ie=process.argv.slice(2),$=new t({binaryName:`overlayed`,binaryLabel:`Overlayed`});[Ee,Ne,Pe,Fe,e.HelpCommand].forEach(e=>{$.register(e)}),K(()=>Y.get()?.currentAccount?.apiKey),$.runExit(Ie);export{};
|