@capgo/cli 3.14.61 → 3.14.65

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,19 @@
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.14.65](https://github.com/Cap-go/capgo-cli/compare/v3.14.64...v3.14.65) (2024-02-08)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * lint issue ([28d026a](https://github.com/Cap-go/capgo-cli/commit/28d026a50e366a13b6f866784a4655c8ba6cc6c0))
11
+
12
+ ### [3.14.64](https://github.com/Cap-go/capgo-cli/compare/v3.14.63...v3.14.64) (2024-02-06)
13
+
14
+ ### [3.14.63](https://github.com/Cap-go/capgo-cli/compare/v3.14.62...v3.14.63) (2024-02-02)
15
+
16
+ ### [3.14.62](https://github.com/Cap-go/capgo-cli/compare/v3.14.61...v3.14.62) (2024-02-01)
17
+
5
18
  ### [3.14.61](https://github.com/Cap-go/capgo-cli/compare/v3.14.60...v3.14.61) (2024-01-22)
6
19
 
7
20
  ### [3.14.60](https://github.com/Cap-go/capgo-cli/compare/v3.14.59...v3.14.60) (2024-01-15)
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- (()=>{"use strict";var e={3018:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.newIconPath=o.checkAppExistsAndHasPermissionOrgErr=o.checkAppExistsAndHasPermissionErr=o.checkAppExists=void 0;const l=r(n(552)),s=n(7304),c=n(2170);o.checkAppExists=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("exist_app_v2",{appid:o}).single();return!!n})),o.checkAppExistsAndHasPermissionErr=(e,n,t,i=!0)=>a(void 0,void 0,void 0,(function*(){const r=yield(0,o.checkAppExists)(e,t),a=yield(0,c.isAllowedApp)(e,n,t);r&&!i&&(l.log.error(`App ${t} already exist`),s.program.error("")),!r&&i&&(l.log.error(`App ${t} does not exist`),s.program.error("")),r&&!a&&(l.log.error(`App ${t} exist and you don't have permission to access it`),s.program.error(""))})),o.checkAppExistsAndHasPermissionOrgErr=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield(0,c.isAllowedAppOrg)(e,o,n);if(!i.okay)switch(i.error){case"INVALID_APIKEY":l.log.error("Invalid apikey, such apikey does not exists!"),s.program.error("");break;case"NO_APP":l.log.error(`App ${n} does not exist`),s.program.error("");break;case"NO_ORG":l.log.error("Could not find organization, please contact support to resolve this!"),s.program.error("")}const r=i.data;return t>r&&(l.log.error(`Insuficcent permissions for app ${n}. Current permission: ${c.OrganizationPerm[i.data]}, required for this action: ${c.OrganizationPerm[t]}.`),s.program.error("")),i.data})),o.newIconPath="assets/icon.png"},7175:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((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 l=n(7304),s=n(3847),c=r(n(552)),d=n(2170);o.checkVersionNotUsedInChannel=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){var r;const{data:a,error:s}=yield e.from("channels").select().eq("app_id",n).eq("created_by",t).eq("version",i.id);if(s&&(c.log.error(`Cannot check Version ${n}@${i.name}`),l.program.error("")),a&&a.length>0){if(c.intro(`❌ Version ${n}@${i.name} is used in ${a.length} channel`),yield c.confirm({message:"unlink it?"}))for(const t of a){const i=c.spinner();i.start(`Unlinking channel ${t.name}`);const{error:a}=yield e.from("channels").update({version:null===(r=yield(0,o.findUnknownVersion)(e,n))||void 0===r?void 0:r.id}).eq("id",t.id);a&&(i.stop(`Cannot update channel ${t.name} ${(0,d.formatError)(a)}`),process.exit(1)),i.stop(`✅ Channel ${t.name} unlinked`)}else c.log.error("Unlink it first"),l.program.error("");c.outro(`Version unlinked from ${a.length} channel`)}})),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 s.Table({title:"Channels",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,Created:(0,d.getHumanDate)(e.created_at),Public:e.public?"✅":"❌"})})),c.log.success(o.render())},o.getActiveChannels=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select().eq("app_id",o).order("created_at",{ascending:!1});return t&&(c.log.error(`App ${o} not found in database`),l.program.error("")),n}))},3043:(e,o,n)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createRSA=o.encryptSource=o.decryptSource=void 0;const t=n(6113),i="aes-128-cbc",r="sha256",a="base64",l=t.constants.RSA_PKCS1_OAEP_PADDING;o.decryptSource=(e,o,n)=>{const[s,c]=o.split(":"),d=(0,t.privateDecrypt)({key:n,padding:l,oaepHash:r},Buffer.from(c,a)),p=Buffer.from(s,a),u=(0,t.createDecipheriv)(i,d,p);return u.setAutoPadding(!0),Buffer.concat([u.update(e),u.final()])},o.encryptSource=(e,o)=>{const n=(0,t.randomBytes)(16),s=(0,t.randomBytes)(16),c=(0,t.createCipheriv)(i,s,n);c.setAutoPadding(!0);const d=`${n.toString(a)}:${(0,t.publicEncrypt)({key:o,padding:l,oaepHash:r},s).toString(a)}`;return{encryptedData:Buffer.concat([c.update(e),c.final()]),ivSessionKey:d}},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"})}}},1915:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.checkVersionNotUsedInDeviceOverride=void 0;const l=n(7304),s=r(n(552)),c=n(2170);o.checkVersionNotUsedInDeviceOverride=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("devices_override").select().eq("app_id",o).eq("version",n.id);if(i&&(s.log.error(`Cannot check Device override ${o}@${n.name}`),l.program.error("")),t&&t.length>0)if(s.intro(`❌ Version ${o}@${n.name} is used in ${t.length} device override`),yield s.confirm({message:"unlink it?"}))for(const o of t){const n=s.spinner();n.start(`Unlinking device ${o.device_id}`);const{error:t}=yield e.from("devices_override").delete().eq("device_id",o.device_id);t&&(n.stop(`Cannot unlink device ${o.device_id} ${(0,c.formatError)(t)}`),process.exit(1)),n.stop(`✅ Device ${o.device_id} unlinked`)}else s.log.error("Unlink it first"),l.program.error("")}))},9740:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkLatest=void 0;const s=l(n(5362)),c=r(n(552)),d=l(n(4147));o.checkLatest=()=>a(void 0,void 0,void 0,(function*(){const e=yield(0,s.default)("@capgo/cli");e!==d.default.version&&c.log.warning(`🚨 You are using @capgo/cli@${d.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.`)}))},1820:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.getVersionData=o.getChannelsVersion=o.getActiveAppVersions=o.displayBundles=o.deleteSpecificVersion=o.deleteAppVersion=void 0;const l=n(7304),s=n(3847),c=r(n(552)),d=n(2170),p=n(7175),u=n(1915);o.deleteAppVersion=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const{error:i}=yield e.from("app_versions").update({deleted:!0}).eq("app_id",o).eq("deleted",!1).eq("user_id",n).eq("name",t);i&&(c.log.error(`App Version ${o}@${t} not found in database`),l.program.error(""))})),o.deleteSpecificVersion=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){const r=yield(0,o.getVersionData)(e,n,t,i);yield(0,p.checkVersionNotUsedInChannel)(e,n,t,r),yield(0,u.checkVersionNotUsedInDeviceOverride)(e,n,r),yield(0,o.deleteAppVersion)(e,n,t,i)})),o.displayBundles=e=>{const o=new s.Table({title:"Bundles",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow(Object.assign({Version:e.name,Created:(0,d.getHumanDate)(e.created_at)},null!=e.keep?{Keep:e.keep}:{}))})),c.log.success(o.render())},o.getActiveAppVersions=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("deleted",!1).order("created_at",{ascending:!1});return i&&(c.log.error(`App ${o} not found in database`),l.program.error("")),t})),o.getChannelsVersion=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select("version").eq("app_id",o);return t&&(c.log.error(`App ${o} not found in database`),l.program.error("")),n.map((e=>e.version))})),o.getVersionData=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const{data:i,error:r}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("name",t).eq("deleted",!1).single();return i&&!r||(c.log.error(`App Version ${o}@${t} doesn't exist`),l.program.error("")),i}))},2622:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addCommand=o.addApp=void 0;const l=n(6113),s=n(9011),c=n(7304),d=r(n(552)),p=n(7561),u=n(9740),f=n(3018),g=n(2170);o.addApp=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){var t,i,r;n&&d.intro("Adding"),yield(0,u.checkLatest)(),o.apikey=o.apikey||(0,g.findSavedKey)();const a=yield(0,g.getConfig)();e=e||(null===(t=null==a?void 0:a.app)||void 0===t?void 0:t.appId);const y=(0,g.useLogSnag)();o.apikey||(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),e||(d.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),c.program.error(""));const v=yield(0,g.createSupabaseClient)(o.apikey),h=yield(0,g.verifyUser)(v,o.apikey,["write","all"]),m=yield(0,f.checkAppExists)(v,e);if(n&&m)d.log.error(`App ${e} already exist`),c.program.error("");else if(m)return!0;let b,_,{name:k,icon:w}=o;e=e||(null===(i=null==a?void 0:a.app)||void 0===i?void 0:i.appId),k=k||(null===(r=null==a?void 0:a.app)||void 0===r?void 0:r.appName)||"Unknown",w=w||"resources/icon.png",w&&k||(d.log.error("Missing argument, you need to provide a appId and a name, or be in a capacitor project"),c.program.error("")),n&&d.log.info(`Adding ${e} to Capgo`),w&&(0,p.existsSync)(w)?(b=(0,p.readFileSync)(w),_=(0,s.getType)(w)||"image/png",d.log.warn(`Found app icon ${w}`)):(0,p.existsSync)(f.newIconPath)?(b=(0,p.readFileSync)(f.newIconPath),_=(0,s.getType)(f.newIconPath)||"image/png",d.log.warn(`Found app icon ${f.newIconPath}`)):d.log.warn(`Cannot find app icon in any of the following locations: ${w}, ${f.newIconPath}`);const C=`icon_${(0,l.randomUUID)()}`;let O="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(b&&_){const{error:o}=yield v.storage.from(`images/${h}/${e}`).upload(C,b,{contentType:_});o&&(d.log.error(`Could not add app ${(0,g.formatError)(o)}`),c.program.error(""));const{data:n}=yield v.storage.from(`images/${h}/${e}`).getPublicUrl(C);O=(null==n?void 0:n.publicUrl)||O}const{error:P}=yield v.from("apps").insert({icon_url:O,user_id:h,name:k,app_id:e});P&&(d.log.error(`Could not add app ${(0,g.formatError)(P)}`),c.program.error(""));const{error:x}=yield v.from("app_versions").insert([{user_id:h,deleted:!0,name:"unknown",app_id:e},{user_id:h,deleted:!0,name:"builtin",app_id:e}]);return x&&(d.log.error(`Could not add app ${(0,g.formatError)(x)}`),c.program.error("")),yield y.track({channel:"app",event:"App Added",icon:"🎉",user_id:h,tags:{"app-id":e},notify:!1}).catch(),d.log.success(`App ${e} added to Capgo. ${n?"You can upload a bundle now":""}`),n&&(d.outro("Done ✅"),process.exit()),!0})),o.addCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){(0,o.addApp)(e,n,!0)}))},3713:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.debugApp=o.waitLog=o.getStats=o.cancelCommand=o.markSnag=void 0;const l=r(n(552)),s=n(7304),c=n(3018),d=n(9740),p=n(2170),u=e=>new Promise((o=>{setTimeout(o,e)}));function f(e,o){return a(this,void 0,void 0,(function*(){try{const n=(yield e.functions.invoke("get_stats",{body:JSON.stringify(o)})).data.data;if((null==n?void 0:n.length)>0)return n[0]}catch(e){l.log.error(`Cannot get stats ${JSON.stringify(e)}`)}return null}))}o.markSnag=(e,o,n,t,i="✅")=>a(void 0,void 0,void 0,(function*(){yield n.track({channel:e,event:t,icon:i,user_id:o,notify:!1}).catch()})),o.cancelCommand=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){l.isCancel(n)&&(yield(0,o.markSnag)(e,t,i,"canceled","🤷"),process.exit())})),o.getStats=f,o.waitLog=(e,n,t,i,r,s)=>a(void 0,void 0,void 0,(function*(){let a=!0,c=(new Date).toISOString();const d=(0,p.convertAppName)(t),g=`${(yield(0,p.getLocalConfig)()).hostWeb}/app/p/${d}`;yield(0,o.markSnag)(e,r,i,"Use waitlog");const y={appId:t,devicesId:s?[s]:void 0,order:[{key:"created_at",sortable:"desc"}],rangeStart:0,rangeEnd:1,after:c};for(;a;){const t=yield f(n,y);if(t){if(l.log.info(`Log from Device: ${t.device_id}`),"get"===t.action)l.log.info("Update Sent your your device, wait until event download complete"),yield(0,o.markSnag)(e,r,i,"done");else if(t.action.startsWith("download_")){const n=t.action.split("_")[1];"complete"===n?(l.log.info("Your bundle has been downloaded on your device, background the app now and open it again to see the update"),yield(0,o.markSnag)(e,r,i,"downloaded")):"fail"===n?(l.log.error("Your bundle has failed to download on your device."),l.log.error("Please check if you have network connection and try again")):l.log.info(`Your bundle is downloading ${n}% ...`)}else{if("set"===t.action)return l.log.info("Your bundle has been set on your device ❤️"),a=!1,yield(0,o.markSnag)(e,r,i,"set"),Promise.resolve(t);"NoChannelOrOverride"===t.action?l.log.error(`No default channel or override (channel/device) found, please create it here ${g}`):"needPlanUpgrade"===t.action?l.log.error("Your are out of quota, please upgrade your plan here https://web.capgo.app/dashboard/settings/plans"):"missingBundle"===t.action?l.log.error("Your bundle is missing, please check how you build your app "):"noNew"===t.action?l.log.error(`Your version in ${t.platform} is the same as your version uploaded, change it to see the update`):"disablePlatformIos"===t.action?l.log.error(`iOS is disabled in the default channel and your device is an iOS device ${g}`):"disablePlatformAndroid"===t.action?l.log.error(`Android is disabled in the default channel and your device is an Android device ${g}`):"disableAutoUpdateToMajor"===t.action?(l.log.error("Auto update to major version is disabled in the default channel."),l.log.error("Set your app to the same major version as the default channel")):"disableAutoUpdateUnderNative"===t.action?(l.log.error("Auto update under native version is disabled in the default channel."),l.log.error("Set your app to the same native version as the default channel.")):"disableDevBuild"===t.action?(l.log.error(`Dev build is disabled in the default channel. ${g}`),l.log.error("Set your channel to allow it if you wanna test your app")):"disableEmulator"===t.action?(l.log.error(`Emulator is disabled in the default channel. ${g}`),l.log.error("Set your channel to allow it if you wanna test your app")):"cannotGetBundle"===t.action?(l.log.error(`We cannot get your bundle from the default channel. ${g}`),l.log.error("Are you sure your default channel has a bundle set?")):"set_fail"===t.action?l.log.error(`Your bundle seems to be corrupted, try to download from ${g} to identify the issue`):"reset"===t.action?l.log.error("Your device has been reset to the builtin bundle, did you added notifyAppReady in your code?"):"update_fail"===t.action?(l.log.error("Your bundle has been installed but failed to call notifyAppReady"),l.log.error("Please check if you have network connection and try again")):"checksum_fail"===t.action?l.log.error("Your bundle has failed to validate checksum, please check your code and send it again to Capgo"):l.log.error(`Log from Capgo ${t.action}`)}c=(new Date).toISOString(),y.after=c}yield u(1e3)}return Promise.resolve()})),o.debugApp=(e,n)=>a(void 0,void 0,void 0,(function*(){var t;l.intro("Debug Live update in Capgo"),yield(0,d.checkLatest)(),n.apikey=n.apikey||(0,p.findSavedKey)();const i=yield(0,p.getConfig)();e=e||(null===(t=null==i?void 0:i.app)||void 0===t?void 0:t.appId);const r=n.device;n.apikey||(l.log.error("Missing API key, you need to provide an API key to delete your app"),s.program.error("")),e||(l.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),s.program.error(""));const a=yield(0,p.createSupabaseClient)(n.apikey),u=(0,p.useLogSnag)(),f=yield(0,p.verifyUser)(a,n.apikey);l.log.info("Getting active bundle in Capgo"),yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,e);const g=yield l.confirm({message:"Automatic check if update working in device ?"});yield(0,o.cancelCommand)("debug",g,f,u),g?(l.log.info(`Wait logs sent to Capgo from ${e} device, Put the app in background and open it again.`),l.log.info("Waiting..."),yield(0,o.waitLog)("debug",a,e,u,f,r),l.outro("Done ✅")):l.outro("Canceled ❌"),l.outro("Done ✅"),process.exit()}))},8437:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteApp=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170);o.deleteApp=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("Deleting"),o.apikey=o.apikey||(0,d.findSavedKey)();const t=yield(0,d.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId);const i=(0,d.useLogSnag)();o.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const r=yield(0,d.createSupabaseClient)(o.apikey),a=yield(0,d.verifyUser)(r,o.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(r,o.apikey,e);const{error:p}=yield r.storage.from(`images/${a}`).remove([e]);p&&s.log.error("Could not delete app logo");const{error:u}=yield r.storage.from(`apps/${e}/${a}`).remove(["versions"]);u&&(s.log.error("Could not delete app version"),l.program.error(""));const{error:f}=yield r.from("apps").delete().eq("app_id",e).eq("user_id",a);f&&(s.log.error("Could not delete app"),l.program.error("")),yield i.track({channel:"app",event:"App Deleted",icon:"🗑️",user_id:a,tags:{"app-id":e},notify:!1}).catch(),s.log.success("App deleted in Capgo"),s.outro("Done ✅"),process.exit()}))},9785:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((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 r=n(7147),a=n(1017),l=i(n(2037)),s=i(n(5362)),c=i(n(7176)),d=i(n(4147));o.getInfo=()=>t(void 0,void 0,void 0,(function*(){console.log(" 💊 Capgo Doctor 💊\n"),console.log(` OS: ${l.default.platform()} ${l.default.version()}\n`),console.log(` Node: ${process.version}\n`),console.log(" Installed Dependencies:\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,r.readFileSync)((0,a.join)(process.cwd(),"package.json"));return JSON.parse(e)})),o={"@capgo/cli":d.default.version};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith("@capgo/")){const t=e[n].replace("^","").replace("~","");o[n]=t}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,s.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()}))},4738:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listApp=o.getActiveApps=void 0;const l=n(7304),s=n(3847),c=r(n(552)),d=n(2170),p=n(9740);o.getActiveApps=e=>a(void 0,void 0,void 0,(function*(){const{data:o,error:n}=yield e.from("apps").select().order("created_at",{ascending:!1});return n&&(c.log.error("Apps not found"),l.program.error("")),o})),o.listApp=e=>a(void 0,void 0,void 0,(function*(){c.intro("List apps in Capgo"),yield(0,p.checkLatest)(),e.apikey=e.apikey||(0,d.findSavedKey)();const n=yield(0,d.createSupabaseClient)(e.apikey);yield(0,d.verifyUser)(n,e.apikey,["write","all","read","upload"]),c.log.info("Getting active bundle in Capgo");const t=yield(0,o.getActiveApps)(n);c.log.info(`Active app in Capgo: ${null==t?void 0:t.length}`),(e=>{const o=new s.Table({title:"Apps",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,id:e.app_id,Created:(0,d.getHumanDate)(e.created_at)})})),c.log.success(o.render())})(t),c.outro("Done ✅"),process.exit()}))},7791:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setApp=void 0;const l=n(6113),s=n(9011),c=n(7304),d=r(n(552)),p=n(7561),u=n(3018),f=n(2170);o.setApp=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;d.intro("Set app"),o.apikey=o.apikey||(0,f.findSavedKey)();const t=yield(0,f.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId),o.apikey||(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),e||(d.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),c.program.error(""));const i=yield(0,f.createSupabaseClient)(o.apikey),r=yield(0,f.verifyUser)(i,o.apikey,["write","all"]);yield(0,u.checkAppExistsAndHasPermissionErr)(i,o.apikey,e);const{name:a,icon:g,retention:y}=o;let v,h;y&&!Number.isNaN(Number(y))?(d.log.error("retention value must be a number"),c.program.error("")):y&&y<0&&(d.log.error("retention value cannot be less than 0"),c.program.error(""));const m=`icon_${(0,l.randomUUID)()}`;let b="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(g&&(0,p.existsSync)(g)?(v=(0,p.readFileSync)(g),h=(0,s.getType)(g)||"image/png",d.log.warn(`Found app icon ${g}`)):(0,p.existsSync)(u.newIconPath)?(v=(0,p.readFileSync)(u.newIconPath),h=(0,s.getType)(u.newIconPath)||"image/png",d.log.warn(`Found app icon ${u.newIconPath}`)):d.log.warn(`Cannot find app icon in any of the following locations: ${g}, ${u.newIconPath}`),v&&h){const{error:o}=yield i.storage.from(`images/${r}/${e}`).upload(m,v,{contentType:h});o&&(d.log.error(`Could not add app ${(0,f.formatError)(o)}`),c.program.error(""));const{data:n}=yield i.storage.from(`images/${r}/${e}`).getPublicUrl(m);b=(null==n?void 0:n.publicUrl)||b}const{error:_}=yield i.from("apps").update({icon_url:b,name:a,retention:y?24*y*60*60:void 0}).eq("app_id",e).eq("user_id",r);_&&(d.log.error(`Could not add app ${(0,f.formatError)(_)}`),c.program.error("")),d.outro("Done ✅"),process.exit()}))},7092:function(e,o,n){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkIndexPosition=o.searchInDirectory=void 0;const i=t(n(7147)),r=t(n(1017)),a=(e,o)=>i.default.readFileSync(e,"utf8").includes(o);o.searchInDirectory=(e,n)=>{const t=i.default.readdirSync(e);for(const l of t){const t=r.default.join(e,l),s=i.default.statSync(t);if(s.isDirectory()){if((0,o.searchInDirectory)(t,n))return!0}else if(s.isFile()&&".js"===r.default.extname(t)&&a(t,n))return!0}return!1},o.checkIndexPosition=e=>{const n=i.default.readdirSync(e);if(1===n.length){const t=r.default.join(e,n[0]);if(i.default.statSync(t).isDirectory())return(0,o.checkIndexPosition)(t)}return n.indexOf("index.html")>-1}},9690:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=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)}))}}},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.cleanupBundle=void 0;const c=n(7304),d=s(n(1505)),p=r(n(552)),u=s(n(1616)),f=n(2170),g=n(1820),y=n(3018),v=n(9740),h=(0,u.default)();o.cleanupBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;p.intro("Cleanup versions in Capgo"),yield(0,v.checkLatest)(),o.apikey=o.apikey||(0,f.findSavedKey)();const{bundle:t,keep:i=4}=o,r=o.force||!1,s=yield(0,f.getConfig)();e=e||(null===(n=null==s?void 0:s.app)||void 0===n?void 0:n.appId),o.apikey||(p.log.error("Missing API key, you need to provide an API key to delete your app"),c.program.error("")),e||(p.log.error("Missing argument, you need to provide a appid, or be in a capacitor project"),c.program.error(""));const u=yield(0,f.createSupabaseClient)(o.apikey),m=yield(0,f.verifyUser)(u,o.apikey);yield(0,y.checkAppExistsAndHasPermissionErr)(u,o.apikey,e),p.log.info("Querying all available versions in Capgo");let b=yield(0,g.getActiveAppVersions)(u,e,m);const _=yield(0,g.getChannelsVersion)(u,e);if(p.log.info(`Total active versions in Capgo: ${null==b?void 0:b.length}`),0===(null==b?void 0:b.length))return void p.log.error("No versions found, aborting cleanup");if(t){const e=`${d.default.inc(t,"major")}`;p.log.info(`Querying available versions in Capgo between ${t} and ${e}`),b=((e,o,n)=>{const t=[];return null==e||e.forEach((e=>{d.default.gte(e.name,o)&&d.default.lt(e.name,`${n}`)&&t.push(e)})),t})(b,t,e),p.log.info(`Active versions in Capgo between ${t} and ${e}: ${null==b?void 0:b.length}`)}const k=[];let w=0;if(b.forEach((e=>{const o=_.find((o=>o===e.id));w<i||o?(e.keep=o?"✅ (Linked to channel)":"✅",w+=1):(e.keep="❌",k.push(e))})),0!==k.length){if((0,g.displayBundles)(b),!r&&"yes"!==h("Do you want to continue removing the versions specified? Type yes to confirm: "))return void p.log.warn("Not confirmed, aborting removal...");p.log.success("You have confirmed removal, removing versions now"),yield((e,o,n,t)=>{var i,r,s;return a(void 0,void 0,void 0,(function*(){var a,c,d,u;try{for(i=!0,r=l(e);!(a=(s=yield r.next()).done);i=!0){u=s.value,i=!1;const e=u;p.log.warn(`Removing ${e.name} created on ${(0,f.getHumanDate)(e.created_at)}`),yield(0,g.deleteSpecificVersion)(o,n,t,e.name)}}catch(e){c={error:e}}finally{try{i||a||!(d=r.return)||(yield d.call(r))}finally{if(c)throw c.error}}}))})(k,u,e,m),p.outro("Done ✅"),process.exit()}else p.log.warn("Nothing to be removed, aborting removal...")}))},2851:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.checkCompatibilityCommand=void 0;const l=r(n(552)),s=n(7304),c=n(3847),d=n(2170),p=n(3018);o.checkCompatibilityCommand=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;l.intro("Check compatibility"),o.apikey=o.apikey||(0,d.findSavedKey)();const t=yield(0,d.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId);const{channel:i}=o;i||(l.log.error("Missing argument, you need to provide a channel"),s.program.error("")),o.apikey||(l.log.error("Missing API key, you need to provide a API key to upload your bundle"),s.program.error("")),e||(l.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),s.program.error(""));const r=yield(0,d.createSupabaseClient)(o.apikey);yield(0,d.verifyUser)(r,o.apikey,["write","all","read","upload"]),yield(0,p.checkAppExistsAndHasPermissionErr)(r,o.apikey,e);const{finalCompatibility:a}=yield(0,d.checkCompatibility)(r,e,i),u=new c.Table({title:"Compatibility",charLength:{"❌":2,"✅":2}}),f=o.text?"Yes":"✅",g=o.text?"No":"❌";a.forEach((e=>{const{name:o,localVersion:n,remoteVersion:t}=e;u.addRow({Package:o,"Local version":null!=n?n:"None","Remote version":null!=t?t:"None",Compatible:t===n?f:g})})),l.log.success(u.render())}))},3151:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.decryptZip=void 0;const l=n(7147),s=n(7304),c=r(n(552)),d=n(3043),p=n(2170),u=n(9740);o.decryptZip=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i,r,a,f,g;c.intro("Decrypt zip file"),yield(0,u.checkLatest)(),(0,l.existsSync)(e)||(c.log.error(`Zip not found at the path ${e}`),s.program.error(""));const y=yield(0,p.getConfig)(),{extConfig:v}=y.app;n.key||(0,l.existsSync)(p.baseKey)||(null===(i=null===(t=v.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===i?void 0:i.privateKey)||(c.log.error(`Private Key not found at the path ${p.baseKey} or in ${y.app.extConfigFilePath}`),s.program.error(""));const h=n.key||p.baseKey;let m=null===(a=null===(r=null==v?void 0:v.plugins)||void 0===r?void 0:r.CapacitorUpdater)||void 0===a?void 0:a.privateKey;(0,l.existsSync)(h)||m?(0,l.existsSync)(h)&&(m=(0,l.readFileSync)(h).toString()):(c.log.error(`Cannot find public key ${h} or as keyData option or in ${y.app.extConfigFilePath}`),s.program.error(""));const b=(0,l.readFileSync)(e),_=(0,d.decryptSource)(b,o,null!==(g=null!==(f=n.keyData)&&void 0!==f?f:m)&&void 0!==g?g:"");(0,l.writeFileSync)(`${e}_decrypted.zip`,_),c.outro(`Decrypted zip file at ${e}_decrypted.zip`),process.exit()}))},4666:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170),p=n(1820);o.deleteBundle=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i;s.intro("Delete bundle"),n.apikey=n.apikey||(0,d.findSavedKey)();const r=yield(0,d.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,d.createSupabaseClient)(n.apikey),u=yield(0,d.verifyUser)(a,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),o=o||(null===(i=null==r?void 0:r.app)||void 0===i?void 0:i.appId),n.apikey||(s.log.error("Missing API key, you need to provide an API key to delete your app"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a bundleId, or be in a capacitor project"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error("")),s.log.info(`Deleting bundle ${o}@${e} from Capgo`),yield(0,p.deleteSpecificVersion)(a,o,u,e),s.log.success(`Bundle ${o}@${e} deleted in Capgo`),s.outro("Done"),process.exit()}))},891:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.encryptZip=void 0;const s=n(7147),c=n(7304),d=l(n(7812)),p=r(n(552)),u=n(9740),f=n(3043),g=n(2170);o.encryptZip=(e,o)=>a(void 0,void 0,void 0,(function*(){p.intro("Encryption"),yield(0,u.checkLatest)();const n=yield(0,g.getLocalConfig)();(0,s.existsSync)(e)||(p.log.error(`Error: Zip not found at the path ${e}`),c.program.error(""));const t=o.key||g.baseKeyPub;let i=o.keyData||"";(0,s.existsSync)(t)||i?(0,s.existsSync)(t)&&(i=(0,s.readFileSync)(t).toString()):(p.log.warning(`Cannot find public key ${t} or as keyData option`),d.default.isCI&&(p.log.error("Error: Missing public key"),c.program.error("")),(yield p.confirm({message:"Do you want to use our public key ?"}))||(p.log.error("Error: Missing public key"),c.program.error("")),i=n.signKey||"");const r=(0,s.readFileSync)(e),a=(0,f.encryptSource)(r,i);p.log.success(`ivSessionKey: ${a.ivSessionKey}`),(0,s.writeFileSync)(`${e}_encrypted.zip`,a.encryptedData),p.log.success(`Encrypted zip saved at ${e}_encrypted.zip`),p.outro("Done ✅"),process.exit()}))},4220:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(1820),p=n(2170),u=n(9740);o.listBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("List bundles"),yield(0,u.checkLatest)(),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||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a appid, or be in a capacitor project"),l.program.error(""));const i=yield(0,p.createSupabaseClient)(o.apikey),r=yield(0,p.verifyUser)(i,o.apikey,["write","all","read","upload"]);s.log.info(`Querying available versions of: ${e} in Capgo`),yield(0,c.checkAppExistsAndHasPermissionErr)(i,o.apikey,e);const a=yield(0,d.getActiveAppVersions)(i,e,r);s.log.info(`Active versions in Capgo: ${null==a?void 0:a.length}`),(0,d.displayBundles)(a),s.outro("Done ✅"),process.exit()}))},3717:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.uploadDeprecatedCommand=o.uploadCommand=o.uploadBundle=void 0;const s=n(6113),c=n(7147),d=l(n(3844)),p=n(7304),u=r(n(552)),f=n(5906),g=l(n(7812)),y=l(n(2167)),v=n(9740),h=n(3018),m=n(3043),b=n(2170),_=n(7092);o.uploadBundle=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){var t,i,r,a;u.intro("Uploading"),yield(0,v.checkLatest)();let{bundle:l,path:k,channel:w}=o;const{external:C,key:O=!1,displayIvSession:P,autoMinUpdateVersion:x,ignoreMetadataCheck:j}=o;let{minUpdateVersion:S}=o;o.apikey=o.apikey||(0,b.findSavedKey)();const $=(0,b.useLogSnag)();w=w||"dev";const A=yield(0,b.getConfig)(),M=!0===(A.app.extConfig.plugins&&A.app.extConfig.plugins.CapacitorUpdater&&A.app.extConfig.plugins.CapacitorUpdater.localS3),D=o.codeCheck;e=e||(null===(t=null==A?void 0:A.app)||void 0===t?void 0:t.appId);const I=(0,s.randomUUID)().split("-")[0];l=l||(null===(r=null===(i=null==A?void 0:A.app)||void 0===i?void 0:i.package)||void 0===r?void 0:r.version)||`0.0.1-beta.${I}`,b.regexSemver.test(l)||(u.log.error(`Your bundle name ${l}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")),k=k||(null===(a=null==A?void 0:A.app)||void 0===a?void 0:a.webDir),o.apikey||(u.log.error("Missing API key, you need to provide a API key to upload your bundle"),p.program.error("")),e&&l&&k||(u.log.error("Missing argument, you need to provide a appid and a bundle and a path, or be in a capacitor project"),p.program.error("")),(0,c.existsSync)(k)||(u.log.error(`Path ${k} does not exist, build your app first, or provide a valid path`),p.program.error("")),(void 0===D||D)&&((0,_.searchInDirectory)(k,"notifyAppReady")||(u.log.error("notifyAppReady() is missing in the source code. see: https://capgo.app/docs/plugin/api/#notifyappready"),p.program.error("")),(0,_.checkIndexPosition)(k)||(u.log.error("index.html is missing in the root folder or in the only folder in the root folder"),p.program.error(""))),u.log.info(`Upload ${e}@${l} started from path "${k}" to Capgo cloud`);const U=yield(0,b.getLocalConfig)(),E=yield(0,b.createSupabaseClient)(o.apikey),q=yield(0,b.verifyUser)(E,o.apikey,["write","all","upload"]);yield(0,b.checkPlanValid)(E,q,!1);const L=yield(0,h.checkAppExistsAndHasPermissionOrgErr)(E,o.apikey,e,b.OrganizationPerm.upload),K=yield(0,b.requireUpdateMetadata)(E,w),{data:N,error:V}=yield E.from("channels").select("version ( minUpdateVersion, native_packages )").eq("name",w).eq("app_id",e).single();let B,z;if(!V&&N&&N.version&&N.version.native_packages&&!j){const o=u.spinner();o.start(`Checking bundle compatibility with channel ${w}`);const{finalCompatibility:n,localDependencies:t}=yield(0,b.checkCompatibility)(E,e,w);if(z=n,B=t,z.find((e=>e.localVersion!==e.remoteVersion)))u.log.error(`Your bundle is not compatible with the channel ${w}`),u.log.warn('You can check compatibility with "npx @capgo/cli bundle compatibility"'),x&&(S=l,u.log.info(`Auto set min-update-version to ${S}`));else if(x)try{const{minUpdateVersion:e}=N.version;e&&b.regexSemver.test(e)||(u.log.error("Invalid remote min update version, skipping auto setting compatibility"),p.program.error("")),S=e,u.log.info(`Auto set min-update-version to ${S}`)}catch(e){u.log.error(`Cannot auto set compatibility, invalid data ${N}`),p.program.error("")}o.stop(`Bundle compatible with ${w} channel`)}else j||(u.log.warn(`Channel ${w} is new or it's your first upload with compatibility check, it will be ignored this time`),B=yield(0,b.getLocalDepenencies)(),x&&(S=l,u.log.info(`Auto set min-update-version to ${S}`)));!K||S||j||(u.log.error("You need to provide a min-update-version to upload a bundle to this channel"),p.program.error("")),S&&(b.regexSemver.test(S)||(u.log.error(`Your minimal version update ${S}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")));const{data:R,error:F}=yield E.rpc("is_trial",{userid:q}).single();(R&&R>0||F)&&(u.log.warn(`WARNING !!\nTrial expires in ${R} days`),u.log.warn(`Upgrade here: ${U.hostWeb}/dashboard/settings/plans`));const{data:H,error:T}=yield E.rpc("exist_app_versions",{appid:e,apikey:o.apikey,name_version:l}).single();(H||T)&&(u.log.error(`Version already exists ${(0,b.formatError)(T)}`),p.program.error(""));const Y=`${l.replace(/[^a-zA-Z0-9-_.!*'()]/g,"__")}.zip`;let W,J="",Z=null;if(C)C&&!C.startsWith("https://")?(u.log.error(`External link should should start with "https://" current is "${C}"`),p.program.error("")):(yield $.track({channel:"app",event:"App external",icon:"📤",user_id:q,tags:{"app-id":e},notify:!1}).catch(),W=o.ivSessionKey);else{const n=new d.default;n.addLocalFolder(k),Z=n.toBuffer();const t=u.spinner();if(t.start("Calculating checksum"),J=yield(0,f.checksum)(Z,"crc32"),t.stop(`Checksum: ${J}`),O||(0,c.existsSync)(b.baseKeyPub)){const n="string"==typeof O?O:b.baseKeyPub;let t=o.keyData||"";t||(0,c.existsSync)(n)||(u.log.error(`Cannot find public key ${n}`),g.default.isCI&&p.program.error(""),(yield u.confirm({message:"Do you want to use our public key ?"}))||(u.log.error("Error: Missing public key"),p.program.error("")),t=U.signKey||""),yield $.track({channel:"app",event:"App encryption",icon:"🔑",user_id:q,tags:{"app-id":e},notify:!1}).catch(),t||(t=(0,c.readFileSync)(n).toString()),u.log.info("Encrypting your bundle");const i=(0,m.encryptSource)(Z,t);W=i.ivSessionKey,P&&u.log.info(`Your Iv Session key is ${W},\nkeep it safe, you will need it to decrypt your bundle.\nIt will be also visible in your dashboard\n`),Z=i.encryptedData}const i=Math.floor(Z.byteLength/1024/1024);i>20&&(u.log.warn(`WARNING !!\nThe app size is ${i} Mb, this may take a while to download for users\n`),u.log.info("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield $.track({channel:"app-error",event:"App Too Large",icon:"🚛",user_id:q,tags:{"app-id":e},notify:!1}).catch())}const G=B?new Map(B.filter((e=>!!e.native&&void 0!==e.native)).map((e=>[e.name,e]))):new Map,Q=G.size>0||!o.ignoreMetadataCheck?Array.from(G,(([e,o])=>({name:e,version:o.version}))):void 0,X={bucket_id:C?void 0:Y,user_id:q,name:l,app_id:e,session_key:W,external_url:C,storage_provider:C?"external":"r2-direct",minUpdateVersion:S,native_packages:Q,checksum:J},{error:ee}=yield(0,b.updateOrCreateVersion)(E,X,o.apikey);if(ee&&(u.log.error(`Cannot add bundle ${(0,b.formatError)(ee)}`),p.program.error("")),!C&&Z){const n=u.spinner();n.start("Uploading Bundle");const t=yield(0,b.uploadUrl)(E,e,Y);t||(u.log.error("Cannot get upload url"),p.program.error("")),yield(0,y.default)({method:"put",url:t,data:Z,headers:M?void 0:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=456789, immutable","x-amz-meta-crc32":J}}),X.storage_provider="r2";const{error:i}=yield(0,b.updateOrCreateVersion)(E,X,o.apikey);i&&(u.log.error(`Cannot update bundle ${(0,b.formatError)(ee)}`),p.program.error("")),n.stop("Bundle Uploaded 💪")}const{data:oe}=yield E.rpc("get_app_versions",{apikey:o.apikey,name_version:l,appid:e}).single();if(oe&&(0,b.hasOrganizationPerm)(L,b.OrganizationPerm.write)){const{error:n,data:t}=yield(0,b.updateOrCreateChannel)(E,{name:w,app_id:e,created_by:q,version:oe});n&&(u.log.error('Cannot set channel, the upload key is not allowed to do that, use the "all" for this.'),p.program.error(""));const i=(0,b.convertAppName)(e),r=`${U.hostWeb}/app/p/${i}/channel/${t.id}`;(null==t?void 0:t.public)?u.log.info("Your update is now available in your public channel 🎉"):(null==t?void 0:t.id)&&u.log.info(`Link device to this bundle to try it: ${r}`),o.bundleUrl&&u.log.info(`Bundle url: ${r}`)}else oe?(0,b.hasOrganizationPerm)(L,b.OrganizationPerm.write)||u.log.warn("Cannot set channel as a upload organization member"):(u.log.warn("Cannot set bundle with upload key, use key with more rights for that"),p.program.error(""));return yield $.track({channel:"app",event:"App Uploaded",icon:"⏫",user_id:q,tags:{"app-id":e},notify:!1}).catch(),n&&(u.outro("Time to share your update to the world 🌍"),process.exit()),!0})),o.uploadCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){try{yield(0,o.uploadBundle)(e,n,!0)}catch(e){u.log.error(JSON.stringify(e)),p.program.error("")}})),o.uploadDeprecatedCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){u.log.warn('⚠️ This command is deprecated, use "npx @capgo/cli bundle upload" instead ⚠️');try{yield(0,o.uploadBundle)(e,n,!0)}catch(e){u.log.error(JSON.stringify(e)),p.program.error("")}}))},3398:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.zipBundle=void 0;const s=n(6113),c=n(7147),d=l(n(3844)),p=n(7304),u=r(n(552)),f=n(5906),g=n(9740),y=n(2170),v=n(7092);o.zipBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n,t,i,r;yield(0,g.checkLatest)();let{bundle:a,path:l}=o;const{json:h}=o,m=(0,y.useLogSnag)(),b=yield(0,y.getConfig)();e=e||(null===(n=null==b?void 0:b.app)||void 0===n?void 0:n.appId);const _=(0,s.randomUUID)().split("-")[0];a=a||(null===(i=null===(t=null==b?void 0:b.app)||void 0===t?void 0:t.package)||void 0===i?void 0:i.version)||`0.0.1-beta.${_}`,h||u.intro(`Zipping ${e}@${a}`),y.regexSemver.test(a)||(h?console.error(JSON.stringify({error:"invalid_semver"})):u.log.error(`Your bundle name ${a}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")),l=l||(null===(r=null==b?void 0:b.app)||void 0===r?void 0:r.webDir),e&&a&&l||(h?console.error(JSON.stringify({error:"missing_argument"})):u.log.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project"),p.program.error("")),h||u.log.info(`Started from path "${l}"`);const k=o.codeCheck;(void 0===k||k)&&((0,v.searchInDirectory)(l,"notifyAppReady")||(h?console.error(JSON.stringify({error:"notifyAppReady_not_in_source_code"})):u.log.error("notifyAppReady() is missing in the source code. see: https://capgo.app/docs/plugin/api/#notifyappready"),p.program.error("")),(0,v.checkIndexPosition)(l)||(h?console.error(JSON.stringify({error:"index_html_not_found"})):u.log.error("index.html is missing in the root folder or in the only folder in the root folder"),p.program.error("")));const w=new d.default;w.addLocalFolder(l);const C=w.toBuffer();h||u.log.info(`Zipped ${C.byteLength} bytes`);const O=u.spinner();h||O.start("Calculating checksum");const P=yield(0,f.checksum)(C,"crc32");h||O.stop(`Checksum: ${P}`);const x=Math.floor(C.byteLength/1024/1024);x>20&&!h&&(u.log.warn(`WARNING !!\nThe app size is ${x} Mb, this may take a while to download for users\n`),u.log.warn("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield m.track({channel:"app-error",event:"App Too Large",icon:"🚛",tags:{"app-id":e},notify:!1}).catch());const j=u.spinner(),S=o.name||`${e}_${a}.zip`;if(h||j.start(`Saving to ${S}`),(0,c.writeFileSync)(S,C),h||j.stop(`Saved to ${S}`),o.json){const e={bundle:a,filename:S,checksum:P};console.log(JSON.stringify(e))}yield m.track({channel:"app",event:"App zip",icon:"⏫",tags:{"app-id":e},notify:!1}).catch(),h||u.outro("Done ✅"),process.exit()}))},1795:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addChannelCommand=o.addChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.addChannel=(e,o,n,t=!0)=>a(void 0,void 0,void 0,(function*(){var i;s.intro("Create channel"),n.apikey=n.apikey||(0,p.findSavedKey)();const r=yield(0,p.getConfig)();o=o||(null===(i=null==r?void 0:r.app)||void 0===i?void 0:i.appId);const a=(0,p.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const u=yield(0,p.createSupabaseClient)(n.apikey),f=yield(0,p.verifyUser)(u,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(u,n.apikey,o),s.log.info(`Creating channel ${o}#${e} to Capgo`);try{const n=yield(0,d.findUnknownVersion)(u,o);n||(s.log.error("Cannot find default version for channel creation, please contact Capgo support 🤨"),l.program.error("")),yield(0,d.createChannel)(u,{name:e,app_id:o,version:n.id,created_by:f}),s.log.success("Channel created ✅"),yield a.track({channel:"channel",event:"Create channel",icon:"✅",user_id:f,tags:{"app-id":o,channel:e},notify:!1}).catch()}catch(e){return s.log.error("Cannot create Channel 🙀"),!1}return t&&(s.outro("Done ✅"),process.exit()),!0})),o.addChannelCommand=(e,n,t)=>a(void 0,void 0,void 0,(function*(){(0,o.addChannel)(e,n,t,!0)}))},2914:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.currentBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170);o.currentBundle=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;const{quiet:i}=n;i||s.intro("List current bundle"),n.apikey=n.apikey||(0,d.findSavedKey)(i);const r=yield(0,d.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,d.createSupabaseClient)(n.apikey),p=yield(0,d.verifyUser)(a,n.apikey,["write","all","read"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),e||(s.log.error("Please provide a channel to get the bundle from."),l.program.error(""));const{data:u,error:f}=yield a.from("channels").select("version ( name )").eq("name",e).eq("app_id",o).eq("created_by",p).limit(1);(f||0===u.length)&&(s.log.error(`Error retrieving channel ${e} for app ${o}. Perhaps the channel does not exists?`),l.program.error(""));const{version:g}=u[0];g||(s.log.error(`Error retrieving channel ${e} for app ${o}. Perhaps the channel does not exists?`),l.program.error("")),i?console.log(g.name):s.log.info(`Current bundle for channel ${e} is ${g.name}`),process.exit()}))},5798:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.deleteChannel=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;s.intro("Delete channel"),n.apikey=n.apikey||(0,p.findSavedKey)();const i=yield(0,p.getConfig)();o=o||(null===(t=null==i?void 0:i.app)||void 0===t?void 0:t.appId);const r=(0,p.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,p.createSupabaseClient)(n.apikey),u=yield(0,p.verifyUser)(a,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),s.log.info(`Deleting channel ${o}#${e} from Capgo`);try{yield(0,d.delChannel)(a,e,o,u),s.log.success("Channel deleted"),yield r.track({channel:"channel",event:"Delete channel",icon:"✅",tags:{"user-id":u,"app-id":o,channel:e},notify:!1}).catch()}catch(e){s.log.error("Cannot delete Channel 🙀")}s.outro("Done ✅"),process.exit()}))},1983:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listChannels=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.listChannels=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("List channels"),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);const i=(0,p.useLogSnag)();o.apikey||s.log.error("Missing API key, you need to provide a API key to upload your bundle"),e||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const r=yield(0,p.createSupabaseClient)(o.apikey),a=yield(0,p.verifyUser)(r,o.apikey,["write","all","read","upload"]);yield(0,c.checkAppExistsAndHasPermissionErr)(r,o.apikey,e),s.log.info("Querying available channels in Capgo");const u=yield(0,d.getActiveChannels)(r,e);s.log.info(`Active channels in Capgo: ${null==u?void 0:u.length}`),(0,d.displayChannels)(u),yield i.track({channel:"channel",event:"List channel",icon:"✅",user_id:a,tags:{"app-id":e},notify:!1}).catch(),s.outro("Done ✅"),process.exit()}))},1541:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170),p=["major","minor","metadata","none"];o.setChannel=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i,r;s.intro("Set channel"),n.apikey=n.apikey||(0,d.findSavedKey)();const a=yield(0,d.getConfig)();o=o||(null===(t=null==a?void 0:a.app)||void 0===t?void 0:t.appId);const u=(0,d.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const f=yield(0,d.createSupabaseClient)(n.apikey),g=yield(0,d.verifyUser)(f,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(f,n.apikey,o);const{bundle:y,latest:v,downgrade:h,upgrade:m,ios:b,android:_,selfAssign:k,state:w,disableAutoUpdate:C}=n;e||(s.log.error("Missing argument, you need to provide a channel"),l.program.error("")),v&&y&&(s.log.error("Cannot set latest and bundle at the same time"),l.program.error("")),null==y&&null==w&&null==v&&null==h&&null==m&&null==b&&null==_&&null==k&&null==C&&(s.log.error("Missing argument, you need to provide a option to set"),l.program.error(""));try{yield(0,d.checkPlanValid)(f,g);const n={created_by:g,app_id:o,name:e,version:void 0},t=v?null===(r=null===(i=null==a?void 0:a.app)||void 0===i?void 0:i.package)||void 0===r?void 0:r.version:y;if(null!=t){const{data:i,error:r}=yield f.from("app_versions").select().eq("app_id",o).eq("name",t).eq("user_id",g).eq("deleted",!1).single();!r&&i||(s.log.error(`Cannot find version ${t}`),l.program.error("")),s.log.info(`Set ${o} channel: ${e} to @${t}`),n.version=i.id}if(null!=w&&("public"!==w&&"private"!==w||s.log.info(`Set ${o} channel: ${e} to public or private is deprecated, use default or normal instead`),s.log.info(`Set ${o} channel: ${e} to ${"public"===w||"default"===w?"default":"normal"}`),n.public="public"===w||"default"===w),null!=h&&(s.log.info(`Set ${o} channel: ${e} to ${h?"allow":"disallow"} downgrade`),n.disableAutoUpdateUnderNative=!h),null!=b&&(s.log.info(`Set ${o} channel: ${e} to ${b?"allow":"disallow"} ios update`),n.ios=!!b),null!=_&&(s.log.info(`Set ${o} channel: ${e} to ${_?"allow":"disallow"} android update`),n.android=!!_),null!=k&&(s.log.info(`Set ${o} channel: ${e} to ${k?"allow":"disallow"} self assign to this channel`),n.allow_device_self_set=!!k),null!=C){let t=C.toLocaleLowerCase();p.includes(t)||(s.log.error(`Channel strategy ${t} is not known. The possible values are: ${p.join(", ")}.`),l.program.error("")),"metadata"===t&&(t="version_number"),n.disableAutoUpdate=t,s.log.info(`Set ${o} channel: ${e} to ${t} disable update strategy to this channel`)}try{const{error:e}=yield(0,d.updateOrCreateChannel)(f,n);e&&(s.log.error('Cannot set channel the upload key is not allowed to do that, use the "all" for this.'),l.program.error(""))}catch(e){s.log.error('Cannot set channel the upload key is not allowed to do that, use the "all" for this.'),l.program.error("")}yield u.track({channel:"channel",event:"Set channel",icon:"✅",user_id:g,tags:{"user-id":g,"app-id":o},notify:!1}).catch()}catch(e){s.log.error(`Unknow error ${(0,d.formatError)(e)}`),l.program.error("")}s.outro("Done ✅"),process.exit()}))},1428: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(7304),r=n(3398),a=n(3464),l=n(4220),s=n(3151),c=n(891),d=n(2622),p=n(9785),u=n(2673),f=n(4666),g=n(1541),y=n(2914),v=n(3717),h=t(n(4147)),m=n(7102),b=n(4738),_=n(9690),k=n(1795),w=n(5798),C=n(1983),O=n(7791),P=n(8437),x=n(3713),j=n(2851);i.program.name(h.default.name).description("Manage packages and bundle versions in Capgo Cloud").version(h.default.version),i.program.command("login [apikey]").alias("l").description("Save apikey to your machine or folder").action(m.loginCommand).option("--local","Only save in local folder"),i.program.command("doctor").description("Get info about your Capgo app install").action(p.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 S=i.program.command("app").description("Manage app");S.command("add [appId]").alias("a").description("Add a new app in Capgo Cloud").action(d.addCommand).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account"),S.command("delete [appId]").alias("d").description("Delete an app in Capgo Cloud").action(P.deleteApp).option("-a, --apikey <apikey>","apikey to link to your account"),S.command("list").alias("l").description("list apps in Capgo Cloud").action(b.listApp).option("-a, --apikey <apikey>","apikey to link to your account"),S.command("debug [appId]").alias("d").description("Listen for live updates event in Capgo Cloud to debug your app").option("-a, --apikey <apikey>","apikey to link to your account").option("-d, --device <device>","the specific device to debug").action(x.debugApp),S.command("set [appId]").alias("s").description("Set an app in Capgo Cloud").action(O.setApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account").option("-r, --retention <retention>","retention period of app bundle in days");const $=i.program.command("bundle").description("Manage bundle");$.command("upload [appId]").alias("u").description("Upload a new bundle in Capgo Cloud").action(v.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("--iv-session-key <key>","Set the iv and session key for bundle url external").option("--key <key>","custom path for public signing key").option("--key-data <keyData>","base64 public signing key").option("--bundle-url","prints bundle url into stdout").option("--no-key","ignore signing key and send clear update").option("--no-code-check","Ignore checking if notifyAppReady() is called in soure code and index present in root folder").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").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel").option("--auto-min-update-version","Set the min update version based on native packages").option("--ignore-metadata-check","Ignores the metadata (node_modules) check when uploading"),$.command("compatibility [appId]").action(j.checkCompatibilityCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-c, --channel <channel>","channel to check the compatibility with").option("--text","output text instead of emojis"),$.command("delete [bundleId] [appId]").alias("d").description("Delete a bundle in Capgo Cloud").action(f.deleteBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("list [appId]").alias("l").description("List bundle in Capgo Cloud").action(l.listBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("unlink [appId]").alias("u").description("Unlink a bundle in Capgo Cloud").action(l.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(_.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("--key-data <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("--key-data <keyData>","base64 private signing key"),$.command("zip [appId]").description("Zip a bundle").action(r.zipBundle).option("-p, --path <path>","path of the folder to upload").option("-b, --bundle <bundle>","bundle version number to name the zip file").option("-n, --name <name>","name of the zip file").option("-j, --json","output in JSON").option("--no-code-check","Ignore checking if notifyAppReady() is called in soure code and index present in root folder");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").option("-a, --apikey <apikey>","apikey to link to your account"),A.command("delete [channelId] [appId]").alias("d").description("Delete channel").action(w.deleteChannel).option("-a, --apikey <apikey>","apikey to link to your account"),A.command("list [appId]").alias("l").description("List channel").action(C.listChannels).option("-a, --apikey <apikey>","apikey to link to your account"),A.command("currentBundle [channel] [appId]").description("Get current bundle for specific channel in Capgo Cloud").action(y.currentBundle).option("-c, --channel <channel>","channel to get the current bundle from").option("-a, --apikey <apikey>","apikey to link to your account").option("--quiet","only print the bundle version"),A.command("set [channelId] [appId]").alias("s").description("Set channel").action(g.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").option("--disable-auto-update <disableAutoUpdate>","Disable auto update strategy for this channel.The possible options are: major, minor, metadata, none");const M=i.program.command("key").description("Manage key");M.command("save").description("Save base64 signing key in capacitor config, usefull for CI").action(u.saveKeyCommand).option("-f, --force","force generate a new one").option("--key","key path to save in capacitor config").option("--key-data","key data to save in capacitor config"),M.command("create").description("Create a new signing key").action(u.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(v.uploadDeprecatedCommand).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("--key-data <keyData>","base64 public signing key").option("--bundle-url","prints bundle url into stdout").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").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel"),i.program.parseAsync()},3464:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.initApp=void 0;const s=n(7147),c=n(2081),d=n(6301),p=r(n(552)),u=l(n(912)),f=n(3713),g=n(2673),y=n(1795),v=n(3717),h=n(7102),m=n(2622),b=n(9740),_=n(2170),k="import { CapacitorUpdater } from '@capgo/capacitor-updater'",w="CapacitorUpdater.notifyAppReady()",C=/import.*from.*/g,O="production",P={stdio:"pipe"},x=(e,o,n)=>a(void 0,void 0,void 0,(function*(){p.isCancel(e)&&(yield(0,f.markSnag)("onboarding-v2",o,n,"canceled","🤷"),process.exit())})),j=(e,o,n)=>a(void 0,void 0,void 0,(function*(){return(0,f.markSnag)("onboarding-v2",e,o,`onboarding-step-${n}`)}));o.initApp=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;p.intro("Capgo onboarding 🛫"),yield(0,b.checkLatest)();const i=(0,_.useLogSnag)(),r=yield(0,_.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),e=e||(0,_.findSavedKey)();const l=p.spinner();l.start("Running: npx @capgo/cli@latest login ***"),(yield(0,h.login)(e,n,!1))?l.stop("Login Done ✅"):l.stop("Login already done ✅");const S=yield(0,_.createSupabaseClient)(e),$=yield(0,_.verifyUser)(S,e,["upload","all","read","write"]);yield j($,i,1),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Add ${n} in Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start(`Running: npx @capgo/cli@latest app add ${n}`),(yield(0,m.addApp)(n,t,!1))?e.stop("App add Done ✅"):e.stop("App already add ✅")}else p.log.info(`Run yourself "npx @capgo/cli@latest app add ${n}"`);yield j(e,o,2)})))($,i,o,n),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Create default channel ${O} for ${t} in Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start(`Running: npx @capgo/cli@latest channel add ${O} ${t} --default`),(yield(0,y.addChannel)(O,t,{default:!0,apikey:n},!1))?e.stop("Channel add Done ✅"):e.stop("Channel already added ✅")}else p.log.info(`Run yourself "npx @capgo/cli@latest channel add ${O} ${t} --default"`);yield j(e,o,3)})))($,i,e,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic Install "@capgo/capacitor-updater" dependency in ${t}?`});if(yield x(n,e,o),n){const e=p.spinner();e.start("Checking if @capgo/capacitor-updater is installed");const o=JSON.parse((0,s.readFileSync)("package.json").toString());let n=o.dependencies["@capacitor/core"]||o.devDependencies["@capacitor/core"];n=null==n?void 0:n.replace("^","").replace("~",""),n?u.default.lt(n,"5.0.0")&&(e.stop(`@capacitor/core version is ${n}, please update to Capacitor v5 first: https://capacitorjs.com/docs/updating/5-0`),process.exit()):(e.stop("Cannot find @capacitor/core in package.json, please run `capgo init` in a capacitor project"),process.exit());const t=(0,d.findPackageManagerType)();"unknown"===t&&(e.stop("Cannot reconize package manager, please run `capgo init` in a capacitor project with npm, pnpm or yarn"),process.exit());const i="yarn"===t?"add":"install";o.dependencies["@capgo/capacitor-updater"]?e.stop("Capgo already installed ✅"):(yield(0,c.execSync)(`${t} ${i} @capgo/capacitor-updater@latest`,P),e.stop("Install Done ✅"))}else p.log.info('Run yourself "npm i @capgo/capacitor-updater@latest"');yield j(e,o,4)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic Add "${w}" code and import in ${t}?`});if(yield x(n,e,o),n){const n=p.spinner();n.start("Adding @capacitor-updater to your main file");const t=yield(0,_.findMainFile)();t||(n.stop("No main.ts, main.js, index.ts or index.js file found, You need to add @capgo/capacitor-updater manually"),process.exit());const i=(0,s.readFileSync)(t).toString(),r=i.match(C),a=null==r?void 0:r.pop();if(a||(n.stop("Cannot find import line in main file, use manual installation: https://capgo.app/docs/plugin/installation/"),process.exit()),i.includes(w))n.stop(`Code already added to ${t} ✅`);else{const e=i.replace(a,`${a}\n${k};\n\n${w};\n`);(0,s.writeFileSync)(t,e),n.stop(`Code added to ${t} ✅`)}yield j(e,o,5)}else p.log.info(`Add to your main file the following code:\n\n${k};\n\n${w};\n`)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic configure end-to-end encryption in ${t} updates?`});if(yield x(n,e,o),n){const n=p.spinner();n.start("Running: npx @capgo/cli@latest key create"),(yield(0,g.createKey)({},!1))?n.stop("key created 🔑"):(n.stop("Cannot create key ❌"),process.exit(1)),(0,f.markSnag)("onboarding-v2",e,o,"Use encryption")}yield j(e,o,6)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){var n;const i=yield p.confirm({message:`Automatic build ${t} with "npm run build" ?`});if(yield x(i,e,o),i){const e=p.spinner();e.start("Running: npm run build && npx cap sync"),(null===(n=JSON.parse((0,s.readFileSync)("package.json").toString()).scripts)||void 0===n?void 0:n.build)||(e.stop("Cannot find build script in package.json, please add it and run `capgo init` again"),process.exit()),(0,c.execSync)("npm run build && npx cap sync",P),e.stop("Build & Sync Done ✅")}else p.log.info("Build yourself with command: npm run build && npx cap sync");yield j(e,o,7)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Automatic upload ${t} bundle to Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start("Running: npx @capgo/cli@latest bundle upload"),(yield(0,v.uploadBundle)(t,{channel:O,apikey:n},!1))?e.stop("Upload Done ✅"):(e.stop("Upload failed ❌"),process.exit())}else p.log.info("Upload yourself with command: npx @capgo/cli@latest bundle upload");yield j(e,o,8)})))($,i,e,o),yield((e,o)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:"Run in device now ?"});if(yield x(n,e,o),n){const e=yield p.select({message:"Pick a platform to run your app",options:[{value:"ios",label:"IOS"},{value:"android",label:"Android"}]});p.isCancel(e)&&process.exit();const o=e,n=p.spinner();n.start(`Running: npx cap run ${o}`),yield(0,c.spawnSync)("npx",["cap","run",o],{stdio:"inherit"}),n.stop("Started Done ✅")}else p.log.info("Run yourself with command: npx cap run <ios|android>");yield j(e,o,9)})))($,i),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:"Automatic check if update working in device ?"});if(yield x(i,e,o),i)p.log.info(`Wait logs sent to Capgo from ${t} device, Put the app in background and open it again.`),p.log.info("Waiting..."),yield(0,f.waitLog)("onboarding-v2",n,t,o,e);else{const e=(0,_.convertAppName)(t);p.log.info(`Check logs in https://web.capgo.app/app/p/${e}/logs to see if update works.`)}yield j(e,o,10)})))($,i,S,o),yield j($,i,0),p.log.info("Welcome onboard ✈️!"),p.log.info("Your Capgo update system is setup"),p.log.info("Next time use `npx @capgo/cli@latest bundle upload` to only upload your bundle"),p.outro("Bye 👋"),process.exit()}))},2673:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.createKeyCommand=o.createKey=o.saveKeyCommand=o.saveKey=void 0;const l=n(7147),s=n(7304),c=n(7778),d=r(n(552)),p=n(3043),u=n(2170),f=n(9740);o.saveKey=(e,o=!0)=>a(void 0,void 0,void 0,(function*(){o&&d.intro("Save keys 🔑");const n=yield(0,u.getConfig)(),{extConfig:t}=n.app,i=e.key||u.baseKey;let r=e.keyData||"";if((0,l.existsSync)(i)||r)(0,l.existsSync)(i)&&(r=(0,l.readFileSync)(i).toString());else{if(!o)return!1;d.log.error(`Cannot find public key ${i} or as keyData option or in ${n.app.extConfigFilePath}`),s.program.error("")}return t&&(t.plugins||(t.plugins={extConfig:{},CapacitorUpdater:{}}),t.plugins.CapacitorUpdater||(t.plugins.CapacitorUpdater={}),t.plugins.CapacitorUpdater.privateKey=r,(0,c.writeConfig)(t,n.app.extConfigFilePath)),o&&(d.log.success(`private key saved into ${n.app.extConfigFilePath} file in local directory`),d.log.success("your app will decode the zip archive with this key")),!0})),o.saveKeyCommand=e=>a(void 0,void 0,void 0,(function*(){d.intro("Save keys 🔑"),yield(0,f.checkLatest)(),yield(0,o.saveKey)(e)})),o.createKey=(e,o=!0)=>a(void 0,void 0,void 0,(function*(){o&&d.intro("Create keys 🔑");const{publicKey:n,privateKey:t}=(0,p.createRSA)();if((0,l.existsSync)(u.baseKeyPub)&&!e.force){if(!o)return!1;d.log.error("Public Key already exists, use --force to overwrite"),s.program.error("")}if((0,l.writeFileSync)(u.baseKeyPub,n),(0,l.existsSync)(u.baseKey)&&!e.force){if(!o)return!1;d.log.error("Private Key already exists, use --force to overwrite"),s.program.error("")}(0,l.writeFileSync)(u.baseKey,t);const i=yield(0,u.getConfig)(),{extConfig:r}=i.app;return r&&(r.plugins||(r.plugins={extConfig:{},CapacitorUpdater:{}}),r.plugins.CapacitorUpdater.privateKey=t,(0,c.writeConfig)(r,i.app.extConfigFilePath)),o&&(d.log.success("Your RSA key has been generated"),d.log.success(`Public key saved in ${u.baseKeyPub}`),d.log.success("This key will be use to encrypt your bundle before sending it to Capgo"),d.log.success("Keep it safe"),d.log.success("Than make it unreadable by Capgo and unmodifiable by anyone"),d.log.success(`Private key saved in ${i.app.extConfigFilePath}`),d.log.success("Your app will be the only one having it"),d.log.success("Only your users can decrypt your update"),d.log.success("Only you can send them an update"),d.outro("Done ✅")),!0})),o.createKeyCommand=e=>a(void 0,void 0,void 0,(function*(){yield(0,f.checkLatest)(),yield(0,o.createKey)(e)}))},7102:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.loginCommand=o.login=void 0;const l=n(7147),s=n(2037),c=n(7304),d=r(n(552)),p=n(2170),u=n(9740);o.login=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){if(n&&d.intro("Login to Capgo"),!e)return n&&(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),!1;yield(0,u.checkLatest)();try{const{local:n}=o,t=(0,p.useLogSnag)();if(n)(0,l.existsSync)(".git")||(d.log.error("To use local you should be in a git repository"),c.program.error("")),(0,l.writeFileSync)(".capgo",`${e}\n`),(0,l.appendFileSync)(".gitignore",".capgo\n");else{const o=(0,s.homedir)();(0,l.writeFileSync)(`${o}/.capgo`,`${e}\n`)}const i=yield(0,p.createSupabaseClient)(e),r=yield(0,p.verifyUser)(i,e,["write","all","upload"]);yield t.track({channel:"user-login",event:"User CLI login",icon:"✅",user_id:r,notify:!1}).catch(),d.log.success(`login saved into .capgo file in ${n?"local":"home"} directory`)}catch(e){d.log.error("Error while saving login"),process.exit(1)}return n&&(d.outro("Done ✅"),process.exit()),!0})),o.loginCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){(0,o.login)(e,n,!0)}))},2170:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__await||function(e){return this instanceof l?(this.v=e,this):new l(e)},s=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)}))}}},c=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,i){o[t]=e[t]?function(o){return(n=!n)?{value:l(e[t](o)),done:!1}:i?i(o):o}:i}},d=this&&this.__asyncGenerator||function(e,o,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=n.apply(e,o||[]),r=[];return t={},a("next"),a("throw"),a("return",(function(e){return function(o){return Promise.resolve(o).then(e,d)}})),t[Symbol.asyncIterator]=function(){return this},t;function a(e,o){i[e]&&(t[e]=function(o){return new Promise((function(n,t){r.push([e,o,n,t])>1||s(e,o)}))},o&&(t[e]=o(t[e])))}function s(e,o){try{(n=i[e](o)).value instanceof l?Promise.resolve(n.value.v).then(c,d):p(r[0][2],n)}catch(e){p(r[0][3],e)}var n}function c(e){s("next",e)}function d(e){s("throw",e)}function p(e,o){e(o),r.shift(),r.length&&s(r[0][0],r[0][1])}},p=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkCompatibility=o.getRemoteDepenencies=o.getLocalDepenencies=o.getHumanDate=o.requireUpdateMetadata=o.verifyUser=o.convertAppName=o.useLogSnag=o.updateOrCreateChannel=o.uploadUrl=o.updateOrCreateVersion=o.formatError=o.findMainFile=o.findSavedKey=o.checkPlanValid=o.isAllowedAppOrg=o.hasOrganizationPerm=o.OrganizationPerm=o.isAllowedApp=o.isAllowedAction=o.isTrial=o.isPaying=o.isGoodPlan=o.checkKey=o.createSupabaseClient=o.getRemoteConfig=o.getLocalConfig=o.getConfig=o.regexSemver=o.defaultHostWeb=o.defaultApiHost=o.defaultHost=o.baseKeyPub=o.baseKey=void 0;const u=n(7147),f=n(2037),g=n(1017),y=n(7778),v=n(7304),h=n(2885),m=p(n(9867)),b=n(1133),_=r(n(552)),k=p(n(2167)),w=n(1406);o.baseKey=".capgo_key",o.baseKeyPub=`${o.baseKey}.pub`,o.defaultHost="https://capgo.app",o.defaultApiHost="https://api.capgo.app",o.defaultHostWeb="https://web.capgo.app",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.getConfig=()=>a(void 0,void 0,void 0,(function*(){let e;try{e=yield(0,y.loadConfig)()}catch(e){_.log.error("No capacitor config file found, run `cap init` first"),v.program.error("")}return e})),o.getLocalConfig=()=>a(void 0,void 0,void 0,(function*(){var e,n,t,i,r,a,l,s,c,d,p,u,f,g,y,v,h,m,b,_,k,w,C,O;try{const P=yield(0,o.getConfig)(),x={host:(null===(i=null===(t=null===(n=null===(e=null==P?void 0:P.app)||void 0===e?void 0:e.extConfig)||void 0===n?void 0:n.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===i?void 0:i.localHost)||o.defaultHost,hostWeb:(null===(s=null===(l=null===(a=null===(r=null==P?void 0:P.app)||void 0===r?void 0:r.extConfig)||void 0===a?void 0:a.plugins)||void 0===l?void 0:l.CapacitorUpdater)||void 0===s?void 0:s.localWebHost)||o.defaultHostWeb};return(null===(u=null===(p=null===(d=null===(c=null==P?void 0:P.app)||void 0===c?void 0:c.extConfig)||void 0===d?void 0:d.plugins)||void 0===p?void 0:p.CapacitorUpdater)||void 0===u?void 0:u.localSupa)&&(null===(v=null===(y=null===(g=null===(f=null==P?void 0:P.app)||void 0===f?void 0:f.extConfig)||void 0===g?void 0:g.plugins)||void 0===y?void 0:y.CapacitorUpdater)||void 0===v?void 0:v.localSupaAnon)&&(x.supaKey=null===(_=null===(b=null===(m=null===(h=null==P?void 0:P.app)||void 0===h?void 0:h.extConfig)||void 0===m?void 0:m.plugins)||void 0===b?void 0:b.CapacitorUpdater)||void 0===_?void 0:_.localSupaAnon,x.supaHost=null===(O=null===(C=null===(w=null===(k=null==P?void 0:P.app)||void 0===k?void 0:k.extConfig)||void 0===w?void 0:w.plugins)||void 0===C?void 0:C.CapacitorUpdater)||void 0===O?void 0:O.localSupa),x}catch(e){return{host:o.defaultHost,hostWeb:o.defaultHostWeb}}}));const C=/([A-Za-z0-9]+)\.(java|swift|kt|scala)$/;var O;function P(e){return d(this,arguments,(function*(){const o=yield l((0,u.readdirSync)(e,{withFileTypes:!0}));for(const n of o){const o=(0,g.resolve)(e,n.name);!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("node_modules")||n.name.startsWith("dist")?yield yield l(o):yield l(yield*c(s(P(o))))}}))}function x(){return a(this,void 0,void 0,(function*(){let e;(0,u.existsSync)("./package.json")||(_.log.error("Missing package.json, you need to be in a capacitor project"),v.program.error(""));try{e=JSON.parse((0,u.readFileSync)("./package.json","utf8"))}catch(e){_.log.error("Invalid package.json, JSON parsing failed"),console.error("json parse error: ",e),v.program.error("")}const{dependencies:o}=e;o||(_.log.error("Missing dependencies section in package.json"),v.program.error(""));for(const[e,n]of Object.entries(o))"string"!=typeof n&&(_.log.error(`Invalid dependency ${e}: ${n}, expected string, got ${typeof n}`),v.program.error(""));(0,u.existsSync)("./node_modules/")||(_.log.error("Missing node_modules folder, please run npm install"),v.program.error(""));let n=!1;const t=yield Promise.all(Object.entries(o).map((([e,o])=>a(this,void 0,void 0,(function*(){if(!(0,u.existsSync)(`./node_modules/${e}`))return n=!0,_.log.error(`Missing dependency ${e}, please run npm install`),{name:e,version:o};let t=!1;return yield(0,w.promiseFiles)(`./node_modules/${e}`).then((e=>{e.find((e=>C.test(e)))&&(t=!0)})).catch((o=>{_.log.error(`Error reading node_modulses files for ${e} package`),console.error(o),v.program.error("")})),{name:e,version:o,native:t}}))))).catch((()=>[]));return(n||t.find((e=>void 0===e.native)))&&v.program.error(""),t}))}function j(e,o,n){return a(this,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("channels").select("version ( \n native_packages \n )").eq("name",n).eq("app_id",o).single();let r;i&&(_.log.error(`Error fetching native packages: ${i.message}`),v.program.error(""));try{r=t.version.native_packages}catch(e){_.log.error("Error parsing native packages"),v.program.error("")}return r||(_.log.error("Error parsing native packages, perhaps the metadata does not exist?"),v.program.error("")),r.forEach((e=>{"object"!=typeof e&&(_.log.error(`Invalid remote native package data: ${e}, expected object, got ${typeof e}`),v.program.error(""));const{name:o,version:n}=e;o&&"string"==typeof o||(_.log.error(`Invalid remote native package name: ${o}, expected string, got ${typeof o}`),v.program.error("")),n&&"string"==typeof n||(_.log.error(`Invalid remote native package version: ${n}, expected string, got ${typeof n}`),v.program.error(""))})),new Map(r.map((e=>[e.name,e])))}))}o.getRemoteConfig=()=>a(void 0,void 0,void 0,(function*(){const e=yield(0,o.getLocalConfig)();return k.default.get(`${o.defaultApiHost}/get_config`).then((e=>e.data)).then((o=>Object.assign(Object.assign({},o),e))).catch((()=>(console.log("Local config",e),e)))})),o.createSupabaseClient=e=>a(void 0,void 0,void 0,(function*(){const n=yield(0,o.getRemoteConfig)();return n.supaHost&&n.supaKey||(_.log.error("Cannot connect to server please try again later"),v.program.error("")),(0,h.createClient)(n.supaHost,n.supaKey,{auth:{persistSession:!1},global:{headers:{capgkey:e}}})})),o.checkKey=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t}=yield e.rpc("is_allowed_capgkey",{apikey:o,keymode:n}).single();if(!t){_.log.error("Invalid API key or insufficient permissions.");const e=n.map(((e,o)=>o===n.length-1?`or ${e}`:`${e}, `)).join("");_.log.error(`Your key should be: ${e} mode.`),v.program.error("")}})),o.isGoodPlan=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_good_plan_v3",{userid:o}).single();return n||!1})),o.isPaying=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_paying",{userid:o}).single();return n||!1})),o.isTrial=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_trial",{userid:o}).single();return n||0})),o.isAllowedAction=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_allowed_action_user",{userid:o}).single();return!!n})),o.isAllowedApp=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t}=yield e.rpc("is_app_owner",{apikey:o,appid:n}).single();return!!t})),function(e){e[e.none=0]="none",e[e.read=1]="read",e[e.upload=2]="upload",e[e.write=3]="write",e[e.admin=4]="admin",e[e.owner=5]="owner"}(O||(o.OrganizationPerm=O={})),o.hasOrganizationPerm=(e,o)=>e>=o,o.isAllowedAppOrg=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.rpc("get_org_perm_for_apikey",{apikey:o,app_id:n}).single();if(i&&(_.log.error("Cannot get permissions for organization!"),console.error(i),process.exit(1)),t.includes("perm")){let e=null;switch(t){case"perm_none":e=O.none;break;case"perm_read":e=O.read;break;case"perm_upload":e=O.upload;break;case"perm_write":e=O.write;break;case"perm_admin":e=O.admin;break;case"perm_owner":e=O.owner;break;default:t.includes("invite")&&(_.log.info("Please accept/deny the organization invitation before trying to access the app"),process.exit(1)),_.log.error(`Invalid output when fetching organization permission. Response: ${t}`),process.exit(1)}return{okay:!0,data:e}}let r=null;switch(t){case"INVALID_APIKEY":r="INVALID_APIKEY";break;case"NO_APP":r="NO_APP";break;case"NO_ORG":r="NO_ORG";break;default:_.log.error(`Invalid error when fetching organization permission. Response: ${t}`),process.exit(1)}return{okay:!1,error:r}})),o.checkPlanValid=(e,t,i=!0)=>a(void 0,void 0,void 0,(function*(){const a=yield(0,o.getRemoteConfig)();(yield(0,o.isAllowedAction)(e,t))||(_.log.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${a.hostWeb}/dashboard/settings/plans\n`),setTimeout((()=>{Promise.resolve().then((()=>r(n(6634)))).then((e=>{e.default(`${a.hostWeb}/dashboard/settings/plans`)})),v.program.error("")}),1e3));const l=yield(0,o.isTrial)(e,t),s=yield(0,o.isPaying)(e,t);l>0&&i&&!s&&_.log.warn(`WARNING !!\nTrial expires in ${l} days, upgrade here: ${a.hostWeb}/dashboard/settings/plans\n`)})),o.findSavedKey=(e=!1)=>{let o,n=`${(0,f.homedir)()}/.capgo`;return(0,u.existsSync)(n)&&(e||_.log.info(`Use global apy key ${n}`),o=(0,u.readFileSync)(n,"utf8").trim()),n=".capgo",!o&&(0,u.existsSync)(n)&&(e||_.log.info(`Use local apy key ${n}`),o=(0,u.readFileSync)(n,"utf8").trim()),o||(_.log.error("Cannot find API key in local folder or global, please login first with npx @capacitor/cli login"),v.program.error("")),o},o.findMainFile=()=>a(void 0,void 0,void 0,(function*(){var e,o,n,t;const i=/(main|index)\.(ts|tsx|js|jsx)$/;let r="";const a=process.cwd(),l=a.split("/").length;try{for(var c,d=!0,p=s(P(a));!(e=(c=yield p.next()).done);d=!0){t=c.value,d=!1;const e=t;if(e.split("/").length-l<=2&&i.test(e)){r=e,_.log.info(`Found main file here ${e}`);break}}}catch(e){o={error:e}}finally{try{d||e||!(n=p.return)||(yield n.call(p))}finally{if(o)throw o.error}}return r})),o.formatError=e=>e?`\n${m.default.render(e)}`:"",o.updateOrCreateVersion=(e,o,n)=>a(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)):e.from("app_versions").insert(o)})),o.uploadUrl=function(e,o,n){return a(this,void 0,void 0,(function*(){const t={app_id:o,bucket_id:n};try{return(yield e.functions.invoke("upload_link",{body:JSON.stringify(t)})).data.url}catch(e){_.log.error(`Cannot get upload url ${JSON.stringify(e)}`)}return""}))},o.updateOrCreateChannel=(e,o)=>a(void 0,void 0,void 0,(function*(){if(!o.app_id||!o.name||!o.created_by)return _.log.error("missing app_id, name, or created_by"),Promise.reject(new Error("missing app_id, name, or created_by"));const{data:n,error:t}=yield e.from("channels").select("enable_progressive_deploy, secondaryVersionPercentage, secondVersion").eq("app_id",o.app_id).eq("name",o.name).single();if(n&&!t){if(n.enable_progressive_deploy){if(_.log.info("Progressive deploy is enabled"),1!==n.secondaryVersionPercentage&&_.log.warn("Latest progressive deploy has not finished"),o.secondVersion=o.version,!n.secondVersion)return _.log.error("missing secondVersion"),Promise.reject(new Error("missing secondVersion"));o.version=n.secondVersion,o.secondaryVersionPercentage=.1,_.log.info("Started new progressive upload!")}return e.from("channels").update(o).eq("app_id",o.app_id).eq("name",o.name).select().single()}return e.from("channels").insert(o).select().single()})),o.useLogSnag=()=>new b.LogSnag({token:"c124f5e9d0ce5bdd14bbb48f815d5583",project:"capgo"}),o.convertAppName=e=>e.replace(/\./g,"--"),o.verifyUser=(e,n,t=["all"])=>a(void 0,void 0,void 0,(function*(){yield(0,o.checkKey)(e,n,t);const{data:i,error:r}=yield e.rpc("get_user_id",{apikey:n}).single(),a=(i||"").toString();return a&&!r||(_.log.error("Cannot auth user with apikey"),v.program.error("")),a})),o.requireUpdateMetadata=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select("disableAutoUpdate").eq("name",o).limit(1);if(t&&(_.log.error(`Cannot check if disableAutoUpdate is required ${JSON.stringify(t)}`),v.program.error("")),0===n.length)return!1;const{disableAutoUpdate:i}=n[0];return"version_number"===i})),o.getHumanDate=e=>new Date(e||"").toLocaleString(),o.getLocalDepenencies=x,o.getRemoteDepenencies=j,o.checkCompatibility=function(e,o,n){return a(this,void 0,void 0,(function*(){const t=yield x(),i=yield j(e,o,n),r=t.filter((e=>!!e.native)).map((e=>{const o=i.get(e.name);return o?{name:e.name,localVersion:e.version,remoteVersion:o.version}:{name:e.name,localVersion:e.version,remoteVersion:void 0}})),a=[...i].filter((([e])=>void 0===t.find((o=>o.name===e)))).map((([e,o])=>({name:e,localVersion:void 0,remoteVersion:o.version})));return r.push(...a),{finalCompatibility:r,localDependencies:t}}))}},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")},2167:e=>{e.exports=require("axios")},7812:e=>{e.exports=require("ci-info")},7304:e=>{e.exports=require("commander")},3847:e=>{e.exports=require("console-table-printer")},5362:e=>{e.exports=require("get-latest-version")},1133:e=>{e.exports=require("logsnag")},9011:e=>{e.exports=require("mime")},1406:e=>{e.exports=require("node-dir")},6634:e=>{e.exports=require("open")},9867:e=>{e.exports=require("prettyjson")},1616:e=>{e.exports=require("prompt-sync")},912:e=>{e.exports=require("semver")},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")},7561:e=>{e.exports=require("node:fs")},2037:e=>{e.exports=require("os")},1017:e=>{e.exports=require("path")},4147:e=>{e.exports=JSON.parse('{"name":"@capgo/cli","version":"3.14.61","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":"5.5.1","@capgo/find-package-manager":"^0.0.7","@clack/prompts":"^0.7.0","@supabase/supabase-js":"^2.38.5","@tomasklaen/checksum":"^1.1.0","@trufflesuite/spinnies":"^0.1.1","adm-zip":"^0.5.10","axios":"^1.6.2","ci-info":"^4.0.0","commander":"11.1.0","console-table-printer":"^2.11.2","get-latest-version":"^5.1.0","logsnag":"1.0.0","mime":"^3.0.0","node-dir":"^0.1.17","open":"^9.1.0","prettyjson":"^1.2.5","prompt-sync":"^4.2.0","qrcode":"^1.5.3","semver":"^7.5.4"},"devDependencies":{"@types/adm-zip":"0.5.5","@types/mime":"^3.0.4","@types/node":"^20.9.4","@types/node-dir":"^0.0.37","@types/npmcli__ci-detect":"^2.0.3","@types/prettyjson":"^0.0.33","@types/prompt-sync":"^4.2.3","@types/qrcode":"^1.5.5","@types/semver":"^7.5.6","@typescript-eslint/eslint-plugin":"6.12.0","@typescript-eslint/parser":"6.12.0","eslint":"8.55.0","eslint-config-airbnb-base":"^15.0.0","eslint-config-prettier":"^9.0.0","eslint-import-resolver-typescript":"3.6.1","eslint-plugin-import":"2.29.0","eslint-plugin-prettier":"^5.0.1","git-format-staged":"3.0.0","husky":"^8.0.3","nodemon":"3.0.2","pkg":"5.8.1","prettier":"3.1.1","ts-loader":"^9.5.1","ts-node":"^10.9.1","tsconfig-paths":"4.2.0","typescript":"5.3.3","webpack":"5.89.0","webpack-cli":"^5.1.4","webpack-node-externals":"^3.0.0"}}')}},o={};!function n(t){var i=o[t];if(void 0!==i)return i.exports;var r=o[t]={exports:{}};return e[t].call(r.exports,r,r.exports,n),r.exports}(1428)})();
2
+ (()=>{"use strict";var e={3018:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.newIconPath=o.checkAppExistsAndHasPermissionOrgErr=o.checkAppExistsAndHasPermissionErr=o.checkAppExists=void 0;const l=r(n(552)),s=n(7304),c=n(2170);o.checkAppExists=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("exist_app_v2",{appid:o}).single();return!!n})),o.checkAppExistsAndHasPermissionErr=(e,n,t,i=!0)=>a(void 0,void 0,void 0,(function*(){const r=yield(0,o.checkAppExists)(e,t),a=yield(0,c.isAllowedApp)(e,n,t);r&&!i&&(l.log.error(`App ${t} already exist`),s.program.error("")),!r&&i&&(l.log.error(`App ${t} does not exist`),s.program.error("")),r&&!a&&(l.log.error(`App ${t} exist and you don't have permission to access it`),s.program.error(""))})),o.checkAppExistsAndHasPermissionOrgErr=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield(0,c.isAllowedAppOrg)(e,o,n);if(!i.okay)switch(i.error){case"INVALID_APIKEY":l.log.error("Invalid apikey, such apikey does not exists!"),s.program.error("");break;case"NO_APP":l.log.error(`App ${n} does not exist`),s.program.error("");break;case"NO_ORG":l.log.error("Could not find organization, please contact support to resolve this!"),s.program.error("")}const r=i.data;return t>r&&(l.log.error(`Insuficcent permissions for app ${n}. Current permission: ${c.OrganizationPerm[i.data]}, required for this action: ${c.OrganizationPerm[t]}.`),s.program.error("")),i.data})),o.newIconPath="assets/icon.png"},7175:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((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 l=n(7304),s=n(3847),c=r(n(552)),d=n(2170);o.checkVersionNotUsedInChannel=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){var r;const{data:a,error:s}=yield e.from("channels").select().eq("app_id",n).eq("created_by",t).eq("version",i.id);if(s&&(c.log.error(`Cannot check Version ${n}@${i.name}`),l.program.error("")),a&&a.length>0){if(c.intro(`❌ Version ${n}@${i.name} is used in ${a.length} channel`),yield c.confirm({message:"unlink it?"}))for(const t of a){const i=c.spinner();i.start(`Unlinking channel ${t.name}`);const{error:a}=yield e.from("channels").update({version:null===(r=yield(0,o.findUnknownVersion)(e,n))||void 0===r?void 0:r.id}).eq("id",t.id);a&&(i.stop(`Cannot update channel ${t.name} ${(0,d.formatError)(a)}`),process.exit(1)),i.stop(`✅ Channel ${t.name} unlinked`)}else c.log.error("Unlink it first"),l.program.error("");c.outro(`Version unlinked from ${a.length} channel`)}})),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 s.Table({title:"Channels",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,Created:(0,d.getHumanDate)(e.created_at),Public:e.public?"✅":"❌"})})),c.log.success(o.render())},o.getActiveChannels=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select().eq("app_id",o).order("created_at",{ascending:!1});return t&&(c.log.error(`App ${o} not found in database`),l.program.error("")),n}))},3043:(e,o,n)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createRSA=o.encryptSource=o.decryptSource=void 0;const t=n(6113),i="aes-128-cbc",r="sha256",a="base64",l=t.constants.RSA_PKCS1_OAEP_PADDING;o.decryptSource=(e,o,n)=>{const[s,c]=o.split(":"),d=(0,t.privateDecrypt)({key:n,padding:l,oaepHash:r},Buffer.from(c,a)),p=Buffer.from(s,a),u=(0,t.createDecipheriv)(i,d,p);return u.setAutoPadding(!0),Buffer.concat([u.update(e),u.final()])},o.encryptSource=(e,o)=>{const n=(0,t.randomBytes)(16),s=(0,t.randomBytes)(16),c=(0,t.createCipheriv)(i,s,n);c.setAutoPadding(!0);const d=`${n.toString(a)}:${(0,t.publicEncrypt)({key:o,padding:l,oaepHash:r},s).toString(a)}`;return{encryptedData:Buffer.concat([c.update(e),c.final()]),ivSessionKey:d}},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"})}}},1915:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.checkVersionNotUsedInDeviceOverride=void 0;const l=n(7304),s=r(n(552)),c=n(2170);o.checkVersionNotUsedInDeviceOverride=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("devices_override").select().eq("app_id",o).eq("version",n.id);if(i&&(s.log.error(`Cannot check Device override ${o}@${n.name}`),l.program.error("")),t&&t.length>0)if(s.intro(`❌ Version ${o}@${n.name} is used in ${t.length} device override`),yield s.confirm({message:"unlink it?"}))for(const o of t){const n=s.spinner();n.start(`Unlinking device ${o.device_id}`);const{error:t}=yield e.from("devices_override").delete().eq("device_id",o.device_id);t&&(n.stop(`Cannot unlink device ${o.device_id} ${(0,c.formatError)(t)}`),process.exit(1)),n.stop(`✅ Device ${o.device_id} unlinked`)}else s.log.error("Unlink it first"),l.program.error("")}))},9740:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkLatest=void 0;const s=l(n(5362)),c=r(n(552)),d=l(n(4147));o.checkLatest=()=>a(void 0,void 0,void 0,(function*(){const e=yield(0,s.default)("@capgo/cli");e!==d.default.version&&c.log.warning(`🚨 You are using @capgo/cli@${d.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.`)}))},1820:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.getVersionData=o.getChannelsVersion=o.getActiveAppVersions=o.displayBundles=o.deleteSpecificVersion=o.deleteAppVersion=void 0;const l=n(7304),s=n(3847),c=r(n(552)),d=n(2170),p=n(7175),u=n(1915);o.deleteAppVersion=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const{error:i}=yield e.from("app_versions").update({deleted:!0}).eq("app_id",o).eq("deleted",!1).eq("user_id",n).eq("name",t);i&&(c.log.error(`App Version ${o}@${t} not found in database`),l.program.error(""))})),o.deleteSpecificVersion=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){const r=yield(0,o.getVersionData)(e,n,t,i);yield(0,p.checkVersionNotUsedInChannel)(e,n,t,r),yield(0,u.checkVersionNotUsedInDeviceOverride)(e,n,r),yield(0,o.deleteAppVersion)(e,n,t,i)})),o.displayBundles=e=>{const o=new s.Table({title:"Bundles",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow(Object.assign({Version:e.name,Created:(0,d.getHumanDate)(e.created_at)},null!=e.keep?{Keep:e.keep}:{}))})),c.log.success(o.render())},o.getActiveAppVersions=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("deleted",!1).order("created_at",{ascending:!1});return i&&(c.log.error(`App ${o} not found in database`),l.program.error("")),t})),o.getChannelsVersion=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select("version").eq("app_id",o);return t&&(c.log.error(`App ${o} not found in database`),l.program.error("")),n.map((e=>e.version))})),o.getVersionData=(e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const{data:i,error:r}=yield e.from("app_versions").select().eq("app_id",o).eq("user_id",n).eq("name",t).eq("deleted",!1).single();return i&&!r||(c.log.error(`App Version ${o}@${t} doesn't exist`),l.program.error("")),i}))},2622:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addCommand=o.addApp=void 0;const l=n(6113),s=n(9011),c=n(7304),d=r(n(552)),p=n(7561),u=n(9740),f=n(3018),g=n(2170);o.addApp=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){var t,i,r;n&&d.intro("Adding"),yield(0,u.checkLatest)(),o.apikey=o.apikey||(0,g.findSavedKey)();const a=yield(0,g.getConfig)();e=e||(null===(t=null==a?void 0:a.app)||void 0===t?void 0:t.appId);const y=(0,g.useLogSnag)();o.apikey||(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),e||(d.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),c.program.error(""));const v=yield(0,g.createSupabaseClient)(o.apikey),h=yield(0,g.verifyUser)(v,o.apikey,["write","all"]),m=yield(0,f.checkAppExists)(v,e);if(n&&m)d.log.error(`App ${e} already exist`),c.program.error("");else if(m)return!0;let b,_,{name:k,icon:w}=o;e=e||(null===(i=null==a?void 0:a.app)||void 0===i?void 0:i.appId),k=k||(null===(r=null==a?void 0:a.app)||void 0===r?void 0:r.appName)||"Unknown",w=w||"resources/icon.png",w&&k||(d.log.error("Missing argument, you need to provide a appId and a name, or be in a capacitor project"),c.program.error("")),n&&d.log.info(`Adding ${e} to Capgo`),w&&(0,p.existsSync)(w)?(b=(0,p.readFileSync)(w),_=(0,s.getType)(w)||"image/png",d.log.warn(`Found app icon ${w}`)):(0,p.existsSync)(f.newIconPath)?(b=(0,p.readFileSync)(f.newIconPath),_=(0,s.getType)(f.newIconPath)||"image/png",d.log.warn(`Found app icon ${f.newIconPath}`)):d.log.warn(`Cannot find app icon in any of the following locations: ${w}, ${f.newIconPath}`);const C=`icon_${(0,l.randomUUID)()}`;let O="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(b&&_){const{error:o}=yield v.storage.from(`images/${h}/${e}`).upload(C,b,{contentType:_});o&&(d.log.error(`Could not add app ${(0,g.formatError)(o)}`),c.program.error(""));const{data:n}=yield v.storage.from(`images/${h}/${e}`).getPublicUrl(C);O=(null==n?void 0:n.publicUrl)||O}const{error:P}=yield v.from("apps").insert({icon_url:O,user_id:h,name:k,app_id:e});P&&(d.log.error(`Could not add app ${(0,g.formatError)(P)}`),c.program.error(""));const{error:x}=yield v.from("app_versions").insert([{user_id:h,deleted:!0,name:"unknown",app_id:e},{user_id:h,deleted:!0,name:"builtin",app_id:e}]);return x&&(d.log.error(`Could not add app ${(0,g.formatError)(x)}`),c.program.error("")),yield y.track({channel:"app",event:"App Added",icon:"🎉",user_id:h,tags:{"app-id":e},notify:!1}).catch(),d.log.success(`App ${e} added to Capgo. ${n?"You can upload a bundle now":""}`),n&&(d.outro("Done ✅"),process.exit()),!0})),o.addCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){(0,o.addApp)(e,n,!0)}))},3713:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.debugApp=o.waitLog=o.getStats=o.cancelCommand=o.markSnag=void 0;const l=r(n(552)),s=n(7304),c=n(3018),d=n(9740),p=n(2170),u=e=>new Promise((o=>{setTimeout(o,e)}));function f(e,o){return a(this,void 0,void 0,(function*(){try{const n=(yield e.functions.invoke("get_stats",{body:JSON.stringify(o)})).data.data;if((null==n?void 0:n.length)>0)return n[0]}catch(e){l.log.error(`Cannot get stats ${JSON.stringify(e)}`)}return null}))}o.markSnag=(e,o,n,t,i="✅")=>a(void 0,void 0,void 0,(function*(){yield n.track({channel:e,event:t,icon:i,user_id:o,notify:!1}).catch()})),o.cancelCommand=(e,n,t,i)=>a(void 0,void 0,void 0,(function*(){l.isCancel(n)&&(yield(0,o.markSnag)(e,t,i,"canceled","🤷"),process.exit())})),o.getStats=f,o.waitLog=(e,n,t,i,r,s)=>a(void 0,void 0,void 0,(function*(){let a=!0,c=(new Date).toISOString();const d=(0,p.convertAppName)(t),g=`${(yield(0,p.getLocalConfig)()).hostWeb}/app/p/${d}`;yield(0,o.markSnag)(e,r,i,"Use waitlog");const y={appId:t,devicesId:s?[s]:void 0,order:[{key:"created_at",sortable:"desc"}],rangeStart:0,rangeEnd:1,after:c};for(;a;){const t=yield f(n,y);if(t){if(l.log.info(`Log from Device: ${t.device_id}`),"get"===t.action)l.log.info("Update Sent your your device, wait until event download complete"),yield(0,o.markSnag)(e,r,i,"done");else if(t.action.startsWith("download_")){const n=t.action.split("_")[1];"complete"===n?(l.log.info("Your bundle has been downloaded on your device, background the app now and open it again to see the update"),yield(0,o.markSnag)(e,r,i,"downloaded")):"fail"===n?(l.log.error("Your bundle has failed to download on your device."),l.log.error("Please check if you have network connection and try again")):l.log.info(`Your bundle is downloading ${n}% ...`)}else{if("set"===t.action)return l.log.info("Your bundle has been set on your device ❤️"),a=!1,yield(0,o.markSnag)(e,r,i,"set"),Promise.resolve(t);"NoChannelOrOverride"===t.action?l.log.error(`No default channel or override (channel/device) found, please create it here ${g}`):"needPlanUpgrade"===t.action?l.log.error("Your are out of quota, please upgrade your plan here https://web.capgo.app/dashboard/settings/plans"):"missingBundle"===t.action?l.log.error("Your bundle is missing, please check how you build your app "):"noNew"===t.action?l.log.error(`Your version in ${t.platform} is the same as your version uploaded, change it to see the update`):"disablePlatformIos"===t.action?l.log.error(`iOS is disabled in the default channel and your device is an iOS device ${g}`):"disablePlatformAndroid"===t.action?l.log.error(`Android is disabled in the default channel and your device is an Android device ${g}`):"disableAutoUpdateToMajor"===t.action?(l.log.error("Auto update to major version is disabled in the default channel."),l.log.error("Set your app to the same major version as the default channel")):"disableAutoUpdateUnderNative"===t.action?(l.log.error("Auto update under native version is disabled in the default channel."),l.log.error("Set your app to the same native version as the default channel.")):"disableDevBuild"===t.action?(l.log.error(`Dev build is disabled in the default channel. ${g}`),l.log.error("Set your channel to allow it if you wanna test your app")):"disableEmulator"===t.action?(l.log.error(`Emulator is disabled in the default channel. ${g}`),l.log.error("Set your channel to allow it if you wanna test your app")):"cannotGetBundle"===t.action?(l.log.error(`We cannot get your bundle from the default channel. ${g}`),l.log.error("Are you sure your default channel has a bundle set?")):"set_fail"===t.action?l.log.error(`Your bundle seems to be corrupted, try to download from ${g} to identify the issue`):"reset"===t.action?l.log.error("Your device has been reset to the builtin bundle, did you added notifyAppReady in your code?"):"update_fail"===t.action?(l.log.error("Your bundle has been installed but failed to call notifyAppReady"),l.log.error("Please check if you have network connection and try again")):"checksum_fail"===t.action?l.log.error("Your bundle has failed to validate checksum, please check your code and send it again to Capgo"):l.log.error(`Log from Capgo ${t.action}`)}c=(new Date).toISOString(),y.after=c}yield u(1e3)}return Promise.resolve()})),o.debugApp=(e,n)=>a(void 0,void 0,void 0,(function*(){var t;l.intro("Debug Live update in Capgo"),yield(0,d.checkLatest)(),n.apikey=n.apikey||(0,p.findSavedKey)();const i=yield(0,p.getConfig)();e=e||(null===(t=null==i?void 0:i.app)||void 0===t?void 0:t.appId);const r=n.device;n.apikey||(l.log.error("Missing API key, you need to provide an API key to delete your app"),s.program.error("")),e||(l.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),s.program.error(""));const a=yield(0,p.createSupabaseClient)(n.apikey),u=(0,p.useLogSnag)(),f=yield(0,p.verifyUser)(a,n.apikey);l.log.info("Getting active bundle in Capgo"),yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,e);const g=yield l.confirm({message:"Automatic check if update working in device ?"});yield(0,o.cancelCommand)("debug",g,f,u),g?(l.log.info(`Wait logs sent to Capgo from ${e} device, Put the app in background and open it again.`),l.log.info("Waiting..."),yield(0,o.waitLog)("debug",a,e,u,f,r),l.outro("Done ✅")):l.outro("Canceled ❌"),l.outro("Done ✅"),process.exit()}))},8437:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteApp=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170);o.deleteApp=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("Deleting"),o.apikey=o.apikey||(0,d.findSavedKey)();const t=yield(0,d.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId);const i=(0,d.useLogSnag)();o.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const r=yield(0,d.createSupabaseClient)(o.apikey),a=yield(0,d.verifyUser)(r,o.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(r,o.apikey,e);const{error:p}=yield r.storage.from(`images/${a}`).remove([e]);p&&s.log.error("Could not delete app logo");const{error:u}=yield r.storage.from(`apps/${e}/${a}`).remove(["versions"]);u&&(s.log.error("Could not delete app version"),l.program.error(""));const{error:f}=yield r.from("apps").delete().eq("app_id",e).eq("user_id",a);f&&(s.log.error("Could not delete app"),l.program.error("")),yield i.track({channel:"app",event:"App Deleted",icon:"🗑️",user_id:a,tags:{"app-id":e},notify:!1}).catch(),s.log.success("App deleted in Capgo"),s.outro("Done ✅"),process.exit()}))},9785:function(e,o,n){var t=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((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 r=n(7147),a=n(1017),l=i(n(2037)),s=i(n(5362)),c=i(n(7176)),d=i(n(4147));o.getInfo=()=>t(void 0,void 0,void 0,(function*(){console.log(" 💊 Capgo Doctor 💊\n"),console.log(` OS: ${l.default.platform()} ${l.default.version()}\n`),console.log(` Node: ${process.version}\n`),console.log(" Installed Dependencies:\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,r.readFileSync)((0,a.join)(process.cwd(),"package.json"));return JSON.parse(e)})),o={"@capgo/cli":d.default.version};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith("@capgo/")){const t=e[n].replace("^","").replace("~","");o[n]=t}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,s.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()}))},4738:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listApp=o.getActiveApps=void 0;const l=n(7304),s=n(3847),c=r(n(552)),d=n(2170),p=n(9740);o.getActiveApps=e=>a(void 0,void 0,void 0,(function*(){const{data:o,error:n}=yield e.from("apps").select().order("created_at",{ascending:!1});return n&&(c.log.error("Apps not found"),l.program.error("")),o})),o.listApp=e=>a(void 0,void 0,void 0,(function*(){c.intro("List apps in Capgo"),yield(0,p.checkLatest)(),e.apikey=e.apikey||(0,d.findSavedKey)();const n=yield(0,d.createSupabaseClient)(e.apikey);yield(0,d.verifyUser)(n,e.apikey,["write","all","read","upload"]),c.log.info("Getting active bundle in Capgo");const t=yield(0,o.getActiveApps)(n);c.log.info(`Active app in Capgo: ${null==t?void 0:t.length}`),(e=>{const o=new s.Table({title:"Apps",charLength:{"❌":2,"✅":2}});e.reverse().forEach((e=>{o.addRow({Name:e.name,id:e.app_id,Created:(0,d.getHumanDate)(e.created_at)})})),c.log.success(o.render())})(t),c.outro("Done ✅"),process.exit()}))},7791:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setApp=void 0;const l=n(6113),s=n(9011),c=n(7304),d=r(n(552)),p=n(7561),u=n(3018),f=n(2170);o.setApp=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;d.intro("Set app"),o.apikey=o.apikey||(0,f.findSavedKey)();const t=yield(0,f.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId),o.apikey||(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),e||(d.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),c.program.error(""));const i=yield(0,f.createSupabaseClient)(o.apikey),r=yield(0,f.verifyUser)(i,o.apikey,["write","all"]);yield(0,u.checkAppExistsAndHasPermissionErr)(i,o.apikey,e);const{name:a,icon:g,retention:y}=o;let v,h;y&&!Number.isNaN(Number(y))?(d.log.error("retention value must be a number"),c.program.error("")):y&&y<0&&(d.log.error("retention value cannot be less than 0"),c.program.error(""));const m=`icon_${(0,l.randomUUID)()}`;let b="https://xvwzpoazmxkqosrdewyv.supabase.co/storage/v1/object/public/images/capgo.png";if(g&&(0,p.existsSync)(g)?(v=(0,p.readFileSync)(g),h=(0,s.getType)(g)||"image/png",d.log.warn(`Found app icon ${g}`)):(0,p.existsSync)(u.newIconPath)?(v=(0,p.readFileSync)(u.newIconPath),h=(0,s.getType)(u.newIconPath)||"image/png",d.log.warn(`Found app icon ${u.newIconPath}`)):d.log.warn(`Cannot find app icon in any of the following locations: ${g}, ${u.newIconPath}`),v&&h){const{error:o}=yield i.storage.from(`images/${r}/${e}`).upload(m,v,{contentType:h});o&&(d.log.error(`Could not add app ${(0,f.formatError)(o)}`),c.program.error(""));const{data:n}=yield i.storage.from(`images/${r}/${e}`).getPublicUrl(m);b=(null==n?void 0:n.publicUrl)||b}const{error:_}=yield i.from("apps").update({icon_url:b,name:a,retention:y?24*y*60*60:void 0}).eq("app_id",e).eq("user_id",r);_&&(d.log.error(`Could not add app ${(0,f.formatError)(_)}`),c.program.error("")),d.outro("Done ✅"),process.exit()}))},7092:function(e,o,n){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkIndexPosition=o.searchInDirectory=void 0;const i=t(n(7147)),r=t(n(1017)),a=(e,o)=>i.default.readFileSync(e,"utf8").includes(o);o.searchInDirectory=(e,n)=>{const t=i.default.readdirSync(e);for(const l of t){const t=r.default.join(e,l),s=i.default.statSync(t);if(s.isDirectory()){if((0,o.searchInDirectory)(t,n))return!0}else if(s.isFile()&&".js"===r.default.extname(t)&&a(t,n))return!0}return!1},o.checkIndexPosition=e=>{const n=i.default.readdirSync(e);if(1===n.length){const t=r.default.join(e,n[0]);if(i.default.statSync(t).isDirectory())return(0,o.checkIndexPosition)(t)}return n.indexOf("index.html")>-1}},9690:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=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)}))}}},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.cleanupBundle=void 0;const c=n(7304),d=s(n(1505)),p=r(n(552)),u=s(n(1616)),f=n(2170),g=n(1820),y=n(3018),v=n(9740),h=(0,u.default)();o.cleanupBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;p.intro("Cleanup versions in Capgo"),yield(0,v.checkLatest)(),o.apikey=o.apikey||(0,f.findSavedKey)();const{bundle:t,keep:i=4}=o,r=o.force||!1,s=yield(0,f.getConfig)();e=e||(null===(n=null==s?void 0:s.app)||void 0===n?void 0:n.appId),o.apikey||(p.log.error("Missing API key, you need to provide an API key to delete your app"),c.program.error("")),e||(p.log.error("Missing argument, you need to provide a appid, or be in a capacitor project"),c.program.error(""));const u=yield(0,f.createSupabaseClient)(o.apikey),m=yield(0,f.verifyUser)(u,o.apikey);yield(0,y.checkAppExistsAndHasPermissionErr)(u,o.apikey,e),p.log.info("Querying all available versions in Capgo");let b=yield(0,g.getActiveAppVersions)(u,e,m);const _=yield(0,g.getChannelsVersion)(u,e);if(p.log.info(`Total active versions in Capgo: ${null==b?void 0:b.length}`),0===(null==b?void 0:b.length))return void p.log.error("No versions found, aborting cleanup");if(t){const e=`${d.default.inc(t,"major")}`;p.log.info(`Querying available versions in Capgo between ${t} and ${e}`),b=((e,o,n)=>{const t=[];return null==e||e.forEach((e=>{d.default.gte(e.name,o)&&d.default.lt(e.name,`${n}`)&&t.push(e)})),t})(b,t,e),p.log.info(`Active versions in Capgo between ${t} and ${e}: ${null==b?void 0:b.length}`)}const k=[];let w=0;if(b.forEach((e=>{const o=_.find((o=>o===e.id));w<i||o?(e.keep=o?"✅ (Linked to channel)":"✅",w+=1):(e.keep="❌",k.push(e))})),0!==k.length){if((0,g.displayBundles)(b),!r&&"yes"!==h("Do you want to continue removing the versions specified? Type yes to confirm: "))return void p.log.warn("Not confirmed, aborting removal...");p.log.success("You have confirmed removal, removing versions now"),yield((e,o,n,t)=>{var i,r,s;return a(void 0,void 0,void 0,(function*(){var a,c,d,u;try{for(i=!0,r=l(e);!(a=(s=yield r.next()).done);i=!0){u=s.value,i=!1;const e=u;p.log.warn(`Removing ${e.name} created on ${(0,f.getHumanDate)(e.created_at)}`),yield(0,g.deleteSpecificVersion)(o,n,t,e.name)}}catch(e){c={error:e}}finally{try{i||a||!(d=r.return)||(yield d.call(r))}finally{if(c)throw c.error}}}))})(k,u,e,m),p.outro("Done ✅"),process.exit()}else p.log.warn("Nothing to be removed, aborting removal...")}))},2851:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.checkCompatibilityCommand=void 0;const l=r(n(552)),s=n(7304),c=n(3847),d=n(2170),p=n(3018);o.checkCompatibilityCommand=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;l.intro("Check compatibility"),o.apikey=o.apikey||(0,d.findSavedKey)();const t=yield(0,d.getConfig)();e=e||(null===(n=null==t?void 0:t.app)||void 0===n?void 0:n.appId);const{channel:i}=o;i||(l.log.error("Missing argument, you need to provide a channel"),s.program.error("")),o.apikey||(l.log.error("Missing API key, you need to provide a API key to upload your bundle"),s.program.error("")),e||(l.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),s.program.error(""));const r=yield(0,d.createSupabaseClient)(o.apikey);yield(0,d.verifyUser)(r,o.apikey,["write","all","read","upload"]),yield(0,p.checkAppExistsAndHasPermissionErr)(r,o.apikey,e);const{finalCompatibility:a}=yield(0,d.checkCompatibility)(r,e,i),u=new c.Table({title:"Compatibility",charLength:{"❌":2,"✅":2}}),f=o.text?"Yes":"✅",g=o.text?"No":"❌";a.forEach((e=>{const{name:o,localVersion:n,remoteVersion:t}=e;u.addRow({Package:o,"Local version":null!=n?n:"None","Remote version":null!=t?t:"None",Compatible:t===n?f:g})})),l.log.success(u.render())}))},3151:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.decryptZip=void 0;const l=n(7147),s=n(7304),c=r(n(552)),d=n(3043),p=n(2170),u=n(9740);o.decryptZip=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i,r,a,f,g;c.intro("Decrypt zip file"),yield(0,u.checkLatest)(),(0,l.existsSync)(e)||(c.log.error(`Zip not found at the path ${e}`),s.program.error(""));const y=yield(0,p.getConfig)(),{extConfig:v}=y.app;n.key||(0,l.existsSync)(p.baseKey)||(null===(i=null===(t=v.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===i?void 0:i.privateKey)||(c.log.error(`Private Key not found at the path ${p.baseKey} or in ${y.app.extConfigFilePath}`),s.program.error(""));const h=n.key||p.baseKey;let m=null===(a=null===(r=null==v?void 0:v.plugins)||void 0===r?void 0:r.CapacitorUpdater)||void 0===a?void 0:a.privateKey;(0,l.existsSync)(h)||m?(0,l.existsSync)(h)&&(m=(0,l.readFileSync)(h).toString()):(c.log.error(`Cannot find public key ${h} or as keyData option or in ${y.app.extConfigFilePath}`),s.program.error(""));const b=(0,l.readFileSync)(e),_=(0,d.decryptSource)(b,o,null!==(g=null!==(f=n.keyData)&&void 0!==f?f:m)&&void 0!==g?g:"");(0,l.writeFileSync)(`${e}_decrypted.zip`,_),c.outro(`Decrypted zip file at ${e}_decrypted.zip`),process.exit()}))},4666:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170),p=n(1820);o.deleteBundle=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i;s.intro("Delete bundle"),n.apikey=n.apikey||(0,d.findSavedKey)();const r=yield(0,d.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,d.createSupabaseClient)(n.apikey),u=yield(0,d.verifyUser)(a,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),o=o||(null===(i=null==r?void 0:r.app)||void 0===i?void 0:i.appId),n.apikey||(s.log.error("Missing API key, you need to provide an API key to delete your app"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a bundleId, or be in a capacitor project"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error("")),s.log.info(`Deleting bundle ${o}@${e} from Capgo`),yield(0,p.deleteSpecificVersion)(a,o,u,e),s.log.success(`Bundle ${o}@${e} deleted in Capgo`),s.outro("Done"),process.exit()}))},891:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.encryptZip=void 0;const s=n(7147),c=n(7304),d=l(n(7812)),p=r(n(552)),u=n(9740),f=n(3043),g=n(2170);o.encryptZip=(e,o)=>a(void 0,void 0,void 0,(function*(){p.intro("Encryption"),yield(0,u.checkLatest)();const n=yield(0,g.getLocalConfig)();(0,s.existsSync)(e)||(p.log.error(`Error: Zip not found at the path ${e}`),c.program.error(""));const t=o.key||g.baseKeyPub;let i=o.keyData||"";(0,s.existsSync)(t)||i?(0,s.existsSync)(t)&&(i=(0,s.readFileSync)(t).toString()):(p.log.warning(`Cannot find public key ${t} or as keyData option`),d.default.isCI&&(p.log.error("Error: Missing public key"),c.program.error("")),(yield p.confirm({message:"Do you want to use our public key ?"}))||(p.log.error("Error: Missing public key"),c.program.error("")),i=n.signKey||"");const r=(0,s.readFileSync)(e),a=(0,f.encryptSource)(r,i);p.log.success(`ivSessionKey: ${a.ivSessionKey}`),(0,s.writeFileSync)(`${e}_encrypted.zip`,a.encryptedData),p.log.success(`Encrypted zip saved at ${e}_encrypted.zip`),p.outro("Done ✅"),process.exit()}))},4220:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(1820),p=n(2170),u=n(9740);o.listBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("List bundles"),yield(0,u.checkLatest)(),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||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),e||(s.log.error("Missing argument, you need to provide a appid, or be in a capacitor project"),l.program.error(""));const i=yield(0,p.createSupabaseClient)(o.apikey),r=yield(0,p.verifyUser)(i,o.apikey,["write","all","read","upload"]);s.log.info(`Querying available versions of: ${e} in Capgo`),yield(0,c.checkAppExistsAndHasPermissionErr)(i,o.apikey,e);const a=yield(0,d.getActiveAppVersions)(i,e,r);s.log.info(`Active versions in Capgo: ${null==a?void 0:a.length}`),(0,d.displayBundles)(a),s.outro("Done ✅"),process.exit()}))},3717:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.uploadDeprecatedCommand=o.uploadCommand=o.uploadBundle=void 0;const s=n(6113),c=n(7147),d=l(n(3844)),p=n(7304),u=r(n(552)),f=n(5906),g=l(n(7812)),y=l(n(2167)),v=n(9740),h=n(3018),m=n(3043),b=n(2170),_=n(7092);o.uploadBundle=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){var t,i,r,a;u.intro("Uploading"),yield(0,v.checkLatest)();let{bundle:l,path:k,channel:w}=o;const{external:C,key:O=!1,displayIvSession:P,autoMinUpdateVersion:x,ignoreMetadataCheck:j}=o;let{minUpdateVersion:S}=o;o.apikey=o.apikey||(0,b.findSavedKey)();const $=(0,b.useLogSnag)();w=w||"dev";const A=yield(0,b.getConfig)(),M=!0===(A.app.extConfig.plugins&&A.app.extConfig.plugins.CapacitorUpdater&&A.app.extConfig.plugins.CapacitorUpdater.localS3),D=o.codeCheck;e=e||(null===(t=null==A?void 0:A.app)||void 0===t?void 0:t.appId);const I=(0,s.randomUUID)().split("-")[0];l=l||(null===(r=null===(i=null==A?void 0:A.app)||void 0===i?void 0:i.package)||void 0===r?void 0:r.version)||`0.0.1-beta.${I}`,b.regexSemver.test(l)||(u.log.error(`Your bundle name ${l}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")),k=k||(null===(a=null==A?void 0:A.app)||void 0===a?void 0:a.webDir),o.apikey||(u.log.error("Missing API key, you need to provide a API key to upload your bundle"),p.program.error("")),e&&l&&k||(u.log.error("Missing argument, you need to provide a appid and a bundle and a path, or be in a capacitor project"),p.program.error("")),(0,c.existsSync)(k)||(u.log.error(`Path ${k} does not exist, build your app first, or provide a valid path`),p.program.error("")),(void 0===D||D)&&((0,_.searchInDirectory)(k,"notifyAppReady")||(u.log.error("notifyAppReady() is missing in the source code. see: https://capgo.app/docs/plugin/api/#notifyappready"),p.program.error("")),(0,_.checkIndexPosition)(k)||(u.log.error("index.html is missing in the root folder or in the only folder in the root folder"),p.program.error(""))),u.log.info(`Upload ${e}@${l} started from path "${k}" to Capgo cloud`);const U=yield(0,b.getLocalConfig)(),E=yield(0,b.createSupabaseClient)(o.apikey),q=yield(0,b.verifyUser)(E,o.apikey,["write","all","upload"]),K=yield(0,h.checkAppExistsAndHasPermissionOrgErr)(E,o.apikey,e,b.OrganizationPerm.upload);yield(0,b.checkPlanValid)(E,q,e,o.apikey,!1);const L=yield(0,b.requireUpdateMetadata)(E,w),{data:N,error:V}=yield E.from("channels").select("version ( minUpdateVersion, native_packages )").eq("name",w).eq("app_id",e).single();let B,z;if(!V&&N&&N.version&&N.version.native_packages&&!j){const o=u.spinner();o.start(`Checking bundle compatibility with channel ${w}`);const{finalCompatibility:n,localDependencies:t}=yield(0,b.checkCompatibility)(E,e,w);if(z=n,B=t,z.find((e=>e.localVersion!==e.remoteVersion)))u.log.error(`Your bundle is not compatible with the channel ${w}`),u.log.warn('You can check compatibility with "npx @capgo/cli bundle compatibility"'),x&&(S=l,u.log.info(`Auto set min-update-version to ${S}`));else if(x)try{const{minUpdateVersion:e}=N.version;e&&b.regexSemver.test(e)||(u.log.error("Invalid remote min update version, skipping auto setting compatibility"),p.program.error("")),S=e,u.log.info(`Auto set min-update-version to ${S}`)}catch(e){u.log.error(`Cannot auto set compatibility, invalid data ${N}`),p.program.error("")}o.stop(`Bundle compatible with ${w} channel`)}else j||(u.log.warn(`Channel ${w} is new or it's your first upload with compatibility check, it will be ignored this time`),B=yield(0,b.getLocalDepenencies)(),x&&(S=l,u.log.info(`Auto set min-update-version to ${S}`)));!L||S||j||(u.log.error("You need to provide a min-update-version to upload a bundle to this channel"),p.program.error("")),S&&(b.regexSemver.test(S)||(u.log.error(`Your minimal version update ${S}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")));const{data:R,error:F}=yield E.rpc("is_trial",{userid:q}).single();(R&&R>0||F)&&(u.log.warn(`WARNING !!\nTrial expires in ${R} days`),u.log.warn(`Upgrade here: ${U.hostWeb}/dashboard/settings/plans`));const{data:H,error:T}=yield E.rpc("exist_app_versions",{appid:e,apikey:o.apikey,name_version:l}).single();(H||T)&&(u.log.error(`Version already exists ${(0,b.formatError)(T)}`),p.program.error(""));const Y=`${l.replace(/[^a-zA-Z0-9-_.!*'()]/g,"__")}.zip`;let W,J="",Z=null;if(C)C&&!C.startsWith("https://")?(u.log.error(`External link should should start with "https://" current is "${C}"`),p.program.error("")):(yield $.track({channel:"app",event:"App external",icon:"📤",user_id:q,tags:{"app-id":e},notify:!1}).catch(),W=o.ivSessionKey);else{const n=new d.default;n.addLocalFolder(k),Z=n.toBuffer();const t=u.spinner();if(t.start("Calculating checksum"),J=yield(0,f.checksum)(Z,"crc32"),t.stop(`Checksum: ${J}`),O||(0,c.existsSync)(b.baseKeyPub)){const n="string"==typeof O?O:b.baseKeyPub;let t=o.keyData||"";t||(0,c.existsSync)(n)||(u.log.error(`Cannot find public key ${n}`),g.default.isCI&&p.program.error(""),(yield u.confirm({message:"Do you want to use our public key ?"}))||(u.log.error("Error: Missing public key"),p.program.error("")),t=U.signKey||""),yield $.track({channel:"app",event:"App encryption",icon:"🔑",user_id:q,tags:{"app-id":e},notify:!1}).catch(),t||(t=(0,c.readFileSync)(n).toString()),u.log.info("Encrypting your bundle");const i=(0,m.encryptSource)(Z,t);W=i.ivSessionKey,P&&u.log.info(`Your Iv Session key is ${W},\nkeep it safe, you will need it to decrypt your bundle.\nIt will be also visible in your dashboard\n`),Z=i.encryptedData}const i=Math.floor(Z.byteLength/1024/1024);i>20&&(u.log.warn(`WARNING !!\nThe app size is ${i} Mb, this may take a while to download for users\n`),u.log.info("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield $.track({channel:"app-error",event:"App Too Large",icon:"🚛",user_id:q,tags:{"app-id":e},notify:!1}).catch())}const G=B?new Map(B.filter((e=>!!e.native&&void 0!==e.native)).map((e=>[e.name,e]))):new Map,Q=G.size>0||!o.ignoreMetadataCheck?Array.from(G,(([e,o])=>({name:e,version:o.version}))):void 0,X=yield(0,b.getAppOwner)(E,e),ee={bucket_id:C?void 0:Y,user_id:X,name:l,app_id:e,session_key:W,external_url:C,storage_provider:C?"external":"r2-direct",minUpdateVersion:S,native_packages:Q,checksum:J},{error:oe}=yield(0,b.updateOrCreateVersion)(E,ee,o.apikey);if(oe&&(u.log.error(`Cannot add bundle ${(0,b.formatError)(oe)}`),p.program.error("")),!C&&Z){const n=u.spinner();n.start("Uploading Bundle");const t=yield(0,b.uploadUrl)(E,e,Y);t||(u.log.error("Cannot get upload url"),p.program.error("")),yield(0,y.default)({method:"put",url:t,data:Z,headers:M?void 0:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=456789, immutable","x-amz-meta-crc32":J}}),ee.storage_provider="r2";const{error:i}=yield(0,b.updateOrCreateVersion)(E,ee,o.apikey);i&&(console.log(i),u.log.error(`Cannot update bundle ${(0,b.formatError)(oe)}`),p.program.error("")),n.stop("Bundle Uploaded 💪")}const{data:ne}=yield E.rpc("get_app_versions",{apikey:o.apikey,name_version:l,appid:e}).single();if(ne&&(0,b.hasOrganizationPerm)(K,b.OrganizationPerm.write)){const{error:n,data:t}=yield(0,b.updateOrCreateChannel)(E,{name:w,app_id:e,created_by:X,version:ne});n&&(u.log.error('Cannot set channel, the upload key is not allowed to do that, use the "all" for this.'),console.log(n),p.program.error(""));const i=(0,b.convertAppName)(e),r=`${U.hostWeb}/app/p/${i}/channel/${t.id}`;(null==t?void 0:t.public)?u.log.info("Your update is now available in your public channel 🎉"):(null==t?void 0:t.id)&&u.log.info(`Link device to this bundle to try it: ${r}`),o.bundleUrl&&u.log.info(`Bundle url: ${r}`)}else ne?(0,b.hasOrganizationPerm)(K,b.OrganizationPerm.write)||u.log.warn("Cannot set channel as a upload organization member"):(u.log.warn("Cannot set bundle with upload key, use key with more rights for that"),p.program.error(""));return yield $.track({channel:"app",event:"App Uploaded",icon:"⏫",user_id:q,tags:{"app-id":e},notify:!1}).catch(),n&&(u.outro("Time to share your update to the world 🌍"),process.exit()),!0})),o.uploadCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){try{yield(0,o.uploadBundle)(e,n,!0)}catch(e){u.log.error(JSON.stringify(e)),p.program.error("")}})),o.uploadDeprecatedCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){u.log.warn('⚠️ This command is deprecated, use "npx @capgo/cli bundle upload" instead ⚠️');try{yield(0,o.uploadBundle)(e,n,!0)}catch(e){u.log.error(JSON.stringify(e)),p.program.error("")}}))},3398:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.zipBundle=void 0;const s=n(6113),c=n(7147),d=l(n(3844)),p=n(7304),u=r(n(552)),f=n(5906),g=n(9740),y=n(2170),v=n(7092);o.zipBundle=(e,o)=>a(void 0,void 0,void 0,(function*(){var n,t,i,r;yield(0,g.checkLatest)();let{bundle:a,path:l}=o;const{json:h}=o,m=(0,y.useLogSnag)(),b=yield(0,y.getConfig)();e=e||(null===(n=null==b?void 0:b.app)||void 0===n?void 0:n.appId);const _=(0,s.randomUUID)().split("-")[0];a=a||(null===(i=null===(t=null==b?void 0:b.app)||void 0===t?void 0:t.package)||void 0===i?void 0:i.version)||`0.0.1-beta.${_}`,h||u.intro(`Zipping ${e}@${a}`),y.regexSemver.test(a)||(h?console.error(JSON.stringify({error:"invalid_semver"})):u.log.error(`Your bundle name ${a}, is not valid it should follow semver convention : https://semver.org/`),p.program.error("")),l=l||(null===(r=null==b?void 0:b.app)||void 0===r?void 0:r.webDir),e&&a&&l||(h?console.error(JSON.stringify({error:"missing_argument"})):u.log.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project"),p.program.error("")),h||u.log.info(`Started from path "${l}"`);const k=o.codeCheck;(void 0===k||k)&&((0,v.searchInDirectory)(l,"notifyAppReady")||(h?console.error(JSON.stringify({error:"notifyAppReady_not_in_source_code"})):u.log.error("notifyAppReady() is missing in the source code. see: https://capgo.app/docs/plugin/api/#notifyappready"),p.program.error("")),(0,v.checkIndexPosition)(l)||(h?console.error(JSON.stringify({error:"index_html_not_found"})):u.log.error("index.html is missing in the root folder or in the only folder in the root folder"),p.program.error("")));const w=new d.default;w.addLocalFolder(l);const C=w.toBuffer();h||u.log.info(`Zipped ${C.byteLength} bytes`);const O=u.spinner();h||O.start("Calculating checksum");const P=yield(0,f.checksum)(C,"crc32");h||O.stop(`Checksum: ${P}`);const x=Math.floor(C.byteLength/1024/1024);x>20&&!h&&(u.log.warn(`WARNING !!\nThe app size is ${x} Mb, this may take a while to download for users\n`),u.log.warn("Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/\n"),yield m.track({channel:"app-error",event:"App Too Large",icon:"🚛",tags:{"app-id":e},notify:!1}).catch());const j=u.spinner(),S=o.name||`${e}_${a}.zip`;if(h||j.start(`Saving to ${S}`),(0,c.writeFileSync)(S,C),h||j.stop(`Saved to ${S}`),o.json){const e={bundle:a,filename:S,checksum:P};console.log(JSON.stringify(e))}yield m.track({channel:"app",event:"App zip",icon:"⏫",tags:{"app-id":e},notify:!1}).catch(),h||u.outro("Done ✅"),process.exit()}))},1795:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.addChannelCommand=o.addChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.addChannel=(e,o,n,t=!0)=>a(void 0,void 0,void 0,(function*(){var i;s.intro("Create channel"),n.apikey=n.apikey||(0,p.findSavedKey)();const r=yield(0,p.getConfig)();o=o||(null===(i=null==r?void 0:r.app)||void 0===i?void 0:i.appId);const a=(0,p.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const u=yield(0,p.createSupabaseClient)(n.apikey),f=yield(0,p.verifyUser)(u,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(u,n.apikey,o),s.log.info(`Creating channel ${o}#${e} to Capgo`);try{const n=yield(0,d.findUnknownVersion)(u,o);n||(s.log.error("Cannot find default version for channel creation, please contact Capgo support 🤨"),l.program.error("")),yield(0,d.createChannel)(u,{name:e,app_id:o,version:n.id,created_by:f}),s.log.success("Channel created ✅"),yield a.track({channel:"channel",event:"Create channel",icon:"✅",user_id:f,tags:{"app-id":o,channel:e},notify:!1}).catch()}catch(e){return s.log.error("Cannot create Channel 🙀"),!1}return t&&(s.outro("Done ✅"),process.exit()),!0})),o.addChannelCommand=(e,n,t)=>a(void 0,void 0,void 0,(function*(){(0,o.addChannel)(e,n,t,!0)}))},2914:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.currentBundle=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170);o.currentBundle=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;const{quiet:i}=n;i||s.intro("List current bundle"),n.apikey=n.apikey||(0,d.findSavedKey)(i);const r=yield(0,d.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,d.createSupabaseClient)(n.apikey),p=yield(0,d.verifyUser)(a,n.apikey,["write","all","read"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),e||(s.log.error("Please provide a channel to get the bundle from."),l.program.error(""));const{data:u,error:f}=yield a.from("channels").select("version ( name )").eq("name",e).eq("app_id",o).eq("created_by",p).limit(1);(f||0===u.length)&&(s.log.error(`Error retrieving channel ${e} for app ${o}. Perhaps the channel does not exists?`),l.program.error(""));const{version:g}=u[0];g||(s.log.error(`Error retrieving channel ${e} for app ${o}. Perhaps the channel does not exists?`),l.program.error("")),i?console.log(g.name):s.log.info(`Current bundle for channel ${e} is ${g.name}`),process.exit()}))},5798:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.deleteChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.deleteChannel=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;s.intro("Delete channel"),n.apikey=n.apikey||(0,p.findSavedKey)();const i=yield(0,p.getConfig)();o=o||(null===(t=null==i?void 0:i.app)||void 0===t?void 0:t.appId);const r=(0,p.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const a=yield(0,p.createSupabaseClient)(n.apikey),u=yield(0,p.verifyUser)(a,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(a,n.apikey,o),s.log.info(`Deleting channel ${o}#${e} from Capgo`);try{yield(0,d.delChannel)(a,e,o,u),s.log.success("Channel deleted"),yield r.track({channel:"channel",event:"Delete channel",icon:"✅",tags:{"user-id":u,"app-id":o,channel:e},notify:!1}).catch()}catch(e){s.log.error("Cannot delete Channel 🙀")}s.outro("Done ✅"),process.exit()}))},1983:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.listChannels=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(7175),p=n(2170);o.listChannels=(e,o)=>a(void 0,void 0,void 0,(function*(){var n;s.intro("List channels"),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);const i=(0,p.useLogSnag)();o.apikey||s.log.error("Missing API key, you need to provide a API key to upload your bundle"),e||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const r=yield(0,p.createSupabaseClient)(o.apikey),a=yield(0,p.verifyUser)(r,o.apikey,["write","all","read","upload"]);yield(0,c.checkAppExistsAndHasPermissionErr)(r,o.apikey,e),s.log.info("Querying available channels in Capgo");const u=yield(0,d.getActiveChannels)(r,e);s.log.info(`Active channels in Capgo: ${null==u?void 0:u.length}`),(0,d.displayChannels)(u),yield i.track({channel:"channel",event:"List channel",icon:"✅",user_id:a,tags:{"app-id":e},notify:!1}).catch(),s.outro("Done ✅"),process.exit()}))},1541:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.setChannel=void 0;const l=n(7304),s=r(n(552)),c=n(3018),d=n(2170),p=["major","minor","metadata","none"];o.setChannel=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t,i,r;s.intro("Set channel"),n.apikey=n.apikey||(0,d.findSavedKey)();const a=yield(0,d.getConfig)();o=o||(null===(t=null==a?void 0:a.app)||void 0===t?void 0:t.appId);const u=(0,d.useLogSnag)();n.apikey||(s.log.error("Missing API key, you need to provide a API key to upload your bundle"),l.program.error("")),o||(s.log.error("Missing argument, you need to provide a appId, or be in a capacitor project"),l.program.error(""));const f=yield(0,d.createSupabaseClient)(n.apikey),g=yield(0,d.verifyUser)(f,n.apikey,["write","all"]);yield(0,c.checkAppExistsAndHasPermissionErr)(f,n.apikey,o);const{bundle:y,latest:v,downgrade:h,upgrade:m,ios:b,android:_,selfAssign:k,state:w,disableAutoUpdate:C}=n;e||(s.log.error("Missing argument, you need to provide a channel"),l.program.error("")),v&&y&&(s.log.error("Cannot set latest and bundle at the same time"),l.program.error("")),null==y&&null==w&&null==v&&null==h&&null==m&&null==b&&null==_&&null==k&&null==C&&(s.log.error("Missing argument, you need to provide a option to set"),l.program.error(""));try{yield(0,d.checkPlanValid)(f,g,o,n.apikey);const t={created_by:g,app_id:o,name:e,version:void 0},c=v?null===(r=null===(i=null==a?void 0:a.app)||void 0===i?void 0:i.package)||void 0===r?void 0:r.version:y;if(null!=c){const{data:n,error:i}=yield f.from("app_versions").select().eq("app_id",o).eq("name",c).eq("user_id",g).eq("deleted",!1).single();!i&&n||(s.log.error(`Cannot find version ${c}`),l.program.error("")),s.log.info(`Set ${o} channel: ${e} to @${c}`),t.version=n.id}if(null!=w&&("public"!==w&&"private"!==w||s.log.info(`Set ${o} channel: ${e} to public or private is deprecated, use default or normal instead`),s.log.info(`Set ${o} channel: ${e} to ${"public"===w||"default"===w?"default":"normal"}`),t.public="public"===w||"default"===w),null!=h&&(s.log.info(`Set ${o} channel: ${e} to ${h?"allow":"disallow"} downgrade`),t.disableAutoUpdateUnderNative=!h),null!=b&&(s.log.info(`Set ${o} channel: ${e} to ${b?"allow":"disallow"} ios update`),t.ios=!!b),null!=_&&(s.log.info(`Set ${o} channel: ${e} to ${_?"allow":"disallow"} android update`),t.android=!!_),null!=k&&(s.log.info(`Set ${o} channel: ${e} to ${k?"allow":"disallow"} self assign to this channel`),t.allow_device_self_set=!!k),null!=C){let n=C.toLocaleLowerCase();p.includes(n)||(s.log.error(`Channel strategy ${n} is not known. The possible values are: ${p.join(", ")}.`),l.program.error("")),"metadata"===n&&(n="version_number"),t.disableAutoUpdate=n,s.log.info(`Set ${o} channel: ${e} to ${n} disable update strategy to this channel`)}try{const{error:e}=yield(0,d.updateOrCreateChannel)(f,t);e&&(s.log.error('Cannot set channel the upload key is not allowed to do that, use the "all" for this.'),l.program.error(""))}catch(e){s.log.error('Cannot set channel the upload key is not allowed to do that, use the "all" for this.'),l.program.error("")}yield u.track({channel:"channel",event:"Set channel",icon:"✅",user_id:g,tags:{"user-id":g,"app-id":o},notify:!1}).catch()}catch(e){s.log.error(`Unknow error ${(0,d.formatError)(e)}`),l.program.error("")}s.outro("Done ✅"),process.exit()}))},1428: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(7304),r=n(3398),a=n(3464),l=n(4220),s=n(3151),c=n(891),d=n(2622),p=n(9785),u=n(2673),f=n(4666),g=n(1541),y=n(2914),v=n(3717),h=t(n(4147)),m=n(7102),b=n(4738),_=n(9690),k=n(1795),w=n(5798),C=n(1983),O=n(7791),P=n(8437),x=n(3713),j=n(2851);i.program.name(h.default.name).description("Manage packages and bundle versions in Capgo Cloud").version(h.default.version),i.program.command("login [apikey]").alias("l").description("Save apikey to your machine or folder").action(m.loginCommand).option("--local","Only save in local folder"),i.program.command("doctor").description("Get info about your Capgo app install").action(p.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 S=i.program.command("app").description("Manage app");S.command("add [appId]").alias("a").description("Add a new app in Capgo Cloud").action(d.addCommand).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account"),S.command("delete [appId]").alias("d").description("Delete an app in Capgo Cloud").action(P.deleteApp).option("-a, --apikey <apikey>","apikey to link to your account"),S.command("list").alias("l").description("list apps in Capgo Cloud").action(b.listApp).option("-a, --apikey <apikey>","apikey to link to your account"),S.command("debug [appId]").alias("d").description("Listen for live updates event in Capgo Cloud to debug your app").option("-a, --apikey <apikey>","apikey to link to your account").option("-d, --device <device>","the specific device to debug").action(x.debugApp),S.command("set [appId]").alias("s").description("Set an app in Capgo Cloud").action(O.setApp).option("-n, --name <name>","app name").option("-i, --icon <icon>","app icon path").option("-a, --apikey <apikey>","apikey to link to your account").option("-r, --retention <retention>","retention period of app bundle in days");const $=i.program.command("bundle").description("Manage bundle");$.command("upload [appId]").alias("u").description("Upload a new bundle in Capgo Cloud").action(v.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("--iv-session-key <key>","Set the iv and session key for bundle url external").option("--key <key>","custom path for public signing key").option("--key-data <keyData>","base64 public signing key").option("--bundle-url","prints bundle url into stdout").option("--no-key","ignore signing key and send clear update").option("--no-code-check","Ignore checking if notifyAppReady() is called in soure code and index present in root folder").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").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel").option("--auto-min-update-version","Set the min update version based on native packages").option("--ignore-metadata-check","Ignores the metadata (node_modules) check when uploading"),$.command("compatibility [appId]").action(j.checkCompatibilityCommand).option("-a, --apikey <apikey>","apikey to link to your account").option("-c, --channel <channel>","channel to check the compatibility with").option("--text","output text instead of emojis"),$.command("delete [bundleId] [appId]").alias("d").description("Delete a bundle in Capgo Cloud").action(f.deleteBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("list [appId]").alias("l").description("List bundle in Capgo Cloud").action(l.listBundle).option("-a, --apikey <apikey>","apikey to link to your account"),$.command("unlink [appId]").alias("u").description("Unlink a bundle in Capgo Cloud").action(l.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(_.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("--key-data <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("--key-data <keyData>","base64 private signing key"),$.command("zip [appId]").description("Zip a bundle").action(r.zipBundle).option("-p, --path <path>","path of the folder to upload").option("-b, --bundle <bundle>","bundle version number to name the zip file").option("-n, --name <name>","name of the zip file").option("-j, --json","output in JSON").option("--no-code-check","Ignore checking if notifyAppReady() is called in soure code and index present in root folder");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").option("-a, --apikey <apikey>","apikey to link to your account"),A.command("delete [channelId] [appId]").alias("d").description("Delete channel").action(w.deleteChannel).option("-a, --apikey <apikey>","apikey to link to your account"),A.command("list [appId]").alias("l").description("List channel").action(C.listChannels).option("-a, --apikey <apikey>","apikey to link to your account"),A.command("currentBundle [channel] [appId]").description("Get current bundle for specific channel in Capgo Cloud").action(y.currentBundle).option("-c, --channel <channel>","channel to get the current bundle from").option("-a, --apikey <apikey>","apikey to link to your account").option("--quiet","only print the bundle version"),A.command("set [channelId] [appId]").alias("s").description("Set channel").action(g.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").option("--disable-auto-update <disableAutoUpdate>","Disable auto update strategy for this channel.The possible options are: major, minor, metadata, none");const M=i.program.command("key").description("Manage key");M.command("save").description("Save base64 signing key in capacitor config, usefull for CI").action(u.saveKeyCommand).option("-f, --force","force generate a new one").option("--key","key path to save in capacitor config").option("--key-data","key data to save in capacitor config"),M.command("create").description("Create a new signing key").action(u.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(v.uploadDeprecatedCommand).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("--key-data <keyData>","base64 public signing key").option("--bundle-url","prints bundle url into stdout").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").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel"),i.program.parseAsync()},3464:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.initApp=void 0;const s=n(7147),c=n(2081),d=n(6301),p=r(n(552)),u=l(n(912)),f=n(3713),g=n(2673),y=n(1795),v=n(3717),h=n(7102),m=n(2622),b=n(9740),_=n(2170),k="import { CapacitorUpdater } from '@capgo/capacitor-updater'",w="CapacitorUpdater.notifyAppReady()",C=/import.*from.*/g,O="production",P={stdio:"pipe"},x=(e,o,n)=>a(void 0,void 0,void 0,(function*(){p.isCancel(e)&&(yield(0,f.markSnag)("onboarding-v2",o,n,"canceled","🤷"),process.exit())})),j=(e,o,n)=>a(void 0,void 0,void 0,(function*(){return(0,f.markSnag)("onboarding-v2",e,o,`onboarding-step-${n}`)}));o.initApp=(e,o,n)=>a(void 0,void 0,void 0,(function*(){var t;p.intro("Capgo onboarding 🛫"),yield(0,b.checkLatest)();const i=(0,_.useLogSnag)(),r=yield(0,_.getConfig)();o=o||(null===(t=null==r?void 0:r.app)||void 0===t?void 0:t.appId),e=e||(0,_.findSavedKey)();const l=p.spinner();l.start("Running: npx @capgo/cli@latest login ***"),(yield(0,h.login)(e,n,!1))?l.stop("Login Done ✅"):l.stop("Login already done ✅");const S=yield(0,_.createSupabaseClient)(e),$=yield(0,_.verifyUser)(S,e,["upload","all","read","write"]);yield j($,i,1),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Add ${n} in Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start(`Running: npx @capgo/cli@latest app add ${n}`),(yield(0,m.addApp)(n,t,!1))?e.stop("App add Done ✅"):e.stop("App already add ✅")}else p.log.info(`Run yourself "npx @capgo/cli@latest app add ${n}"`);yield j(e,o,2)})))($,i,o,n),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Create default channel ${O} for ${t} in Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start(`Running: npx @capgo/cli@latest channel add ${O} ${t} --default`),(yield(0,y.addChannel)(O,t,{default:!0,apikey:n},!1))?e.stop("Channel add Done ✅"):e.stop("Channel already added ✅")}else p.log.info(`Run yourself "npx @capgo/cli@latest channel add ${O} ${t} --default"`);yield j(e,o,3)})))($,i,e,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic Install "@capgo/capacitor-updater" dependency in ${t}?`});if(yield x(n,e,o),n){const e=p.spinner();e.start("Checking if @capgo/capacitor-updater is installed");const o=JSON.parse((0,s.readFileSync)("package.json").toString());let n=o.dependencies["@capacitor/core"]||o.devDependencies["@capacitor/core"];n=null==n?void 0:n.replace("^","").replace("~",""),n?u.default.lt(n,"5.0.0")&&(e.stop(`@capacitor/core version is ${n}, please update to Capacitor v5 first: https://capacitorjs.com/docs/updating/5-0`),process.exit()):(e.stop("Cannot find @capacitor/core in package.json, please run `capgo init` in a capacitor project"),process.exit());const t=(0,d.findPackageManagerType)();"unknown"===t&&(e.stop("Cannot reconize package manager, please run `capgo init` in a capacitor project with npm, pnpm or yarn"),process.exit());const i="yarn"===t?"add":"install";o.dependencies["@capgo/capacitor-updater"]?e.stop("Capgo already installed ✅"):(yield(0,c.execSync)(`${t} ${i} @capgo/capacitor-updater@latest`,P),e.stop("Install Done ✅"))}else p.log.info('Run yourself "npm i @capgo/capacitor-updater@latest"');yield j(e,o,4)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic Add "${w}" code and import in ${t}?`});if(yield x(n,e,o),n){const n=p.spinner();n.start("Adding @capacitor-updater to your main file");const t=yield(0,_.findMainFile)();t||(n.stop("No main.ts, main.js, index.ts or index.js file found, You need to add @capgo/capacitor-updater manually"),process.exit());const i=(0,s.readFileSync)(t).toString(),r=i.match(C),a=null==r?void 0:r.pop();if(a||(n.stop("Cannot find import line in main file, use manual installation: https://capgo.app/docs/plugin/installation/"),process.exit()),i.includes(w))n.stop(`Code already added to ${t} ✅`);else{const e=i.replace(a,`${a}\n${k};\n\n${w};\n`);(0,s.writeFileSync)(t,e),n.stop(`Code added to ${t} ✅`)}yield j(e,o,5)}else p.log.info(`Add to your main file the following code:\n\n${k};\n\n${w};\n`)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:`Automatic configure end-to-end encryption in ${t} updates?`});if(yield x(n,e,o),n){const n=p.spinner();n.start("Running: npx @capgo/cli@latest key create"),(yield(0,g.createKey)({},!1))?n.stop("key created 🔑"):(n.stop("Cannot create key ❌"),process.exit(1)),(0,f.markSnag)("onboarding-v2",e,o,"Use encryption")}yield j(e,o,6)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){var n;const i=yield p.confirm({message:`Automatic build ${t} with "npm run build" ?`});if(yield x(i,e,o),i){const e=p.spinner();e.start("Running: npm run build && npx cap sync"),(null===(n=JSON.parse((0,s.readFileSync)("package.json").toString()).scripts)||void 0===n?void 0:n.build)||(e.stop("Cannot find build script in package.json, please add it and run `capgo init` again"),process.exit()),(0,c.execSync)("npm run build && npx cap sync",P),e.stop("Build & Sync Done ✅")}else p.log.info("Build yourself with command: npm run build && npx cap sync");yield j(e,o,7)})))($,i,0,o),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:`Automatic upload ${t} bundle to Capgo?`});if(yield x(i,e,o),i){const e=p.spinner();e.start("Running: npx @capgo/cli@latest bundle upload"),(yield(0,v.uploadBundle)(t,{channel:O,apikey:n},!1))?e.stop("Upload Done ✅"):(e.stop("Upload failed ❌"),process.exit())}else p.log.info("Upload yourself with command: npx @capgo/cli@latest bundle upload");yield j(e,o,8)})))($,i,e,o),yield((e,o)=>a(void 0,void 0,void 0,(function*(){const n=yield p.confirm({message:"Run in device now ?"});if(yield x(n,e,o),n){const e=yield p.select({message:"Pick a platform to run your app",options:[{value:"ios",label:"IOS"},{value:"android",label:"Android"}]});p.isCancel(e)&&process.exit();const o=e,n=p.spinner();n.start(`Running: npx cap run ${o}`),yield(0,c.spawnSync)("npx",["cap","run",o],{stdio:"inherit"}),n.stop("Started Done ✅")}else p.log.info("Run yourself with command: npx cap run <ios|android>");yield j(e,o,9)})))($,i),yield((e,o,n,t)=>a(void 0,void 0,void 0,(function*(){const i=yield p.confirm({message:"Automatic check if update working in device ?"});if(yield x(i,e,o),i)p.log.info(`Wait logs sent to Capgo from ${t} device, Put the app in background and open it again.`),p.log.info("Waiting..."),yield(0,f.waitLog)("onboarding-v2",n,t,o,e);else{const e=(0,_.convertAppName)(t);p.log.info(`Check logs in https://web.capgo.app/app/p/${e}/logs to see if update works.`)}yield j(e,o,10)})))($,i,S,o),yield j($,i,0),p.log.info("Welcome onboard ✈️!"),p.log.info("Your Capgo update system is setup"),p.log.info("Next time use `npx @capgo/cli@latest bundle upload` to only upload your bundle"),p.outro("Bye 👋"),process.exit()}))},2673:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.createKeyCommand=o.createKey=o.saveKeyCommand=o.saveKey=void 0;const l=n(7147),s=n(7304),c=n(7778),d=r(n(552)),p=n(3043),u=n(2170),f=n(9740);o.saveKey=(e,o=!0)=>a(void 0,void 0,void 0,(function*(){o&&d.intro("Save keys 🔑");const n=yield(0,u.getConfig)(),{extConfig:t}=n.app,i=e.key||u.baseKey;let r=e.keyData||"";if((0,l.existsSync)(i)||r)(0,l.existsSync)(i)&&(r=(0,l.readFileSync)(i).toString());else{if(!o)return!1;d.log.error(`Cannot find public key ${i} or as keyData option or in ${n.app.extConfigFilePath}`),s.program.error("")}return t&&(t.plugins||(t.plugins={extConfig:{},CapacitorUpdater:{}}),t.plugins.CapacitorUpdater||(t.plugins.CapacitorUpdater={}),t.plugins.CapacitorUpdater.privateKey=r,(0,c.writeConfig)(t,n.app.extConfigFilePath)),o&&(d.log.success(`private key saved into ${n.app.extConfigFilePath} file in local directory`),d.log.success("your app will decode the zip archive with this key")),!0})),o.saveKeyCommand=e=>a(void 0,void 0,void 0,(function*(){d.intro("Save keys 🔑"),yield(0,f.checkLatest)(),yield(0,o.saveKey)(e)})),o.createKey=(e,o=!0)=>a(void 0,void 0,void 0,(function*(){o&&d.intro("Create keys 🔑");const{publicKey:n,privateKey:t}=(0,p.createRSA)();if((0,l.existsSync)(u.baseKeyPub)&&!e.force){if(!o)return!1;d.log.error("Public Key already exists, use --force to overwrite"),s.program.error("")}if((0,l.writeFileSync)(u.baseKeyPub,n),(0,l.existsSync)(u.baseKey)&&!e.force){if(!o)return!1;d.log.error("Private Key already exists, use --force to overwrite"),s.program.error("")}(0,l.writeFileSync)(u.baseKey,t);const i=yield(0,u.getConfig)(),{extConfig:r}=i.app;return r&&(r.plugins||(r.plugins={extConfig:{},CapacitorUpdater:{}}),r.plugins.CapacitorUpdater.privateKey=t,(0,c.writeConfig)(r,i.app.extConfigFilePath)),o&&(d.log.success("Your RSA key has been generated"),d.log.success(`Public key saved in ${u.baseKeyPub}`),d.log.success("This key will be use to encrypt your bundle before sending it to Capgo"),d.log.success("Keep it safe"),d.log.success("Than make it unreadable by Capgo and unmodifiable by anyone"),d.log.success(`Private key saved in ${i.app.extConfigFilePath}`),d.log.success("Your app will be the only one having it"),d.log.success("Only your users can decrypt your update"),d.log.success("Only you can send them an update"),d.outro("Done ✅")),!0})),o.createKeyCommand=e=>a(void 0,void 0,void 0,(function*(){yield(0,f.checkLatest)(),yield(0,o.createKey)(e)}))},7102:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))};Object.defineProperty(o,"__esModule",{value:!0}),o.loginCommand=o.login=void 0;const l=n(7147),s=n(2037),c=n(7304),d=r(n(552)),p=n(2170),u=n(9740);o.login=(e,o,n=!0)=>a(void 0,void 0,void 0,(function*(){if(n&&d.intro("Login to Capgo"),!e)return n&&(d.log.error("Missing API key, you need to provide a API key to upload your bundle"),c.program.error("")),!1;yield(0,u.checkLatest)();try{const{local:n}=o,t=(0,p.useLogSnag)();if(n)(0,l.existsSync)(".git")||(d.log.error("To use local you should be in a git repository"),c.program.error("")),(0,l.writeFileSync)(".capgo",`${e}\n`),(0,l.appendFileSync)(".gitignore",".capgo\n");else{const o=(0,s.homedir)();(0,l.writeFileSync)(`${o}/.capgo`,`${e}\n`)}const i=yield(0,p.createSupabaseClient)(e),r=yield(0,p.verifyUser)(i,e,["write","all","upload"]);yield t.track({channel:"user-login",event:"User CLI login",icon:"✅",user_id:r,notify:!1}).catch(),d.log.success(`login saved into .capgo file in ${n?"local":"home"} directory`)}catch(e){d.log.error("Error while saving login"),process.exit(1)}return n&&(d.outro("Done ✅"),process.exit()),!0})),o.loginCommand=(e,n)=>a(void 0,void 0,void 0,(function*(){(0,o.login)(e,n,!0)}))},2170:function(e,o,n){var t=this&&this.__createBinding||(Object.create?function(e,o,n,t){void 0===t&&(t=n);var i=Object.getOwnPropertyDescriptor(o,n);i&&!("get"in i?!o.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return o[n]}}),Object.defineProperty(e,t,i)}:function(e,o,n,t){void 0===t&&(t=n),e[t]=o[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,o){Object.defineProperty(e,"default",{enumerable:!0,value:o})}:function(e,o){e.default=o}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var o={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(o,e,n);return i(o,e),o},a=this&&this.__awaiter||function(e,o,n,t){return new(n||(n=Promise))((function(i,r){function a(e){try{s(t.next(e))}catch(e){r(e)}}function l(e){try{s(t.throw(e))}catch(e){r(e)}}function s(e){var o;e.done?i(e.value):(o=e.value,o instanceof n?o:new n((function(e){e(o)}))).then(a,l)}s((t=t.apply(e,o||[])).next())}))},l=this&&this.__await||function(e){return this instanceof l?(this.v=e,this):new l(e)},s=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)}))}}},c=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,i){o[t]=e[t]?function(o){return(n=!n)?{value:l(e[t](o)),done:!1}:i?i(o):o}:i}},d=this&&this.__asyncGenerator||function(e,o,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=n.apply(e,o||[]),r=[];return t={},a("next"),a("throw"),a("return",(function(e){return function(o){return Promise.resolve(o).then(e,d)}})),t[Symbol.asyncIterator]=function(){return this},t;function a(e,o){i[e]&&(t[e]=function(o){return new Promise((function(n,t){r.push([e,o,n,t])>1||s(e,o)}))},o&&(t[e]=o(t[e])))}function s(e,o){try{(n=i[e](o)).value instanceof l?Promise.resolve(n.value.v).then(c,d):p(r[0][2],n)}catch(e){p(r[0][3],e)}var n}function c(e){s("next",e)}function d(e){s("throw",e)}function p(e,o){e(o),r.shift(),r.length&&s(r[0][0],r[0][1])}},p=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.checkCompatibility=o.getRemoteDepenencies=o.getLocalDepenencies=o.getHumanDate=o.requireUpdateMetadata=o.verifyUser=o.convertAppName=o.useLogSnag=o.updateOrCreateChannel=o.uploadUrl=o.updateOrCreateVersion=o.formatError=o.findMainFile=o.findSavedKey=o.checkPlanValid=o.isAllowedAppOrg=o.hasOrganizationPerm=o.OrganizationPerm=o.isAllowedApp=o.getAppOwner=o.isAllowedActionAppIdApiKey=o.isAllowedAction=o.isTrial=o.isPaying=o.isGoodPlan=o.checkKey=o.createSupabaseClient=o.getRemoteConfig=o.getLocalConfig=o.getConfig=o.regexSemver=o.defaultHostWeb=o.defaultApiHost=o.defaultHost=o.baseKeyPub=o.baseKey=void 0;const u=n(7147),f=n(2037),g=n(1017),y=n(7778),v=n(7304),h=n(2885),m=p(n(9867)),b=n(1133),_=r(n(552)),k=p(n(2167)),w=n(1406);o.baseKey=".capgo_key",o.baseKeyPub=`${o.baseKey}.pub`,o.defaultHost="https://capgo.app",o.defaultApiHost="https://api.capgo.app",o.defaultHostWeb="https://web.capgo.app",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.getConfig=()=>a(void 0,void 0,void 0,(function*(){let e;try{e=yield(0,y.loadConfig)()}catch(e){_.log.error("No capacitor config file found, run `cap init` first"),v.program.error("")}return e})),o.getLocalConfig=()=>a(void 0,void 0,void 0,(function*(){var e,n,t,i,r,a,l,s,c,d,p,u,f,g,y,v,h,m,b,_,k,w,C,O;try{const P=yield(0,o.getConfig)(),x={host:(null===(i=null===(t=null===(n=null===(e=null==P?void 0:P.app)||void 0===e?void 0:e.extConfig)||void 0===n?void 0:n.plugins)||void 0===t?void 0:t.CapacitorUpdater)||void 0===i?void 0:i.localHost)||o.defaultHost,hostWeb:(null===(s=null===(l=null===(a=null===(r=null==P?void 0:P.app)||void 0===r?void 0:r.extConfig)||void 0===a?void 0:a.plugins)||void 0===l?void 0:l.CapacitorUpdater)||void 0===s?void 0:s.localWebHost)||o.defaultHostWeb};return(null===(u=null===(p=null===(d=null===(c=null==P?void 0:P.app)||void 0===c?void 0:c.extConfig)||void 0===d?void 0:d.plugins)||void 0===p?void 0:p.CapacitorUpdater)||void 0===u?void 0:u.localSupa)&&(null===(v=null===(y=null===(g=null===(f=null==P?void 0:P.app)||void 0===f?void 0:f.extConfig)||void 0===g?void 0:g.plugins)||void 0===y?void 0:y.CapacitorUpdater)||void 0===v?void 0:v.localSupaAnon)&&(x.supaKey=null===(_=null===(b=null===(m=null===(h=null==P?void 0:P.app)||void 0===h?void 0:h.extConfig)||void 0===m?void 0:m.plugins)||void 0===b?void 0:b.CapacitorUpdater)||void 0===_?void 0:_.localSupaAnon,x.supaHost=null===(O=null===(C=null===(w=null===(k=null==P?void 0:P.app)||void 0===k?void 0:k.extConfig)||void 0===w?void 0:w.plugins)||void 0===C?void 0:C.CapacitorUpdater)||void 0===O?void 0:O.localSupa),x}catch(e){return{host:o.defaultHost,hostWeb:o.defaultHostWeb}}}));const C=/([A-Za-z0-9]+)\.(java|swift|kt|scala)$/;var O;function P(e){return d(this,arguments,(function*(){const o=yield l((0,u.readdirSync)(e,{withFileTypes:!0}));for(const n of o){const o=(0,g.resolve)(e,n.name);!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("node_modules")||n.name.startsWith("dist")?yield yield l(o):yield l(yield*c(s(P(o))))}}))}function x(){return a(this,void 0,void 0,(function*(){let e;(0,u.existsSync)("./package.json")||(_.log.error("Missing package.json, you need to be in a capacitor project"),v.program.error(""));try{e=JSON.parse((0,u.readFileSync)("./package.json","utf8"))}catch(e){_.log.error("Invalid package.json, JSON parsing failed"),console.error("json parse error: ",e),v.program.error("")}const{dependencies:o}=e;o||(_.log.error("Missing dependencies section in package.json"),v.program.error(""));for(const[e,n]of Object.entries(o))"string"!=typeof n&&(_.log.error(`Invalid dependency ${e}: ${n}, expected string, got ${typeof n}`),v.program.error(""));(0,u.existsSync)("./node_modules/")||(_.log.error("Missing node_modules folder, please run npm install"),v.program.error(""));let n=!1;const t=yield Promise.all(Object.entries(o).map((([e,o])=>a(this,void 0,void 0,(function*(){if(!(0,u.existsSync)(`./node_modules/${e}`))return n=!0,_.log.error(`Missing dependency ${e}, please run npm install`),{name:e,version:o};let t=!1;return yield(0,w.promiseFiles)(`./node_modules/${e}`).then((e=>{e.find((e=>C.test(e)))&&(t=!0)})).catch((o=>{_.log.error(`Error reading node_modulses files for ${e} package`),console.error(o),v.program.error("")})),{name:e,version:o,native:t}}))))).catch((()=>[]));return(n||t.find((e=>void 0===e.native)))&&v.program.error(""),t}))}function j(e,o,n){return a(this,void 0,void 0,(function*(){const{data:t,error:i}=yield e.from("channels").select("version ( \n native_packages \n )").eq("name",n).eq("app_id",o).single();let r;i&&(_.log.error(`Error fetching native packages: ${i.message}`),v.program.error(""));try{r=t.version.native_packages}catch(e){_.log.error("Error parsing native packages"),v.program.error("")}return r||(_.log.error("Error parsing native packages, perhaps the metadata does not exist?"),v.program.error("")),r.forEach((e=>{"object"!=typeof e&&(_.log.error(`Invalid remote native package data: ${e}, expected object, got ${typeof e}`),v.program.error(""));const{name:o,version:n}=e;o&&"string"==typeof o||(_.log.error(`Invalid remote native package name: ${o}, expected string, got ${typeof o}`),v.program.error("")),n&&"string"==typeof n||(_.log.error(`Invalid remote native package version: ${n}, expected string, got ${typeof n}`),v.program.error(""))})),new Map(r.map((e=>[e.name,e])))}))}o.getRemoteConfig=()=>a(void 0,void 0,void 0,(function*(){const e=yield(0,o.getLocalConfig)();return k.default.get(`${o.defaultApiHost}/get_config`).then((e=>e.data)).then((o=>Object.assign(Object.assign({},o),e))).catch((()=>(console.log("Local config",e),e)))})),o.createSupabaseClient=e=>a(void 0,void 0,void 0,(function*(){const n=yield(0,o.getRemoteConfig)();return n.supaHost&&n.supaKey||(_.log.error("Cannot connect to server please try again later"),v.program.error("")),(0,h.createClient)(n.supaHost,n.supaKey,{auth:{persistSession:!1},global:{headers:{capgkey:e}}})})),o.checkKey=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t}=yield e.rpc("is_allowed_capgkey",{apikey:o,keymode:n}).single();if(!t){_.log.error("Invalid API key or insufficient permissions.");const e=n.map(((e,o)=>o===n.length-1?`or ${e}`:`${e}, `)).join("");_.log.error(`Your key should be: ${e} mode.`),v.program.error("")}})),o.isGoodPlan=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_good_plan_v3",{userid:o}).single();return n||!1})),o.isPaying=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_paying",{userid:o}).single();return n||!1})),o.isTrial=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_trial",{userid:o}).single();return n||0})),o.isAllowedAction=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n}=yield e.rpc("is_allowed_action_user",{userid:o}).single();return!!n})),o.isAllowedActionAppIdApiKey=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t}=yield e.rpc("is_allowed_action",{apikey:n,appid:o}).single();return!!t})),o.getAppOwner=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("apps").select("user_id").eq("app_id",o).single();return t&&(_.log.error("Cannot get app owner, exiting"),_.log.error("Please report the following error to capgo's staff"),console.error(t),process.exit(1)),n.user_id})),o.isAllowedApp=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t}=yield e.rpc("is_app_owner",{apikey:o,appid:n}).single();return!!t})),function(e){e[e.none=0]="none",e[e.read=1]="read",e[e.upload=2]="upload",e[e.write=3]="write",e[e.admin=4]="admin",e[e.owner=5]="owner"}(O||(o.OrganizationPerm=O={})),o.hasOrganizationPerm=(e,o)=>e>=o,o.isAllowedAppOrg=(e,o,n)=>a(void 0,void 0,void 0,(function*(){const{data:t,error:i}=yield e.rpc("get_org_perm_for_apikey",{apikey:o,app_id:n}).single();if(i&&(_.log.error("Cannot get permissions for organization!"),console.error(i),process.exit(1)),t.includes("perm")){let e=null;switch(t){case"perm_none":e=O.none;break;case"perm_read":e=O.read;break;case"perm_upload":e=O.upload;break;case"perm_write":e=O.write;break;case"perm_admin":e=O.admin;break;case"perm_owner":e=O.owner;break;default:t.includes("invite")&&(_.log.info("Please accept/deny the organization invitation before trying to access the app"),process.exit(1)),_.log.error(`Invalid output when fetching organization permission. Response: ${t}`),process.exit(1)}return{okay:!0,data:e}}let r=null;switch(t){case"INVALID_APIKEY":r="INVALID_APIKEY";break;case"NO_APP":r="NO_APP";break;case"NO_ORG":r="NO_ORG";break;default:_.log.error(`Invalid error when fetching organization permission. Response: ${t}`),process.exit(1)}return{okay:!1,error:r}})),o.checkPlanValid=(e,t,i,l,s=!0)=>a(void 0,void 0,void 0,(function*(){const a=yield(0,o.getRemoteConfig)();(yield(0,o.isAllowedActionAppIdApiKey)(e,i,l))||(_.log.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${a.hostWeb}/dashboard/settings/plans\n`),setTimeout((()=>{Promise.resolve().then((()=>r(n(6634)))).then((e=>{e.default(`${a.hostWeb}/dashboard/settings/plans`)})),v.program.error("")}),1e3));const c=yield(0,o.isTrial)(e,t),d=yield(0,o.isPaying)(e,t);c>0&&s&&!d&&_.log.warn(`WARNING !!\nTrial expires in ${c} days, upgrade here: ${a.hostWeb}/dashboard/settings/plans\n`)})),o.findSavedKey=(e=!1)=>{let o,n=`${(0,f.homedir)()}/.capgo`;return(0,u.existsSync)(n)&&(e||_.log.info(`Use global apy key ${n}`),o=(0,u.readFileSync)(n,"utf8").trim()),n=".capgo",!o&&(0,u.existsSync)(n)&&(e||_.log.info(`Use local apy key ${n}`),o=(0,u.readFileSync)(n,"utf8").trim()),o||(_.log.error("Cannot find API key in local folder or global, please login first with npx @capacitor/cli login"),v.program.error("")),o},o.findMainFile=()=>a(void 0,void 0,void 0,(function*(){var e,o,n,t;const i=/(main|index)\.(ts|tsx|js|jsx)$/;let r="";const a=process.cwd(),l=a.split("/").length;try{for(var c,d=!0,p=s(P(a));!(e=(c=yield p.next()).done);d=!0){t=c.value,d=!1;const e=t;if(e.split("/").length-l<=2&&i.test(e)){r=e,_.log.info(`Found main file here ${e}`);break}}}catch(e){o={error:e}}finally{try{d||e||!(n=p.return)||(yield n.call(p))}finally{if(o)throw o.error}}return r})),o.formatError=e=>e?`\n${m.default.render(e)}`:"",o.updateOrCreateVersion=(e,o,n)=>a(void 0,void 0,void 0,(function*(){return e.from("app_versions").upsert(o,{onConflict:"name,app_id"}).eq("app_id",o.app_id).eq("name",o.name)})),o.uploadUrl=function(e,o,n){return a(this,void 0,void 0,(function*(){const t={app_id:o,bucket_id:n};try{return(yield e.functions.invoke("upload_link",{body:JSON.stringify(t)})).data.url}catch(e){_.log.error(`Cannot get upload url ${JSON.stringify(e)}`)}return""}))},o.updateOrCreateChannel=(e,o)=>a(void 0,void 0,void 0,(function*(){if(!o.app_id||!o.name||!o.created_by)return _.log.error("missing app_id, name, or created_by"),Promise.reject(new Error("missing app_id, name, or created_by"));const{data:n,error:t}=yield e.from("channels").select("enable_progressive_deploy, secondaryVersionPercentage, secondVersion").eq("app_id",o.app_id).eq("name",o.name).single();if(n&&!t){if(n.enable_progressive_deploy){if(_.log.info("Progressive deploy is enabled"),1!==n.secondaryVersionPercentage&&_.log.warn("Latest progressive deploy has not finished"),o.secondVersion=o.version,!n.secondVersion)return _.log.error("missing secondVersion"),Promise.reject(new Error("missing secondVersion"));o.version=n.secondVersion,o.secondaryVersionPercentage=.1,_.log.info("Started new progressive upload!")}return e.from("channels").update(o).eq("app_id",o.app_id).eq("name",o.name).select().single()}return e.from("channels").insert(o).select().single()})),o.useLogSnag=()=>new b.LogSnag({token:"c124f5e9d0ce5bdd14bbb48f815d5583",project:"capgo"}),o.convertAppName=e=>e.replace(/\./g,"--"),o.verifyUser=(e,n,t=["all"])=>a(void 0,void 0,void 0,(function*(){yield(0,o.checkKey)(e,n,t);const{data:i,error:r}=yield e.rpc("get_user_id",{apikey:n}).single(),a=(i||"").toString();return a&&!r||(_.log.error("Cannot auth user with apikey"),v.program.error("")),a})),o.requireUpdateMetadata=(e,o)=>a(void 0,void 0,void 0,(function*(){const{data:n,error:t}=yield e.from("channels").select("disableAutoUpdate").eq("name",o).limit(1);if(t&&(_.log.error(`Cannot check if disableAutoUpdate is required ${JSON.stringify(t)}`),v.program.error("")),0===n.length)return!1;const{disableAutoUpdate:i}=n[0];return"version_number"===i})),o.getHumanDate=e=>new Date(e||"").toLocaleString(),o.getLocalDepenencies=x,o.getRemoteDepenencies=j,o.checkCompatibility=function(e,o,n){return a(this,void 0,void 0,(function*(){const t=yield x(),i=yield j(e,o,n),r=t.filter((e=>!!e.native)).map((e=>{const o=i.get(e.name);return o?{name:e.name,localVersion:e.version,remoteVersion:o.version}:{name:e.name,localVersion:e.version,remoteVersion:void 0}})),a=[...i].filter((([e])=>void 0===t.find((o=>o.name===e)))).map((([e,o])=>({name:e,localVersion:void 0,remoteVersion:o.version})));return r.push(...a),{finalCompatibility:r,localDependencies:t}}))}},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")},2167:e=>{e.exports=require("axios")},7812:e=>{e.exports=require("ci-info")},7304:e=>{e.exports=require("commander")},3847:e=>{e.exports=require("console-table-printer")},5362:e=>{e.exports=require("get-latest-version")},1133:e=>{e.exports=require("logsnag")},9011:e=>{e.exports=require("mime")},1406:e=>{e.exports=require("node-dir")},6634:e=>{e.exports=require("open")},9867:e=>{e.exports=require("prettyjson")},1616:e=>{e.exports=require("prompt-sync")},912:e=>{e.exports=require("semver")},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")},7561:e=>{e.exports=require("node:fs")},2037:e=>{e.exports=require("os")},1017:e=>{e.exports=require("path")},4147:e=>{e.exports=JSON.parse('{"name":"@capgo/cli","version":"3.14.65","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":"5.5.1","@capgo/find-package-manager":"^0.0.7","@clack/prompts":"^0.7.0","@supabase/supabase-js":"^2.38.5","@tomasklaen/checksum":"^1.1.0","@trufflesuite/spinnies":"^0.1.1","adm-zip":"^0.5.10","axios":"^1.6.2","ci-info":"^4.0.0","commander":"11.1.0","console-table-printer":"^2.11.2","get-latest-version":"^5.1.0","logsnag":"1.0.0","mime":"^3.0.0","node-dir":"^0.1.17","open":"^9.1.0","prettyjson":"^1.2.5","prompt-sync":"^4.2.0","qrcode":"^1.5.3","semver":"^7.5.4"},"devDependencies":{"@types/adm-zip":"0.5.5","@types/mime":"^3.0.4","@types/node":"^20.9.4","@types/node-dir":"^0.0.37","@types/npmcli__ci-detect":"^2.0.3","@types/prettyjson":"^0.0.33","@types/prompt-sync":"^4.2.3","@types/qrcode":"^1.5.5","@types/semver":"^7.5.6","@typescript-eslint/eslint-plugin":"6.12.0","@typescript-eslint/parser":"6.12.0","eslint":"8.55.0","eslint-config-airbnb-base":"^15.0.0","eslint-config-prettier":"^9.0.0","eslint-import-resolver-typescript":"3.6.1","eslint-plugin-import":"2.29.0","eslint-plugin-prettier":"^5.0.1","git-format-staged":"3.0.0","husky":"^8.0.3","nodemon":"3.0.2","pkg":"5.8.1","prettier":"3.1.1","ts-loader":"^9.5.1","ts-node":"^10.9.1","tsconfig-paths":"4.2.0","typescript":"5.3.3","webpack":"5.89.0","webpack-cli":"^5.1.4","webpack-node-externals":"^3.0.0"}}')}},o={};!function n(t){var i=o[t];if(void 0!==i)return i.exports;var r=o[t]={exports:{}};return e[t].call(r.exports,r,r.exports,n),r.exports}(1428)})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/cli",
3
- "version": "3.14.61",
3
+ "version": "3.14.65",
4
4
  "description": "A CLI to upload to capgo servers",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -5,7 +5,7 @@ import { checkVersionNotUsedInDeviceOverride } from '../api/devices_override';
5
5
  import { checkVersionNotUsedInChannel } from '../api/channels';
6
6
  import { checkAppExistsAndHasPermissionErr } from "../api/app";
7
7
  import {
8
- OptionsBase,
8
+ OptionsBase,
9
9
  getConfig, createSupabaseClient,
10
10
  formatError, findSavedKey, checkPlanValid, useLogSnag, verifyUser
11
11
  } from '../utils';
@@ -47,7 +47,7 @@ export const unlinkDevice = async (channel: string, appId: string, options: Opti
47
47
  program.error('');
48
48
  }
49
49
  try {
50
- await checkPlanValid(supabase, userId)
50
+ await checkPlanValid(supabase, userId, appId, options.apikey)
51
51
 
52
52
  const versionData = await getVersionData(supabase, appId, userId, bundle);
53
53
  await checkVersionNotUsedInChannel(supabase, appId, userId, versionData);
@@ -19,7 +19,8 @@ import {
19
19
  getLocalDepenencies,
20
20
  verifyUser,
21
21
  OrganizationPerm,
22
- hasOrganizationPerm
22
+ hasOrganizationPerm,
23
+ getAppOwner
23
24
  } from '../utils';
24
25
  import { checkIndexPosition, searchInDirectory } from './check';
25
26
 
@@ -54,10 +55,10 @@ export const uploadBundle = async (appid: string, options: Options, shouldExit =
54
55
  channel = channel || 'dev';
55
56
 
56
57
  const config = await getConfig();
57
- const localS3: boolean = (config.app.extConfig.plugins && config.app.extConfig.plugins.CapacitorUpdater
58
+ const localS3: boolean = (config.app.extConfig.plugins && config.app.extConfig.plugins.CapacitorUpdater
58
59
  && config.app.extConfig.plugins.CapacitorUpdater.localS3) === true;
59
60
 
60
- const checkNotifyAppReady = options.codeCheck
61
+ const checkNotifyAppReady = options.codeCheck
61
62
  appid = appid || config?.app?.appId
62
63
  // create bundle name format : 1.0.0-beta.x where x is a uuid
63
64
  const uuid = randomUUID().split('-')[0];
@@ -90,8 +91,8 @@ export const uploadBundle = async (appid: string, options: Options, shouldExit =
90
91
  }
91
92
  const foundIndex = checkIndexPosition(path);
92
93
  if (!foundIndex) {
93
- p.log.error(`index.html is missing in the root folder or in the only folder in the root folder`);
94
- program.error('');
94
+ p.log.error(`index.html is missing in the root folder or in the only folder in the root folder`);
95
+ program.error('');
95
96
  }
96
97
  }
97
98
 
@@ -100,22 +101,22 @@ export const uploadBundle = async (appid: string, options: Options, shouldExit =
100
101
  const localConfig = await getLocalConfig()
101
102
  const supabase = await createSupabaseClient(options.apikey)
102
103
  const userId = await verifyUser(supabase, options.apikey, ['write', 'all', 'upload']);
103
- await checkPlanValid(supabase, userId, false)
104
104
  // Check we have app access to this appId
105
105
  // await checkAppExistsAndHasPermissionErr(supabase, options.apikey, appid);
106
106
 
107
107
  const permissions = await checkAppExistsAndHasPermissionOrgErr(supabase, options.apikey, appid, OrganizationPerm.upload)
108
+ await checkPlanValid(supabase, userId, appid, options.apikey, false)
108
109
 
109
110
  const updateMetadataRequired = await requireUpdateMetadata(supabase, channel)
110
111
 
111
112
  // Check compatibility here
112
113
  const { data: channelData, error: channelError } = await supabase
113
- .from('channels')
114
- .select('version ( minUpdateVersion, native_packages )')
115
- .eq('name', channel)
116
- .eq('app_id', appid)
117
- .single()
118
-
114
+ .from('channels')
115
+ .select('version ( minUpdateVersion, native_packages )')
116
+ .eq('name', channel)
117
+ .eq('app_id', appid)
118
+ .single()
119
+
119
120
  // eslint-disable-next-line no-undef-init
120
121
  let localDependencies: Awaited<ReturnType<typeof getLocalDepenencies>> | undefined = undefined;
121
122
  let finalCompatibility: Awaited<ReturnType<typeof checkCompatibility>>['finalCompatibility'];
@@ -124,14 +125,14 @@ export const uploadBundle = async (appid: string, options: Options, shouldExit =
124
125
  if (!channelError && channelData && channelData.version && (channelData.version as any).native_packages && !ignoreMetadataCheck) {
125
126
  const spinner = p.spinner();
126
127
  spinner.start(`Checking bundle compatibility with channel ${channel}`);
127
- const {
128
+ const {
128
129
  finalCompatibility: finalCompatibilityWithChannel,
129
- localDependencies: localDependenciesWithChannel
130
+ localDependencies: localDependenciesWithChannel
130
131
  } = await checkCompatibility(supabase, appid, channel)
131
132
 
132
133
  finalCompatibility = finalCompatibilityWithChannel
133
134
  localDependencies = localDependenciesWithChannel
134
-
135
+
135
136
  if (finalCompatibility.find((x) => x.localVersion !== x.remoteVersion)) {
136
137
  p.log.error(`Your bundle is not compatible with the channel ${channel}`);
137
138
  p.log.warn(`You can check compatibility with "npx @capgo/cli bundle compatibility"`);
@@ -147,7 +148,7 @@ export const uploadBundle = async (appid: string, options: Options, shouldExit =
147
148
  p.log.error('Invalid remote min update version, skipping auto setting compatibility');
148
149
  program.error('');
149
150
  }
150
-
151
+
151
152
  minUpdateVersion = lastMinUpdateVersion
152
153
  p.log.info(`Auto set min-update-version to ${minUpdateVersion}`);
153
154
  } catch (error) {
@@ -285,15 +286,17 @@ It will be also visible in your dashboard\n`);
285
286
  }
286
287
 
287
288
  const hashedLocalDependencies = localDependencies ? new Map(localDependencies
288
- .filter((a) => !!a.native && a.native !== undefined)
289
- .map((a) => [a.name, a])) : new Map()
289
+ .filter((a) => !!a.native && a.native !== undefined)
290
+ .map((a) => [a.name, a])) : new Map()
290
291
 
291
292
  // eslint-disable-next-line max-len
292
293
  const nativePackages = (hashedLocalDependencies.size > 0 || !options.ignoreMetadataCheck) ? Array.from(hashedLocalDependencies, ([name, value]) => ({ name, version: value.version })) : undefined
293
294
 
295
+ const appOwner = await getAppOwner(supabase, appid)
296
+
294
297
  const versionData = {
295
298
  bucket_id: external ? undefined : fileName,
296
- user_id: userId,
299
+ user_id: appOwner,
297
300
  name: bundle,
298
301
  app_id: appid,
299
302
  session_key: sessionKey,
@@ -323,14 +326,15 @@ It will be also visible in your dashboard\n`);
323
326
  url,
324
327
  data: zipped,
325
328
  headers: (!localS3 ? {
326
- "Content-Type": "application/octet-stream",
327
- "Cache-Control": "public, max-age=456789, immutable",
328
- "x-amz-meta-crc32": checksum,
329
+ "Content-Type": "application/octet-stream",
330
+ "Cache-Control": "public, max-age=456789, immutable",
331
+ "x-amz-meta-crc32": checksum,
329
332
  } : undefined)
330
333
  })
331
334
  versionData.storage_provider = 'r2'
332
335
  const { error: dbError2 } = await updateOrCreateVersion(supabase, versionData, options.apikey)
333
336
  if (dbError2) {
337
+ console.log(dbError2)
334
338
  p.log.error(`Cannot update bundle ${formatError(dbError)}`);
335
339
  program.error('');
336
340
  }
@@ -344,11 +348,12 @@ It will be also visible in your dashboard\n`);
344
348
  const { error: dbError3, data } = await updateOrCreateChannel(supabase, {
345
349
  name: channel,
346
350
  app_id: appid,
347
- created_by: userId,
351
+ created_by: appOwner,
348
352
  version: versionId,
349
353
  })
350
354
  if (dbError3) {
351
355
  p.log.error(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this.`);
356
+ console.log(dbError3)
352
357
  program.error('');
353
358
  }
354
359
  const appidWeb = convertAppName(appid)
@@ -359,7 +364,7 @@ It will be also visible in your dashboard\n`);
359
364
  p.log.info(`Link device to this bundle to try it: ${bundleUrl}`);
360
365
  }
361
366
 
362
- if(options.bundleUrl) {
367
+ if (options.bundleUrl) {
363
368
  p.log.info(`Bundle url: ${bundleUrl}`);
364
369
  }
365
370
  } else if (!versionId) {
@@ -66,7 +66,7 @@ export const setChannel = async (channel: string, appId: string, options: Option
66
66
  program.error('');
67
67
  }
68
68
  try {
69
- await checkPlanValid(supabase, userId)
69
+ await checkPlanValid(supabase, userId, appId, options.apikey)
70
70
  const channelPayload: Database['public']['Tables']['channels']['Insert'] = {
71
71
  created_by: userId,
72
72
  app_id: appId,
package/src/utils.ts CHANGED
@@ -36,16 +36,17 @@ export const getConfig = async () => {
36
36
 
37
37
  export const getLocalConfig = async () => {
38
38
  try {
39
- const config: Config = await getConfig();
40
- const capConfig: Partial<CapgoConfig> = {
41
- host: (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localHost || defaultHost) as string,
42
- hostWeb: (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localWebHost || defaultHostWeb) as string,
43
- }
44
- if (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupa && config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupaAnon) {
45
- capConfig.supaKey = config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupaAnon
46
- capConfig.supaHost = config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupa
47
- }
48
- return capConfig
39
+ const config: Config = await getConfig();
40
+ const capConfig: Partial<CapgoConfig> = {
41
+ host: (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localHost || defaultHost) as string,
42
+ hostWeb: (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localWebHost || defaultHostWeb) as string,
43
+ }
44
+ // eslint-disable-next-line max-len
45
+ if (config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupa && config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupaAnon) {
46
+ capConfig.supaKey = config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupaAnon
47
+ capConfig.supaHost = config?.app?.extConfig?.plugins?.CapacitorUpdater?.localSupa
48
+ }
49
+ return capConfig
49
50
  } catch (error) {
50
51
  return {
51
52
  host: defaultHost,
@@ -68,13 +69,13 @@ export const getRemoteConfig = async () => {
68
69
  // call host + /api/get_config and parse the result as json using axios
69
70
  const localConfig = await getLocalConfig()
70
71
  return axios
71
- .get(`${defaultApiHost}/get_config`)
72
- .then((res) => res.data as CapgoConfig)
73
- .then(data => ({...data, ...localConfig} as CapgoConfig))
74
- .catch(() => {
75
- console.log('Local config', localConfig);
76
- return localConfig
77
- })
72
+ .get(`${defaultApiHost}/get_config`)
73
+ .then((res) => res.data as CapgoConfig)
74
+ .then(data => ({ ...data, ...localConfig } as CapgoConfig))
75
+ .catch(() => {
76
+ console.log('Local config', localConfig);
77
+ return localConfig
78
+ })
78
79
  }
79
80
 
80
81
  export const createSupabaseClient = async (apikey: string) => {
@@ -97,7 +98,7 @@ export const createSupabaseClient = async (apikey: string) => {
97
98
 
98
99
  export const checkKey = async (supabase: SupabaseClient<Database>, apikey: string,
99
100
  keymode: Database['public']['Enums']['key_mode'][]) => {
100
- const { data: apiAccess} = await supabase
101
+ const { data: apiAccess } = await supabase
101
102
  .rpc('is_allowed_capgkey', { apikey, keymode })
102
103
  .single()
103
104
 
@@ -143,6 +144,31 @@ export const isAllowedAction = async (supabase: SupabaseClient<Database>, userId
143
144
  return !!data
144
145
  }
145
146
 
147
+ export const isAllowedActionAppIdApiKey = async (supabase: SupabaseClient<Database>, appId: string, apikey: string): Promise<boolean> => {
148
+ const { data } = await supabase
149
+ .rpc('is_allowed_action', { apikey, appid: appId })
150
+ .single()
151
+
152
+ return !!data
153
+ }
154
+
155
+ export const getAppOwner = async (supabase: SupabaseClient<Database>, appId: string): Promise<string> => {
156
+ const { data, error } = await supabase
157
+ .from('apps')
158
+ .select('user_id')
159
+ .eq('app_id', appId)
160
+ .single()
161
+
162
+ if (error) {
163
+ p.log.error('Cannot get app owner, exiting')
164
+ p.log.error('Please report the following error to capgo\'s staff')
165
+ console.error(error)
166
+ process.exit(1)
167
+ }
168
+
169
+ return data.user_id
170
+ }
171
+
146
172
  export const isAllowedApp = async (supabase: SupabaseClient<Database>, apikey: string, appId: string): Promise<boolean> => {
147
173
  const { data } = await supabase
148
174
  .rpc('is_app_owner', { apikey, appid: appId })
@@ -151,20 +177,20 @@ export const isAllowedApp = async (supabase: SupabaseClient<Database>, apikey: s
151
177
  }
152
178
 
153
179
  export enum OrganizationPerm {
154
- 'none' = 0,
155
- 'read' = 1,
156
- 'upload' = 2,
157
- 'write' = 3,
158
- 'admin' = 4,
159
- 'owner' = 5,
180
+ 'none' = 0,
181
+ 'read' = 1,
182
+ 'upload' = 2,
183
+ 'write' = 3,
184
+ 'admin' = 4,
185
+ 'owner' = 5,
160
186
  }
161
187
 
162
188
  export const hasOrganizationPerm = (perm: OrganizationPerm, required: OrganizationPerm): boolean => (perm as number) >= (required as number)
163
189
 
164
190
  export const isAllowedAppOrg = async (
165
191
  supabase: SupabaseClient<Database>,
166
- apikey: string,
167
- appId: string,
192
+ apikey: string,
193
+ appId: string,
168
194
  ): Promise<{ okay: true, data: OrganizationPerm } | { okay: false, error: 'INVALID_APIKEY' | 'NO_APP' | 'NO_ORG' }> => {
169
195
  const { data, error } = await supabase
170
196
  .rpc('get_org_perm_for_apikey', { apikey, app_id: appId })
@@ -179,7 +205,7 @@ export const isAllowedAppOrg = async (
179
205
  const ok = (data as string).includes('perm')
180
206
  if (ok) {
181
207
  let perm = null as (OrganizationPerm | null)
182
-
208
+
183
209
  switch (data as string) {
184
210
  case 'perm_none': {
185
211
  perm = OrganizationPerm.none
@@ -250,9 +276,9 @@ export const isAllowedAppOrg = async (
250
276
  }
251
277
  }
252
278
 
253
- export const checkPlanValid = async (supabase: SupabaseClient<Database>, userId: string, warning = true) => {
279
+ export const checkPlanValid = async (supabase: SupabaseClient<Database>, userId: string, appId: string, apikey: string, warning = true) => {
254
280
  const config = await getRemoteConfig()
255
- const validPlan = await isAllowedAction(supabase, userId)
281
+ const validPlan = await isAllowedActionAppIdApiKey(supabase, appId, apikey)
256
282
  if (!validPlan) {
257
283
  p.log.error(`You need to upgrade your plan to continue to use capgo.\n Upgrade here: ${config.hostWeb}/dashboard/settings/plans\n`);
258
284
  setTimeout(() => {
@@ -362,26 +388,15 @@ interface Config {
362
388
  }
363
389
 
364
390
  export const updateOrCreateVersion = async (supabase: SupabaseClient<Database>,
365
- update: Database['public']['Tables']['app_versions']['Insert'], apikey: string) => {
391
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
392
+ update: Database['public']['Tables']['app_versions']['Insert'], apikey: string) =>
366
393
  // console.log('updateOrCreateVersion', update, apikey)
367
- const { data, error } = await supabase
368
- .rpc('exist_app_versions', { appid: update.app_id, name_version: update.name, apikey })
369
- .single()
370
394
 
371
- if (data && !error) {
372
- update.deleted = false
373
- return supabase
374
- .from('app_versions')
375
- .update(update)
376
- .eq('app_id', update.app_id)
377
- .eq('name', update.name)
378
- }
379
- // console.log('create Version', data, error)
395
+ supabase.from('app_versions')
396
+ .upsert(update, { onConflict: 'name,app_id' })
397
+ .eq('app_id', update.app_id)
398
+ .eq('name', update.name)
380
399
 
381
- return supabase
382
- .from('app_versions')
383
- .insert(update)
384
- }
385
400
 
386
401
  export async function uploadUrl(supabase: SupabaseClient<Database>, appId: string, bucketId: string): Promise<string> {
387
402
  const data = {
@@ -416,7 +431,7 @@ export const updateOrCreateChannel = async (supabase: SupabaseClient<Database>,
416
431
  if (data.enable_progressive_deploy) {
417
432
  p.log.info('Progressive deploy is enabled')
418
433
 
419
- if (data.secondaryVersionPercentage !== 1)
434
+ if (data.secondaryVersionPercentage !== 1)
420
435
  p.log.warn('Latest progressive deploy has not finished')
421
436
 
422
437
  update.secondVersion = update.version
@@ -427,7 +442,7 @@ export const updateOrCreateChannel = async (supabase: SupabaseClient<Database>,
427
442
  update.version = data.secondVersion
428
443
  update.secondaryVersionPercentage = 0.1
429
444
  p.log.info('Started new progressive upload!')
430
-
445
+
431
446
  // update.version = undefined
432
447
  }
433
448
  return supabase
@@ -505,7 +520,7 @@ export async function getLocalDepenencies() {
505
520
  program.error('');
506
521
  }
507
522
 
508
-
523
+
509
524
  let packageJson;
510
525
  try {
511
526
  packageJson = JSON.parse(readFileSync('./package.json', 'utf8'));
@@ -514,7 +529,7 @@ export async function getLocalDepenencies() {
514
529
  console.error('json parse error: ', err)
515
530
  program.error('');
516
531
  }
517
-
532
+
518
533
  const { dependencies } = packageJson
519
534
  if (!dependencies) {
520
535
  p.log.error("Missing dependencies section in package.json");
@@ -543,9 +558,9 @@ export async function getLocalDepenencies() {
543
558
  if (!dependencyFolderExists) {
544
559
  anyInvalid = true
545
560
  p.log.error(`Missing dependency ${key}, please run npm install`);
546
- return {name: key, version: value}
561
+ return { name: key, version: value }
547
562
  }
548
-
563
+
549
564
  let hasNativeFiles = false;
550
565
  await promiseFiles(`./node_modules/${key}`)
551
566
  .then(files => {
@@ -632,36 +647,36 @@ export async function checkCompatibility(supabase: SupabaseClient<Database>, app
632
647
  const dependenciesObject = await getLocalDepenencies()
633
648
  const mappedRemoteNativePackages = await getRemoteDepenencies(supabase, appId, channel)
634
649
 
635
- const finalDepenencies:
636
- ({
637
- name: string;
638
- localVersion: string;
639
- remoteVersion: string;
640
- } | {
641
- name: string;
642
- localVersion: string;
643
- remoteVersion: undefined;
644
- } | {
645
- name: string;
646
- localVersion: undefined;
647
- remoteVersion: string;
648
- })[] = dependenciesObject
649
- .filter((a) => !!a.native)
650
- .map((local) => {
651
- const remotePackage = mappedRemoteNativePackages.get(local.name)
652
- if (remotePackage)
650
+ const finalDepenencies:
651
+ ({
652
+ name: string;
653
+ localVersion: string;
654
+ remoteVersion: string;
655
+ } | {
656
+ name: string;
657
+ localVersion: string;
658
+ remoteVersion: undefined;
659
+ } | {
660
+ name: string;
661
+ localVersion: undefined;
662
+ remoteVersion: string;
663
+ })[] = dependenciesObject
664
+ .filter((a) => !!a.native)
665
+ .map((local) => {
666
+ const remotePackage = mappedRemoteNativePackages.get(local.name)
667
+ if (remotePackage)
668
+ return {
669
+ name: local.name,
670
+ localVersion: local.version,
671
+ remoteVersion: remotePackage.version
672
+ }
673
+
653
674
  return {
654
675
  name: local.name,
655
676
  localVersion: local.version,
656
- remoteVersion: remotePackage.version
677
+ remoteVersion: undefined
657
678
  }
658
-
659
- return {
660
- name: local.name,
661
- localVersion: local.version,
662
- remoteVersion: undefined
663
- }
664
- })
679
+ })
665
680
 
666
681
  const removeNotInLocal = [...mappedRemoteNativePackages]
667
682
  .filter(([remoteName]) => dependenciesObject.find((a) => a.name === remoteName) === undefined)
@@ -669,8 +684,8 @@ export async function checkCompatibility(supabase: SupabaseClient<Database>, app
669
684
 
670
685
  finalDepenencies.push(...removeNotInLocal)
671
686
 
672
- return {
687
+ return {
673
688
  finalCompatibility: finalDepenencies,
674
689
  localDependencies: dependenciesObject,
675
- }
690
+ }
676
691
  }