@capgo/cli 3.2.0 → 3.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/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [3.4.0](https://github.com/Cap-go/capgo-cli/compare/v3.3.0...v3.4.0) (2023-03-01)
6
+
7
+
8
+ ### Features
9
+
10
+ * allow end-to-end in init ([5b2bae3](https://github.com/Cap-go/capgo-cli/commit/5b2bae3173b7f06862562871f7d9c39fe38304fe))
11
+
12
+ ## [3.3.0](https://github.com/Cap-go/capgo-cli/compare/v3.2.0...v3.3.0) (2023-03-01)
13
+
14
+
15
+ ### Features
16
+
17
+ * add unlink command and prompts ([a178363](https://github.com/Cap-go/capgo-cli/commit/a178363e8f651e024346b857e9d4693791c5738f))
18
+
5
19
  ## [3.2.0](https://github.com/Cap-go/capgo-cli/compare/v3.1.0...v3.2.0) (2023-02-28)
6
20
 
7
21
 
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- (()=>{"use strict";var e={642:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.newIconPath=o.checkAppExistsAndHasPermissionErr=o.checkAppExistsAndHasPermission=void 0;const i=n(304);o.checkAppExistsAndHasPermission=(e,o,n,i=!0)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.rpc("exist_app",{appid:o,apikey:n}).single();return t!==i||a})),o.checkAppExistsAndHasPermissionErr=(e,n,a,r=!0)=>t(void 0,void 0,void 0,(function*(){(yield(0,o.checkAppExistsAndHasPermission)(e,n,a,r))&&i.program.error(`App ${n} does not exist or you don't have permission to access it`)})),o.newIconPath="assets/icon.png"},860:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.getActiveChannels=o.displayChannels=o.delChannel=o.createChannel=o.findUnknownVersion=o.checkVersionNotUsedInChannel=void 0;const i=n(304),a=n(847),r=n(246);o.checkVersionNotUsedInChannel=(e,o,n,a)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:s}=yield e.from("channels").select().eq("app_id",o).eq("created_by",n).eq("version",a.id);if(s&&i.program.error(`Cannot check Version ${o}@${a.name} ${(0,r.formatError)(s)}`),t&&t.length>0){const e=(0,r.convertAppName)(o);i.program.error(`❌ Version ${o}@${a.name} is used in channel ${t[0].name}, unlink it first:\nhttps://web.capgo.app/app/p/${e}/channel/${t[0].id}\nClick on top right button and unlink.\n${(0,r.formatError)(s)}`)}})),o.findUnknownVersion=(e,o)=>e.from("app_versions").select("id").eq("app_id",o).eq("name","unknown").throwOnError().single().then((({data:e})=>e)),o.createChannel=(e,o)=>e.from("channels").insert(o).select().single(),o.delChannel=(e,o,n,t)=>e.from("channels").delete().eq("name",o).eq("app_id",n).eq("created_by",t).single(),o.displayChannels=e=>{const o=new a.Table({title:"Channels",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,Created:(0,r.getHumanDate)(e.created_at),Public:e.public?"✅":"❌"})})),o.printTable()},o.getActiveChannels=(e,o,n)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.from("channels").select().eq("app_id",o).eq("created_by",n).order("created_at",{ascending:!1});return a&&i.program.error(`App ${o} not found in database ${(0,r.formatError)(a)} `),t}))},213:(e,o,n)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createRSA=o.encryptSource=o.decryptSource=void 0;const t=n(113),i="aes-128-cbc",a="sha256",r="base64",s=t.constants.RSA_PKCS1_OAEP_PADDING;o.decryptSource=(e,o,n)=>{const[c,p]=o.split(":"),l=(0,t.privateDecrypt)({key:n,padding:s,oaepHash:a},Buffer.from(p,r)),d=Buffer.from(c,r),u=l.toString(r);console.log("\nSessionB64",u);const y=(0,t.createDecipheriv)(i,l,d);return y.setAutoPadding(!0),Buffer.concat([y.update(e),y.final()])},o.encryptSource=(e,o)=>{const n=(0,t.randomBytes)(16),c=(0,t.randomBytes)(16),p=(0,t.createCipheriv)(i,c,n);p.setAutoPadding(!0);const l=`${n.toString(r)}:${(0,t.publicEncrypt)({key:o,padding:s,oaepHash:a},c).toString(r)}`;return{encryptedData:Buffer.concat([p.update(e),p.final()]),ivSessionKey:l}},o.createRSA=()=>{const{publicKey:e,privateKey:o}=(0,t.generateKeyPairSync)("rsa",{modulusLength:2048});return{publicKey:e.export({type:"pkcs1",format:"pem"}),privateKey:o.export({type:"pkcs1",format:"pem"})}}},933:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.checkVersionNotUsedInDeviceOverride=void 0;const i=n(304),a=n(246);o.checkVersionNotUsedInDeviceOverride=(e,o,n)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:r}=yield e.from("devices_override").select().eq("app_id",o).eq("version",n.id);if(r&&i.program.error(`Cannot check Device override ${o}@${n.name} ${(0,a.formatError)(r)}`),t&&t.length>0){const e=(0,a.convertAppName)(o);i.program.error(`❌ Version ${o} @${n.name} is used in a device override, unlink it first:\nhttps://web.capgo.app/app/p/${e}/d/${t[0].device_id}\n${(0,a.formatError)(r)}`)}}))},350:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteFromStorage=void 0;const i=n(304),a=n(246);o.deleteFromStorage=(e,o,n,r,s)=>t(void 0,void 0,void 0,(function*(){const{error:t}=yield e.storage.from("apps").remove([`${o}/${n}/versions/${r.bucket_id} `]);t&&i.program.error(`Something went wrong when trying to delete ${n} @${s} ${(0,a.formatError)(t)} `)}))},484:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkLatest=void 0;const a=i(n(362)),r=i(n(598));o.checkLatest=()=>t(void 0,void 0,void 0,(function*(){const e=yield(0,a.default)("@capgo/cli");e!==r.default.version&&console.log("%s",`🚨 You are using @capgo/cli@${r.default.version} it's not the latest version.\nPlease use @capgo/cli@${e}" or @capgo/cli@latest to keep up to date with the latest features and bug fixes.`)}))},89:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.getVersionData=o.getActiveAppVersions=o.displayBundles=o.deleteSpecificVersion=o.deleteAppVersion=void 0;const i=n(304),a=n(847),r=n(246),s=n(860),c=n(933),p=n(350);o.deleteAppVersion=(e,o,n,a)=>t(void 0,void 0,void 0,(function*(){const{error:t}=yield e.from("app_versions").update({deleted:!0}).eq("app_id",o).eq("deleted",!1).eq("user_id",n).eq("name",a);t&&i.program.error(`App Version ${o}@${a} not found in database '${(0,r.formatError)(t)}'`)})),o.deleteSpecificVersion=(e,n,i,a)=>t(void 0,void 0,void 0,(function*(){const t=yield(0,o.getVersionData)(e,n,i,a);yield(0,s.checkVersionNotUsedInChannel)(e,n,i,t),yield(0,c.checkVersionNotUsedInDeviceOverride)(e,n,t),yield(0,p.deleteFromStorage)(e,i,n,t,a),yield(0,o.deleteAppVersion)(e,n,i,a)})),o.displayBundles=e=>{const o=new a.Table({title:"Bundles",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow(Object.assign({Version:e.name,Created:(0,r.getHumanDate)(e.created_at)},null!=e.keep?{Keep:e.keep}:{}))})),o.printTable()},o.getActiveAppVersions=(e,o,n)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("deleted",!1).order("created_at",{ascending:!1});return a&&i.program.error(`App ${o} not found in database ${(0,r.formatError)(a)} `),t})),o.getVersionData=(e,o,n,a)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:s}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("name",a).eq("deleted",!1).single();return t&&!s||i.program.error(`App Version ${o}@${a} doesn't exist ${(0,r.formatError)(s)}`),t}))},124:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addCommand=o.addApp=void 0;const i=n(11),a=n(304),r=n(113),s=n(470),c=n(484),p=n(642),l=n(246);o.addApp=(e,o,n=!0)=>t(void 0,void 0,void 0,(function*(){var t,d,u;yield(0,c.checkLatest)(),o.apikey=o.apikey||(0,l.findSavedKey)();const y=yield(0,l.getConfig)();e=e||(null===(t=null==y?void 0:y.app)||void 0===t?void 0:t.appId);const g=(0,l.useLogSnag)();o.apikey||a.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||a.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const v=(0,l.createSupabaseClient)(o.apikey),f=yield(0,l.verifyUser)(v,o.apikey,["write","all"]);if(n)yield(0,p.checkAppExistsAndHasPermissionErr)(v,e,o.apikey,!1);else if(yield(0,p.checkAppExistsAndHasPermission)(v,e,o.apikey,!1))return!1;let h,m,{name:k,icon:b}=o;e=e||(null===(d=null==y?void 0:y.app)||void 0===d?void 0:d.appId),k=k||(null===(u=null==y?void 0:y.app)||void 0===u?void 0:u.appName)||"Unknown",b=b||"resources/icon.png",b&&k||a.program.error("Missing argument, you need to provide a appId and a name, or be in a capacitor project"),console.log(`Adding ${e} to Capgo`),b&&(0,s.existsSync)(b)?(h=(0,s.readFileSync)(b),m=(0,i.getType)(b)||"image/png",console.warn(`Found app icon ${b}`)):(0,s.existsSync)(p.newIconPath)?(h=(0,s.readFileSync)(p.newIconPath),m=(0,i.getType)(p.newIconPath)||"image/png",console.warn(`Found app icon ${p.newIconPath}`)):console.warn(`Cannot find app icon in any of the following locations: ${b}, ${p.newIconPath}`);const{data:w,error:_}=yield v.rpc("exist_app_v2",{appid:e}).single();(w||_)&&a.program.error(`App ${e} already exists ${(0,l.formatError)(_)}`);const x=`icon_${(0,r.randomUUID)()}`;let C="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(h&&m){const{error:o}=yield v.storage.from(`images/${f}/${e}`).upload(x,h,{contentType:m});o&&a.program.error(`Could not add app ${(0,l.formatError)(o)}`);const{data:n}=yield v.storage.from(`images/${f}/${e}`).getPublicUrl(x);C=(null==n?void 0:n.publicUrl)||C}const{error:$}=yield v.from("apps").insert({icon_url:C,user_id:f,name:k,app_id:e});$&&a.program.error(`Could not add app ${(0,l.formatError)($)}`);const{error:A}=yield v.from("app_versions").insert([{user_id:f,deleted:!0,name:"unknown",app_id:e},{user_id:f,deleted:!0,name:"builtin",app_id:e}]);return A&&a.program.error(`Could not add app ${(0,l.formatError)(A)}`),yield g.publish({channel:"app",event:"App Added",icon:"🎉",tags:{"user-id":f,"app-id":e},notify:!1}).catch(),console.log("App added to server, you can upload a bundle now"),n&&(console.log("Done ✅"),process.exit()),!0})),o.addCommand=(e,n)=>t(void 0,void 0,void 0,(function*(){(0,o.addApp)(e,n,!0)}))},10:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteApp=void 0;const i=n(304),a=n(642),r=n(246);o.deleteApp=(e,o)=>t(void 0,void 0,void 0,(function*(){var n;o.apikey=o.apikey||(0,r.findSavedKey)();const t=yield(0,r.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId);const s=(0,r.useLogSnag)();o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const c=(0,r.createSupabaseClient)(o.apikey),p=yield(0,r.verifyUser)(c,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(c,e,o.apikey);const{error:l}=yield c.storage.from(`images/${p}`).remove([e]);l&&i.program.error(`Could not add app ${(0,r.formatError)(l)}`);const{error:d}=yield c.storage.from(`apps/${e}/${p}`).remove(["versions"]);d&&i.program.error(`Could not delete app version ${(0,r.formatError)(d)}`);const{error:u}=yield c.from("apps").delete().eq("app_id",e).eq("user_id",p);u&&i.program.error(`Could not delete app ${(0,r.formatError)(u)}`),yield s.publish({channel:"app",event:"App Deleted",icon:"🗑️",tags:{"user-id":p,"app-id":e},notify:!1}).catch(),console.log("App deleted in Capgo"),console.log("Done ✅"),process.exit()}))},90:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.getInfo=void 0;const a=n(147),r=i(n(362)),s=n(17),c=i(n(176)),p=i(n(598));o.getInfo=()=>t(void 0,void 0,void 0,(function*(){console.log(" 💊 Capgo Doctor 💊"),console.log("\n"),console.log(" Installed Dependencies:"),console.log("\n");const e=yield t(void 0,void 0,void 0,(function*(){const{dependencies:e}=yield t(void 0,void 0,void 0,(function*(){const e=(0,a.readFileSync)((0,s.join)(process.cwd(),"package.json"));return JSON.parse(e)})),o={"@capgo/cli":p.default.version};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith("@capgo/")&&(o[n]=e[n]);return o}));0===Object.keys(e).length&&(console.log("\n"),console.log("%s","🚨 No dependencies found"),process.exit(1));for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o)){const n=e[o];console.log(` ${o}: ${n}`)}console.log("\n");const o=new c.default;o.add("loading",{text:"Loading latest dependencies"});const n=yield(e=>t(void 0,void 0,void 0,(function*(){const o={},n=[];for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&n.push((0,r.default)(o));return yield Promise.all(n).then((n=>{const t=Object.keys(e);for(let e=0;e<n.length;e+=1){const i=n[e];i&&(o[t[e]]=i)}})),o})))(e);o.succeed("loading",{text:"Latest Dependencies:"}),console.log("\n");for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){const o=n[e];console.log(` ${e}: ${o}`)}JSON.stringify(e)!==JSON.stringify(n)&&(console.log("\n"),console.log("%s","🚨 Some dependencies are not up to date"),process.exit(1)),console.log("\n"),console.log("%s","✅ All dependencies are up to date"),process.exit()}))},367:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listApp=o.getActiveApps=void 0;const i=n(304),a=n(847),r=n(642),s=n(246),c=n(484);o.getActiveApps=(e,o)=>t(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("apps").select().eq("user_id",o).order("created_at",{ascending:!1});return t&&i.program.error(`Apps not found in database ${(0,s.formatError)(t)} `),n})),o.listApp=(e,n)=>t(void 0,void 0,void 0,(function*(){var t;yield(0,c.checkLatest)(),n.apikey=n.apikey||(0,s.findSavedKey)();const p=yield(0,s.getConfig)();e=e||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId),n.apikey||i.program.error("Missing API key, you need to provide an API key to delete your app"),e||i.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const l=(0,s.createSupabaseClient)(n.apikey),d=yield(0,s.verifyUser)(l,n.apikey);console.log("Querying available versions in Capgo"),yield(0,r.checkAppExistsAndHasPermissionErr)(l,e,n.apikey);const u=yield(0,o.getActiveApps)(l,d);console.log(`Active app in Capgo: ${null==u?void 0:u.length}`),(e=>{const o=new a.Table({title:"Apps",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,Created:(0,s.getHumanDate)(e.created_at)})})),o.printTable()})(u),console.log("Done ✅"),process.exit()}))},444:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setApp=void 0;const i=n(11),a=n(304),r=n(113),s=n(470),c=n(642),p=n(246);o.setApp=(e,o)=>t(void 0,void 0,void 0,(function*(){var n;o.apikey=o.apikey||(0,p.findSavedKey)();const t=yield(0,p.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId),o.apikey||a.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||a.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,p.createSupabaseClient)(o.apikey),d=yield(0,p.verifyUser)(l,o.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(l,e,o.apikey);const{name:u,icon:y}=o;let g,v;const f=`icon_${(0,r.randomUUID)()}`;let h="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(y&&(0,s.existsSync)(y)?(g=(0,s.readFileSync)(y),v=(0,i.getType)(y)||"image/png",console.warn(`Found app icon ${y}`)):(0,s.existsSync)(c.newIconPath)?(g=(0,s.readFileSync)(c.newIconPath),v=(0,i.getType)(c.newIconPath)||"image/png",console.warn(`Found app icon ${c.newIconPath}`)):console.warn(`Cannot find app icon in any of the following locations: ${y}, ${c.newIconPath}`),g&&v){const{error:o}=yield l.storage.from(`images/${d}/${e}`).upload(f,g,{contentType:v});o&&a.program.error(`Could not add app ${(0,p.formatError)(o)}`);const{data:n}=yield l.storage.from(`images/${d}/${e}`).getPublicUrl(f);h=(null==n?void 0:n.publicUrl)||h}const{error:m}=yield l.from("apps").update({icon_url:h,name:u}).eq("app_id",e).eq("user_id",d);m&&a.program.error(`Could not add app ${(0,p.formatError)(m)}`),console.log("Done ✅"),process.exit()}))},957:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))},i=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),o={},t("next"),t("throw"),t("return"),o[Symbol.asyncIterator]=function(){return this},o);function t(n){o[n]=e[n]&&function(o){return new Promise((function(t,i){!function(e,o,n,t){Promise.resolve(t).then((function(o){e({value:o,done:n})}),o)}(t,i,(o=e[n](o)).done,o.value)}))}}},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.cleanupBundle=void 0;const r=n(304),s=a(n(505)),c=a(n(616)),p=n(246),l=n(89),d=n(642),u=n(484),y=(0,c.default)();o.cleanupBundle=(e,o)=>t(void 0,void 0,void 0,(function*(){var n;yield(0,u.checkLatest)();const a=o.apikey||(0,p.findSavedKey)(),{bundle:c,keep:g=4}=o,v=o.force||!1,f=yield(0,p.getConfig)();e=e||(null===(n=null==f?void 0:f.app)||void 0===n?void 0:n.appId),a||r.program.error("Missing API key, you need to provide an API key to delete your app"),e||r.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const h=(0,p.createSupabaseClient)(a),m=yield(0,p.verifyUser)(h,a);yield(0,d.checkAppExistsAndHasPermissionErr)(h,e,a),console.log("Querying all available versions in Capgo");let k=yield(0,l.getActiveAppVersions)(h,e,m);if(console.log(`Total active versions in Capgo: ${null==k?void 0:k.length}`),0===(null==k?void 0:k.length))return void console.log("No versions found, aborting cleanup");if(c){const e=`${s.default.inc(c,"major")}`;console.log(`Querying available versions in Capgo between ${c} and ${e}`),k=((e,o,n)=>{const t=[];return null==e||e.forEach((e=>{s.default.gte(e.name,o)&&s.default.lt(e.name,`${n}`)&&t.push(e)})),t})(k,c,e),console.log(`Active versions in Capgo between ${c} and ${e}: ${null==k?void 0:k.length}`)}const b=[];if(k.forEach(((e,o)=>{o<g?e.keep="✅":(e.keep="❌",b.push(e))})),0!==b.length){if((0,l.displayBundles)(k),!v&&"yes"!==y("Do you want to continue removing the versions specified? Type yes to confirm: "))return void console.log("Not confirmed, aborting removal...");console.log("You have confirmed removal, removing versions now"),yield((e,o,n,a)=>{var r,s,c;return t(void 0,void 0,void 0,(function*(){var t,d,u,y;try{for(r=!0,s=i(e);!(t=(c=yield s.next()).done);){y=c.value,r=!1;try{const e=y;console.log(`Removing ${e.name} created on ${(0,p.getHumanDate)(e.created_at)}`),yield(0,l.deleteSpecificVersion)(o,n,a,e.name)}finally{r=!0}}}catch(e){d={error:e}}finally{try{r||t||!(u=s.return)||(yield u.call(s))}finally{if(d)throw d.error}}}))})(b,h,e,m),console.log("Done ✅"),process.exit()}else console.log("Nothing to be removed, aborting removal...")}))},628:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.decryptZip=void 0;const i=n(304),a=n(147),r=n(213),s=n(246),c=n(484);o.decryptZip=(e,o,n)=>t(void 0,void 0,void 0,(function*(){var t,p,l;yield(0,c.checkLatest)(),(0,a.existsSync)(e)||i.program.error(`Zip not found at the path ${e}`);const d=yield(0,s.getConfig)(),{extConfig:u}=d.app;n.key||(0,a.existsSync)(s.baseKey)||(null===(p=null===(t=u.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===p?void 0:p.privateKey)||i.program.error(`Private Key not found at the path ${s.baseKey} or in ${d.app.extConfigFilePath}`);const y=n.key||s.baseKey;let{privateKey:g}=n.keyData||(null===(l=null==u?void 0:u.plugins)||void 0===l?void 0:l.CapacitorUpdater)||"";(0,a.existsSync)(y)||g?(0,a.existsSync)(y)&&(g=(0,a.readFileSync)(y).toString()):i.program.error(`Cannot find public key ${y} or as keyData option or in ${d.app.extConfigFilePath}`);const v=(0,a.readFileSync)(e),f=(0,r.decryptSource)(v,o,g);(0,a.writeFileSync)(`${e}_decrypted.zip`,f),console.log("Done ✅"),process.exit()}))},6:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteBundle=void 0;const i=n(304),a=n(642),r=n(246),s=n(89);o.deleteBundle=(e,o,n)=>t(void 0,void 0,void 0,(function*(){var t,c;n.apikey=n.apikey||(0,r.findSavedKey)();const p=yield(0,r.getConfig)();e=e||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId),n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,r.createSupabaseClient)(n.apikey),d=yield(0,r.verifyUser)(l,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(l,e,n.apikey);const u=n.apikey||(0,r.findSavedKey)();e=e||(null===(c=null==p?void 0:p.app)||void 0===c?void 0:c.appId),u||i.program.error("Missing API key, you need to provide an API key to delete your app"),o||i.program.error("Missing argument, you need to provide a bundleId, or be in a capacitor project"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project"),console.log(`Delete ${e}@${o} from Capgo`),yield(0,s.deleteSpecificVersion)(l,e,d,o),console.log(`${e}@${o} deleted from server`),console.log("Done ✅"),process.exit()}))},278:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.encryptZip=void 0;const i=n(304),a=n(147),r=n(484),s=n(213),c=n(246);o.encryptZip=(e,o)=>t(void 0,void 0,void 0,(function*(){yield(0,r.checkLatest)(),(0,a.existsSync)(e)||i.program.error(`Zip not found at the path ${e}`);const n=o.key||c.baseKeyPub;let t=o.keyData||"";(0,a.existsSync)(n)||t?(0,a.existsSync)(n)&&(t=(0,a.readFileSync)(n).toString()):i.program.error(`Cannot find public key ${n} or as keyData option`);const p=(0,a.readFileSync)(e),l=(0,s.encryptSource)(p,t);console.log("ivSessionKey",l.ivSessionKey),(0,a.writeFileSync)(`${e}_encrypted.zip`,l.encryptedData),console.log("Done ✅"),process.exit()}))},135:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listBundle=void 0;const i=n(304),a=n(642),r=n(89),s=n(246),c=n(484);o.listBundle=(e,o)=>t(void 0,void 0,void 0,(function*(){var n;yield(0,c.checkLatest)(),o.apikey=o.apikey||(0,s.findSavedKey)();const t=yield(0,s.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId),o.apikey||i.program.error("Missing API key, you need to provide an API key to delete your app"),e||i.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const p=(0,s.createSupabaseClient)(o.apikey),l=yield(0,s.verifyUser)(p,o.apikey);console.log("Querying available versions in Capgo"),yield(0,a.checkAppExistsAndHasPermissionErr)(p,e,o.apikey);const d=yield(0,r.getActiveAppVersions)(p,e,l);console.log(`Active versions in Capgo: ${null==d?void 0:d.length}`),(0,r.displayBundles)(d),console.log("Done ✅"),process.exit()}))},883:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.uploadCommand=o.uploadBundle=void 0;const a=i(n(844)),r=n(304),s=n(113),c=i(n(295)),p=n(147),l=n(906),d=n(484),u=n(642),y=n(213),g=n(246);o.uploadBundle=(e,o,n=!0)=>t(void 0,void 0,void 0,(function*(){var t,i,v,f;yield(0,d.checkLatest)();let{bundle:h,path:m,channel:k}=o;const{external:b,key:w=!1,displayIvSession:_}=o,x=o.apikey||(0,g.findSavedKey)(),C=(0,g.useLogSnag)();k=k||"dev";const $=yield(0,g.getConfig)();e=e||(null===(t=null==$?void 0:$.app)||void 0===t?void 0:t.appId);const A=(0,s.randomUUID)().split("-")[0];h=h||(null===(v=null===(i=null==$?void 0:$.app)||void 0===i?void 0:i.package)||void 0===v?void 0:v.version)||`0.0.1-beta.${A}`,g.regexSemver.test(h)||r.program.error(`Your bundle name ${h}, is not valid it should follow semver convention : https://semver.org/`),m=m||(null===(f=null==$?void 0:$.app)||void 0===f?void 0:f.webDir),x||r.program.error("Missing API key, you need to provide a API key to upload your bundle"),e&&h&&m||r.program.error("Missing argument, you need to provide a appid and a bundle and a path, or be in a capacitor project"),console.log(`Upload ${e}@${h} started from path "${m}" to Capgo cloud`);const S=(0,g.createSupabaseClient)(x),P=yield(0,g.verifyUser)(S,x,["write","all","upload"]);yield(0,g.checkPlanValid)(S,P,!1),yield(0,u.checkAppExistsAndHasPermissionErr)(S,e,x);const I=new c.default.MultiBar({clearOnComplete:!1,hideCursor:!0},c.default.Presets.shades_grey),D=I.create(7,0,{format:"Uploading: [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} Part"},c.default.Presets.shades_grey);D.start(7,0,{speed:"N/A"});const{data:E,error:j}=yield S.rpc("exist_app_versions",{apikey:x,name_version:h,appid:e}).single();(E||j)&&(I.stop(),r.program.error(`This app bundle already exist or was deleted, you cannot re-upload it ${(0,g.formatError)(j)}`)),D.increment();const{data:M,error:U}=yield S.rpc("is_trial",{userid:P}).single();(M&&M>0||U)&&I.log(`WARNING !!\nTrial expires in ${M} days, upgrade here: ${g.hostWeb}/dashboard/settings/plans\n`),D.increment();const{data:q,error:K}=yield S.rpc("exist_app",{appid:e,apikey:x}).single();q&&!K||(I.stop(),r.program.error(`Cannot find app ${e} in your account \n${(0,g.formatError)(K)}`)),D.increment();const{data:O,error:F}=yield S.rpc("exist_app_versions",{appid:e,apikey:x,name_version:h}).single();(O||F)&&r.program.error(`Version already exists ${(0,g.formatError)(F)}`),D.increment();const N=(0,s.randomUUID)();let T,V="";if(b)b&&!b.startsWith("https://")&&(I.stop(),r.program.error(`External link should should start with "https://" current is "${b}"`));else{const o=new a.default;o.addLocalFolder(m);let n=o.toBuffer();if(V=yield(0,l.checksum)(n,"crc32"),w||(0,p.existsSync)(g.baseKeyPub)){const e="string"==typeof w?w:g.baseKeyPub;(0,p.existsSync)(e)||r.program.error(`Cannot find public key ${e}`);const o=(0,p.readFileSync)(e);I.log("Encrypting your bundle\n");const t=(0,y.encryptSource)(n,o.toString());T=t.ivSessionKey,_&&I.log(`Your Iv Session key is ${T},\nkeep it safe, you will need it to decrypt your bundle.\nIt will be also visible in your dashboard\n`),n=t.encryptedData}const t=Math.floor(n.byteLength/1024/1024),i=`apps/${P}/${e}/versions`;D.increment(),t>20&&(I.log(`WARNING !!\nThe app size is ${t} Mb, this may take a while to download for users\n`),I.log("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield C.publish({channel:"app-error",event:"App Too Large",icon:"🚛",tags:{"user-id":P,"app-id":e},notify:!1}).catch());const{error:s}=yield S.storage.from(i).upload(N,n,{contentType:"application/zip",cacheControl:"2592000"});s&&(I.stop(),r.program.error(`Cannot upload ${(0,g.formatError)(s)}`))}D.increment();const{data:L,error:z}=yield(0,g.updateOrCreateVersion)(S,{bucket_id:b?void 0:N,user_id:P,name:h,app_id:e,session_key:T,external_url:b,checksum:V},x);if(z&&(I.stop(),r.program.error(`Cannot add bundle ${(0,g.formatError)(z)}`)),D.increment(),L){const{error:o}=yield(0,g.updateOrCreateChannel)(S,{name:k,app_id:e,created_by:P,version:L.id},x);o&&I.log("Cannot set bundle with upload key, use key with more rights for that\n")}else I.log("Cannot set bundle with upload key, use key with more rights for that\n");I.stop();const B=(0,g.convertAppName)(e);return console.log("App uploaded to server"),console.log(`Try it in mobile app: ${g.host}/app_mobile`),console.log(`Or set the channel ${k} as public here: ${g.hostWeb}/app/package/${B}`),console.log("To use with live update in your own app"),console.log(`You can link specific device to this bundle to make user try it first, here: ${g.hostWeb}/app/p/${B}/devices`),yield C.publish({channel:"app",event:"App Uploaded",icon:"⏫",tags:{"user-id":P,"app-id":e},notify:!1}).catch(),n&&(console.log("Done ✅"),process.exit()),!0})),o.uploadCommand=(e,n)=>t(void 0,void 0,void 0,(function*(){(0,o.uploadBundle)(e,n,!0)}))},339:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addChannelCommand=o.addChannel=void 0;const i=n(304),a=n(642),r=n(860),s=n(246);o.addChannel=(e,o,n,c=!0)=>t(void 0,void 0,void 0,(function*(){var t;n.apikey=n.apikey||(0,s.findSavedKey)();const p=yield(0,s.getConfig)();o=o||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId);const l=(0,s.useLogSnag)();n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),o||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const d=(0,s.createSupabaseClient)(n.apikey),u=yield(0,s.verifyUser)(d,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(d,o,n.apikey),console.log(`Create channel ${o}#${e} to Capgo cloud`);try{const n=yield(0,r.findUnknownVersion)(d,o);n||i.program.error("Cannot find default version for channel creation, please contact Capgo support 🤨"),yield(0,r.createChannel)(d,{name:e,app_id:o,version:n.id,created_by:u}),console.log("Channel created ✅"),yield l.publish({channel:"app",event:"Create channel",icon:"✅",tags:{"user-id":u,"app-id":o,channel:e},notify:!1}).catch()}catch(e){return console.log("Cannot create Channel 🙀",e),!1}return c&&(console.log("Done ✅"),process.exit()),!0})),o.addChannelCommand=(e,n,i)=>t(void 0,void 0,void 0,(function*(){(0,o.addChannel)(e,n,i,!0)}))},879:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteChannel=void 0;const i=n(304),a=n(642),r=n(860),s=n(246);o.deleteChannel=(e,o,n)=>t(void 0,void 0,void 0,(function*(){var t;n.apikey=n.apikey||(0,s.findSavedKey)();const c=yield(0,s.getConfig)();o=o||(null===(t=null==c?void 0:c.app)||void 0===t?void 0:t.appId);const p=(0,s.useLogSnag)();n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),o||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,s.createSupabaseClient)(n.apikey),d=yield(0,s.verifyUser)(l,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(l,o,n.apikey),console.log(`Delete channel ${o}#${e} to Capgo cloud`);try{yield(0,r.delChannel)(l,e,o,d),console.log("Channel Delete ✅"),yield p.publish({channel:"app",event:"Delete channel",icon:"✅",tags:{"user-id":d,"app-id":o,channel:e},notify:!1}).catch()}catch(e){console.log("Cannot delete Channel 🙀",e)}console.log("Done ✅"),process.exit()}))},416:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listChannels=void 0;const i=n(304),a=n(642),r=n(860),s=n(246);o.listChannels=(e,o)=>t(void 0,void 0,void 0,(function*(){var n;o.apikey=o.apikey||(0,s.findSavedKey)();const t=yield(0,s.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId),o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const c=(0,s.createSupabaseClient)(o.apikey),p=yield(0,s.verifyUser)(c,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(c,e,o.apikey),console.log("Querying available versions in Capgo"),yield(0,a.checkAppExistsAndHasPermissionErr)(c,e,o.apikey);const l=yield(0,r.getActiveChannels)(c,e,p);console.log(`Active channels in Capgo: ${null==l?void 0:l.length}`),(0,r.displayChannels)(l),console.log("Done ✅"),process.exit()}))},687:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setChannel=void 0;const i=n(304),a=n(642),r=n(246);o.setChannel=(e,o,n)=>t(void 0,void 0,void 0,(function*(){var t,s,c;n.apikey=n.apikey||(0,r.findSavedKey)();const p=yield(0,r.getConfig)();o=o||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId);const l=(0,r.useLogSnag)();n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),o||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const d=(0,r.createSupabaseClient)(n.apikey),u=yield(0,r.verifyUser)(d,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(d,o,n.apikey);const{bundle:y,latest:g,downgrade:v,upgrade:f,ios:h,android:m,selfAssign:k,state:b}=n;e||i.program.error("Missing argument, you need to provide a channel"),g&&y&&i.program.error("Cannot set latest and bundle at the same time"),null==y&&null==b&&null==g&&null==v&&null==f&&null==h&&null==m&&null==k&&i.program.error("Missing argument, you need to provide a option to set");try{yield(0,r.checkPlanValid)(d,u),yield(0,a.checkAppExistsAndHasPermissionErr)(d,o,n.apikey);const t={created_by:u,app_id:o,name:e,version:void 0},w=g?null===(c=null===(s=null==p?void 0:p.app)||void 0===s?void 0:s.package)||void 0===c?void 0:c.version:y;if(null!=w){const{data:n,error:a}=yield d.from("app_versions").select().eq("app_id",o).eq("name",w).eq("user_id",u).eq("deleted",!1).single();!a&&n||i.program.error(`Cannot find version ${w}`),console.log(`Set ${o} channel: ${e} to @${w}`),t.version=n.id}null!=b&&("public"!==b&&"private"!==b||console.log(`Set ${o} channel: ${e} to public or private is deprecated, use default or normal instead`),console.log(`Set ${o} channel: ${e} to ${"public"===b||"default"===b?"default":"normal"}`),t.public="public"===b||"default"===b),null!=v&&(console.log(`Set ${o} channel: ${e} to ${v?"allow":"disallow"} downgrade`),t.disableAutoUpdateUnderNative=!v),null!=f&&(console.log(`Set ${o} channel: ${e} to ${f?"allow":"disallow"} upgrade`),t.disableAutoUpdateToMajor=!f),null!=h&&(console.log(`Set ${o} channel: ${e} to ${h?"allow":"disallow"} ios update`),t.ios=!!h),null!=m&&(console.log(`Set ${o} channel: ${e} to ${m?"allow":"disallow"} android update`),t.android=!!m),null!=k&&(console.log(`Set ${o} channel: ${e} to ${k?"allow":"disallow"} self assign to this channel`),t.allow_device_self_set=!!k);try{const{error:e}=yield(0,r.updateOrCreateChannel)(d,t,n.apikey);e&&i.program.error(`Cannot set channel ${(0,r.formatError)(e)}`)}catch(e){i.program.error(`Cannot set channel ${(0,r.formatError)(e)}`)}yield l.publish({channel:"app",event:"Set app",icon:"✅",tags:{"user-id":u,"app-id":o},notify:!1}).catch()}catch(e){i.program.error(`Unknow error ${(0,r.formatError)(e)}`)}console.log("Done ✅"),process.exit()}))},714:function(e,o,n){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0});const i=n(304),a=n(12),r=n(135),s=n(628),c=n(278),p=n(124),l=n(90),d=n(285),u=n(6),y=n(687),g=n(883),v=t(n(598)),f=n(640),h=n(367),m=n(957),k=n(339),b=n(879),w=n(416),_=n(444),x=n(10);i.program.description("Manage packages and bundle versions in capgo Cloud").version(v.default.version),i.program.command("login [apikey]").alias("l").description("Save apikey to your machine or folder").action(f.loginCommand).option("--local","Only save in local folder"),i.program.command("doctor").description("Get info about your Capgo app install").action(l.getInfo),i.program.command("init [apikey] [appid]").description("Init a new app").action(a.initApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account");const C=i.program.command("app").description("Manage app");C.command("add [appid]").alias("a").description("Add a new app in capgo Cloud").action(p.addCommand).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account"),C.command("delete [appid]").alias("d").description("Delete an app in capgo Cloud").action(x.deleteApp).option("-a, --apikey <apikey>","apikey to link to your account"),C.command("list [appid]").alias("l").description("list apps in capgo Cloud").action(h.listApp).option("-a, --apikey <apikey>","apikey to link to your account"),C.command("set [appid]").alias("s").description("Set an app in capgo Cloud").action(_.setApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account");const $=i.program.command("bundle").description("Manage bundle");$.command("upload [appid]").alias("u").description("Upload a new bundle in capgo Cloud").action(g.uploadCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-p, --path <path>","path of the folder to upload").option("-c, --channel <channel>","channel to link to").option("-e, --external <url>","link to external url intead of upload to capgo cloud").option("--key <key>","custom path for public signing key").option("--keyData <keyData>","base64 public signing key").option("--no-key","ignore signing key and send clear update").option("--display-iv-session","Show in the console the iv and session key used to encrypt the update").option("-b, --bundle <bundle>","bundle version number of the file to upload"),$.command("delete [appid]").alias("d").description("Delete a bundle in capgo Cloud").action(u.deleteBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("list [appid]").alias("l").description("List bundle in capgo Cloud").action(r.listBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("cleanup [appid]").alias("c").action(m.cleanupBundle).description("Cleanup bundle in capgo Cloud").option("-b, --bundle <bundle>","bundle version number of the app to delete").option("-a, --apikey <apikey>","apikey to link to your account").option("-k, --keep <keep>","number of version to keep").option("-f, --force","force removal"),$.command("decrypt [zipPath] [sessionKey]").alias("l").description("Decrypt a signed zip bundle").action(s.decryptZip).option("--key <key>","custom path for private signing key").option("--keyData <keyData>","base64 private signing key"),$.command("encrypt [zipPath]").description("Encrypt a zip bundle").action(c.encryptZip).option("--key <key>","custom path for private signing key").option("--keyData <keyData>","base64 private signing key");const A=i.program.command("channel").description("Manage channel");A.command("add [channelid] [appid]").alias("a").description("Create channel").action(k.addChannelCommand).option("-d, --default","set the channel as default"),A.command("delete [channelid] [appid]").alias("d").description("Delete channel").action(b.deleteChannel),A.command("list [appid]").alias("l").description("List channel").action(w.listChannels),A.command("set [channelid] [appid]").alias("s").description("Set channel").action(y.setChannel).option("-a, --apikey <apikey>","apikey to link to your account").option("-b, --bundle <bundle>","bundle version number of the file to set").option("-s, --state <state>","set the state of the channel, default or normal").option("--latest","get the latest version key in the package.json to set it to the channel").option("--downgrade","Allow to downgrade to version under native one").option("--no-downgrade","Disable downgrade to version under native one").option("--upgrade","Allow to upgrade to version above native one").option("--no-upgrade","Disable upgrade to version above native one").option("--ios","Allow sending update to ios devices").option("--no-ios","Disable sending update to ios devices").option("--android","Allow sending update to android devices").option("--no-android","Disable sending update to android devices").option("--self-assign","Allow to device to self assign to this channel").option("--no-self-assign","Disable devices to self assign to this channel"),i.program.command("key [option]").description("Save base64 signing key in capacitor config, usefull for CI").action(d.manageKey).option("-f, --force","force generate a new one"),i.program.command("upload [appid]").alias("u").description("(Deprecated) Upload a new bundle to capgo Cloud").action(g.uploadCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-p, --path <path>","path of the folder to upload").option("-c, --channel <channel>","channel to link to").option("-e, --external <url>","link to external url intead of upload to capgo cloud").option("--key <key>","custom path for public signing key").option("--keyData <keyData>","base64 public signing key").option("--no-key","ignore signing key and send clear update").option("--display-iv-session","Show in the console the iv and session key used to encrypt the update").option("-b, --bundle <bundle>","bundle version number of the file to upload"),i.program.parseAsync()},12:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.initApp=void 0;const i=n(147),a=n(301),r=n(81),s=n(339),c=n(883),p=n(640),l=n(124),d=n(484),u=n(246),y="CapacitorUpdater.notifyAppReady();",g=/import.*from.*/g,v="production";o.initApp=(e,o,n)=>t(void 0,void 0,void 0,(function*(){var t,f;yield(0,d.checkLatest)();const h=yield(0,u.getConfig)();o=o||(null===(t=null==h?void 0:h.app)||void 0===t?void 0:t.appId);const m=(0,a.findPackageManagerType)();"unknown"===m&&(console.log("Cannot reconize package manager, please run `capgo init` in a capacitor project with npm, pnpm or yarn"),process.exit());const k=yield(0,u.findMainFile)(),b=JSON.parse((0,i.readFileSync)("package.json").toString());(null===(f=b.scripts)||void 0===f?void 0:f.build)||(console.log("Cannot find build script in package.json, please add it and run `capgo init` again"),process.exit()),console.log("Running: npx @capgo/cli@latest login ***"),(yield(0,p.login)(e,n,!1))?console.log("Login Done ✅"):console.log("Login already done ✅"),console.log(`Running: npx @capgo/cli@latest app add ${o}`),(yield(0,l.addApp)(o,n,!1))?console.log("App add Done ✅"):console.log("App already add ✅"),console.log(`Running: npx @capgo/cli@latest channel add ${v} ${o} -d`),(yield(0,s.addChannel)(v,o,{default:!0,apikey:e},!1))?console.log("Channel add Done ✅"):console.log("Channel already added ✅");const w="yarn"===m?"add":"install";if(b.dependencies["@capgo/capacitor-updater"])console.log("Capgo already installed ✅");else{const e=yield(0,r.execSync)(`${m} ${w} @capgo/capacitor-updater@latest`);console.log(e.toString()),console.log("Install Done ✅")}const _=(0,i.readFileSync)(k).toString(),x=_.match(g),C=null==x?void 0:x.pop();if(C||(console.log("Cannot find import line in main file, use manual installation: https://docs.capgo.app/installation"),process.exit()),_.includes(y))console.log(`Code already added to ${k} ✅`);else{const e=_.replace(C,`${C}\nimport { CapacitorUpdater } from '@capgo/capacitor-updater';\n\n${y}\n`);(0,i.writeFileSync)(k,e),console.log(`Code added to ${k} ✅`)}console.log("Running: npm run build && npx cap sync");const $=yield(0,r.execSync)("npm run build && npx cap sync");console.log($.toString()),console.log("Build & Sync Done ✅"),console.log("Running: npx @capgo/cli@latest bundle upload"),(yield(0,c.uploadBundle)(o,{channel:v,apikey:e},!1))?console.log("Upload Done ✅"):(console.log("Upload failed ❌"),process.exit()),console.log("Init Done ✅"),console.log("Now run the app in your phone or emulator with: npx cap run");const A=o.replace(/\./g,"--");console.log(`Then watch logs in https://web.capgo.app/app/p/${A}/logs`),process.exit()}))},285:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.manageKey=void 0;const i=n(304),a=n(147),r=n(778),s=n(213),c=n(246),p=n(484);o.manageKey=(e,o)=>t(void 0,void 0,void 0,(function*(){var n,l;yield(0,p.checkLatest)(),"save"===e?(n=o.key,l=o.keyData,t(void 0,void 0,void 0,(function*(){(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository");const e=yield(0,c.getConfig)(),{extConfig:o}=e.app,t=n||c.baseKey;let s=l||"";(0,a.existsSync)(t)||s?(0,a.existsSync)(t)&&(s=(0,a.readFileSync)(t).toString()):i.program.error(`Cannot find public key ${t} or as keyData option or in ${e.app.extConfigFilePath}`),o&&(o.plugins||(o.plugins={}),o.plugins.CapacitorUpdater||(o.plugins.CapacitorUpdater={}),o.plugins.CapacitorUpdater.privateKey=s,(0,r.writeConfig)(o,e.app.extConfigFilePath)),console.log(`private key saved into ${e.app.extConfigFilePath} file in local directory`),console.log("your app will decode the zip archive with this key\n")}))):"create"===e?(e=>{t(void 0,void 0,void 0,(function*(){(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository");const{publicKey:o,privateKey:n}=(0,s.createRSA)();(0,a.existsSync)(c.baseKeyPub)&&!e.force&&i.program.error("Public Key already exists, use --force to overwrite"),(0,a.writeFileSync)(c.baseKeyPub,o),(0,a.existsSync)(c.baseKey)&&!e.force&&i.program.error("Private Key already exists, use --force to overwrite"),(0,a.writeFileSync)(c.baseKey,n);const t=yield(0,c.getConfig)(),{extConfig:p}=t.app;p&&(p.plugins||(p.plugins={}),p.plugins.CapacitorUpdater||(p.plugins.CapacitorUpdater={}),p.plugins.CapacitorUpdater.privateKey=n,(0,r.writeConfig)(p,t.app.extConfigFilePath)),console.log("Your RSA key has been generated using node-rsa with this settings:\n\n- encryptionScheme — 'pkcs1_oaep'.\n- signingScheme — 'pkcs8-sha256'.\n- bits — 2048.\n- exp — 65537.\n"),console.log(`public key saved into ${c.baseKeyPub} file in local directory\n`),console.log("This key will be use to encode your zipped bundle before sending it to Capgo,\nthan make them unreadable by Capgo and unmodifiable by anyone\n"),console.log(`Private key saved into ${t.app.extConfigFilePath} file in local directory`),console.log("Your app will decode with this key the zipped bundle\n")}))})(o):i.program.error("You should provide a valid option (create or save)"),process.exit()}))},640:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.loginCommand=o.login=void 0;const i=n(304),a=n(147),r=n(37),s=n(246),c=n(484);o.login=(e,o,n=!0)=>t(void 0,void 0,void 0,(function*(){if(!e)return n&&i.program.error("Missing API key, you need to provide a API key to upload your bundle"),!1;yield(0,c.checkLatest)();try{const{local:n}=o,t=(0,s.useLogSnag)();if(n)(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository"),(0,a.writeFileSync)(".capgo",`${e}\n`),(0,a.appendFileSync)(".gitignore",".capgo\n");else{const o=(0,r.homedir)();(0,a.writeFileSync)(`${o}/.capgo`,`${e}\n`)}const c=(0,s.createSupabaseClient)(e),p=yield(0,s.verifyUser)(c,e,["write","all","upload"]);yield t.publish({channel:"user-login",event:"User CLI login",icon:"✅",tags:{"user-id":p},notify:!1}).catch(),console.log(`login saved into .capgo file in ${n?"local":"home"} directory`)}catch(e){console.error(e),process.exit(1)}return n&&(console.log("Done ✅"),process.exit()),!0})),o.loginCommand=(e,n)=>t(void 0,void 0,void 0,(function*(){(0,o.login)(e,n,!0)}))},246:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(r,s)}c((t=t.apply(e,o||[])).next())}))},i=this&&this.__await||function(e){return this instanceof i?(this.v=e,this):new i(e)},a=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),o={},t("next"),t("throw"),t("return"),o[Symbol.asyncIterator]=function(){return this},o);function t(n){o[n]=e[n]&&function(o){return new Promise((function(t,i){!function(e,o,n,t){Promise.resolve(t).then((function(o){e({value:o,done:n})}),o)}(t,i,(o=e[n](o)).done,o.value)}))}}},r=this&&this.__asyncDelegator||function(e){var o,n;return o={},t("next"),t("throw",(function(e){throw e})),t("return"),o[Symbol.iterator]=function(){return this},o;function t(t,a){o[t]=e[t]?function(o){return(n=!n)?{value:i(e[t](o)),done:"return"===t}:a?a(o):o}:a}},s=this&&this.__asyncGenerator||function(e,o,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,a=n.apply(e,o||[]),r=[];return t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t;function s(e){a[e]&&(t[e]=function(o){return new Promise((function(n,t){r.push([e,o,n,t])>1||c(e,o)}))})}function c(e,o){try{(n=a[e](o)).value instanceof i?Promise.resolve(n.value.v).then(p,l):d(r[0][2],n)}catch(e){d(r[0][3],e)}var n}function p(e){c("next",e)}function l(e){c("throw",e)}function d(e,o){e(o),r.shift(),r.length&&c(r[0][0],r[0][1])}},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.getHumanDate=o.verifyUser=o.convertAppName=o.useLogSnag=o.updateOrCreateChannel=o.updateOrCreateVersion=o.getConfig=o.formatError=o.findMainFile=o.findSavedKey=o.checkPlanValid=o.isAllowedAction=o.isTrial=o.isPaying=o.isGoodPlan=o.checkKey=o.regexSemver=o.createSupabaseClient=o.supaAnon=o.hostSupa=o.hostWeb=o.host=o.baseKeyPub=o.baseKey=void 0;const p=n(778),l=n(304),d=n(885),u=c(n(867)),y=n(147),g=n(37),v=n(133),f=n(17);function h(e){return s(this,arguments,(function*(){const o=yield i((0,y.readdirSync)(e,{withFileTypes:!0}));for(const n of o){const o=(0,f.resolve)(e,n.name);!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("node_modules")||n.name.startsWith("dist")?yield yield i(o):yield i(yield*r(a(h(o))))}}))}o.baseKey=".capgo_key",o.baseKeyPub=`${o.baseKey}.pub`,o.host="https://capgo.app",o.hostWeb="https://web.capgo.app",o.hostSupa="https://xvwzpoazmxkqosrdewyv.supabase.co",o.supaAnon="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYzNzgwNTAwOSwiZXhwIjoxOTUzMzgxMDA5fQ.8tgID1d4jodPwuo_fz4KHN4o1XKB9fnqyt0_GaJSj-w",o.createSupabaseClient=e=>(0,d.createClient)(o.hostSupa,o.supaAnon,{global:{headers:{capgkey:e}}}),o.regexSemver=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,o.checkKey=(e,n,i)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.rpc("is_allowed_capgkey",{apikey:n,keymode:i}).single();t&&!a||l.program.error(`Invalid API key or insufficient permissions ${(0,o.formatError)(a)}`)})),o.isGoodPlan=(e,o)=>t(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.rpc("is_good_plan_v2",{userid:o}).single();if(t)throw t;return n||!1})),o.isPaying=(e,o)=>t(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.rpc("is_paying",{userid:o}).single();if(t)throw t;return n||!1})),o.isTrial=(e,o)=>t(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.rpc("is_trial",{userid:o}).single();if(t)throw t;return n||0})),o.isAllowedAction=(e,o)=>t(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.rpc("is_allowed_action_user",{userid:o}).single();if(t)throw t;return n})),o.checkPlanValid=(e,n,i=!0)=>t(void 0,void 0,void 0,(function*(){(yield(0,o.isAllowedAction)(e,n))||l.program.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${o.hostWeb}/dashboard/settings/plans\n`);const t=yield(0,o.isTrial)(e,n);t>0&&i&&console.log(`WARNING !!\nTrial expires in ${t} days, upgrade here: ${o.hostWeb}/dashboard/settings/plans\n`)})),o.findSavedKey=()=>{let e,o=`${(0,g.homedir)()}/.capgo`;return(0,y.existsSync)(o)&&(console.log(`Use global apy key ${o}`),e=(0,y.readFileSync)(o,"utf8").trim()),o=".capgo",!e&&(0,y.existsSync)(o)&&(console.log(`Use local apy key ${o}`),e=(0,y.readFileSync)(o,"utf8").trim()),e||l.program.error("Key not found, please login first"),e},o.findMainFile=()=>t(void 0,void 0,void 0,(function*(){var e,o,n,t;const i=/(main|index)\.(ts|js)$/;let r="";const s=process.cwd(),c=s.split("/").length;try{for(var p,d=!0,u=a(h(s));!(e=(p=yield u.next()).done);){t=p.value,d=!1;try{const e=t;if(e.split("/").length-c<=2&&i.test(e)){r=e,console.log("Found main file here",e);break}}finally{d=!0}}}catch(e){o={error:e}}finally{try{d||e||!(n=u.return)||(yield n.call(u))}finally{if(o)throw o.error}}return r||l.program.error("No main.ts, main.js, index.ts or index.js file found, please run cap init first"),r})),o.formatError=e=>e?`\n${u.default.render(e)}`:"",o.getConfig=()=>t(void 0,void 0,void 0,(function*(){let e;try{e=yield(0,p.loadConfig)()}catch(e){l.program.error("No capacitor config file found, run `cap init` first")}return e})),o.updateOrCreateVersion=(e,o,n)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.rpc("exist_app_versions",{appid:o.app_id,name_version:o.name,apikey:n}).single();return t&&!i?(o.deleted=!1,e.from("app_versions").update(o).eq("app_id",o.app_id).eq("name",o.name).single()):e.from("app_versions").insert(o).select().single()})),o.updateOrCreateChannel=(e,o,n)=>t(void 0,void 0,void 0,(function*(){if(!o.app_id||!o.name||!o.created_by)return console.error("missing app_id, name, or created_by"),Promise.reject(new Error("missing app_id, name, or created_by"));const{data:t,error:i}=yield e.rpc("exist_channel",{appid:o.app_id,name_channel:o.name,apikey:n}).single();return t&&!i?e.from("channels").update(o).eq("app_id",o.app_id).eq("name",o.name).eq("created_by",o.created_by).single():e.from("channels").insert(o).select().single()})),o.useLogSnag=()=>new v.LogSnag({token:"c124f5e9d0ce5bdd14bbb48f815d5583",project:"capgo"}),o.convertAppName=e=>e.replace(/\./g,"--"),o.verifyUser=(e,n,i=["all"])=>t(void 0,void 0,void 0,(function*(){yield(0,o.checkKey)(e,n,i);const{data:t,error:a}=yield e.rpc("get_user_id",{apikey:n}).single(),r=t?t.toString():"";return r&&!a||l.program.error(`Cannot verify user ${(0,o.formatError)(a)}`),r})),o.getHumanDate=e=>new Date(e||"").toLocaleString()},778:e=>{e.exports=require("@capacitor/cli/dist/config")},301:e=>{e.exports=require("@capgo/find-package-manager")},885:e=>{e.exports=require("@supabase/supabase-js")},906:e=>{e.exports=require("@tomasklaen/checksum")},176:e=>{e.exports=require("@trufflesuite/spinnies")},844:e=>{e.exports=require("adm-zip")},295:e=>{e.exports=require("cli-progress")},304:e=>{e.exports=require("commander")},847:e=>{e.exports=require("console-table-printer")},470:e=>{e.exports=require("fs-extra")},362:e=>{e.exports=require("get-latest-version")},133:e=>{e.exports=require("logsnag")},11:e=>{e.exports=require("mime")},867:e=>{e.exports=require("prettyjson")},616:e=>{e.exports=require("prompt-sync")},505:e=>{e.exports=require("semver/preload")},81:e=>{e.exports=require("child_process")},113:e=>{e.exports=require("crypto")},147:e=>{e.exports=require("fs")},37:e=>{e.exports=require("os")},17:e=>{e.exports=require("path")},598:e=>{e.exports=JSON.parse('{"name":"@capgo/cli","version":"3.2.0","description":"A CLI to upload to capgo servers","main":"dist/index.js","bin":{"capgo":"dist/index.js"},"repository":{"type":"git","url":"git+https://github.com/Cap-go/capgo-cli.git"},"bugs":{"url":"https://github.com/Cap-go/capgo-cli/issues"},"engines":{"npm":">=7.0.0","node":">=16.0.0"},"keywords":["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli"],"scripts":{"dev":"set NODE_ENV=development && npx webpack --config webpack.config.js","no-debug":"node dist/index.js","test":"npx --yes ts-node -T src/index.ts","build":"npx --yes webpack --config webpack.config.js","dev-build":"SUPA_DB=development npx webpack --config webpack.config.js","pack":"pkg","types":"npx --yes supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts","test_rls":"ts-node ./test/test_headers_rls.ts","lint":"eslint . --ext .ts --fix"},"author":"github.com/riderx","license":"Apache 2.0","dependencies":{"@capacitor/cli":"4.6.3","@capgo/find-package-manager":"^0.0.7","@supabase/supabase-js":"^2.5.0","@tomasklaen/checksum":"^1.1.0","@trufflesuite/spinnies":"^0.1.1","adm-zip":"^0.5.10","cli-progress":"3.12.0","commander":"10.0.0","console-table-printer":"^2.11.1","fs-extra":"11.1.0","get-latest-version":"^5.0.0","logsnag":"^0.1.6","mime":"^3.0.0","prettyjson":"^1.2.5","prompt-sync":"^4.2.0","semver":"^7.3.8"},"devDependencies":{"@types/adm-zip":"0.5.0","@types/cli-progress":"^3.11.0","@types/fs-extra":"^9.0.13","@types/mime":"^3.0.1","@types/node":"^18.11.18","@types/prettyjson":"^0.0.30","@types/prompt-sync":"^4.2.0","@types/semver":"^7.3.13","@typescript-eslint/eslint-plugin":"5.53.0","@typescript-eslint/parser":"5.53.0","eslint":"8.35.0","eslint-config-airbnb-base":"^15.0.0","eslint-config-prettier":"^8.6.0","eslint-import-resolver-typescript":"3.5.3","eslint-plugin-import":"2.27.5","eslint-plugin-prettier":"^4.2.1","git-format-staged":"3.0.0","husky":"^8.0.3","nodemon":"2.0.20","pkg":"5.8.0","prettier":"2.8.4","ts-loader":"^9.4.2","ts-node":"^10.9.1","tsconfig-paths":"4.1.2","typescript":"4.9.5","webpack":"5.75.0","webpack-cli":"^5.0.1","webpack-node-externals":"^3.0.0"}}')}},o={};!function n(t){var i=o[t];if(void 0!==i)return i.exports;var a=o[t]={exports:{}};return e[t].call(a.exports,a,a.exports,n),a.exports}(714)})();
2
+ (()=>{"use strict";var e={7642:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.newIconPath=n.checkAppExistsAndHasPermissionErr=n.checkAppExistsAndHasPermission=void 0;const i=o(7304);n.checkAppExistsAndHasPermission=(e,n,o,i=!0)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.rpc("exist_app",{appid:n,apikey:o}).single();return t!==i||a})),n.checkAppExistsAndHasPermissionErr=(e,o,a,r=!0)=>t(void 0,void 0,void 0,(function*(){(yield(0,n.checkAppExistsAndHasPermission)(e,o,a,r))&&i.program.error(`App ${o} does not exist or you don't have permission to access it`)})),n.newIconPath="assets/icon.png"},4860:function(e,n,o){var t=this&&this.__createBinding||(Object.create?function(e,n,o,t){void 0===t&&(t=o);var i=Object.getOwnPropertyDescriptor(n,o);i&&!("get"in i?!n.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return n[o]}}),Object.defineProperty(e,t,i)}:function(e,n,o,t){void 0===t&&(t=o),e[t]=n[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(n,e,o);return i(n,e),n},r=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.getActiveChannels=n.displayChannels=n.delChannel=n.createChannel=n.findUnknownVersion=n.checkVersionNotUsedInChannel=void 0;const s=o(7304),c=o(3847),p=a(o(552)),l=o(7246);n.checkVersionNotUsedInChannel=(e,o,t,i)=>r(void 0,void 0,void 0,(function*(){var a;const{data:r,error:c}=yield e.from("channels").select().eq("app_id",o).eq("created_by",t).eq("version",i.id);if(c&&s.program.error(`Cannot check Version ${o}@${i.name} ${(0,l.formatError)(c)}`),r&&r.length>0){if(p.intro(`❌ Version ${o}@${i.name} is used in ${r.length} channel`),yield p.confirm({message:"unlink it?"}))for(const t of r){const i=p.spinner();i.start(`Unlinking channel ${t.name}`);const{error:r}=yield e.from("channels").update({version:null===(a=yield(0,n.findUnknownVersion)(e,o))||void 0===a?void 0:a.id}).eq("id",t.id);r&&(i.stop(`Cannot update channel ${t.name} ${(0,l.formatError)(r)}`),process.exit(1)),i.stop(`✅ Channel ${t.name} unlinked`)}else s.program.error("unlink it first");p.outro(`Version unlinked from ${r.length} channel`)}})),n.findUnknownVersion=(e,n)=>e.from("app_versions").select("id").eq("app_id",n).eq("name","unknown").throwOnError().single().then((({data:e})=>e)),n.createChannel=(e,n)=>e.from("channels").insert(n).select().single(),n.delChannel=(e,n,o,t)=>e.from("channels").delete().eq("name",n).eq("app_id",o).eq("created_by",t).single(),n.displayChannels=e=>{const n=new c.Table({title:"Channels",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{n.addRow({Name:e.name,Created:(0,l.getHumanDate)(e.created_at),Public:e.public?"✅":"❌"})})),n.printTable()},n.getActiveChannels=(e,n,o)=>r(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("channels").select().eq("app_id",n).eq("created_by",o).order("created_at",{ascending:!1});return i&&s.program.error(`App ${n} not found in database ${(0,l.formatError)(i)} `),t}))},6213:(e,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createRSA=n.encryptSource=n.decryptSource=void 0;const t=o(6113),i="aes-128-cbc",a="sha256",r="base64",s=t.constants.RSA_PKCS1_OAEP_PADDING;n.decryptSource=(e,n,o)=>{const[c,p]=n.split(":"),l=(0,t.privateDecrypt)({key:o,padding:s,oaepHash:a},Buffer.from(p,r)),d=Buffer.from(c,r),u=l.toString(r);console.log("\nSessionB64",u);const y=(0,t.createDecipheriv)(i,l,d);return y.setAutoPadding(!0),Buffer.concat([y.update(e),y.final()])},n.encryptSource=(e,n)=>{const o=(0,t.randomBytes)(16),c=(0,t.randomBytes)(16),p=(0,t.createCipheriv)(i,c,o);p.setAutoPadding(!0);const l=`${o.toString(r)}:${(0,t.publicEncrypt)({key:n,padding:s,oaepHash:a},c).toString(r)}`;return{encryptedData:Buffer.concat([p.update(e),p.final()]),ivSessionKey:l}},n.createRSA=()=>{const{publicKey:e,privateKey:n}=(0,t.generateKeyPairSync)("rsa",{modulusLength:2048});return{publicKey:e.export({type:"pkcs1",format:"pem"}),privateKey:n.export({type:"pkcs1",format:"pem"})}}},5933:function(e,n,o){var t=this&&this.__createBinding||(Object.create?function(e,n,o,t){void 0===t&&(t=o);var i=Object.getOwnPropertyDescriptor(n,o);i&&!("get"in i?!n.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return n[o]}}),Object.defineProperty(e,t,i)}:function(e,n,o,t){void 0===t&&(t=o),e[t]=n[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(n,e,o);return i(n,e),n},r=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.checkVersionNotUsedInDeviceOverride=void 0;const s=o(7304),c=a(o(552)),p=o(7246);n.checkVersionNotUsedInDeviceOverride=(e,n,o)=>r(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("devices_override").select().eq("app_id",n).eq("version",o.id);if(i&&s.program.error(`Cannot check Device override ${n}@${o.name} ${(0,p.formatError)(i)}`),t&&t.length>0)if(c.intro(`❌ Version ${n}@${o.name} is used in ${t.length} device override`),yield c.confirm({message:"unlink it?"}))for(const n of t){const o=c.spinner();o.start(`Unlinking device ${n.device_id}`);const{error:t}=yield e.from("devices_override").delete().eq("device_id",n.device_id);t&&(o.stop(`Cannot unlink device ${n.device_id} ${(0,p.formatError)(t)}`),process.exit(1)),o.stop(`✅ Device ${n.device_id} unlinked`)}else s.program.error("unlink it first")}))},3350:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.deleteFromStorage=void 0;const i=o(7304),a=o(7246);n.deleteFromStorage=(e,n,o,r,s)=>t(void 0,void 0,void 0,(function*(){const{error:t}=yield e.storage.from("apps").remove([`${n}/${o}/versions/${r.bucket_id} `]);t&&i.program.error(`Something went wrong when trying to delete ${o} @${s} ${(0,a.formatError)(t)} `)}))},484:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.checkLatest=void 0;const a=i(o(5362)),r=i(o(4147));n.checkLatest=()=>t(void 0,void 0,void 0,(function*(){const e=yield(0,a.default)("@capgo/cli");e!==r.default.version&&console.log("%s",`🚨 You are using @capgo/cli@${r.default.version} it's not the latest version.\nPlease use @capgo/cli@${e}" or @capgo/cli@latest to keep up to date with the latest features and bug fixes.`)}))},1089:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.getVersionData=n.getActiveAppVersions=n.displayBundles=n.deleteSpecificVersion=n.deleteAppVersion=void 0;const i=o(7304),a=o(3847),r=o(7246),s=o(4860),c=o(5933),p=o(3350);n.deleteAppVersion=(e,n,o,a)=>t(void 0,void 0,void 0,(function*(){const{error:t}=yield e.from("app_versions").update({deleted:!0}).eq("app_id",n).eq("deleted",!1).eq("user_id",o).eq("name",a);t&&i.program.error(`App Version ${n}@${a} not found in database '${(0,r.formatError)(t)}'`)})),n.deleteSpecificVersion=(e,o,i,a)=>t(void 0,void 0,void 0,(function*(){const t=yield(0,n.getVersionData)(e,o,i,a);yield(0,s.checkVersionNotUsedInChannel)(e,o,i,t),yield(0,c.checkVersionNotUsedInDeviceOverride)(e,o,t),yield(0,p.deleteFromStorage)(e,i,o,t,a),yield(0,n.deleteAppVersion)(e,o,i,a)})),n.displayBundles=e=>{const n=new a.Table({title:"Bundles",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{n.addRow(Object.assign({Version:e.name,Created:(0,r.getHumanDate)(e.created_at)},null!=e.keep?{Keep:e.keep}:{}))})),n.printTable()},n.getActiveAppVersions=(e,n,o)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.from("app_versions").select().eq("app_id",n).eq("user_id",o).eq("deleted",!1).order("created_at",{ascending:!1});return a&&i.program.error(`App ${n} not found in database ${(0,r.formatError)(a)} `),t})),n.getVersionData=(e,n,o,a)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:s}=yield e.from("app_versions").select().eq("app_id",n).eq("user_id",o).eq("name",a).eq("deleted",!1).single();return t&&!s||i.program.error(`App Version ${n}@${a} doesn't exist ${(0,r.formatError)(s)}`),t}))},3124:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.addCommand=n.addApp=void 0;const i=o(9011),a=o(7304),r=o(6113),s=o(4470),c=o(484),p=o(7642),l=o(7246);n.addApp=(e,n,o=!0)=>t(void 0,void 0,void 0,(function*(){var t,d,u;yield(0,c.checkLatest)(),n.apikey=n.apikey||(0,l.findSavedKey)();const y=yield(0,l.getConfig)();e=e||(null===(t=null==y?void 0:y.app)||void 0===t?void 0:t.appId);const f=(0,l.useLogSnag)();n.apikey||a.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||a.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const g=(0,l.createSupabaseClient)(n.apikey),v=yield(0,l.verifyUser)(g,n.apikey,["write","all"]);if(o)yield(0,p.checkAppExistsAndHasPermissionErr)(g,e,n.apikey,!1);else if(yield(0,p.checkAppExistsAndHasPermission)(g,e,n.apikey,!1))return!1;let h,m,{name:b,icon:k}=n;e=e||(null===(d=null==y?void 0:y.app)||void 0===d?void 0:d.appId),b=b||(null===(u=null==y?void 0:y.app)||void 0===u?void 0:u.appName)||"Unknown",k=k||"resources/icon.png",k&&b||a.program.error("Missing argument, you need to provide a appId and a name, or be in a capacitor project"),console.log(`Adding ${e} to Capgo`),k&&(0,s.existsSync)(k)?(h=(0,s.readFileSync)(k),m=(0,i.getType)(k)||"image/png",console.warn(`Found app icon ${k}`)):(0,s.existsSync)(p.newIconPath)?(h=(0,s.readFileSync)(p.newIconPath),m=(0,i.getType)(p.newIconPath)||"image/png",console.warn(`Found app icon ${p.newIconPath}`)):console.warn(`Cannot find app icon in any of the following locations: ${k}, ${p.newIconPath}`);const{data:_,error:w}=yield g.rpc("exist_app_v2",{appid:e}).single();(_||w)&&a.program.error(`App ${e} already exists ${(0,l.formatError)(w)}`);const x=`icon_${(0,r.randomUUID)()}`;let C="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(h&&m){const{error:n}=yield g.storage.from(`images/${v}/${e}`).upload(x,h,{contentType:m});n&&a.program.error(`Could not add app ${(0,l.formatError)(n)}`);const{data:o}=yield g.storage.from(`images/${v}/${e}`).getPublicUrl(x);C=(null==o?void 0:o.publicUrl)||C}const{error:$}=yield g.from("apps").insert({icon_url:C,user_id:v,name:b,app_id:e});$&&a.program.error(`Could not add app ${(0,l.formatError)($)}`);const{error:A}=yield g.from("app_versions").insert([{user_id:v,deleted:!0,name:"unknown",app_id:e},{user_id:v,deleted:!0,name:"builtin",app_id:e}]);return A&&a.program.error(`Could not add app ${(0,l.formatError)(A)}`),yield f.publish({channel:"app",event:"App Added",icon:"🎉",tags:{"user-id":v,"app-id":e},notify:!1}).catch(),console.log("App added to server, you can upload a bundle now"),o&&(console.log("Done ✅"),process.exit()),!0})),n.addCommand=(e,o)=>t(void 0,void 0,void 0,(function*(){(0,n.addApp)(e,o,!0)}))},2010:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.deleteApp=void 0;const i=o(7304),a=o(7642),r=o(7246);n.deleteApp=(e,n)=>t(void 0,void 0,void 0,(function*(){var o;n.apikey=n.apikey||(0,r.findSavedKey)();const t=yield(0,r.getConfig)();e=e||(null===(o=null==t?void 0:t.app)||void 0===o?void 0:o.appId);const s=(0,r.useLogSnag)();n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const c=(0,r.createSupabaseClient)(n.apikey),p=yield(0,r.verifyUser)(c,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(c,e,n.apikey);const{error:l}=yield c.storage.from(`images/${p}`).remove([e]);l&&i.program.error(`Could not add app ${(0,r.formatError)(l)}`);const{error:d}=yield c.storage.from(`apps/${e}/${p}`).remove(["versions"]);d&&i.program.error(`Could not delete app version ${(0,r.formatError)(d)}`);const{error:u}=yield c.from("apps").delete().eq("app_id",e).eq("user_id",p);u&&i.program.error(`Could not delete app ${(0,r.formatError)(u)}`),yield s.publish({channel:"app",event:"App Deleted",icon:"🗑️",tags:{"user-id":p,"app-id":e},notify:!1}).catch(),console.log("App deleted in Capgo"),console.log("Done ✅"),process.exit()}))},8090:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.getInfo=void 0;const a=o(7147),r=i(o(5362)),s=o(1017),c=i(o(7176)),p=i(o(4147));n.getInfo=()=>t(void 0,void 0,void 0,(function*(){console.log(" 💊 Capgo Doctor 💊"),console.log("\n"),console.log(" Installed Dependencies:"),console.log("\n");const e=yield t(void 0,void 0,void 0,(function*(){const{dependencies:e}=yield t(void 0,void 0,void 0,(function*(){const e=(0,a.readFileSync)((0,s.join)(process.cwd(),"package.json"));return JSON.parse(e)})),n={"@capgo/cli":p.default.version};for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&o.startsWith("@capgo/")&&(n[o]=e[o]);return n}));0===Object.keys(e).length&&(console.log("\n"),console.log("%s","🚨 No dependencies found"),process.exit(1));for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const o=e[n];console.log(` ${n}: ${o}`)}console.log("\n");const n=new c.default;n.add("loading",{text:"Loading latest dependencies"});const o=yield(e=>t(void 0,void 0,void 0,(function*(){const n={},o=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&o.push((0,r.default)(n));return yield Promise.all(o).then((o=>{const t=Object.keys(e);for(let e=0;e<o.length;e+=1){const i=o[e];i&&(n[t[e]]=i)}})),n})))(e);n.succeed("loading",{text:"Latest Dependencies:"}),console.log("\n");for(const e in o)if(Object.prototype.hasOwnProperty.call(o,e)){const n=o[e];console.log(` ${e}: ${n}`)}JSON.stringify(e)!==JSON.stringify(o)&&(console.log("\n"),console.log("%s","🚨 Some dependencies are not up to date"),process.exit(1)),console.log("\n"),console.log("%s","✅ All dependencies are up to date"),process.exit()}))},9367:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.listApp=n.getActiveApps=void 0;const i=o(7304),a=o(3847),r=o(7642),s=o(7246),c=o(484);n.getActiveApps=(e,n)=>t(void 0,void 0,void 0,(function*(){const{data:o,error:t}=yield e.from("apps").select().eq("user_id",n).order("created_at",{ascending:!1});return t&&i.program.error(`Apps not found in database ${(0,s.formatError)(t)} `),o})),n.listApp=(e,o)=>t(void 0,void 0,void 0,(function*(){var t;yield(0,c.checkLatest)(),o.apikey=o.apikey||(0,s.findSavedKey)();const p=yield(0,s.getConfig)();e=e||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId),o.apikey||i.program.error("Missing API key, you need to provide an API key to delete your app"),e||i.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const l=(0,s.createSupabaseClient)(o.apikey),d=yield(0,s.verifyUser)(l,o.apikey);console.log("Querying available versions in Capgo"),yield(0,r.checkAppExistsAndHasPermissionErr)(l,e,o.apikey);const u=yield(0,n.getActiveApps)(l,d);console.log(`Active app in Capgo: ${null==u?void 0:u.length}`),(e=>{const n=new a.Table({title:"Apps",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{n.addRow({Name:e.name,Created:(0,s.getHumanDate)(e.created_at)})})),n.printTable()})(u),console.log("Done ✅"),process.exit()}))},444:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.setApp=void 0;const i=o(9011),a=o(7304),r=o(6113),s=o(4470),c=o(7642),p=o(7246);n.setApp=(e,n)=>t(void 0,void 0,void 0,(function*(){var o;n.apikey=n.apikey||(0,p.findSavedKey)();const t=yield(0,p.getConfig)();e=e||(null===(o=null==t?void 0:t.app)||void 0===o?void 0:o.appId),n.apikey||a.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||a.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,p.createSupabaseClient)(n.apikey),d=yield(0,p.verifyUser)(l,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(l,e,n.apikey);const{name:u,icon:y}=n;let f,g;const v=`icon_${(0,r.randomUUID)()}`;let h="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(y&&(0,s.existsSync)(y)?(f=(0,s.readFileSync)(y),g=(0,i.getType)(y)||"image/png",console.warn(`Found app icon ${y}`)):(0,s.existsSync)(c.newIconPath)?(f=(0,s.readFileSync)(c.newIconPath),g=(0,i.getType)(c.newIconPath)||"image/png",console.warn(`Found app icon ${c.newIconPath}`)):console.warn(`Cannot find app icon in any of the following locations: ${y}, ${c.newIconPath}`),f&&g){const{error:n}=yield l.storage.from(`images/${d}/${e}`).upload(v,f,{contentType:g});n&&a.program.error(`Could not add app ${(0,p.formatError)(n)}`);const{data:o}=yield l.storage.from(`images/${d}/${e}`).getPublicUrl(v);h=(null==o?void 0:o.publicUrl)||h}const{error:m}=yield l.from("apps").update({icon_url:h,name:u}).eq("app_id",e).eq("user_id",d);m&&a.program.error(`Could not add app ${(0,p.formatError)(m)}`),console.log("Done ✅"),process.exit()}))},6957:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))},i=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=e[Symbol.asyncIterator];return o?o.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),n={},t("next"),t("throw"),t("return"),n[Symbol.asyncIterator]=function(){return this},n);function t(o){n[o]=e[o]&&function(n){return new Promise((function(t,i){!function(e,n,o,t){Promise.resolve(t).then((function(n){e({value:n,done:o})}),n)}(t,i,(n=e[o](n)).done,n.value)}))}}},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.cleanupBundle=void 0;const r=o(7304),s=a(o(1505)),c=a(o(1616)),p=o(7246),l=o(1089),d=o(7642),u=o(484),y=(0,c.default)();n.cleanupBundle=(e,n)=>t(void 0,void 0,void 0,(function*(){var o;yield(0,u.checkLatest)();const a=n.apikey||(0,p.findSavedKey)(),{bundle:c,keep:f=4}=n,g=n.force||!1,v=yield(0,p.getConfig)();e=e||(null===(o=null==v?void 0:v.app)||void 0===o?void 0:o.appId),a||r.program.error("Missing API key, you need to provide an API key to delete your app"),e||r.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const h=(0,p.createSupabaseClient)(a),m=yield(0,p.verifyUser)(h,a);yield(0,d.checkAppExistsAndHasPermissionErr)(h,e,a),console.log("Querying all available versions in Capgo");let b=yield(0,l.getActiveAppVersions)(h,e,m);if(console.log(`Total active versions in Capgo: ${null==b?void 0:b.length}`),0===(null==b?void 0:b.length))return void console.log("No versions found, aborting cleanup");if(c){const e=`${s.default.inc(c,"major")}`;console.log(`Querying available versions in Capgo between ${c} and ${e}`),b=((e,n,o)=>{const t=[];return null==e||e.forEach((e=>{s.default.gte(e.name,n)&&s.default.lt(e.name,`${o}`)&&t.push(e)})),t})(b,c,e),console.log(`Active versions in Capgo between ${c} and ${e}: ${null==b?void 0:b.length}`)}const k=[];if(b.forEach(((e,n)=>{n<f?e.keep="✅":(e.keep="❌",k.push(e))})),0!==k.length){if((0,l.displayBundles)(b),!g&&"yes"!==y("Do you want to continue removing the versions specified? Type yes to confirm: "))return void console.log("Not confirmed, aborting removal...");console.log("You have confirmed removal, removing versions now"),yield((e,n,o,a)=>{var r,s,c;return t(void 0,void 0,void 0,(function*(){var t,d,u,y;try{for(r=!0,s=i(e);!(t=(c=yield s.next()).done);){y=c.value,r=!1;try{const e=y;console.log(`Removing ${e.name} created on ${(0,p.getHumanDate)(e.created_at)}`),yield(0,l.deleteSpecificVersion)(n,o,a,e.name)}finally{r=!0}}}catch(e){d={error:e}}finally{try{r||t||!(u=s.return)||(yield u.call(s))}finally{if(d)throw d.error}}}))})(k,h,e,m),console.log("Done ✅"),process.exit()}else console.log("Nothing to be removed, aborting removal...")}))},8628:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.decryptZip=void 0;const i=o(7304),a=o(7147),r=o(6213),s=o(7246),c=o(484);n.decryptZip=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var t,p,l;yield(0,c.checkLatest)(),(0,a.existsSync)(e)||i.program.error(`Zip not found at the path ${e}`);const d=yield(0,s.getConfig)(),{extConfig:u}=d.app;o.key||(0,a.existsSync)(s.baseKey)||(null===(p=null===(t=u.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===p?void 0:p.privateKey)||i.program.error(`Private Key not found at the path ${s.baseKey} or in ${d.app.extConfigFilePath}`);const y=o.key||s.baseKey;let{privateKey:f}=o.keyData||(null===(l=null==u?void 0:u.plugins)||void 0===l?void 0:l.CapacitorUpdater)||"";(0,a.existsSync)(y)||f?(0,a.existsSync)(y)&&(f=(0,a.readFileSync)(y).toString()):i.program.error(`Cannot find public key ${y} or as keyData option or in ${d.app.extConfigFilePath}`);const g=(0,a.readFileSync)(e),v=(0,r.decryptSource)(g,n,f);(0,a.writeFileSync)(`${e}_decrypted.zip`,v),console.log("Done ✅"),process.exit()}))},2006:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.deleteBundle=void 0;const i=o(7304),a=o(7642),r=o(7246),s=o(1089);n.deleteBundle=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var t,c;o.apikey=o.apikey||(0,r.findSavedKey)();const p=yield(0,r.getConfig)();e=e||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId),o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,r.createSupabaseClient)(o.apikey),d=yield(0,r.verifyUser)(l,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(l,e,o.apikey);const u=o.apikey||(0,r.findSavedKey)();e=e||(null===(c=null==p?void 0:p.app)||void 0===c?void 0:c.appId),u||i.program.error("Missing API key, you need to provide an API key to delete your app"),n||i.program.error("Missing argument, you need to provide a bundleId, or be in a capacitor project"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project"),console.log(`Delete ${e}@${n} from Capgo`),yield(0,s.deleteSpecificVersion)(l,e,d,n),console.log(`${e}@${n} deleted from server`),console.log("Done ✅"),process.exit()}))},6278:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.encryptZip=void 0;const i=o(7304),a=o(7147),r=o(484),s=o(6213),c=o(7246);n.encryptZip=(e,n)=>t(void 0,void 0,void 0,(function*(){yield(0,r.checkLatest)(),(0,a.existsSync)(e)||i.program.error(`Zip not found at the path ${e}`);const o=n.key||c.baseKeyPub;let t=n.keyData||"";(0,a.existsSync)(o)||t?(0,a.existsSync)(o)&&(t=(0,a.readFileSync)(o).toString()):i.program.error(`Cannot find public key ${o} or as keyData option`);const p=(0,a.readFileSync)(e),l=(0,s.encryptSource)(p,t);console.log("ivSessionKey",l.ivSessionKey),(0,a.writeFileSync)(`${e}_encrypted.zip`,l.encryptedData),console.log("Done ✅"),process.exit()}))},9135:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.listBundle=void 0;const i=o(7304),a=o(7642),r=o(1089),s=o(7246),c=o(484);n.listBundle=(e,n)=>t(void 0,void 0,void 0,(function*(){var o;yield(0,c.checkLatest)(),n.apikey=n.apikey||(0,s.findSavedKey)();const t=yield(0,s.getConfig)();e=e||(null===(o=null==t?void 0:t.app)||void 0===o?void 0:o.appId),n.apikey||i.program.error("Missing API key, you need to provide an API key to delete your app"),e||i.program.error("Missing argument, you need to provide a appid, or be in a capacitor project");const p=(0,s.createSupabaseClient)(n.apikey),l=yield(0,s.verifyUser)(p,n.apikey);console.log("Querying available versions in Capgo"),yield(0,a.checkAppExistsAndHasPermissionErr)(p,e,n.apikey);const d=yield(0,r.getActiveAppVersions)(p,e,l);console.log(`Active versions in Capgo: ${null==d?void 0:d.length}`),(0,r.displayBundles)(d),console.log("Done ✅"),process.exit()}))},7883:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.uploadCommand=n.uploadBundle=void 0;const a=i(o(3844)),r=o(7304),s=o(6113),c=i(o(295)),p=o(7147),l=o(5906),d=o(484),u=o(7642),y=o(6213),f=o(7246);n.uploadBundle=(e,n,o=!0)=>t(void 0,void 0,void 0,(function*(){var t,i,g,v;yield(0,d.checkLatest)();let{bundle:h,path:m,channel:b}=n;const{external:k,key:_=!1,displayIvSession:w}=n,x=n.apikey||(0,f.findSavedKey)(),C=(0,f.useLogSnag)();b=b||"dev";const $=yield(0,f.getConfig)();e=e||(null===(t=null==$?void 0:$.app)||void 0===t?void 0:t.appId);const A=(0,s.randomUUID)().split("-")[0];h=h||(null===(g=null===(i=null==$?void 0:$.app)||void 0===i?void 0:i.package)||void 0===g?void 0:g.version)||`0.0.1-beta.${A}`,f.regexSemver.test(h)||r.program.error(`Your bundle name ${h}, is not valid it should follow semver convention : https://semver.org/`),m=m||(null===(v=null==$?void 0:$.app)||void 0===v?void 0:v.webDir),x||r.program.error("Missing API key, you need to provide a API key to upload your bundle"),e&&h&&m||r.program.error("Missing argument, you need to provide a appid and a bundle and a path, or be in a capacitor project"),console.log(`Upload ${e}@${h} started from path "${m}" to Capgo cloud`);const S=(0,f.createSupabaseClient)(x),P=yield(0,f.verifyUser)(S,x,["write","all","upload"]);yield(0,f.checkPlanValid)(S,P,!1),yield(0,u.checkAppExistsAndHasPermissionErr)(S,e,x);const I=new c.default.MultiBar({clearOnComplete:!1,hideCursor:!0},c.default.Presets.shades_grey),j=I.create(7,0,{format:"Uploading: [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} Part"},c.default.Presets.shades_grey);j.start(7,0,{speed:"N/A"});const{data:D,error:M}=yield S.rpc("exist_app_versions",{apikey:x,name_version:h,appid:e}).single();(D||M)&&(I.stop(),r.program.error(`This app bundle already exist or was deleted, you cannot re-upload it ${(0,f.formatError)(M)}`)),j.increment();const{data:E,error:O}=yield S.rpc("is_trial",{userid:P}).single();(E&&E>0||O)&&I.log(`WARNING !!\nTrial expires in ${E} days, upgrade here: ${f.hostWeb}/dashboard/settings/plans\n`),j.increment();const{data:K,error:U}=yield S.rpc("exist_app",{appid:e,apikey:x}).single();K&&!U||(I.stop(),r.program.error(`Cannot find app ${e} in your account \n${(0,f.formatError)(U)}`)),j.increment();const{data:q,error:F}=yield S.rpc("exist_app_versions",{appid:e,apikey:x,name_version:h}).single();(q||F)&&r.program.error(`Version already exists ${(0,f.formatError)(F)}`),j.increment();const V=(0,s.randomUUID)();let L,T="";if(k)k&&!k.startsWith("https://")&&(I.stop(),r.program.error(`External link should should start with "https://" current is "${k}"`));else{const n=new a.default;n.addLocalFolder(m);let o=n.toBuffer();if(T=yield(0,l.checksum)(o,"crc32"),_||(0,p.existsSync)(f.baseKeyPub)){const e="string"==typeof _?_:f.baseKeyPub;(0,p.existsSync)(e)||r.program.error(`Cannot find public key ${e}`);const n=(0,p.readFileSync)(e);I.log("Encrypting your bundle\n");const t=(0,y.encryptSource)(o,n.toString());L=t.ivSessionKey,w&&I.log(`Your Iv Session key is ${L},\nkeep it safe, you will need it to decrypt your bundle.\nIt will be also visible in your dashboard\n`),o=t.encryptedData}const t=Math.floor(o.byteLength/1024/1024),i=`apps/${P}/${e}/versions`;j.increment(),t>20&&(I.log(`WARNING !!\nThe app size is ${t} Mb, this may take a while to download for users\n`),I.log("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield C.publish({channel:"app-error",event:"App Too Large",icon:"🚛",tags:{"user-id":P,"app-id":e},notify:!1}).catch());const{error:s}=yield S.storage.from(i).upload(V,o,{contentType:"application/zip",cacheControl:"2592000"});s&&(I.stop(),r.program.error(`Cannot upload ${(0,f.formatError)(s)}`))}j.increment();const{data:N,error:z}=yield(0,f.updateOrCreateVersion)(S,{bucket_id:k?void 0:V,user_id:P,name:h,app_id:e,session_key:L,external_url:k,checksum:T},x);if(z&&(I.stop(),r.program.error(`Cannot add bundle ${(0,f.formatError)(z)}`)),j.increment(),N){const{error:n}=yield(0,f.updateOrCreateChannel)(S,{name:b,app_id:e,created_by:P,version:N.id},x);n&&I.log("Cannot set bundle with upload key, use key with more rights for that\n")}else I.log("Cannot set bundle with upload key, use key with more rights for that\n");I.stop();const B=(0,f.convertAppName)(e);return console.log("App uploaded to server"),console.log(`Try it in mobile app: ${f.host}/app_mobile`),console.log(`Or set the channel ${b} as public here: ${f.hostWeb}/app/package/${B}`),console.log("To use with live update in your own app"),console.log(`You can link specific device to this bundle to make user try it first, here: ${f.hostWeb}/app/p/${B}/devices`),yield C.publish({channel:"app",event:"App Uploaded",icon:"⏫",tags:{"user-id":P,"app-id":e},notify:!1}).catch(),o&&(console.log("Done ✅"),process.exit()),!0})),n.uploadCommand=(e,o)=>t(void 0,void 0,void 0,(function*(){(0,n.uploadBundle)(e,o,!0)}))},9339:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.addChannelCommand=n.addChannel=void 0;const i=o(7304),a=o(7642),r=o(4860),s=o(7246);n.addChannel=(e,n,o,c=!0)=>t(void 0,void 0,void 0,(function*(){var t;o.apikey=o.apikey||(0,s.findSavedKey)();const p=yield(0,s.getConfig)();n=n||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId);const l=(0,s.useLogSnag)();o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),n||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const d=(0,s.createSupabaseClient)(o.apikey),u=yield(0,s.verifyUser)(d,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(d,n,o.apikey),console.log(`Create channel ${n}#${e} to Capgo cloud`);try{const o=yield(0,r.findUnknownVersion)(d,n);o||i.program.error("Cannot find default version for channel creation, please contact Capgo support 🤨"),yield(0,r.createChannel)(d,{name:e,app_id:n,version:o.id,created_by:u}),console.log("Channel created ✅"),yield l.publish({channel:"channel",event:"Create channel",icon:"✅",tags:{"user-id":u,"app-id":n,channel:e},notify:!1}).catch()}catch(e){return console.log("Cannot create Channel 🙀",e),!1}return c&&(console.log("Done ✅"),process.exit()),!0})),n.addChannelCommand=(e,o,i)=>t(void 0,void 0,void 0,(function*(){(0,n.addChannel)(e,o,i,!0)}))},879:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.deleteChannel=void 0;const i=o(7304),a=o(7642),r=o(4860),s=o(7246);n.deleteChannel=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var t;o.apikey=o.apikey||(0,s.findSavedKey)();const c=yield(0,s.getConfig)();n=n||(null===(t=null==c?void 0:c.app)||void 0===t?void 0:t.appId);const p=(0,s.useLogSnag)();o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),n||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const l=(0,s.createSupabaseClient)(o.apikey),d=yield(0,s.verifyUser)(l,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(l,n,o.apikey),console.log(`Delete channel ${n}#${e} to Capgo cloud`);try{yield(0,r.delChannel)(l,e,n,d),console.log("Channel Delete ✅"),yield p.publish({channel:"channel",event:"Delete channel",icon:"✅",tags:{"user-id":d,"app-id":n,channel:e},notify:!1}).catch()}catch(e){console.log("Cannot delete Channel 🙀",e)}console.log("Done ✅"),process.exit()}))},2416:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.listChannels=void 0;const i=o(7304),a=o(7642),r=o(4860),s=o(7246);n.listChannels=(e,n)=>t(void 0,void 0,void 0,(function*(){var o;n.apikey=n.apikey||(0,s.findSavedKey)();const t=yield(0,s.getConfig)();e=e||(null===(o=null==t?void 0:t.app)||void 0===o?void 0:o.appId);const c=(0,s.useLogSnag)();n.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),e||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const p=(0,s.createSupabaseClient)(n.apikey),l=yield(0,s.verifyUser)(p,n.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(p,e,n.apikey),console.log("Querying available versions in Capgo"),yield(0,a.checkAppExistsAndHasPermissionErr)(p,e,n.apikey);const d=yield(0,r.getActiveChannels)(p,e,l);console.log(`Active channels in Capgo: ${null==d?void 0:d.length}`),(0,r.displayChannels)(d),yield c.publish({channel:"channel",event:"List channel",icon:"✅",tags:{"user-id":l,"app-id":e},notify:!1}).catch(),console.log("Done ✅"),process.exit()}))},2687:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.setChannel=void 0;const i=o(7304),a=o(7642),r=o(7246);n.setChannel=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var t,s,c;o.apikey=o.apikey||(0,r.findSavedKey)();const p=yield(0,r.getConfig)();n=n||(null===(t=null==p?void 0:p.app)||void 0===t?void 0:t.appId);const l=(0,r.useLogSnag)();o.apikey||i.program.error("Missing API key, you need to provide a API key to upload your bundle"),n||i.program.error("Missing argument, you need to provide a appId, or be in a capacitor project");const d=(0,r.createSupabaseClient)(o.apikey),u=yield(0,r.verifyUser)(d,o.apikey,["write","all"]);yield(0,a.checkAppExistsAndHasPermissionErr)(d,n,o.apikey);const{bundle:y,latest:f,downgrade:g,upgrade:v,ios:h,android:m,selfAssign:b,state:k}=o;e||i.program.error("Missing argument, you need to provide a channel"),f&&y&&i.program.error("Cannot set latest and bundle at the same time"),null==y&&null==k&&null==f&&null==g&&null==v&&null==h&&null==m&&null==b&&i.program.error("Missing argument, you need to provide a option to set");try{yield(0,r.checkPlanValid)(d,u),yield(0,a.checkAppExistsAndHasPermissionErr)(d,n,o.apikey);const t={created_by:u,app_id:n,name:e,version:void 0},_=f?null===(c=null===(s=null==p?void 0:p.app)||void 0===s?void 0:s.package)||void 0===c?void 0:c.version:y;if(null!=_){const{data:o,error:a}=yield d.from("app_versions").select().eq("app_id",n).eq("name",_).eq("user_id",u).eq("deleted",!1).single();!a&&o||i.program.error(`Cannot find version ${_}`),console.log(`Set ${n} channel: ${e} to @${_}`),t.version=o.id}null!=k&&("public"!==k&&"private"!==k||console.log(`Set ${n} channel: ${e} to public or private is deprecated, use default or normal instead`),console.log(`Set ${n} channel: ${e} to ${"public"===k||"default"===k?"default":"normal"}`),t.public="public"===k||"default"===k),null!=g&&(console.log(`Set ${n} channel: ${e} to ${g?"allow":"disallow"} downgrade`),t.disableAutoUpdateUnderNative=!g),null!=v&&(console.log(`Set ${n} channel: ${e} to ${v?"allow":"disallow"} upgrade`),t.disableAutoUpdateToMajor=!v),null!=h&&(console.log(`Set ${n} channel: ${e} to ${h?"allow":"disallow"} ios update`),t.ios=!!h),null!=m&&(console.log(`Set ${n} channel: ${e} to ${m?"allow":"disallow"} android update`),t.android=!!m),null!=b&&(console.log(`Set ${n} channel: ${e} to ${b?"allow":"disallow"} self assign to this channel`),t.allow_device_self_set=!!b);try{const{error:e}=yield(0,r.updateOrCreateChannel)(d,t,o.apikey);e&&i.program.error(`Cannot set channel ${(0,r.formatError)(e)}`)}catch(e){i.program.error(`Cannot set channel ${(0,r.formatError)(e)}`)}yield l.publish({channel:"channel",event:"Set channel",icon:"✅",tags:{"user-id":u,"app-id":n},notify:!1}).catch()}catch(e){i.program.error(`Unknow error ${(0,r.formatError)(e)}`)}console.log("Done ✅"),process.exit()}))},1714:function(e,n,o){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0});const i=o(7304),a=o(5012),r=o(9135),s=o(8628),c=o(6278),p=o(3124),l=o(8090),d=o(2285),u=o(2006),y=o(2687),f=o(7883),g=t(o(4147)),v=o(8640),h=o(9367),m=o(6957),b=o(9339),k=o(879),_=o(2416),w=o(444),x=o(2010);i.program.description("Manage packages and bundle versions in Capgo Cloud").version(g.default.version),i.program.command("login [apikey]").alias("l").description("Save apikey to your machine or folder").action(v.loginCommand).option("--local","Only save in local folder"),i.program.command("doctor").description("Get info about your Capgo app install").action(l.getInfo),i.program.command("init [apikey] [appid]").description("Init a new app").action(a.initApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account");const C=i.program.command("app").description("Manage app");C.command("add [appid]").alias("a").description("Add a new app in Capgo Cloud").action(p.addCommand).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account"),C.command("delete [appid]").alias("d").description("Delete an app in Capgo Cloud").action(x.deleteApp).option("-a, --apikey <apikey>","apikey to link to your account"),C.command("list [appid]").alias("l").description("list apps in Capgo Cloud").action(h.listApp).option("-a, --apikey <apikey>","apikey to link to your account"),C.command("set [appid]").alias("s").description("Set an app in Capgo Cloud").action(w.setApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account");const $=i.program.command("bundle").description("Manage bundle");$.command("upload [appid]").alias("u").description("Upload a new bundle in Capgo Cloud").action(f.uploadCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-p, --path <path>","path of the folder to upload").option("-c, --channel <channel>","channel to link to").option("-e, --external <url>","link to external url intead of upload to Capgo Cloud").option("--key <key>","custom path for public signing key").option("--keyData <keyData>","base64 public signing key").option("--no-key","ignore signing key and send clear update").option("--display-iv-session","Show in the console the iv and session key used to encrypt the update").option("-b, --bundle <bundle>","bundle version number of the bundle to upload"),$.command("delete [appid]").alias("d").description("Delete a bundle in Capgo Cloud").action(u.deleteBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("list [appid]").alias("l").description("List bundle in Capgo Cloud").action(r.listBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("unlink [appid]").alias("u").description("Unlink a bundle in Capgo Cloud").action(r.listBundle).option("-a, --apikey <apikey>","apikey to link to your account").option("-b, --bundle <bundle>","bundle version number of the bundle to unlink"),$.command("cleanup [appid]").alias("c").action(m.cleanupBundle).description("Cleanup bundle in Capgo Cloud").option("-b, --bundle <bundle>","bundle version number of the app to delete").option("-a, --apikey <apikey>","apikey to link to your account").option("-k, --keep <keep>","number of version to keep").option("-f, --force","force removal"),$.command("decrypt [zipPath] [sessionKey]").alias("l").description("Decrypt a signed zip bundle").action(s.decryptZip).option("--key <key>","custom path for private signing key").option("--keyData <keyData>","base64 private signing key"),$.command("encrypt [zipPath]").description("Encrypt a zip bundle").action(c.encryptZip).option("--key <key>","custom path for private signing key").option("--keyData <keyData>","base64 private signing key");const A=i.program.command("channel").description("Manage channel");A.command("add [channelid] [appid]").alias("a").description("Create channel").action(b.addChannelCommand).option("-d, --default","set the channel as default"),A.command("delete [channelid] [appid]").alias("d").description("Delete channel").action(k.deleteChannel),A.command("list [appid]").alias("l").description("List channel").action(_.listChannels),A.command("set [channelid] [appid]").alias("s").description("Set channel").action(y.setChannel).option("-a, --apikey <apikey>","apikey to link to your account").option("-b, --bundle <bundle>","bundle version number of the file to set").option("-s, --state <state>","set the state of the channel, default or normal").option("--latest","get the latest version key in the package.json to set it to the channel").option("--downgrade","Allow to downgrade to version under native one").option("--no-downgrade","Disable downgrade to version under native one").option("--upgrade","Allow to upgrade to version above native one").option("--no-upgrade","Disable upgrade to version above native one").option("--ios","Allow sending update to ios devices").option("--no-ios","Disable sending update to ios devices").option("--android","Allow sending update to android devices").option("--no-android","Disable sending update to android devices").option("--self-assign","Allow to device to self assign to this channel").option("--no-self-assign","Disable devices to self assign to this channel");const S=i.program.command("key").description("Manage key");S.command("save").description("Save base64 signing key in capacitor config, usefull for CI").action(d.saveKeyCommand).option("-f, --force","force generate a new one"),S.command("create").description("Create a new signing key").action(d.createKeyCommand).option("-f, --force","force generate a new one"),i.program.command("upload [appid]").alias("u").description("(Deprecated) Upload a new bundle to Capgo Cloud").action(f.uploadCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-p, --path <path>","path of the folder to upload").option("-c, --channel <channel>","channel to link to").option("-e, --external <url>","link to external url intead of upload to Capgo Cloud").option("--key <key>","custom path for public signing key").option("--keyData <keyData>","base64 public signing key").option("--no-key","ignore signing key and send clear update").option("--display-iv-session","Show in the console the iv and session key used to encrypt the update").option("-b, --bundle <bundle>","bundle version number of the file to upload"),i.program.parseAsync()},5012:function(e,n,o){var t=this&&this.__createBinding||(Object.create?function(e,n,o,t){void 0===t&&(t=o);var i=Object.getOwnPropertyDescriptor(n,o);i&&!("get"in i?!n.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return n[o]}}),Object.defineProperty(e,t,i)}:function(e,n,o,t){void 0===t&&(t=o),e[t]=n[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(n,e,o);return i(n,e),n},r=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.initApp=void 0;const s=o(7147),c=o(6301),p=o(2081),l=a(o(552)),d=o(2285),u=o(9339),y=o(7883),f=o(8640),g=o(3124),v=o(484),h=o(7246),m="CapacitorUpdater.notifyAppReady();",b=/import.*from.*/g,k="production";n.initApp=(e,n,o)=>r(void 0,void 0,void 0,(function*(){var t,i;yield(0,v.checkLatest)();const a=yield(0,h.getConfig)();n=n||(null===(t=null==a?void 0:a.app)||void 0===t?void 0:t.appId),l.intro("Capgo init");const r=l.spinner();if(r.start("Running: npx @capgo/cli@latest login ***"),(yield(0,f.login)(e,o,!1))?r.stop("Login Done ✅"):r.stop("Login already done ✅"),yield l.confirm({message:`Add ${n} in Capgo?`})){const e=l.spinner();e.start(`Running: npx @capgo/cli@latest app add ${n}`),(yield(0,g.addApp)(n,o,!1))?e.stop("App add Done ✅"):e.stop("App already add ✅")}if(yield l.confirm({message:`Create channel ${k} in Capgo?`})){const o=l.spinner();o.start(`Running: npx @capgo/cli@latest channel add ${k} ${n} -d`),(yield(0,u.addChannel)(k,n,{default:!0,apikey:e},!1))?o.stop("Channel add Done ✅"):o.stop("Channel already added ✅")}if(yield l.confirm({message:"Install @capgo/capacitor-updater ?"})){const e=l.spinner();e.start("Checking if capgo is installed");const n=JSON.parse((0,s.readFileSync)("package.json").toString()),o=(0,c.findPackageManagerType)();"unknown"===o&&(e.stop("Cannot reconize package manager, please run `capgo init` in a capacitor project with npm, pnpm or yarn"),process.exit());const t="yarn"===o?"add":"install";n.dependencies["@capgo/capacitor-updater"]?e.stop("Capgo already installed ✅"):(yield(0,p.execSync)(`${o} ${t} @capgo/capacitor-updater@latest`),e.stop("Install Done ✅"))}if(yield l.confirm({message:"Add @capacitor-updater to your main file?"})){const e=l.spinner();e.start("Adding @capacitor-updater to your main file");const n=yield(0,h.findMainFile)();n||(e.stop("No main.ts, main.js, index.ts or index.js file found, please run cap init first"),process.exit());const o=(0,s.readFileSync)(n).toString(),t=o.match(b),i=null==t?void 0:t.pop();if(i||(e.stop("Cannot find import line in main file, use manual installation: https://docs.capgo.app/installation"),process.exit()),o.includes(m))e.stop(`Code already added to ${n} ✅`);else{const t=o.replace(i,`${i}\nimport { CapacitorUpdater } from '@capgo/capacitor-updater';\n\n${m}\n`);(0,s.writeFileSync)(n,t),e.stop(`Code added to ${n} ✅`)}}if(yield l.confirm({message:"Use end-to-end encryption?"})){const e=l.spinner();e.start("Running: npx @capgo/cli@latest key create"),(yield(0,d.createKey)({},!1))?e.stop("key created 🔑"):(e.stop("Cannot create key ❌"),process.exit(1))}if(yield l.confirm({message:"Build the project?"})){const e=l.spinner();e.start("Running: npm run build && npx cap sync"),(null===(i=JSON.parse((0,s.readFileSync)("package.json").toString()).scripts)||void 0===i?void 0:i.build)||(e.stop("Cannot find build script in package.json, please add it and run `capgo init` again"),process.exit()),yield(0,p.execSync)("npm run build && npx cap sync"),e.stop("Build & Sync Done ✅")}if(yield l.confirm({message:"Upload the bundle?"})){const o=l.spinner();o.start("Running: npx @capgo/cli@latest bundle upload"),(yield(0,y.uploadBundle)(n,{channel:k,apikey:e},!1))?o.stop("Upload Done ✅"):(o.stop("Upload failed ❌"),process.exit())}l.outro("You're all set ✅!"),console.log("Now run the app in your phone or emulator with: npx cap run");const _=n.replace(/\./g,"--");console.log(`Then watch logs in https://web.capgo.app/app/p/${_}/logs`),process.exit()}))},2285:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.createKeyCommand=n.createKey=n.saveKeyCommand=n.saveKey=void 0;const i=o(7304),a=o(7147),r=o(7778),s=o(6213),c=o(7246),p=o(484);n.saveKey=(e,n=!0)=>t(void 0,void 0,void 0,(function*(){(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository");const o=yield(0,c.getConfig)(),{extConfig:t}=o.app,s=e.key||c.baseKey;let p=e.keyData||"";if((0,a.existsSync)(s)||p)(0,a.existsSync)(s)&&(p=(0,a.readFileSync)(s).toString());else{if(!n)return!1;i.program.error(`Cannot find public key ${s} or as keyData option or in ${o.app.extConfigFilePath}`)}return t&&(t.plugins||(t.plugins={}),t.plugins.CapacitorUpdater||(t.plugins.CapacitorUpdater={}),t.plugins.CapacitorUpdater.privateKey=p,(0,r.writeConfig)(t,o.app.extConfigFilePath)),n&&(console.log(`private key saved into ${o.app.extConfigFilePath} file in local directory`),console.log("your app will decode the zip archive with this key\n")),!0})),n.saveKeyCommand=e=>t(void 0,void 0,void 0,(function*(){yield(0,p.checkLatest)(),yield(0,n.saveKey)(e)})),n.createKey=(e,n=!0)=>t(void 0,void 0,void 0,(function*(){(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository");const{publicKey:o,privateKey:t}=(0,s.createRSA)();if((0,a.existsSync)(c.baseKeyPub)&&!e.force){if(!n)return!1;i.program.error("Public Key already exists, use --force to overwrite")}if((0,a.writeFileSync)(c.baseKeyPub,o),(0,a.existsSync)(c.baseKey)&&!e.force){if(!n)return!1;i.program.error("Private Key already exists, use --force to overwrite")}(0,a.writeFileSync)(c.baseKey,t);const p=yield(0,c.getConfig)(),{extConfig:l}=p.app;return l&&(l.plugins||(l.plugins={}),l.plugins.CapacitorUpdater||(l.plugins.CapacitorUpdater={}),l.plugins.CapacitorUpdater.privateKey=t,(0,r.writeConfig)(l,p.app.extConfigFilePath)),n&&(console.log("Your RSA key has been generated\n"),console.log(`public key saved into ${c.baseKeyPub} file in local directory\n`),console.log("This key will be use to encode AES key used to crypt your zipped bundle before sending it to Capgo,\n than make them unreadable by Capgo and unmodifiable by anyone\n"),console.log(`Private key saved into ${p.app.extConfigFilePath} file in local directory`),console.log("Your app will decode with this RSA key the AES key and use it to decode the zipped bundle\n")),!0})),n.createKeyCommand=e=>t(void 0,void 0,void 0,(function*(){yield(0,p.checkLatest)(),yield(0,n.createKey)(e)}))},8640:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.loginCommand=n.login=void 0;const i=o(7304),a=o(7147),r=o(2037),s=o(7246),c=o(484);n.login=(e,n,o=!0)=>t(void 0,void 0,void 0,(function*(){if(!e)return o&&i.program.error("Missing API key, you need to provide a API key to upload your bundle"),!1;yield(0,c.checkLatest)();try{const{local:o}=n,t=(0,s.useLogSnag)();if(o)(0,a.existsSync)(".git")||i.program.error("To use local you should be in a git repository"),(0,a.writeFileSync)(".capgo",`${e}\n`),(0,a.appendFileSync)(".gitignore",".capgo\n");else{const n=(0,r.homedir)();(0,a.writeFileSync)(`${n}/.capgo`,`${e}\n`)}const c=(0,s.createSupabaseClient)(e),p=yield(0,s.verifyUser)(c,e,["write","all","upload"]);yield t.publish({channel:"user-login",event:"User CLI login",icon:"✅",tags:{"user-id":p},notify:!1}).catch(),console.log(`login saved into .capgo file in ${o?"local":"home"} directory`)}catch(e){console.error(e),process.exit(1)}return o&&(console.log("Done ✅"),process.exit()),!0})),n.loginCommand=(e,o)=>t(void 0,void 0,void 0,(function*(){(0,n.login)(e,o,!0)}))},7246:function(e,n,o){var t=this&&this.__awaiter||function(e,n,o,t){return new(o||(o=Promise))((function(i,a){function r(e){try{c(t.next(e))}catch(e){a(e)}}function s(e){try{c(t.throw(e))}catch(e){a(e)}}function c(e){var n;e.done?i(e.value):(n=e.value,n instanceof o?n:new o((function(e){e(n)}))).then(r,s)}c((t=t.apply(e,n||[])).next())}))},i=this&&this.__await||function(e){return this instanceof i?(this.v=e,this):new i(e)},a=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=e[Symbol.asyncIterator];return o?o.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),n={},t("next"),t("throw"),t("return"),n[Symbol.asyncIterator]=function(){return this},n);function t(o){n[o]=e[o]&&function(n){return new Promise((function(t,i){!function(e,n,o,t){Promise.resolve(t).then((function(n){e({value:n,done:o})}),n)}(t,i,(n=e[o](n)).done,n.value)}))}}},r=this&&this.__asyncDelegator||function(e){var n,o;return n={},t("next"),t("throw",(function(e){throw e})),t("return"),n[Symbol.iterator]=function(){return this},n;function t(t,a){n[t]=e[t]?function(n){return(o=!o)?{value:i(e[t](n)),done:"return"===t}:a?a(n):n}:a}},s=this&&this.__asyncGenerator||function(e,n,o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,a=o.apply(e,n||[]),r=[];return t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t;function s(e){a[e]&&(t[e]=function(n){return new Promise((function(o,t){r.push([e,n,o,t])>1||c(e,n)}))})}function c(e,n){try{(o=a[e](n)).value instanceof i?Promise.resolve(o.value.v).then(p,l):d(r[0][2],o)}catch(e){d(r[0][3],e)}var o}function p(e){c("next",e)}function l(e){c("throw",e)}function d(e,n){e(n),r.shift(),r.length&&c(r[0][0],r[0][1])}},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.getHumanDate=n.verifyUser=n.convertAppName=n.useLogSnag=n.updateOrCreateChannel=n.updateOrCreateVersion=n.getConfig=n.formatError=n.findMainFile=n.findSavedKey=n.checkPlanValid=n.isAllowedAction=n.isTrial=n.isPaying=n.isGoodPlan=n.checkKey=n.regexSemver=n.createSupabaseClient=n.supaAnon=n.hostSupa=n.hostWeb=n.host=n.baseKeyPub=n.baseKey=void 0;const p=o(7778),l=o(7304),d=o(2885),u=c(o(9867)),y=o(7147),f=o(2037),g=o(1133),v=o(1017),h=c(o(6634));function m(e){return s(this,arguments,(function*(){const n=yield i((0,y.readdirSync)(e,{withFileTypes:!0}));for(const o of n){const n=(0,v.resolve)(e,o.name);!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("node_modules")||o.name.startsWith("dist")?yield yield i(n):yield i(yield*r(a(m(n))))}}))}n.baseKey=".capgo_key",n.baseKeyPub=`${n.baseKey}.pub`,n.host="https://capgo.app",n.hostWeb="https://web.capgo.app",n.hostSupa="https://xvwzpoazmxkqosrdewyv.supabase.co",n.supaAnon="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYzNzgwNTAwOSwiZXhwIjoxOTUzMzgxMDA5fQ.8tgID1d4jodPwuo_fz4KHN4o1XKB9fnqyt0_GaJSj-w",n.createSupabaseClient=e=>(0,d.createClient)(n.hostSupa,n.supaAnon,{global:{headers:{capgkey:e}}}),n.regexSemver=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,n.checkKey=(e,o,i)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:a}=yield e.rpc("is_allowed_capgkey",{apikey:o,keymode:i}).single();t&&!a||l.program.error(`Invalid API key or insufficient permissions ${(0,n.formatError)(a)}`)})),n.isGoodPlan=(e,n)=>t(void 0,void 0,void 0,(function*(){const{data:o,error:t}=yield e.rpc("is_good_plan_v2",{userid:n}).single();if(t)throw t;return o||!1})),n.isPaying=(e,n)=>t(void 0,void 0,void 0,(function*(){const{data:o,error:t}=yield e.rpc("is_paying",{userid:n}).single();if(t)throw t;return o||!1})),n.isTrial=(e,n)=>t(void 0,void 0,void 0,(function*(){const{data:o,error:t}=yield e.rpc("is_trial",{userid:n}).single();if(t)throw t;return o||0})),n.isAllowedAction=(e,n)=>t(void 0,void 0,void 0,(function*(){const{data:o,error:t}=yield e.rpc("is_allowed_action_user",{userid:n}).single();if(t)throw t;return o})),n.checkPlanValid=(e,o,i=!0)=>t(void 0,void 0,void 0,(function*(){(yield(0,n.isAllowedAction)(e,o))||(console.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${n.hostWeb}/dashboard/settings/plans\n`),setTimeout((()=>{(0,h.default)(`${n.hostWeb}/dashboard/settings/plans`),l.program.error("")}),1e3));const t=yield(0,n.isTrial)(e,o);t>0&&i&&console.log(`WARNING !!\nTrial expires in ${t} days, upgrade here: ${n.hostWeb}/dashboard/settings/plans\n`)})),n.findSavedKey=()=>{let e,n=`${(0,f.homedir)()}/.capgo`;return(0,y.existsSync)(n)&&(console.log(`Use global apy key ${n}`),e=(0,y.readFileSync)(n,"utf8").trim()),n=".capgo",!e&&(0,y.existsSync)(n)&&(console.log(`Use local apy key ${n}`),e=(0,y.readFileSync)(n,"utf8").trim()),e||l.program.error("Key not found, please login first"),e},n.findMainFile=()=>t(void 0,void 0,void 0,(function*(){var e,n,o,t;const i=/(main|index)\.(ts|js)$/;let r="";const s=process.cwd(),c=s.split("/").length;try{for(var p,l=!0,d=a(m(s));!(e=(p=yield d.next()).done);){t=p.value,l=!1;try{const e=t;if(e.split("/").length-c<=2&&i.test(e)){r=e,console.log("Found main file here",e);break}}finally{l=!0}}}catch(e){n={error:e}}finally{try{l||e||!(o=d.return)||(yield o.call(d))}finally{if(n)throw n.error}}return r})),n.formatError=e=>e?`\n${u.default.render(e)}`:"",n.getConfig=()=>t(void 0,void 0,void 0,(function*(){let e;try{e=yield(0,p.loadConfig)()}catch(e){l.program.error("No capacitor config file found, run `cap init` first")}return e})),n.updateOrCreateVersion=(e,n,o)=>t(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.rpc("exist_app_versions",{appid:n.app_id,name_version:n.name,apikey:o}).single();return t&&!i?(n.deleted=!1,e.from("app_versions").update(n).eq("app_id",n.app_id).eq("name",n.name).single()):e.from("app_versions").insert(n).select().single()})),n.updateOrCreateChannel=(e,n,o)=>t(void 0,void 0,void 0,(function*(){if(!n.app_id||!n.name||!n.created_by)return console.error("missing app_id, name, or created_by"),Promise.reject(new Error("missing app_id, name, or created_by"));const{data:t,error:i}=yield e.rpc("exist_channel",{appid:n.app_id,name_channel:n.name,apikey:o}).single();return t&&!i?e.from("channels").update(n).eq("app_id",n.app_id).eq("name",n.name).eq("created_by",n.created_by).single():e.from("channels").insert(n).select().single()})),n.useLogSnag=()=>new g.LogSnag({token:"c124f5e9d0ce5bdd14bbb48f815d5583",project:"capgo"}),n.convertAppName=e=>e.replace(/\./g,"--"),n.verifyUser=(e,o,i=["all"])=>t(void 0,void 0,void 0,(function*(){yield(0,n.checkKey)(e,o,i);const{data:t,error:a}=yield e.rpc("get_user_id",{apikey:o}).single(),r=t?t.toString():"";return r&&!a||l.program.error(`Cannot verify user ${(0,n.formatError)(a)}`),r})),n.getHumanDate=e=>new Date(e||"").toLocaleString()},7778:e=>{e.exports=require("@capacitor/cli/dist/config")},6301:e=>{e.exports=require("@capgo/find-package-manager")},552:e=>{e.exports=require("@clack/prompts")},2885:e=>{e.exports=require("@supabase/supabase-js")},5906:e=>{e.exports=require("@tomasklaen/checksum")},7176:e=>{e.exports=require("@trufflesuite/spinnies")},3844:e=>{e.exports=require("adm-zip")},295:e=>{e.exports=require("cli-progress")},7304:e=>{e.exports=require("commander")},3847:e=>{e.exports=require("console-table-printer")},4470:e=>{e.exports=require("fs-extra")},5362:e=>{e.exports=require("get-latest-version")},1133:e=>{e.exports=require("logsnag")},9011:e=>{e.exports=require("mime")},6634:e=>{e.exports=require("open")},9867:e=>{e.exports=require("prettyjson")},1616:e=>{e.exports=require("prompt-sync")},1505:e=>{e.exports=require("semver/preload")},2081:e=>{e.exports=require("child_process")},6113:e=>{e.exports=require("crypto")},7147:e=>{e.exports=require("fs")},2037:e=>{e.exports=require("os")},1017:e=>{e.exports=require("path")},4147:e=>{e.exports=JSON.parse('{"name":"@capgo/cli","version":"3.4.0","description":"A CLI to upload to capgo servers","main":"dist/index.js","bin":{"capgo":"dist/index.js"},"repository":{"type":"git","url":"git+https://github.com/Cap-go/capgo-cli.git"},"bugs":{"url":"https://github.com/Cap-go/capgo-cli/issues"},"engines":{"npm":">=7.0.0","node":">=16.0.0"},"keywords":["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli"],"scripts":{"dev":"set NODE_ENV=development && npx webpack --config webpack.config.js","no-debug":"node dist/index.js","test":"npx --yes ts-node -T src/index.ts","build":"npx --yes webpack --config webpack.config.js","dev-build":"SUPA_DB=development npx webpack --config webpack.config.js","pack":"pkg","types":"npx --yes supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts","test_rls":"ts-node ./test/test_headers_rls.ts","lint":"eslint . --ext .ts --fix"},"author":"github.com/riderx","license":"Apache 2.0","dependencies":{"@capacitor/cli":"4.6.3","@capgo/find-package-manager":"^0.0.7","@clack/prompts":"^0.6.1","@supabase/supabase-js":"^2.5.0","@tomasklaen/checksum":"^1.1.0","@trufflesuite/spinnies":"^0.1.1","adm-zip":"^0.5.10","cli-progress":"3.12.0","commander":"10.0.0","console-table-printer":"^2.11.1","fs-extra":"11.1.0","get-latest-version":"^5.0.0","logsnag":"^0.1.6","mime":"^3.0.0","open":"^8.4.2","prettyjson":"^1.2.5","prompt-sync":"^4.2.0","semver":"^7.3.8"},"devDependencies":{"@types/adm-zip":"0.5.0","@types/cli-progress":"^3.11.0","@types/fs-extra":"^9.0.13","@types/mime":"^3.0.1","@types/node":"^18.11.18","@types/open":"^6.2.1","@types/prettyjson":"^0.0.30","@types/prompt-sync":"^4.2.0","@types/semver":"^7.3.13","@typescript-eslint/eslint-plugin":"5.53.0","@typescript-eslint/parser":"5.53.0","eslint":"8.35.0","eslint-config-airbnb-base":"^15.0.0","eslint-config-prettier":"^8.6.0","eslint-import-resolver-typescript":"3.5.3","eslint-plugin-import":"2.27.5","eslint-plugin-prettier":"^4.2.1","git-format-staged":"3.0.0","husky":"^8.0.3","nodemon":"2.0.20","pkg":"5.8.0","prettier":"2.8.4","ts-loader":"^9.4.2","ts-node":"^10.9.1","tsconfig-paths":"4.1.2","typescript":"4.9.5","webpack":"5.75.0","webpack-cli":"^5.0.1","webpack-node-externals":"^3.0.0"}}')}},n={};!function o(t){var i=n[t];if(void 0!==i)return i.exports;var a=n[t]={exports:{}};return e[t].call(a.exports,a,a.exports,o),a.exports}(1714)})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/cli",
3
- "version": "3.2.0",
3
+ "version": "3.4.0",
4
4
  "description": "A CLI to upload to capgo servers",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -44,6 +44,7 @@
44
44
  "dependencies": {
45
45
  "@capacitor/cli": "4.6.3",
46
46
  "@capgo/find-package-manager": "^0.0.7",
47
+ "@clack/prompts": "^0.6.1",
47
48
  "@supabase/supabase-js": "^2.5.0",
48
49
  "@tomasklaen/checksum": "^1.1.0",
49
50
  "@trufflesuite/spinnies": "^0.1.1",
@@ -55,6 +56,7 @@
55
56
  "get-latest-version": "^5.0.0",
56
57
  "logsnag": "^0.1.6",
57
58
  "mime": "^3.0.0",
59
+ "open": "^8.4.2",
58
60
  "prettyjson": "^1.2.5",
59
61
  "prompt-sync": "^4.2.0",
60
62
  "semver": "^7.3.8"
@@ -65,6 +67,7 @@
65
67
  "@types/fs-extra": "^9.0.13",
66
68
  "@types/mime": "^3.0.1",
67
69
  "@types/node": "^18.11.18",
70
+ "@types/open": "^6.2.1",
68
71
  "@types/prettyjson": "^0.0.30",
69
72
  "@types/prompt-sync": "^4.2.0",
70
73
  "@types/semver": "^7.3.13",
@@ -2,7 +2,8 @@ import { SupabaseClient } from '@supabase/supabase-js';
2
2
  import { program } from 'commander';
3
3
  import { Table } from 'console-table-printer';
4
4
  import { Database } from 'types/supabase.types';
5
- import { convertAppName, formatError, getHumanDate } from '../utils';
5
+ import * as p from '@clack/prompts';
6
+ import { formatError, getHumanDate } from '../utils';
6
7
 
7
8
  export const checkVersionNotUsedInChannel = async (supabase: SupabaseClient<Database>,
8
9
  appid: string, userId: string, versionData: Database['public']['Tables']['app_versions']['Row']) => {
@@ -15,11 +16,29 @@ export const checkVersionNotUsedInChannel = async (supabase: SupabaseClient<Data
15
16
  if (errorChannel)
16
17
  program.error(`Cannot check Version ${appid}@${versionData.name} ${formatError(errorChannel)}`);
17
18
  if (channelFound && channelFound.length > 0) {
18
- const appidWeb = convertAppName(appid)
19
- program.error(`❌ Version ${appid}@${versionData.name} is used in channel ${channelFound[0].name}, unlink it first:
20
- https://web.capgo.app/app/p/${appidWeb}/channel/${channelFound[0].id}
21
- Click on top right button and unlink.
22
- ${formatError(errorChannel)}`);
19
+ p.intro(`❌ Version ${appid}@${versionData.name} is used in ${channelFound.length} channel`)
20
+ if (await p.confirm({ message: 'unlink it?' })) {
21
+ // loop on all channels and set version to unknown
22
+ for (const channel of channelFound) {
23
+ const s = p.spinner();
24
+ s.start(`Unlinking channel ${channel.name}`)
25
+ const { error: errorChannelUpdate } = await supabase
26
+ .from('channels')
27
+ .update({
28
+ version: (await findUnknownVersion(supabase, appid))?.id
29
+ })
30
+ .eq('id', channel.id)
31
+ if (errorChannelUpdate) {
32
+ s.stop(`Cannot update channel ${channel.name} ${formatError(errorChannelUpdate)}`)
33
+ process.exit(1)
34
+ }
35
+ s.stop(`✅ Channel ${channel.name} unlinked`)
36
+ }
37
+ }
38
+ else {
39
+ program.error(`unlink it first`);
40
+ }
41
+ p.outro(`Version unlinked from ${channelFound.length} channel`)
23
42
  }
24
43
  }
25
44
 
@@ -48,21 +67,21 @@ export const delChannel = (supabase: SupabaseClient<Database>, name: string, app
48
67
 
49
68
 
50
69
  export const displayChannels = (data: (Database['public']['Tables']['channels']['Row'] & { keep?: string })[]) => {
51
- const p = new Table({
70
+ const t = new Table({
52
71
  title: "Channels",
53
72
  charLength: { "❌": 2, "✅": 2 },
54
73
  });
55
74
 
56
75
  // add rows with color
57
76
  data.reverse().forEach(row => {
58
- p.addRow({
77
+ t.addRow({
59
78
  Name: row.name,
60
79
  Created: getHumanDate(row.created_at),
61
80
  Public: row.public ? '✅' : '❌'
62
81
  });
63
82
  });
64
83
 
65
- p.printTable();
84
+ t.printTable();
66
85
  }
67
86
 
68
87
  export const getActiveChannels = async (supabase: SupabaseClient<Database>, appid: string, userId: string) => {
@@ -1,10 +1,12 @@
1
1
  import { SupabaseClient } from '@supabase/supabase-js';
2
2
  import { program } from 'commander';
3
3
  import { Database } from 'types/supabase.types';
4
- import { convertAppName, formatError } from '../utils';
4
+ import * as p from '@clack/prompts';
5
+ import { formatError } from '../utils';
5
6
 
6
7
  export const checkVersionNotUsedInDeviceOverride = async (supabase: SupabaseClient<Database>,
7
8
  appid: string, versionData: Database['public']['Tables']['app_versions']['Row']) => {
9
+
8
10
  const { data: deviceFound, error: errorDevice } = await supabase
9
11
  .from('devices_override')
10
12
  .select()
@@ -13,9 +15,25 @@ export const checkVersionNotUsedInDeviceOverride = async (supabase: SupabaseClie
13
15
  if (errorDevice)
14
16
  program.error(`Cannot check Device override ${appid}@${versionData.name} ${formatError(errorDevice)}`);
15
17
  if (deviceFound && deviceFound.length > 0) {
16
- const appidWeb = convertAppName(appid)
17
- program.error(`❌ Version ${appid} @${versionData.name} is used in a device override, unlink it first:
18
- https://web.capgo.app/app/p/${appidWeb}/d/${deviceFound[0].device_id}
19
- ${formatError(errorDevice)}`);
18
+ p.intro(`❌ Version ${appid}@${versionData.name} is used in ${deviceFound.length} device override`)
19
+ if (await p.confirm({ message: 'unlink it?' })) {
20
+ // loop on all devices and set version to unknown
21
+ for (const device of deviceFound) {
22
+ const s = p.spinner();
23
+ s.start(`Unlinking device ${device.device_id}`)
24
+ const { error: errorDeviceDel } = await supabase
25
+ .from('devices_override')
26
+ .delete()
27
+ .eq('device_id', device.device_id)
28
+ if (errorDeviceDel) {
29
+ s.stop(`Cannot unlink device ${device.device_id} ${formatError(errorDeviceDel)}`)
30
+ process.exit(1)
31
+ }
32
+ s.stop(`✅ Device ${device.device_id} unlinked`)
33
+ }
34
+ }
35
+ else {
36
+ program.error(`unlink it first`);
37
+ }
20
38
  }
21
39
  }
@@ -0,0 +1,64 @@
1
+ import { program } from 'commander';
2
+ import { getVersionData } from 'api/versions';
3
+ import { checkVersionNotUsedInDeviceOverride } from '../api/devices_override';
4
+ import { checkVersionNotUsedInChannel } from '../api/channels';
5
+ import { OptionsBase } from '../api/utils';
6
+ import { checkAppExistsAndHasPermissionErr } from "../api/app";
7
+ import {
8
+ getConfig, createSupabaseClient,
9
+ formatError, findSavedKey, checkPlanValid, useLogSnag, verifyUser
10
+ } from '../utils';
11
+
12
+ interface Options extends OptionsBase {
13
+ bundle?: string
14
+ }
15
+
16
+ export const unlinkDevice = async (channel: string, appId: string, options: Options) => {
17
+ options.apikey = options.apikey || findSavedKey()
18
+ const config = await getConfig();
19
+ appId = appId || config?.app?.appId
20
+ const snag = useLogSnag()
21
+ let { bundle } = options;
22
+
23
+ bundle = bundle || config?.app?.package?.version
24
+
25
+ if (!options.apikey) {
26
+ program.error("Missing API key, you need to provide a API key to upload your bundle");
27
+ }
28
+ if (!appId) {
29
+ program.error("Missing argument, you need to provide a appId, or be in a capacitor project");
30
+ }
31
+ if (!bundle) {
32
+ program.error("Missing argument, you need to provide a bundle, or be in a capacitor project");
33
+ }
34
+ const supabase = createSupabaseClient(options.apikey)
35
+
36
+ const userId = await verifyUser(supabase, options.apikey, ['write', 'all']);
37
+ // Check we have app access to this appId
38
+ await checkAppExistsAndHasPermissionErr(supabase, appId, options.apikey);
39
+
40
+ if (!channel) {
41
+ program.error("Missing argument, you need to provide a channel");
42
+ }
43
+ try {
44
+ await checkPlanValid(supabase, userId)
45
+
46
+ const versionData = await getVersionData(supabase, appId, userId, bundle);
47
+ await checkVersionNotUsedInChannel(supabase, appId, userId, versionData);
48
+ await checkVersionNotUsedInDeviceOverride(supabase, appId, versionData);
49
+ await snag.publish({
50
+ channel: 'bundle',
51
+ event: 'Unlink bundle',
52
+ icon: '✅',
53
+ tags: {
54
+ 'user-id': userId,
55
+ 'app-id': appId,
56
+ },
57
+ notify: false,
58
+ }).catch()
59
+ } catch (err) {
60
+ program.error(`Unknow error ${formatError(err)}`);
61
+ }
62
+ console.log(`Done ✅`);
63
+ process.exit()
64
+ }
@@ -40,7 +40,7 @@ export const addChannel = async (channelId: string, appId: string, options: Opti
40
40
  });
41
41
  console.log(`Channel created ✅`);
42
42
  await snag.publish({
43
- channel: 'app',
43
+ channel: 'channel',
44
44
  event: 'Create channel',
45
45
  icon: '✅',
46
46
  tags: {
@@ -27,7 +27,7 @@ export const deleteChannel = async (channelId: string, appId: string, options: O
27
27
  await delChannel(supabase, channelId, appId, userId);
28
28
  console.log(`Channel Delete ✅`);
29
29
  await snag.publish({
30
- channel: 'app',
30
+ channel: 'channel',
31
31
  event: 'Delete channel',
32
32
  icon: '✅',
33
33
  tags: {
@@ -2,12 +2,13 @@ import { program } from 'commander';
2
2
  import { checkAppExistsAndHasPermissionErr } from '../api/app';
3
3
  import { getActiveChannels, displayChannels } from '../api/channels';
4
4
  import { OptionsBase } from '../api/utils';
5
- import { findSavedKey, getConfig, createSupabaseClient, verifyUser } from '../utils';
5
+ import { findSavedKey, getConfig, createSupabaseClient, verifyUser, useLogSnag } from '../utils';
6
6
 
7
7
  export const listChannels = async (appId: string, options: OptionsBase) => {
8
8
  options.apikey = options.apikey || findSavedKey()
9
9
  const config = await getConfig();
10
10
  appId = appId || config?.app?.appId
11
+ const snag = useLogSnag()
11
12
 
12
13
  if (!options.apikey) {
13
14
  program.error("Missing API key, you need to provide a API key to upload your bundle");
@@ -32,6 +33,16 @@ export const listChannels = async (appId: string, options: OptionsBase) => {
32
33
  console.log(`Active channels in Capgo: ${allVersions?.length}`);
33
34
 
34
35
  displayChannels(allVersions);
36
+ await snag.publish({
37
+ channel: 'channel',
38
+ event: 'List channel',
39
+ icon: '✅',
40
+ tags: {
41
+ 'user-id': userId,
42
+ 'app-id': appId,
43
+ },
44
+ notify: false,
45
+ }).catch()
35
46
  console.log(`Done ✅`);
36
47
  process.exit()
37
48
  }
@@ -115,8 +115,8 @@ export const setChannel = async (channel: string, appId: string, options: Option
115
115
  program.error(`Cannot set channel ${formatError(e)}`);
116
116
  }
117
117
  await snag.publish({
118
- channel: 'app',
119
- event: 'Set app',
118
+ channel: 'channel',
119
+ event: 'Set channel',
120
120
  icon: '✅',
121
121
  tags: {
122
122
  'user-id': userId,
package/src/index.ts CHANGED
@@ -5,7 +5,7 @@ import { decryptZip } from './bundle/decrypt';
5
5
  import { encryptZip } from './bundle/encrypt';
6
6
  import { addCommand } from './app/add';
7
7
  import { getInfo } from './app/info';
8
- import { manageKey } from './key';
8
+ import { saveKeyCommand, createKeyCommand } from './key';
9
9
  import { deleteBundle } from './bundle/delete';
10
10
  import { setChannel } from './channel/set';
11
11
  import { uploadCommand } from './bundle/upload';
@@ -20,7 +20,7 @@ import { setApp } from './app/set';
20
20
  import { deleteApp } from './app/delete';
21
21
 
22
22
  program
23
- .description('Manage packages and bundle versions in capgo Cloud')
23
+ .description('Manage packages and bundle versions in Capgo Cloud')
24
24
  .version(pack.version);
25
25
 
26
26
  program
@@ -50,7 +50,7 @@ const app = program
50
50
  app
51
51
  .command('add [appid]')
52
52
  .alias('a')
53
- .description('Add a new app in capgo Cloud')
53
+ .description('Add a new app in Capgo Cloud')
54
54
  .action(addCommand)
55
55
  .option('-n, --name <name>', 'app name')
56
56
  .option('-i, --icon <icon>', 'app icon path')
@@ -59,21 +59,21 @@ app
59
59
  app
60
60
  .command('delete [appid]')
61
61
  .alias('d')
62
- .description('Delete an app in capgo Cloud')
62
+ .description('Delete an app in Capgo Cloud')
63
63
  .action(deleteApp)
64
64
  .option('-a, --apikey <apikey>', 'apikey to link to your account');
65
65
 
66
66
  app
67
67
  .command('list [appid]')
68
68
  .alias('l')
69
- .description('list apps in capgo Cloud')
69
+ .description('list apps in Capgo Cloud')
70
70
  .action(listApp)
71
71
  .option('-a, --apikey <apikey>', 'apikey to link to your account');
72
72
 
73
73
  app
74
74
  .command('set [appid]')
75
75
  .alias('s')
76
- .description('Set an app in capgo Cloud')
76
+ .description('Set an app in Capgo Cloud')
77
77
  .action(setApp)
78
78
  .option('-n, --name <name>', 'app name')
79
79
  .option('-i, --icon <icon>', 'app icon path')
@@ -86,37 +86,45 @@ const bundle = program
86
86
  bundle
87
87
  .command('upload [appid]')
88
88
  .alias('u')
89
- .description('Upload a new bundle in capgo Cloud')
89
+ .description('Upload a new bundle in Capgo Cloud')
90
90
  .action(uploadCommand)
91
91
  .option('-a, --apikey <apikey>', 'apikey to link to your account')
92
92
  .option('-p, --path <path>', 'path of the folder to upload')
93
93
  .option('-c, --channel <channel>', 'channel to link to')
94
- .option('-e, --external <url>', 'link to external url intead of upload to capgo cloud')
94
+ .option('-e, --external <url>', 'link to external url intead of upload to Capgo Cloud')
95
95
  .option('--key <key>', 'custom path for public signing key')
96
96
  .option('--keyData <keyData>', 'base64 public signing key')
97
97
  .option('--no-key', 'ignore signing key and send clear update')
98
98
  .option('--display-iv-session', 'Show in the console the iv and session key used to encrypt the update')
99
- .option('-b, --bundle <bundle>', 'bundle version number of the file to upload');
99
+ .option('-b, --bundle <bundle>', 'bundle version number of the bundle to upload');
100
100
 
101
101
  bundle
102
102
  .command('delete [appid]')
103
103
  .alias('d')
104
- .description('Delete a bundle in capgo Cloud')
104
+ .description('Delete a bundle in Capgo Cloud')
105
105
  .action(deleteBundle)
106
106
  .option('-a, --apikey <apikey>', 'apikey to link to your account')
107
107
 
108
108
  bundle
109
109
  .command('list [appid]')
110
110
  .alias('l')
111
- .description('List bundle in capgo Cloud')
111
+ .description('List bundle in Capgo Cloud')
112
112
  .action(listBundle)
113
113
  .option('-a, --apikey <apikey>', 'apikey to link to your account');
114
114
 
115
+ bundle
116
+ .command('unlink [appid]')
117
+ .alias('u')
118
+ .description('Unlink a bundle in Capgo Cloud')
119
+ .action(listBundle)
120
+ .option('-a, --apikey <apikey>', 'apikey to link to your account')
121
+ .option('-b, --bundle <bundle>', 'bundle version number of the bundle to unlink');
122
+
115
123
  bundle
116
124
  .command('cleanup [appid]')
117
125
  .alias('c')
118
126
  .action(cleanupBundle)
119
- .description('Cleanup bundle in capgo Cloud')
127
+ .description('Cleanup bundle in Capgo Cloud')
120
128
  .option('-b, --bundle <bundle>', 'bundle version number of the app to delete')
121
129
  .option('-a, --apikey <apikey>', 'apikey to link to your account')
122
130
  .option('-k, --keep <keep>', 'number of version to keep')
@@ -180,21 +188,31 @@ channel
180
188
  .option('--self-assign', 'Allow to device to self assign to this channel')
181
189
  .option('--no-self-assign', 'Disable devices to self assign to this channel');
182
190
 
183
- program
184
- .command('key [option]')
191
+ const key = program
192
+ .command('key')
193
+ .description('Manage key');
194
+
195
+ key
196
+ .command('save')
185
197
  .description('Save base64 signing key in capacitor config, usefull for CI')
186
- .action(manageKey)
198
+ .action(saveKeyCommand)
199
+ .option('-f, --force', 'force generate a new one');
200
+
201
+ key
202
+ .command('create')
203
+ .description('Create a new signing key')
204
+ .action(createKeyCommand)
187
205
  .option('-f, --force', 'force generate a new one');
188
206
 
189
207
  program
190
208
  .command('upload [appid]')
191
209
  .alias('u')
192
- .description('(Deprecated) Upload a new bundle to capgo Cloud')
210
+ .description('(Deprecated) Upload a new bundle to Capgo Cloud')
193
211
  .action(uploadCommand)
194
212
  .option('-a, --apikey <apikey>', 'apikey to link to your account')
195
213
  .option('-p, --path <path>', 'path of the folder to upload')
196
214
  .option('-c, --channel <channel>', 'channel to link to')
197
- .option('-e, --external <url>', 'link to external url intead of upload to capgo cloud')
215
+ .option('-e, --external <url>', 'link to external url intead of upload to Capgo Cloud')
198
216
  .option('--key <key>', 'custom path for public signing key')
199
217
  .option('--keyData <keyData>', 'base64 public signing key')
200
218
  .option('--no-key', 'ignore signing key and send clear update')
package/src/init.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { writeFileSync, readFileSync } from 'fs';
2
2
  import { findPackageManagerType } from '@capgo/find-package-manager'
3
3
  import { execSync } from 'child_process';
4
+ import * as p from '@clack/prompts';
5
+ import { createKey } from './key';
4
6
  import { addChannel } from './channel/add';
5
7
  import { uploadBundle } from './bundle/upload';
6
8
  import { login } from './login';
@@ -23,97 +25,133 @@ export const initApp = async (apikey: string, appId: string, options: SuperOptio
23
25
  const config = await getConfig();
24
26
  appId = appId || config?.app?.appId
25
27
 
26
- const pm = findPackageManagerType();
27
- if (pm === 'unknown') {
28
- console.log(`Cannot reconize package manager, please run \`capgo init\` in a capacitor project with npm, pnpm or yarn`)
29
- process.exit()
30
- }
31
- const mainFilePath = await findMainFile();
32
- const pack = JSON.parse(readFileSync('package.json').toString());
33
- // check in script build exist
34
- if (!pack.scripts?.build) {
35
- console.log(`Cannot find build script in package.json, please add it and run \`capgo init\` again`)
36
- process.exit()
37
- }
28
+ p.intro(`Capgo init`);
38
29
 
39
- console.log(`Running: npx @capgo/cli@latest login ***`);
30
+ const log = p.spinner();
31
+ log.start('Running: npx @capgo/cli@latest login ***');
40
32
  const loginRes = await login(apikey, options, false);
41
33
  if (!loginRes) {
42
- console.log(`Login already done ✅`);
34
+ log.stop('Login already done ✅');
43
35
  } else {
44
- console.log(`Login Done ✅`);
36
+ log.stop('Login Done ✅');
45
37
  }
46
38
 
47
- console.log(`Running: npx @capgo/cli@latest app add ${appId}`);
48
- const addRes = await addApp(appId, options, false);
49
- if (!addRes) {
50
- console.log(`App already add ✅`);
51
- } else {
52
- console.log(`App add Done ✅`);
39
+ if (await p.confirm({ message: `Add ${appId} in Capgo?` })) {
40
+ const s = p.spinner();
41
+ s.start(`Running: npx @capgo/cli@latest app add ${appId}`);
42
+ const addRes = await addApp(appId, options, false);
43
+ if (!addRes) {
44
+ s.stop(`App already add ✅`);
45
+ } else {
46
+ s.stop(`App add Done ✅`);
47
+ }
53
48
  }
54
49
 
55
- // create production channel public
56
- console.log(`Running: npx @capgo/cli@latest channel add ${defaultChannel} ${appId} -d`);
57
- const addChannelRes = await addChannel(defaultChannel, appId, {
58
- default: true,
59
- apikey,
60
- }, false);
61
- if (!addChannelRes) {
62
- console.log(`Channel already added ✅`);
63
- } else {
64
- console.log(`Channel add Done ✅`);
50
+ if (await p.confirm({ message: `Create channel ${defaultChannel} in Capgo?` })) {
51
+ const s = p.spinner();
52
+ // create production channel public
53
+ s.start(`Running: npx @capgo/cli@latest channel add ${defaultChannel} ${appId} -d`);
54
+ const addChannelRes = await addChannel(defaultChannel, appId, {
55
+ default: true,
56
+ apikey,
57
+ }, false);
58
+ if (!addChannelRes) {
59
+ s.stop(`Channel already added ✅`);
60
+ } else {
61
+ s.stop(`Channel add Done ✅`);
62
+ }
65
63
  }
66
64
 
67
- // // use pm to install capgo
68
- // // run command pm install @capgo/capacitor-updater@latest
69
- const installCmd = pm === 'yarn' ? 'add' : 'install'
70
- // check if capgo is already installed in package.json
71
- if (pack.dependencies['@capgo/capacitor-updater']) {
72
- console.log(`Capgo already installed ✅`)
73
- }
74
- else {
75
- const res = await execSync(`${pm} ${installCmd} @capgo/capacitor-updater@latest`)
76
- console.log(res.toString())
77
- console.log(`Install Done ✅`);
65
+ if (await p.confirm({ message: 'Install @capgo/capacitor-updater ?' })) {
66
+ const s = p.spinner();
67
+ s.start(`Checking if capgo is installed`);
68
+ const pack = JSON.parse(readFileSync('package.json').toString());
69
+ const pm = findPackageManagerType();
70
+ if (pm === 'unknown') {
71
+ s.stop(`Cannot reconize package manager, please run \`capgo init\` in a capacitor project with npm, pnpm or yarn`)
72
+ process.exit()
73
+ }
74
+ // // use pm to install capgo
75
+ // // run command pm install @capgo/capacitor-updater@latest
76
+ const installCmd = pm === 'yarn' ? 'add' : 'install'
77
+ // check if capgo is already installed in package.json
78
+ if (pack.dependencies['@capgo/capacitor-updater']) {
79
+ s.stop(`Capgo already installed ✅`)
80
+ }
81
+ else {
82
+ await execSync(`${pm} ${installCmd} @capgo/capacitor-updater@latest`)
83
+ s.stop(`Install Done ✅`);
84
+ }
78
85
  }
79
86
 
80
- // open main file and inject codeInject
81
- const mainFile = readFileSync(mainFilePath);
82
- // find the last import line in the file and inject codeInject after it
83
- const mainFileContent = mainFile.toString();
84
- const matches = mainFileContent.match(regexImport);
85
- const last = matches?.pop();
86
- if (!last) {
87
- console.log(`Cannot find import line in main file, use manual installation: https://docs.capgo.app/installation`)
88
- process.exit()
89
- }
87
+ if (await p.confirm({ message: 'Add @capacitor-updater to your main file?' })) {
88
+ const s = p.spinner();
89
+ s.start(`Adding @capacitor-updater to your main file`);
90
+ const mainFilePath = await findMainFile();
91
+ if (!mainFilePath) {
92
+ s.stop('No main.ts, main.js, index.ts or index.js file found, please run cap init first');
93
+ process.exit()
94
+ }
95
+ // open main file and inject codeInject
96
+ const mainFile = readFileSync(mainFilePath);
97
+ // find the last import line in the file and inject codeInject after it
98
+ const mainFileContent = mainFile.toString();
99
+ const matches = mainFileContent.match(regexImport);
100
+ const last = matches?.pop();
101
+ if (!last) {
102
+ s.stop(`Cannot find import line in main file, use manual installation: https://docs.capgo.app/installation`)
103
+ process.exit()
104
+ }
90
105
 
91
- if (mainFileContent.includes(codeInject)) {
92
- console.log(`Code already added to ${mainFilePath} ✅`)
93
- } else {
94
- const newMainFileContent = mainFileContent.replace(last, `${last}\n${importInject}\n\n${codeInject}\n`)
95
- writeFileSync(mainFilePath, newMainFileContent);
96
- console.log(`Code added to ${mainFilePath} ✅`);
106
+ if (mainFileContent.includes(codeInject)) {
107
+ s.stop(`Code already added to ${mainFilePath} ✅`)
108
+ } else {
109
+ const newMainFileContent = mainFileContent.replace(last, `${last}\n${importInject}\n\n${codeInject}\n`)
110
+ writeFileSync(mainFilePath, newMainFileContent);
111
+ s.stop(`Code added to ${mainFilePath} ✅`);
112
+ }
97
113
  }
98
114
 
99
- console.log(`Running: npm run build && npx cap sync`);
100
- const res2 = await execSync(`npm run build && npx cap sync`)
101
- console.log(res2.toString())
102
- console.log(`Build & Sync Done ✅`);
103
115
 
104
- console.log(`Running: npx @capgo/cli@latest bundle upload`);
105
- const uploadRes = await uploadBundle(appId, {
106
- channel: defaultChannel,
107
- apikey,
108
- }, false);
109
- if (!uploadRes) {
110
- console.log(`Upload failed ❌`);
111
- process.exit()
112
- } else {
113
- console.log(`Upload Done ✅`);
116
+ if (await p.confirm({ message: 'Use end-to-end encryption?' })) {
117
+ const s = p.spinner();
118
+ s.start(`Running: npx @capgo/cli@latest key create`);
119
+ const keyRes = await createKey({}, false);
120
+ if (!keyRes) {
121
+ s.stop(`Cannot create key ❌`);
122
+ process.exit(1)
123
+ } else {
124
+ s.stop(`key created 🔑`);
125
+ }
126
+ }
127
+ if (await p.confirm({ message: 'Build the project?' })) {
128
+ const s = p.spinner();
129
+ s.start(`Running: npm run build && npx cap sync`);
130
+ const pack = JSON.parse(readFileSync('package.json').toString());
131
+ // check in script build exist
132
+ if (!pack.scripts?.build) {
133
+ s.stop(`Cannot find build script in package.json, please add it and run \`capgo init\` again`)
134
+ process.exit()
135
+ }
136
+ await execSync(`npm run build && npx cap sync`)
137
+ s.stop(`Build & Sync Done ✅`);
114
138
  }
115
139
 
116
- console.log(`Init Done ✅`);
140
+ if (await p.confirm({ message: 'Upload the bundle?' })) {
141
+ const s = p.spinner();
142
+ s.start(`Running: npx @capgo/cli@latest bundle upload`);
143
+ const uploadRes = await uploadBundle(appId, {
144
+ channel: defaultChannel,
145
+ apikey,
146
+ }, false);
147
+ if (!uploadRes) {
148
+ s.stop(`Upload failed ❌`);
149
+ process.exit()
150
+ } else {
151
+ s.stop(`Upload Done ✅`);
152
+ }
153
+ }
154
+ p.outro(`You're all set ✅!`);
117
155
  console.log(`Now run the app in your phone or emulator with: npx cap run`)
118
156
  const appIdUrl = appId.replace(/\./g, '--')
119
157
  console.log(`Then watch logs in https://web.capgo.app/app/p/${appIdUrl}/logs`)
package/src/key.ts CHANGED
@@ -5,13 +5,15 @@ import { createRSA } from './api/crypto';
5
5
  import { baseKey, baseKeyPub, getConfig } from './utils';
6
6
  import { checkLatest } from './api/update';
7
7
 
8
- interface Options {
9
- force?: boolean;
8
+ interface saveOptions {
10
9
  key?: string
11
10
  keyData?: string
12
11
  }
12
+ interface Options {
13
+ force?: boolean;
14
+ }
13
15
 
14
- const saveKey = async (privateKeyPath: string | undefined, privateKeyData: string | undefined) => {
16
+ export const saveKey = async (options: saveOptions, log = true) => {
15
17
  if (!existsSync('.git')) {
16
18
  program.error('To use local you should be in a git repository');
17
19
  }
@@ -19,13 +21,17 @@ const saveKey = async (privateKeyPath: string | undefined, privateKeyData: strin
19
21
  const config = await getConfig();
20
22
  const { extConfig } = config.app;
21
23
 
22
- const keyPath = privateKeyPath || baseKey
24
+ const keyPath = options.key || baseKey
23
25
  // check if publicKey exist
24
26
 
25
- let privateKey = privateKeyData || "";
27
+ let privateKey = options.keyData || "";
26
28
 
27
29
  if (!existsSync(keyPath) && !privateKey) {
28
- program.error(`Cannot find public key ${keyPath} or as keyData option or in ${config.app.extConfigFilePath}`)
30
+ if (log) {
31
+ program.error(`Cannot find public key ${keyPath} or as keyData option or in ${config.app.extConfigFilePath}`)
32
+ } else {
33
+ return false
34
+ }
29
35
  } else if (existsSync(keyPath)) {
30
36
  // open with fs publicKey path
31
37
  const keyFile = readFileSync(keyPath)
@@ -43,13 +49,18 @@ const saveKey = async (privateKeyPath: string | undefined, privateKeyData: strin
43
49
  // console.log('extConfig', extConfig)
44
50
  writeConfig(extConfig, config.app.extConfigFilePath)
45
51
  }
46
-
47
- console.log(`private key saved into ${config.app.extConfigFilePath} file in local directory`);
48
- console.log(`your app will decode the zip archive with this key\n`);
49
-
52
+ if (log) {
53
+ console.log(`private key saved into ${config.app.extConfigFilePath} file in local directory`);
54
+ console.log(`your app will decode the zip archive with this key\n`);
55
+ }
56
+ return true
57
+ }
58
+ export const saveKeyCommand = async (options: saveOptions) => {
59
+ await checkLatest();
60
+ await saveKey(options)
50
61
  }
51
62
 
52
- const createKey = async (options: Options) => {
63
+ export const createKey = async (options: Options, log = true) => {
53
64
  // write in file .capgo the apikey in home directory
54
65
 
55
66
  if (!existsSync('.git')) {
@@ -59,11 +70,19 @@ const createKey = async (options: Options) => {
59
70
 
60
71
  // check if baseName already exist
61
72
  if (existsSync(baseKeyPub) && !options.force) {
62
- program.error(`Public Key already exists, use --force to overwrite`);
73
+ if (log) {
74
+ program.error(`Public Key already exists, use --force to overwrite`);
75
+ } else {
76
+ return false
77
+ }
63
78
  }
64
79
  writeFileSync(baseKeyPub, publicKey);
65
80
  if (existsSync(baseKey) && !options.force) {
66
- program.error(`Private Key already exists, use --force to overwrite`);
81
+ if (log) {
82
+ program.error(`Private Key already exists, use --force to overwrite`);
83
+ } else {
84
+ return false
85
+ }
67
86
  }
68
87
  writeFileSync(baseKey, privateKey);
69
88
 
@@ -81,27 +100,18 @@ const createKey = async (options: Options) => {
81
100
  writeConfig(extConfig, config.app.extConfigFilePath)
82
101
  }
83
102
 
84
- console.log(`Your RSA key has been generated using node-rsa with this settings:\n
85
- - encryptionScheme 'pkcs1_oaep'.
86
- - signingScheme 'pkcs8-sha256'.
87
- - bits 2048.
88
- - exp 65537.\n`);
89
- console.log(`public key saved into ${baseKeyPub} file in local directory\n`);
90
- console.log(`This key will be use to encode your zipped bundle before sending it to Capgo,
91
- than make them unreadable by Capgo and unmodifiable by anyone\n`);
92
- console.log(`Private key saved into ${config.app.extConfigFilePath} file in local directory`);
93
- console.log(`Your app will decode with this key the zipped bundle\n`);
103
+ if (log) {
104
+ console.log(`Your RSA key has been generated\n`);
105
+ console.log(`public key saved into ${baseKeyPub} file in local directory\n`);
106
+ console.log(`This key will be use to encode AES key used to crypt your zipped bundle before sending it to Capgo,
107
+ than make them unreadable by Capgo and unmodifiable by anyone\n`);
108
+ console.log(`Private key saved into ${config.app.extConfigFilePath} file in local directory`);
109
+ console.log(`Your app will decode with this RSA key the AES key and use it to decode the zipped bundle\n`);
110
+ }
111
+ return true
94
112
  }
95
113
 
96
- export const manageKey = async (option: string, options: Options) => {
114
+ export const createKeyCommand = async (options: Options) => {
97
115
  await checkLatest();
98
- if (option === 'save') {
99
- saveKey(options.key, options.keyData);
100
- } else
101
- if (option === 'create') {
102
- createKey(options);
103
- } else {
104
- program.error('You should provide a valid option (create or save)');
105
- }
106
- process.exit()
107
- }
116
+ await createKey(options)
117
+ }
package/src/utils.ts CHANGED
@@ -7,6 +7,7 @@ import { homedir } from 'os';
7
7
  import { LogSnag } from 'logsnag';
8
8
  import { Database } from 'types/supabase.types';
9
9
  import { resolve } from 'path';
10
+ import open from 'open';
10
11
 
11
12
  export const baseKey = '.capgo_key';
12
13
  export const baseKeyPub = `${baseKey}.pub`;
@@ -88,7 +89,11 @@ export const isAllowedAction = async (supabase: SupabaseClient<Database>, userId
88
89
  export const checkPlanValid = async (supabase: SupabaseClient<Database>, userId: string, warning = true) => {
89
90
  const validPlan = await isAllowedAction(supabase, userId)
90
91
  if (!validPlan) {
91
- program.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${hostWeb}/dashboard/settings/plans\n`);
92
+ console.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${hostWeb}/dashboard/settings/plans\n`);
93
+ setTimeout(() => {
94
+ open(`${hostWeb}/dashboard/settings/plans`)
95
+ program.error('')
96
+ }, 1000)
92
97
  }
93
98
  const trialDays = await isTrial(supabase, userId)
94
99
  if (trialDays > 0 && warning) {
@@ -144,8 +149,6 @@ export const findMainFile = async () => {
144
149
  break
145
150
  }
146
151
  }
147
- if (!mainFile)
148
- program.error('No main.ts, main.js, index.ts or index.js file found, please run cap init first');
149
152
  return mainFile
150
153
  }
151
154