@capgo/cli 7.119.2 → 7.120.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -91,7 +91,7 @@ Expecting one of '${B.join("', '")}'`);if(this._lifeCycleHooks[A])this._lifeCycl
91
91
  `),this.outputHelp({error:!0});let B=Q||{},I=B.exitCode||1,E=B.code||"commander.error";this._exit(I,E,A)}_parseOptionsEnv(){this.options.forEach((A)=>{if(A.envVar&&A.envVar in a0.env){let Q=A.attributeName();if(this.getOptionValue(Q)===void 0||["default","config","env"].includes(this.getOptionValueSource(Q)))if(A.required||A.optional)this.emit(`optionEnv:${A.name()}`,a0.env[A.envVar]);else this.emit(`optionEnv:${A.name()}`)}})}_parseOptionsImplied(){let A=new UhA(this.options),Q=(B)=>{return this.getOptionValue(B)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(B))};this.options.filter((B)=>B.implied!==void 0&&Q(B.attributeName())&&A.valueFromOption(this.getOptionValue(B.attributeName()),B)).forEach((B)=>{Object.keys(B.implied).filter((I)=>!Q(I)).forEach((I)=>{this.setOptionValueWithSource(I,B.implied[I],"implied")})})}missingArgument(A){let Q=`error: missing required argument '${A}'`;this.error(Q,{code:"commander.missingArgument"})}optionMissingArgument(A){let Q=`error: option '${A.flags}' argument missing`;this.error(Q,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(A){let Q=`error: required option '${A.flags}' not specified`;this.error(Q,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(A,Q){let B=(D)=>{let $=D.attributeName(),G=this.getOptionValue($),Y=this.options.find((X)=>X.negate&&$===X.attributeName()),H=this.options.find((X)=>!X.negate&&$===X.attributeName());if(Y&&(Y.presetArg===void 0&&G===!1||Y.presetArg!==void 0&&G===Y.presetArg))return Y;return H||D},I=(D)=>{let $=B(D),G=$.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${$.envVar}'`;return`option '${$.flags}'`},E=`error: ${I(A)} cannot be used with ${I(Q)}`;this.error(E,{code:"commander.conflictingOption"})}unknownOption(A){if(this._allowUnknownOption)return;let Q="";if(A.startsWith("--")&&this._showSuggestionAfterError){let I=[],E=this;do{let D=E.createHelp().visibleOptions(E).filter(($)=>$.long).map(($)=>$.long);I=I.concat(D),E=E.parent}while(E&&!E._enablePositionalOptions);Q=h0A(A,I)}let B=`error: unknown option '${A}'${Q}`;this.error(B,{code:"commander.unknownOption"})}_excessArguments(A){if(this._allowExcessArguments)return;let Q=this.registeredArguments.length,B=Q===1?"":"s",E=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${Q} argument${B} but got ${A.length}.`;this.error(E,{code:"commander.excessArguments"})}unknownCommand(){let A=this.args[0],Q="";if(this._showSuggestionAfterError){let I=[];this.createHelp().visibleCommands(this).forEach((E)=>{if(I.push(E.name()),E.alias())I.push(E.alias())}),Q=h0A(A,I)}let B=`error: unknown command '${A}'${Q}`;this.error(B,{code:"commander.unknownCommand"})}version(A,Q,B){if(A===void 0)return this._version;this._version=A,Q=Q||"-V, --version",B=B||"output the version number";let I=this.createOption(Q,B);return this._versionOptionName=I.attributeName(),this._registerOption(I),this.on("option:"+I.name(),()=>{this._outputConfiguration.writeOut(`${A}
92
92
  `),this._exit(0,"commander.version",A)}),this}description(A,Q){if(A===void 0&&Q===void 0)return this._description;if(this._description=A,Q)this._argsDescription=Q;return this}summary(A){if(A===void 0)return this._summary;return this._summary=A,this}alias(A){if(A===void 0)return this._aliases[0];let Q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)Q=this.commands[this.commands.length-1];if(A===Q._name)throw Error("Command alias can't be the same as its name");let B=this.parent?._findCommand(A);if(B){let I=[B.name()].concat(B.aliases()).join("|");throw Error(`cannot add alias '${A}' to command '${this.name()}' as already have command '${I}'`)}return Q._aliases.push(A),this}aliases(A){if(A===void 0)return this._aliases;return A.forEach((Q)=>this.alias(Q)),this}usage(A){if(A===void 0){if(this._usage)return this._usage;let Q=this.registeredArguments.map((B)=>{return GhA(B)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?Q:[]).join(" ")}return this._usage=A,this}name(A){if(A===void 0)return this._name;return this._name=A,this}helpGroup(A){if(A===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=A,this}commandsGroup(A){if(A===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=A,this}optionsGroup(A){if(A===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=A,this}_initOptionGroup(A){if(this._defaultOptionGroup&&!A.helpGroupHeading)A.helpGroup(this._defaultOptionGroup)}_initCommandGroup(A){if(this._defaultCommandGroup&&!A.helpGroup())A.helpGroup(this._defaultCommandGroup)}nameFromFilename(A){return this._name=JJ.basename(A,JJ.extname(A)),this}executableDir(A){if(A===void 0)return this._executableDir;return this._executableDir=A,this}helpInformation(A){let Q=this.createHelp(),B=this._getOutputContext(A);Q.prepareContext({error:B.error,helpWidth:B.helpWidth,outputHasColors:B.hasColors});let I=Q.formatHelp(this,Q);if(B.hasColors)return I;return this._outputConfiguration.stripColor(I)}_getOutputContext(A){A=A||{};let Q=!!A.error,B,I,E;if(Q)B=($)=>this._outputConfiguration.writeErr($),I=this._outputConfiguration.getErrHasColors(),E=this._outputConfiguration.getErrHelpWidth();else B=($)=>this._outputConfiguration.writeOut($),I=this._outputConfiguration.getOutHasColors(),E=this._outputConfiguration.getOutHelpWidth();return{error:Q,write:($)=>{if(!I)$=this._outputConfiguration.stripColor($);return B($)},hasColors:I,helpWidth:E}}outputHelp(A){let Q;if(typeof A==="function")Q=A,A=void 0;let B=this._getOutputContext(A),I={error:B.error,write:B.write,command:this};this._getCommandAndAncestors().reverse().forEach((D)=>D.emit("beforeAllHelp",I)),this.emit("beforeHelp",I);let E=this.helpInformation({error:B.error});if(Q){if(E=Q(E),typeof E!=="string"&&!Buffer.isBuffer(E))throw Error("outputHelp callback must return a string or a Buffer")}if(B.write(E),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",I),this._getCommandAndAncestors().forEach((D)=>D.emit("afterAllHelp",I))}helpOption(A,Q){if(typeof A==="boolean"){if(A){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(A??"-h, --help",Q??"display help for command"),A||Q)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(A){return this._helpOption=A,this._initOptionGroup(A),this}help(A){this.outputHelp(A);let Q=Number(a0.exitCode??0);if(Q===0&&A&&typeof A!=="function"&&A.error)Q=1;this._exit(Q,"commander.help","(outputHelp)")}addHelpText(A,Q){let B=["beforeAll","before","after","afterAll"];if(!B.includes(A))throw Error(`Unexpected value for position to addHelpText.
93
93
  Expecting one of '${B.join("', '")}'`);let I=`${A}Help`;return this.on(I,(E)=>{let D;if(typeof Q==="function")D=Q({error:E.error,command:E.command});else D=Q;if(D)E.write(`${D}
94
- `)}),this}_outputHelpIfRequested(A){let Q=this._getHelpOption();if(Q&&A.find((I)=>Q.is(I)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function u0A(A){return A.map((Q)=>{if(!Q.startsWith("--inspect"))return Q;let B,I="127.0.0.1",E="9229",D;if((D=Q.match(/^(--inspect(-brk)?)$/))!==null)B=D[1];else if((D=Q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(B=D[1],/^\d+$/.test(D[3]))E=D[3];else I=D[3];else if((D=Q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)B=D[1],I=D[3],E=D[4];if(B&&E!=="0")return`${B}=${I}:${parseInt(E)+1}`;return Q})}function lg(){if(a0.env.NO_COLOR||a0.env.FORCE_COLOR==="0"||a0.env.FORCE_COLOR==="false")return!1;if(a0.env.FORCE_COLOR||a0.env.CLICOLOR_FORCE!==void 0)return!0;return}HhA.Command=dg;HhA.useColor=lg});var p0A=x((KhA)=>{var{Argument:c0A}=M2(),{Command:pg}=m0A(),{CommanderError:FhA,InvalidArgumentError:l0A}=aW(),{Help:WhA}=hg(),{Option:d0A}=ug();KhA.program=new pg;KhA.createCommand=(A)=>new pg(A);KhA.createOption=(A,Q)=>new d0A(A,Q);KhA.createArgument=(A,Q)=>new c0A(A,Q);KhA.Command=pg;KhA.Option=d0A;KhA.Argument=c0A;KhA.Help=WhA;KhA.CommanderError=FhA;KhA.InvalidArgumentError=l0A;KhA.InvalidOptionArgumentError=l0A});var fE;var YJ=PA(()=>{fE={name:"@capgo/cli",type:"module",version:"7.119.2",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/capgo/tree/main/cli#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/capgo.git",directory:"cli"},bugs:{url:"https://github.com/Cap-go/capgo/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"bunx --bun supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsgo --project tsconfig.tsgo.json --noEmit",lint:"bun run lint:ox","lint:ox":"oxlint --config ../.oxlintrc.json src","lint:fix":"oxlint --config ../.oxlintrc.json --fix src","check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:android-service-account-validation":"bun test/test-android-service-account-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:build-needed":"bun test/test-build-needed.mjs","test:ci-prompts":"bun test/test-ci-prompts.mjs","test:ci-secrets":"bun test/test-ci-secrets.mjs","test:android-onboarding-progress":"bun test/test-android-onboarding-progress.mjs","test:onboarding-telemetry":"bun test/test-onboarding-telemetry.mjs","test:v2-event-migration":"bun test/test-v2-event-migration.mjs","test:analytics":"bun test/test-analytics.mjs","test:analytics-error-category":"bun test/test-analytics-error-category.mjs","test:analytics-org-resolver":"bun test/test-analytics-org-resolver.mjs","test:supabase-perf":"bun test/test-supabase-perf.mjs","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:onboarding-recovery":"bun test/test-onboarding-recovery.mjs","test:onboarding-progress":"bun test/test-onboarding-progress.mjs","test:onboarding-run-targets":"bun test/test-onboarding-run-targets.mjs","test:run-device-command":"bun test/test-run-device-command.mjs","test:init-app-conflict":"bun test/test-init-app-conflict.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs",test:"bun run build && bun run test:version-detection:setup && bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:android-service-account-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:build-needed && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:mcp-analytics && bun run test:app-created-source && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:build-platform-selection && bun run test:onboarding-recovery && bun run test:onboarding-progress && bun run test:onboarding-run-targets && bun run test:run-device-command && bun run test:init-app-conflict && bun run test:init-guardrails && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:apple-api-import-helpers && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:ai-render-markdown","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^7.0.4","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.6"},devDependencies:{"@antfu/eslint-config":"^9.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.3.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.4.0","@modelcontextprotocol/sdk":"^1.29.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.106.2","@tanstack/intent":"^0.0.41","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.9.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.15","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260526.1","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.17","ci-info":"^4.4.0",commander:"^14.0.3",eslint:"^10.4.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.67.0",partysocket:"^1.1.19",prettyjson:"^1.2.5",tmp:"^0.2.6","tus-js-client":"^4.3.1",typescript:"^6.0.3",ws:"^8.21.0",zod:"^4.4.3"}}});function jhA(A){if(A&&typeof A==="object"&&"status"in A){let Q=A.status;if(typeof Q==="number")return Q}return}function PhA(A){if(A instanceof Error)return A.message;if(typeof A==="string")return A;return""}function sW(A){if(A&&typeof A==="object"&&"code"in A){let I=A.code;if(typeof I==="string"&&I.startsWith("commander."))return"commander"}let Q=jhA(A);if(Q!==void 0){if(Q===401)return"unauthorized";if(Q===403)return"forbidden";if(Q===404)return"not_found";if(Q===413)return"payload_too_large";if(Q>=500)return"server_error"}let B=PhA(A).toLowerCase();if(/econnrefused|enotfound|fetch failed|network|socket|dns/.test(B))return"network_error";if(/timed out|timeout|etimedout|aborted/.test(B))return"timeout";if(/invalid|must be|required|not allowed|malformed|validation/.test(B))return"validation_error";return"unknown"}function i0A(A){if(A===401)return"unauthorized";if(A===403)return"forbidden";if(A===404)return"not_found";if(A===408||A===504)return"timeout";if(A===413)return"payload_too_large";if(A===429)return"rate_limited";if(A===400||A===422)return"validation_error";if(A>=500)return"server_error";return"unknown"}var r0A=x((PhQ,_hA)=>{_hA.exports=[{name:"Agola CI",constant:"AGOLA",env:"AGOLA_GIT_REF",pr:"AGOLA_PULL_REQUEST_ID"},{name:"Alpic",constant:"ALPIC",env:"ALPIC_HOST"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE",pr:{env:"AC_GIT_PR",ne:"false"}},{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN",pr:{env:"CODEBUILD_WEBHOOK_EVENT",any:["PULL_REQUEST_CREATED","PULL_REQUEST_UPDATED","PULL_REQUEST_REOPENED"]}},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"TF_BUILD",pr:{BUILD_REASON:"PullRequest"}},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"Cloudflare Pages",constant:"CLOUDFLARE_PAGES",env:"CF_PAGES"},{name:"Cloudflare Workers",constant:"CLOUDFLARE_WORKERS",env:"WORKERS_CI"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codemagic",constant:"CODEMAGIC",env:"CM_BUILD_ID",pr:"CM_PULL_REQUEST"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"Earthly",constant:"EARTHLY",env:"EARTHLY_CI"},{name:"Expo Application Services",constant:"EAS",env:"EAS_BUILD"},{name:"Gerrit",constant:"GERRIT",env:"GERRIT_PROJECT"},{name:"Gitea Actions",constant:"GITEA_ACTIONS",env:"GITEA_ACTIONS"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Google Cloud Build",constant:"GOOGLE_CLOUD_BUILD",env:"BUILDER_OUTPUT"},{name:"Harness CI",constant:"HARNESS",env:"HARNESS_BUILD_ID"},{name:"Heroku",constant:"HEROKU",env:{env:"NODE",includes:"/app/.heroku/node/bin/node"}},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Prow",constant:"PROW",env:"PROW_JOB_ID"},{name:"ReleaseHub",constant:"RELEASEHUB",env:"RELEASE_BUILD_ID"},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Sourcehut",constant:"SOURCEHUT",env:{CI_NAME:"sourcehut"}},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vela",constant:"VELA",env:"VELA",pr:{VELA_PULL_REQUEST:"1"}},{name:"Vercel",constant:"VERCEL",env:{any:["NOW_BUILDER","VERCEL"]},pr:"VERCEL_GIT_PULL_REQUEST_ID"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"},{name:"Woodpecker",constant:"WOODPECKER",env:{CI:"woodpecker"},pr:{CI_BUILD_EVENT:"pull_request"}},{name:"Xcode Cloud",constant:"XCODE_CLOUD",env:"CI_XCODE_PROJECT",pr:"CI_PULL_REQUEST_NUMBER"},{name:"Xcode Server",constant:"XCODE_SERVER",env:"XCS"}]});var rg=x((ng)=>{var o0A=r0A(),eE=process.env;Object.defineProperty(ng,"_vendors",{value:o0A.map(function(A){return A.constant})});ng.name=null;ng.isPR=null;ng.id=null;if(eE.CI!=="false")o0A.forEach(function(A){let B=(Array.isArray(A.env)?A.env:[A.env]).every(function(I){return a0A(I)});if(ng[A.constant]=B,!B)return;ng.name=A.name,ng.isPR=khA(A),ng.id=A.constant});ng.isCI=!!(eE.CI!=="false"&&(eE.BUILD_ID||eE.BUILD_NUMBER||eE.CI||eE.CI_APP_ID||eE.CI_BUILD_ID||eE.CI_BUILD_NUMBER||eE.CI_NAME||eE.CONTINUOUS_INTEGRATION||eE.RUN_ID||ng.name||!1));function a0A(A){if(typeof A==="string")return!!eE[A];if("env"in A)return eE[A.env]&&eE[A.env].includes(A.includes);if("any"in A)return A.any.some(function(Q){return!!eE[Q]});return Object.keys(A).every(function(Q){return eE[Q]===A[Q]})}function khA(A){switch(typeof A.pr){case"string":return!!eE[A.pr];case"object":if("env"in A.pr)if("any"in A.pr)return A.pr.any.some(function(Q){return eE[A.pr.env]===Q});else return A.pr.env in eE&&eE[A.pr.env]!==A.pr.ne;else if("any"in A.pr)return A.pr.any.some(function(Q){return!!eE[Q]});else return a0A(A.pr);default:return null}}});import{homedir as e0A,platform as xhA,release as ghA}from"node:os";import{arch as bhA,cwd as AIA,env as h5,version as yhA}from"node:process";function tW(A){return A==="1"||A?.toLowerCase()==="true"||A?.toLowerCase()==="yes"}function mhA(){if(tW(h5.CAPGO_DISABLE_TELEMETRY)||tW(h5.CAPGO_DISABLE_POSTHOG))return;return h5.CAPGO_CLI_POSTHOG_API_KEY?.trim()||h5.POSTHOG_API_KEY?.trim()||hhA}function chA(A){let Q=A.replace(/\/+$/,"");if(Q.endsWith("/i/v0/e"))return`${Q}/`;let B=Q.replace(/\/capture$/,"/");return new URL("i/v0/e/",B.endsWith("/")?B:`${B}/`).toString()}function lhA(A){if(A instanceof Error)return{cause:A.cause,message:A.message,name:A.name||"Error",stack:A.stack};if(typeof A==="string")return{message:A,name:"Error",stack:void 0};try{return{message:JSON.stringify(A)??String(A),name:"Error",stack:void 0}}catch{return{message:String(A),name:"Error",stack:void 0}}}function dhA(A){let Q=A,B=AIA(),I=e0A();if(B)Q=Q.replaceAll(B,"<cwd>");if(I)Q=Q.replaceAll(I,"~");return Q}function phA(A){let Q=A,B=AIA(),I=e0A();if(B)Q=Q.replaceAll(B,"<cwd>");if(I)Q=Q.replaceAll(I,"~");return Q.replace(/<cwd>\/[^\s"',)]+/g,"<cwd>/<path>").replace(/~\/[^\s"',)]+/g,"~/<path>").replace(/[\w.%+-]+@[\w.-]+\.[A-Z]{2,}/gi,"<email>").replace(/(https?:\/\/)([^/\s:@]+):([^/\s@]+)@/gi,"$1<redacted>@").replace(/\b[a-z][\w-]*(?:\.[\w-]+){2,}\b/gi,"<app_id>").replace(/\b[a-z]:\\[^\s"',)]+/gi,"<path>").replace(/(^|[\s"'(])\/[^\s"',)]+/g,"$1<path>").replace(/(--(?:token|api[-_]?key|key|password|secret|private[-_]?key|jwt|session|auth)(?:=|\s+))("[^"]+"|'[^']+'|\S+)/gi,"$1<redacted>").replace(/\b((?:token|api[-_]?key|password|secret|authorization)\s*[:=]\s*)[^\s,;]+/gi,"$1<redacted>")}function nhA(A,Q){let B=A?.split(`
94
+ `)}),this}_outputHelpIfRequested(A){let Q=this._getHelpOption();if(Q&&A.find((I)=>Q.is(I)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function u0A(A){return A.map((Q)=>{if(!Q.startsWith("--inspect"))return Q;let B,I="127.0.0.1",E="9229",D;if((D=Q.match(/^(--inspect(-brk)?)$/))!==null)B=D[1];else if((D=Q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(B=D[1],/^\d+$/.test(D[3]))E=D[3];else I=D[3];else if((D=Q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)B=D[1],I=D[3],E=D[4];if(B&&E!=="0")return`${B}=${I}:${parseInt(E)+1}`;return Q})}function lg(){if(a0.env.NO_COLOR||a0.env.FORCE_COLOR==="0"||a0.env.FORCE_COLOR==="false")return!1;if(a0.env.FORCE_COLOR||a0.env.CLICOLOR_FORCE!==void 0)return!0;return}HhA.Command=dg;HhA.useColor=lg});var p0A=x((KhA)=>{var{Argument:c0A}=M2(),{Command:pg}=m0A(),{CommanderError:FhA,InvalidArgumentError:l0A}=aW(),{Help:WhA}=hg(),{Option:d0A}=ug();KhA.program=new pg;KhA.createCommand=(A)=>new pg(A);KhA.createOption=(A,Q)=>new d0A(A,Q);KhA.createArgument=(A,Q)=>new c0A(A,Q);KhA.Command=pg;KhA.Option=d0A;KhA.Argument=c0A;KhA.Help=WhA;KhA.CommanderError=FhA;KhA.InvalidArgumentError=l0A;KhA.InvalidOptionArgumentError=l0A});var fE;var YJ=PA(()=>{fE={name:"@capgo/cli",type:"module",version:"7.120.0",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/capgo/tree/main/cli#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/capgo.git",directory:"cli"},bugs:{url:"https://github.com/Cap-go/capgo/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"bunx --bun supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsgo --project tsconfig.tsgo.json --noEmit",lint:"bun run lint:ox","lint:ox":"oxlint --config ../.oxlintrc.json src","lint:fix":"oxlint --config ../.oxlintrc.json --fix src","check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:android-service-account-validation":"bun test/test-android-service-account-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:build-needed":"bun test/test-build-needed.mjs","test:ci-prompts":"bun test/test-ci-prompts.mjs","test:ci-secrets":"bun test/test-ci-secrets.mjs","test:android-onboarding-progress":"bun test/test-android-onboarding-progress.mjs","test:onboarding-telemetry":"bun test/test-onboarding-telemetry.mjs","test:v2-event-migration":"bun test/test-v2-event-migration.mjs","test:analytics":"bun test/test-analytics.mjs","test:analytics-error-category":"bun test/test-analytics-error-category.mjs","test:analytics-org-resolver":"bun test/test-analytics-org-resolver.mjs","test:supabase-perf":"bun test/test-supabase-perf.mjs","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:onboarding-recovery":"bun test/test-onboarding-recovery.mjs","test:onboarding-progress":"bun test/test-onboarding-progress.mjs","test:onboarding-run-targets":"bun test/test-onboarding-run-targets.mjs","test:run-device-command":"bun test/test-run-device-command.mjs","test:init-app-conflict":"bun test/test-init-app-conflict.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs",test:"bun run build && bun run test:version-detection:setup && bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:android-service-account-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:build-needed && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:mcp-analytics && bun run test:app-created-source && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:build-platform-selection && bun run test:onboarding-recovery && bun run test:onboarding-progress && bun run test:onboarding-run-targets && bun run test:run-device-command && bun run test:init-app-conflict && bun run test:init-guardrails && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:apple-api-import-helpers && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:ai-render-markdown","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^7.0.4","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.6"},devDependencies:{"@antfu/eslint-config":"^9.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.3.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.4.0","@modelcontextprotocol/sdk":"^1.29.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.106.2","@tanstack/intent":"^0.0.41","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.9.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.15","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260526.1","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.17","ci-info":"^4.4.0",commander:"^14.0.3",eslint:"^10.4.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.67.0",partysocket:"^1.1.19",prettyjson:"^1.2.5",tmp:"^0.2.6","tus-js-client":"^4.3.1",typescript:"^6.0.3",ws:"^8.21.0",zod:"^4.4.3"}}});function jhA(A){if(A&&typeof A==="object"&&"status"in A){let Q=A.status;if(typeof Q==="number")return Q}return}function PhA(A){if(A instanceof Error)return A.message;if(typeof A==="string")return A;return""}function sW(A){if(A&&typeof A==="object"&&"code"in A){let I=A.code;if(typeof I==="string"&&I.startsWith("commander."))return"commander"}let Q=jhA(A);if(Q!==void 0){if(Q===401)return"unauthorized";if(Q===403)return"forbidden";if(Q===404)return"not_found";if(Q===413)return"payload_too_large";if(Q>=500)return"server_error"}let B=PhA(A).toLowerCase();if(/econnrefused|enotfound|fetch failed|network|socket|dns/.test(B))return"network_error";if(/timed out|timeout|etimedout|aborted/.test(B))return"timeout";if(/invalid|must be|required|not allowed|malformed|validation/.test(B))return"validation_error";return"unknown"}function i0A(A){if(A===401)return"unauthorized";if(A===403)return"forbidden";if(A===404)return"not_found";if(A===408||A===504)return"timeout";if(A===413)return"payload_too_large";if(A===429)return"rate_limited";if(A===400||A===422)return"validation_error";if(A>=500)return"server_error";return"unknown"}var r0A=x((PhQ,_hA)=>{_hA.exports=[{name:"Agola CI",constant:"AGOLA",env:"AGOLA_GIT_REF",pr:"AGOLA_PULL_REQUEST_ID"},{name:"Alpic",constant:"ALPIC",env:"ALPIC_HOST"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE",pr:{env:"AC_GIT_PR",ne:"false"}},{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN",pr:{env:"CODEBUILD_WEBHOOK_EVENT",any:["PULL_REQUEST_CREATED","PULL_REQUEST_UPDATED","PULL_REQUEST_REOPENED"]}},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"TF_BUILD",pr:{BUILD_REASON:"PullRequest"}},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"Cloudflare Pages",constant:"CLOUDFLARE_PAGES",env:"CF_PAGES"},{name:"Cloudflare Workers",constant:"CLOUDFLARE_WORKERS",env:"WORKERS_CI"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codemagic",constant:"CODEMAGIC",env:"CM_BUILD_ID",pr:"CM_PULL_REQUEST"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"Earthly",constant:"EARTHLY",env:"EARTHLY_CI"},{name:"Expo Application Services",constant:"EAS",env:"EAS_BUILD"},{name:"Gerrit",constant:"GERRIT",env:"GERRIT_PROJECT"},{name:"Gitea Actions",constant:"GITEA_ACTIONS",env:"GITEA_ACTIONS"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Google Cloud Build",constant:"GOOGLE_CLOUD_BUILD",env:"BUILDER_OUTPUT"},{name:"Harness CI",constant:"HARNESS",env:"HARNESS_BUILD_ID"},{name:"Heroku",constant:"HEROKU",env:{env:"NODE",includes:"/app/.heroku/node/bin/node"}},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Prow",constant:"PROW",env:"PROW_JOB_ID"},{name:"ReleaseHub",constant:"RELEASEHUB",env:"RELEASE_BUILD_ID"},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Sourcehut",constant:"SOURCEHUT",env:{CI_NAME:"sourcehut"}},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vela",constant:"VELA",env:"VELA",pr:{VELA_PULL_REQUEST:"1"}},{name:"Vercel",constant:"VERCEL",env:{any:["NOW_BUILDER","VERCEL"]},pr:"VERCEL_GIT_PULL_REQUEST_ID"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"},{name:"Woodpecker",constant:"WOODPECKER",env:{CI:"woodpecker"},pr:{CI_BUILD_EVENT:"pull_request"}},{name:"Xcode Cloud",constant:"XCODE_CLOUD",env:"CI_XCODE_PROJECT",pr:"CI_PULL_REQUEST_NUMBER"},{name:"Xcode Server",constant:"XCODE_SERVER",env:"XCS"}]});var rg=x((ng)=>{var o0A=r0A(),eE=process.env;Object.defineProperty(ng,"_vendors",{value:o0A.map(function(A){return A.constant})});ng.name=null;ng.isPR=null;ng.id=null;if(eE.CI!=="false")o0A.forEach(function(A){let B=(Array.isArray(A.env)?A.env:[A.env]).every(function(I){return a0A(I)});if(ng[A.constant]=B,!B)return;ng.name=A.name,ng.isPR=khA(A),ng.id=A.constant});ng.isCI=!!(eE.CI!=="false"&&(eE.BUILD_ID||eE.BUILD_NUMBER||eE.CI||eE.CI_APP_ID||eE.CI_BUILD_ID||eE.CI_BUILD_NUMBER||eE.CI_NAME||eE.CONTINUOUS_INTEGRATION||eE.RUN_ID||ng.name||!1));function a0A(A){if(typeof A==="string")return!!eE[A];if("env"in A)return eE[A.env]&&eE[A.env].includes(A.includes);if("any"in A)return A.any.some(function(Q){return!!eE[Q]});return Object.keys(A).every(function(Q){return eE[Q]===A[Q]})}function khA(A){switch(typeof A.pr){case"string":return!!eE[A.pr];case"object":if("env"in A.pr)if("any"in A.pr)return A.pr.any.some(function(Q){return eE[A.pr.env]===Q});else return A.pr.env in eE&&eE[A.pr.env]!==A.pr.ne;else if("any"in A.pr)return A.pr.any.some(function(Q){return!!eE[Q]});else return a0A(A.pr);default:return null}}});import{homedir as e0A,platform as xhA,release as ghA}from"node:os";import{arch as bhA,cwd as AIA,env as h5,version as yhA}from"node:process";function tW(A){return A==="1"||A?.toLowerCase()==="true"||A?.toLowerCase()==="yes"}function mhA(){if(tW(h5.CAPGO_DISABLE_TELEMETRY)||tW(h5.CAPGO_DISABLE_POSTHOG))return;return h5.CAPGO_CLI_POSTHOG_API_KEY?.trim()||h5.POSTHOG_API_KEY?.trim()||hhA}function chA(A){let Q=A.replace(/\/+$/,"");if(Q.endsWith("/i/v0/e"))return`${Q}/`;let B=Q.replace(/\/capture$/,"/");return new URL("i/v0/e/",B.endsWith("/")?B:`${B}/`).toString()}function lhA(A){if(A instanceof Error)return{cause:A.cause,message:A.message,name:A.name||"Error",stack:A.stack};if(typeof A==="string")return{message:A,name:"Error",stack:void 0};try{return{message:JSON.stringify(A)??String(A),name:"Error",stack:void 0}}catch{return{message:String(A),name:"Error",stack:void 0}}}function dhA(A){let Q=A,B=AIA(),I=e0A();if(B)Q=Q.replaceAll(B,"<cwd>");if(I)Q=Q.replaceAll(I,"~");return Q}function phA(A){let Q=A,B=AIA(),I=e0A();if(B)Q=Q.replaceAll(B,"<cwd>");if(I)Q=Q.replaceAll(I,"~");return Q.replace(/<cwd>\/[^\s"',)]+/g,"<cwd>/<path>").replace(/~\/[^\s"',)]+/g,"~/<path>").replace(/[\w.%+-]+@[\w.-]+\.[A-Z]{2,}/gi,"<email>").replace(/(https?:\/\/)([^/\s:@]+):([^/\s@]+)@/gi,"$1<redacted>@").replace(/\b[a-z][\w-]*(?:\.[\w-]+){2,}\b/gi,"<app_id>").replace(/\b[a-z]:\\[^\s"',)]+/gi,"<path>").replace(/(^|[\s"'(])\/[^\s"',)]+/g,"$1<path>").replace(/(--(?:token|api[-_]?key|key|password|secret|private[-_]?key|jwt|session|auth)(?:=|\s+))("[^"]+"|'[^']+'|\S+)/gi,"$1<redacted>").replace(/\b((?:token|api[-_]?key|password|secret|authorization)\s*[:=]\s*)[^\s,;]+/gi,"$1<redacted>")}function nhA(A,Q){let B=A?.split(`
95
95
  `).slice(1).map((I)=>{let E=I.trim(),D=E.startsWith("at ")?E.slice(3):E,$=Q,G=D,Y=D.lastIndexOf(" (");if(Y!==-1&&D.endsWith(")"))$=D.slice(0,Y).trim()||Q,G=D.slice(Y+2,-1);else{let F=D.lastIndexOf(" "),W=F===-1?"":D.slice(F+1);if(/:\d+:\d+$/.test(W))$=D.slice(0,F).trim()||Q,G=W}let H=G.lastIndexOf(":"),X=H===-1?-1:G.lastIndexOf(":",H-1);if(H===-1||X===-1)return{function:Q,platform:"custom",lang:"javascript"};return{function:$,filename:dhA(G.slice(0,X)),lineno:Number.parseInt(G.slice(X+1,H),10),colno:Number.parseInt(G.slice(H+1),10),platform:"custom",lang:"javascript"}}).filter(Boolean);return B&&B.length>0?B:[{function:Q,platform:"custom",lang:"javascript"}]}function ihA(A){if(!A||typeof A!=="object"||!("code"in A))return;let{code:Q}=A;return typeof Q==="string"?Q:void 0}function QIA(A){return!ihA(A)?.startsWith("commander.")}function og(A){let Q=[],B=A;while(B?.parent){let I=B.name();if(I)Q.push(I);B=B.parent}return Q.reverse().join(" ")||"unknown"}async function ag(A){let Q=mhA();if(!Q)return!1;let B=h5.CAPGO_CLI_POSTHOG_API_HOST?.trim()||h5.POSTHOG_API_HOST?.trim()||fhA,I;try{I=chA(B)}catch{return!1}let E=lhA(A.error),D=phA(E.message),$=`cli:${fE.version}:${A.functionName}`,G=nhA(E.stack,A.functionName),Y=G[0],H=[$,A.kind,E.name||"Error",Y?.function||A.functionName,Y&&"filename"in Y?Y.filename:"unknown",String(A.status??1)].join(":"),X={token:Q,event:"$exception",properties:{distinct_id:$,$exception_list:[{type:E.name||"Error",value:D,mechanism:{handled:!0,synthetic:!1},stacktrace:{type:"raw",frames:G}}],$exception_fingerprint:H,architecture:bhA,cli_version:fE.version,error_kind:A.kind,function_name:A.functionName,is_ci:Boolean(h5.CI),node_version:yhA,os_platform:xhA(),os_release:ghA(),runtime:"cli",status:A.status},timestamp:new Date().toISOString()};try{let F=new AbortController,W=setTimeout(()=>F.abort(),uhA);try{return(await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:F.signal})).ok}finally{clearTimeout(W)}}catch{return!1}}var fhA="https://eu.i.posthog.com/i/v0/e/",hhA="phc_NXDyDajQaTQVwb25DEhIVZfxVUn4R0Y348Z7vWYHZUi",uhA=1500;var sg=PA(()=>{YJ()});import{existsSync as l4}from"fs";var eW=(A=".",Q="unknown")=>{let B=`${A}/bun.lockb`,I=`${A}/bun.lock`,E=`${A}/pnpm-lock.yaml`,D=`${A}/shrinkwrap.yaml`,$=`${A}/yarn.lock`,G=`${A}/package-lock.json`,Y=`${A}/npm-shrinkwrap.json`;if(l4(B)||l4(I))return"bun";if(l4(E)||l4(D))return"pnpm";if(l4($))return"yarn";if(l4(G)||l4(Y))return"npm";return Q},z2=(A=eW(),Q=!1)=>{switch(A){case"bun":return Q?"bun install":"install";case"pnpm":return Q?"pnpm install":"install";case"yarn":return Q?"yarn install":"install";case"npm":return Q?"npm install":"install";case"unknown":return Q?"unknown unknown":"unknown";default:return Q?"npm install":"install"}},BIA=(A=".",Q="npx")=>{let B=`${A}/bun.lockb`,I=`${A}/bun.lock`,E=`${A}/pnpm-lock.yaml`,D=`${A}/shrinkwrap.yaml`,$=`${A}/yarn.lock`,G=`${A}/package-lock.json`,Y=`${A}/npm-shrinkwrap.json`;if(l4(B)||l4(I))return"bunx";if(l4(E)||l4(D))return"pnpm exec";if(l4($))return"yarn dlx";if(l4(G)||l4(Y))return"npx";return Q};var IIA=()=>{};function L2(A,Q){if(isNaN(A)||isNaN(Q))throw Error("Cannot compare against non-numbers");return A===Q?0:A<Q?-1:1}function $IA(A=[],Q=[]){if(A.length&&!Q.length)return-1;if(!A.length&&Q.length)return 1;return 0}function O2(A=[],Q=[]){let B=Math.max(A.length,Q.length);for(let I=0;I<B;I++){let E=A[I],D=Q[I];if(E===void 0&&D===void 0)return 0;if(D===void 0)return 1;if(E===void 0)return-1;if(typeof E==="string"&&typeof D==="number")return 1;if(typeof E==="number"&&typeof D==="string")return-1;if(E<D)return-1;if(E>D)return 1}return 0}function eg(A){return typeof A==="number"&&!Number.isNaN(A)&&(!Number.isFinite(A)||0<=A&&A<=Number.MAX_SAFE_INTEGER)}function d4(A){return A.split(".").filter(Boolean).map((Q)=>{if(shA.test(Q)){let B=Number(Q);if(eg(B))return B}return Q})}function d6(A){return A.split(".").filter(Boolean)}function V2(A,Q){let B=Number(A);if(!eg(B))throw TypeError(Q);return B}function UJ(A){return Number.isNaN(A.major)&&Number.isNaN(A.minor)&&Number.isNaN(A.patch)&&(A.prerelease===void 0||A.prerelease.length===0)&&(A.build===void 0||A.build.length===0)}var kX="0|[1-9]\\d*",rhA="\\d*[a-zA-Z-][a-zA-Z0-9-]*",ohA,EIA,GIA,DIA="[0-9A-Za-z-]+",JIA,YIA,UIA,HIA="(?:<|>)?=?",ahA="x|X|\\*",tg,R2,XIA,CIA,Ab=256,shA;var RD=PA(()=>{ohA=`(?<major>${kX})\\.(?<minor>${kX})\\.(?<patch>${kX})`,EIA=`(?:${kX}|${rhA})`,GIA=`(?:-(?<prerelease>${EIA}(?:\\.${EIA})*))`,JIA=`(?:\\+(?<buildmetadata>${DIA}(?:\\.${DIA})*))`,YIA=`v?${ohA}${GIA}?${JIA}?`,UIA=new RegExp(`^${YIA}$`),tg=`${kX}|${ahA}`,R2=`[v=\\s]*(?<major>${tg})(?:\\.(?<minor>${tg})(?:\\.(?<patch>${tg})${GIA}?${JIA}?)?)?`,XIA=new RegExp(`^(?<operator>~>?|\\^|${HIA})\\s*${R2}$`),CIA=new RegExp(`^(?<operator>${HIA})\\s*(${YIA})$|^$`);shA=new RegExp(`^${kX}$`)});function X4(A,Q){if(A===Q)return 0;return L2(A.major,Q.major)||L2(A.minor,Q.minor)||L2(A.patch,Q.patch)||$IA(A.prerelease,Q.prerelease)||O2(A.prerelease,Q.prerelease)}var sD=PA(()=>{RD()});function FIA(A,Q){let B=A.prerelease?.length||Q.prerelease?.length;if(A.major!==Q.major)return B?"premajor":"major";if(A.minor!==Q.minor)return B?"preminor":"minor";if(A.patch!==Q.patch)return B?"prepatch":"patch";if(O2(A.prerelease,Q.prerelease)!==0)return"prerelease"}var WIA=PA(()=>{RD()});function Qb(A){return A.toFixed(0)}function U8(A){let Q=Qb(A.major),B=Qb(A.minor),I=Qb(A.patch),E=A.prerelease?.join(".")??"",D=A.build?.join(".")??"";return[[`${Q}.${B}.${I}`,E].filter((Y)=>Y).join("-"),D].filter((Y)=>Y).join("+")}function thA(A,Q){if(UJ(Q))return!0;let B=X4(A,Q);switch(Q.operator){case"=":case void 0:return B===0;case"!=":return B!==0;case">":return B>0;case"<":return B<0;case">=":return B>=0;case"<=":return B<=0}}function T2(A,Q){for(let B of Q)if(!thA(A,B))return!1;if(!A.prerelease?.length)return!0;for(let B of Q){if(UJ(B))continue;if(!B.prerelease?.length)continue;let{major:I,minor:E,patch:D}=B;if(A.major===I&&A.minor===E&&A.patch===D)return!0}return!1}var S2=PA(()=>{RD();sD()});function AK(A,Q){return Q.some((B)=>T2(A,B))}var QK=PA(()=>{S2()});function ehA(A=[]){let Q=[...A],B=Q.length;while(B>=0){let I=Q[B];if(typeof I==="number"){Q[B]=I+1;break}B-=1}if(B===-1)Q.push(0);return Q}function BK(A=[],Q){let B=ehA(A);if(!Q)return B;let I=d4(Q);if(I.every((E)=>typeof E==="string")){if(I.every((E,D)=>E===B[D])&&typeof B[I.length]==="number")return B;I=[...I,0]}return I}function S9(A,Q,B={}){let I=B.build!==void 0?d6(B.build):A.build??[];switch(Q){case"premajor":return{major:A.major+1,minor:0,patch:0,prerelease:BK(A.prerelease,B.prerelease),build:I};case"preminor":return{major:A.major,minor:A.minor+1,patch:0,prerelease:BK(A.prerelease,B.prerelease),build:I};case"prepatch":return{major:A.major,minor:A.minor,patch:A.patch+1,prerelease:BK(A.prerelease,B.prerelease),build:I};case"prerelease":{let D=(A.prerelease??[]).length===0?A.patch+1:A.patch;return{major:A.major,minor:A.minor,patch:D,prerelease:BK(A.prerelease,B.prerelease),build:I}}case"major":return{major:(A.prerelease??[]).length===0||A.minor!==0||A.patch!==0?A.major+1:A.major,minor:0,patch:0,prerelease:[],build:I};case"minor":{let D=(A.prerelease??[]).length===0||A.patch!==0?A.minor+1:A.minor;return{major:A.major,minor:D,patch:0,prerelease:[],build:I}}case"patch":{let D=(A.prerelease??[]).length===0?A.patch+1:A.patch;return{major:A.major,minor:A.minor,patch:D,prerelease:[],build:I}}case"pre":return{major:A.major,minor:A.minor,patch:A.patch,prerelease:BK(A.prerelease,B.prerelease),build:I};default:throw TypeError(`Cannot increment version: invalid argument ${Q}`)}}var KIA=PA(()=>{RD()});var j2,vX;var IK=PA(()=>{j2={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},vX={operator:void 0,...j2}});var Bb=PA(()=>{IK();RD()});function Ib(A,Q){return X4(A,Q)>0}var Eb=PA(()=>{sD()});var qIA=PA(()=>{QK();Eb()});function VD(A,Q){return X4(A,Q)<0}var Db=PA(()=>{sD()});var ZIA=PA(()=>{QK();Db()});function AuA(A){let B=A.match(CIA)?.groups;if(!B)return null;let{operator:I}=B;return{operator:I||void 0,...j2}}function mI(A){return!A||A.toLowerCase()==="x"||A==="*"}function QuA(A){if(mI(A.major))return;if(mI(A.minor))return{operator:">=",major:+A.major,minor:0,patch:0,prerelease:[],build:[]};if(mI(A.patch))return{operator:">=",major:+A.major,minor:+A.minor,patch:0,prerelease:[],build:[]};return{operator:">=",major:+A.major,minor:+A.minor,patch:+A.patch,prerelease:A.prerelease?d4(A.prerelease):[],build:[]}}function BuA(A){if(mI(A.major))return;if(mI(A.minor))return{operator:"<",major:+A.major+1,minor:0,patch:0,prerelease:[],build:[]};if(mI(A.patch))return{operator:"<",major:+A.major,minor:+A.minor+1,patch:0,prerelease:[],build:[]};if(A.prerelease)return{operator:"<=",major:+A.major,minor:+A.minor,patch:+A.patch,prerelease:d4(A.prerelease),build:[]};return{operator:"<=",major:+A.major,minor:+A.minor,patch:+A.patch,prerelease:[],build:[]}}function IuA(A){let Q=A.match(new RegExp(`^${R2}`)),B=Q?.groups;if(!B)return null;let I=Q[0].length,E=A.slice(I).match(/^\s+-\s+/);if(!E)return null;let D=E[0].length,G=A.slice(I+D).match(new RegExp(`^${R2}\\s*$`))?.groups,Y=QuA(B),H=BuA(G);return[Y,H].filter(Boolean)}function EuA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[vX];if(B)return[{operator:">=",major:E,minor:0,patch:0},{operator:"<",major:E+1,minor:0,patch:0}];if(I){if(E===0)return[{operator:">=",major:E,minor:D,patch:0},{operator:"<",major:E,minor:D+1,patch:0}];return[{operator:">=",major:E,minor:D,patch:0},{operator:"<",major:E+1,minor:0,patch:0}]}let G=d4(A.prerelease??"");if(E===0){if(D===0)return[{operator:">=",major:E,minor:D,patch:$,prerelease:G},{operator:"<",major:E,minor:D,patch:$+1}];return[{operator:">=",major:E,minor:D,patch:$,prerelease:G},{operator:"<",major:E,minor:D+1,patch:0}]}return[{operator:">=",major:E,minor:D,patch:$,prerelease:G},{operator:"<",major:E+1,minor:0,patch:0}]}function DuA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[vX];if(B)return[{operator:">=",major:E,minor:0,patch:0},{operator:"<",major:E+1,minor:0,patch:0}];if(I)return[{operator:">=",major:E,minor:D,patch:0},{operator:"<",major:E,minor:D+1,patch:0}];let G=d4(A.prerelease??"");return[{operator:">=",major:E,minor:D,patch:$,prerelease:G},{operator:"<",major:E,minor:D+1,patch:0}]}function $uA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[{operator:"<",major:0,minor:0,patch:0}];if(B){if(I)return[{operator:"<",major:E,minor:0,patch:0}];return[{operator:"<",major:E,minor:0,patch:0}]}if(I)return[{operator:"<",major:E,minor:D,patch:0}];let G=d4(A.prerelease??""),Y=d6(A.build??"");return[{operator:"<",major:E,minor:D,patch:$,prerelease:G,build:Y}]}function GuA(A){let Q=mI(A.minor),B=mI(A.patch),I=+A.major,E=+A.minor,D=+A.patch;if(Q)return[{operator:"<",major:I+1,minor:0,patch:0}];if(B)return[{operator:"<",major:I,minor:E+1,patch:0}];let $=d4(A.prerelease??""),G=d6(A.build??"");return[{operator:"<=",major:I,minor:E,patch:D,prerelease:$,build:G}]}function JuA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[{operator:"<",major:0,minor:0,patch:0}];if(B)return[{operator:">=",major:E+1,minor:0,patch:0}];if(I)return[{operator:">=",major:E,minor:D+1,patch:0}];let G=d4(A.prerelease??""),Y=d6(A.build??"");return[{operator:">",major:E,minor:D,patch:$,prerelease:G,build:Y}]}function YuA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[vX];if(B)return[{operator:">=",major:E,minor:0,patch:0}];if(I)return[{operator:">=",major:E,minor:D,patch:0}];let G=d4(A.prerelease??""),Y=d6(A.build??"");return[{operator:">=",major:E,minor:D,patch:$,prerelease:G,build:Y}]}function UuA(A){let Q=mI(A.major),B=mI(A.minor),I=mI(A.patch),E=+A.major,D=+A.minor,$=+A.patch;if(Q)return[vX];if(B)return[{operator:">=",major:E,minor:0,patch:0},{operator:"<",major:E+1,minor:0,patch:0}];if(I)return[{operator:">=",major:E,minor:D,patch:0},{operator:"<",major:E,minor:D+1,patch:0}];let G=d4(A.prerelease??""),Y=d6(A.build??"");return[{operator:A.operator==="="?"=":void 0,major:E,minor:D,patch:$,prerelease:G,build:Y}]}function HuA(A){let Q=A.match(XIA)?.groups;if(!Q)return AuA(A);switch(Q.operator){case"^":return EuA(Q);case"~":case"~>":return DuA(Q);case"<":return $uA(Q);case"<=":return GuA(Q);case">":return JuA(Q);case">=":return YuA(Q);default:return UuA(Q)}}function XuA(A){return A.split(/\s+/).flatMap(HuA)}function P2(A){let Q=A.replaceAll(/(?<=[<>=~^])(\s+)/g,"").split(/\s*\|\|\s*/).map((B)=>IuA(B)||XuA(B));if(Q.some((B)=>B.includes(null)))throw TypeError(`Cannot parse version range: range "${A}" is invalid`);return Q}var $b=PA(()=>{RD();IK()});function hB(A){if(typeof A!=="string")throw TypeError(`Cannot parse version as version must be a string: received ${typeof A}`);if(A.length>Ab)throw TypeError(`Cannot parse version as version length is too long: length is ${A.length}, max length is ${Ab}`);A=A.trim();let Q=A.match(UIA)?.groups;if(!Q)throw TypeError(`Cannot parse version: ${A}`);let B=V2(Q.major,`Cannot parse version ${A}: invalid major version`),I=V2(Q.minor,`Cannot parse version ${A}: invalid minor version`),E=V2(Q.patch,`Cannot parse version ${A}: invalid patch version`),D=Q.prerelease?d4(Q.prerelease):[],$=Q.buildmetadata?d6(Q.buildmetadata):[];return{major:B,minor:I,patch:E,prerelease:D,build:$}}var _2=PA(()=>{RD();RD()});function MIA(A,Q){let B=A.operator,I=Q.operator;if(B===void 0){if(UJ(A))return!0;return AK(A,[[Q]])}if(I===void 0){if(UJ(Q))return!0;return AK(Q,[[A]])}let E=X4(A,Q);return(B===">="||B===">")&&(I===">="||I===">")||(B==="<="||B==="<")&&(I==="<="||I==="<")||E===0&&((B===">="||B==="<=")&&(I===">="||I==="<="))||E===-1&&(B===">="||B===">")&&(I==="<="||I==="<")||E===1&&(B==="<="||B==="<")&&(I===">="||I===">")}function CuA(A){return A.every((Q)=>{return Q.some((B)=>FuA(B))})}function FuA(A){for(let Q=0;Q<A.length-1;Q++){let B=A[Q];for(let I of A.slice(Q+1))if(!MIA(B,I))return!1}return!0}function NIA(A,Q){return CuA([A,Q])&&A.some((B)=>{return Q.some((I)=>{return B.every((E)=>{return I.every((D)=>MIA(E,D))})})})}var wIA=PA(()=>{RD();sD();QK()});var zIA=PA(()=>{$b()});var LIA=PA(()=>{IK();IK();Bb()});function EK(A){try{return hB(A),!0}catch{return!1}}var OIA=PA(()=>{_2()});var RIA=PA(()=>{_2()});var VIA=PA(()=>{RD()});var TIA=PA(()=>{sD()});var SIA=PA(()=>{sD()});var jIA=PA(()=>{S2();RD();sD()});function PIA(A,Q){return X4(A,Q)>=0}var _IA=PA(()=>{sD()});var kIA=PA(()=>{S2();RD();sD()});var vIA=PA(()=>{sD()});var c$=PA(()=>{sD();WIA();QK();KIA();Bb();qIA();ZIA();$b();_2();wIA();zIA();LIA();OIA();RIA();VIA();TIA();SIA();Eb();jIA();_IA();Db();kIA();vIA()});var p4=x((RmQ,x2)=>{var xIA,gIA,bIA,yIA,fIA,hIA,uIA,mIA,cIA,lIA,dIA,pIA,nIA,k2,Gb,iIA,rIA,oIA,xX,aIA,sIA,tIA,eIA,AEA,QEA,BEA,IEA,EEA,v2,DEA,$EA,GEA;(function(A){var Q=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(I){A(B(Q,B(I)))});else if(typeof x2==="object"&&typeof RmQ==="object")A(B(Q,B(RmQ)));else A(B(Q));function B(I,E){if(I!==Q)if(typeof Object.create==="function")Object.defineProperty(I,"__esModule",{value:!0});else I.__esModule=!0;return function(D,$){return I[D]=E?E(D,$):$}}})(function(A){var Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(D,$){D.__proto__=$}||function(D,$){for(var G in $)if(Object.prototype.hasOwnProperty.call($,G))D[G]=$[G]};xIA=function(D,$){if(typeof $!=="function"&&$!==null)throw TypeError("Class extends value "+String($)+" is not a constructor or null");Q(D,$);function G(){this.constructor=D}D.prototype=$===null?Object.create($):(G.prototype=$.prototype,new G)},gIA=Object.assign||function(D){for(var $,G=1,Y=arguments.length;G<Y;G++){$=arguments[G];for(var H in $)if(Object.prototype.hasOwnProperty.call($,H))D[H]=$[H]}return D},bIA=function(D,$){var G={};for(var Y in D)if(Object.prototype.hasOwnProperty.call(D,Y)&&$.indexOf(Y)<0)G[Y]=D[Y];if(D!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var H=0,Y=Object.getOwnPropertySymbols(D);H<Y.length;H++)if($.indexOf(Y[H])<0&&Object.prototype.propertyIsEnumerable.call(D,Y[H]))G[Y[H]]=D[Y[H]]}return G},yIA=function(D,$,G,Y){var H=arguments.length,X=H<3?$:Y===null?Y=Object.getOwnPropertyDescriptor($,G):Y,F;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")X=Reflect.decorate(D,$,G,Y);else for(var W=D.length-1;W>=0;W--)if(F=D[W])X=(H<3?F(X):H>3?F($,G,X):F($,G))||X;return H>3&&X&&Object.defineProperty($,G,X),X},fIA=function(D,$){return function(G,Y){$(G,Y,D)}},hIA=function(D,$,G,Y,H,X){function F(c){if(c!==void 0&&typeof c!=="function")throw TypeError("Function expected");return c}var W=Y.kind,q=W==="getter"?"get":W==="setter"?"set":"value",Z=!$&&D?Y.static?D:D.prototype:null,M=$||(Z?Object.getOwnPropertyDescriptor(Z,Y.name):{}),L,O=!1;for(var T=G.length-1;T>=0;T--){var R={};for(var S in Y)R[S]=S==="access"?{}:Y[S];for(var S in Y.access)R.access[S]=Y.access[S];R.addInitializer=function(c){if(O)throw TypeError("Cannot add initializers after decoration has completed");X.push(F(c||null))};var j=(0,G[T])(W==="accessor"?{get:M.get,set:M.set}:M[q],R);if(W==="accessor"){if(j===void 0)continue;if(j===null||typeof j!=="object")throw TypeError("Object expected");if(L=F(j.get))M.get=L;if(L=F(j.set))M.set=L;if(L=F(j.init))H.unshift(L)}else if(L=F(j))if(W==="field")H.unshift(L);else M[q]=L}if(Z)Object.defineProperty(Z,Y.name,M);O=!0},uIA=function(D,$,G){var Y=arguments.length>2;for(var H=0;H<$.length;H++)G=Y?$[H].call(D,G):$[H].call(D);return Y?G:void 0},mIA=function(D){return typeof D==="symbol"?D:"".concat(D)},cIA=function(D,$,G){if(typeof $==="symbol")$=$.description?"[".concat($.description,"]"):"";return Object.defineProperty(D,"name",{configurable:!0,value:G?"".concat(G," ",$):$})},lIA=function(D,$){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(D,$)},dIA=function(D,$,G,Y){function H(X){return X instanceof G?X:new G(function(F){F(X)})}return new(G||(G=Promise))(function(X,F){function W(M){try{Z(Y.next(M))}catch(L){F(L)}}function q(M){try{Z(Y.throw(M))}catch(L){F(L)}}function Z(M){M.done?X(M.value):H(M.value).then(W,q)}Z((Y=Y.apply(D,$||[])).next())})},pIA=function(D,$){var G={label:0,sent:function(){if(X[0]&1)throw X[1];return X[1]},trys:[],ops:[]},Y,H,X,F=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return F.next=W(0),F.throw=W(1),F.return=W(2),typeof Symbol==="function"&&(F[Symbol.iterator]=function(){return this}),F;function W(Z){return function(M){return q([Z,M])}}function q(Z){if(Y)throw TypeError("Generator is already executing.");while(F&&(F=0,Z[0]&&(G=0)),G)try{if(Y=1,H&&(X=Z[0]&2?H.return:Z[0]?H.throw||((X=H.return)&&X.call(H),0):H.next)&&!(X=X.call(H,Z[1])).done)return X;if(H=0,X)Z=[Z[0]&2,X.value];switch(Z[0]){case 0:case 1:X=Z;break;case 4:return G.label++,{value:Z[1],done:!1};case 5:G.label++,H=Z[1],Z=[0];continue;case 7:Z=G.ops.pop(),G.trys.pop();continue;default:if((X=G.trys,!(X=X.length>0&&X[X.length-1]))&&(Z[0]===6||Z[0]===2)){G=0;continue}if(Z[0]===3&&(!X||Z[1]>X[0]&&Z[1]<X[3])){G.label=Z[1];break}if(Z[0]===6&&G.label<X[1]){G.label=X[1],X=Z;break}if(X&&G.label<X[2]){G.label=X[2],G.ops.push(Z);break}if(X[2])G.ops.pop();G.trys.pop();continue}Z=$.call(D,G)}catch(M){Z=[6,M],H=0}finally{Y=X=0}if(Z[0]&5)throw Z[1];return{value:Z[0]?Z[1]:void 0,done:!0}}},nIA=function(D,$){for(var G in D)if(G!=="default"&&!Object.prototype.hasOwnProperty.call($,G))v2($,D,G)},v2=Object.create?function(D,$,G,Y){if(Y===void 0)Y=G;var H=Object.getOwnPropertyDescriptor($,G);if(!H||("get"in H?!$.__esModule:H.writable||H.configurable))H={enumerable:!0,get:function(){return $[G]}};Object.defineProperty(D,Y,H)}:function(D,$,G,Y){if(Y===void 0)Y=G;D[Y]=$[G]},k2=function(D){var $=typeof Symbol==="function"&&Symbol.iterator,G=$&&D[$],Y=0;if(G)return G.call(D);if(D&&typeof D.length==="number")return{next:function(){if(D&&Y>=D.length)D=void 0;return{value:D&&D[Y++],done:!D}}};throw TypeError($?"Object is not iterable.":"Symbol.iterator is not defined.")},Gb=function(D,$){var G=typeof Symbol==="function"&&D[Symbol.iterator];if(!G)return D;var Y=G.call(D),H,X=[],F;try{while(($===void 0||$-- >0)&&!(H=Y.next()).done)X.push(H.value)}catch(W){F={error:W}}finally{try{if(H&&!H.done&&(G=Y.return))G.call(Y)}finally{if(F)throw F.error}}return X},iIA=function(){for(var D=[],$=0;$<arguments.length;$++)D=D.concat(Gb(arguments[$]));return D},rIA=function(){for(var D=0,$=0,G=arguments.length;$<G;$++)D+=arguments[$].length;for(var Y=Array(D),H=0,$=0;$<G;$++)for(var X=arguments[$],F=0,W=X.length;F<W;F++,H++)Y[H]=X[F];return Y},oIA=function(D,$,G){if(G||arguments.length===2){for(var Y=0,H=$.length,X;Y<H;Y++)if(X||!(Y in $)){if(!X)X=Array.prototype.slice.call($,0,Y);X[Y]=$[Y]}}return D.concat(X||Array.prototype.slice.call($))},xX=function(D){return this instanceof xX?(this.v=D,this):new xX(D)},aIA=function(D,$,G){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var Y=G.apply(D,$||[]),H,X=[];return H=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),W("next"),W("throw"),W("return",F),H[Symbol.asyncIterator]=function(){return this},H;function F(T){return function(R){return Promise.resolve(R).then(T,L)}}function W(T,R){if(Y[T]){if(H[T]=function(S){return new Promise(function(j,c){X.push([T,S,j,c])>1||q(T,S)})},R)H[T]=R(H[T])}}function q(T,R){try{Z(Y[T](R))}catch(S){O(X[0][3],S)}}function Z(T){T.value instanceof xX?Promise.resolve(T.value.v).then(M,L):O(X[0][2],T)}function M(T){q("next",T)}function L(T){q("throw",T)}function O(T,R){if(T(R),X.shift(),X.length)q(X[0][0],X[0][1])}},sIA=function(D){var $,G;return $={},Y("next"),Y("throw",function(H){throw H}),Y("return"),$[Symbol.iterator]=function(){return this},$;function Y(H,X){$[H]=D[H]?function(F){return(G=!G)?{value:xX(D[H](F)),done:!1}:X?X(F):F}:X}},tIA=function(D){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var $=D[Symbol.asyncIterator],G;return $?$.call(D):(D=typeof k2==="function"?k2(D):D[Symbol.iterator](),G={},Y("next"),Y("throw"),Y("return"),G[Symbol.asyncIterator]=function(){return this},G);function Y(X){G[X]=D[X]&&function(F){return new Promise(function(W,q){F=D[X](F),H(W,q,F.done,F.value)})}}function H(X,F,W,q){Promise.resolve(q).then(function(Z){X({value:Z,done:W})},F)}},eIA=function(D,$){if(Object.defineProperty)Object.defineProperty(D,"raw",{value:$});else D.raw=$;return D};var B=Object.create?function(D,$){Object.defineProperty(D,"default",{enumerable:!0,value:$})}:function(D,$){D.default=$},I=function(D){return I=Object.getOwnPropertyNames||function($){var G=[];for(var Y in $)if(Object.prototype.hasOwnProperty.call($,Y))G[G.length]=Y;return G},I(D)};AEA=function(D){if(D&&D.__esModule)return D;var $={};if(D!=null){for(var G=I(D),Y=0;Y<G.length;Y++)if(G[Y]!=="default")v2($,D,G[Y])}return B($,D),$},QEA=function(D){return D&&D.__esModule?D:{default:D}},BEA=function(D,$,G,Y){if(G==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof $==="function"?D!==$||!Y:!$.has(D))throw TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?Y:G==="a"?Y.call(D):Y?Y.value:$.get(D)},IEA=function(D,$,G,Y,H){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!H)throw TypeError("Private accessor was defined without a setter");if(typeof $==="function"?D!==$||!H:!$.has(D))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?H.call(D,G):H?H.value=G:$.set(D,G),G},EEA=function(D,$){if($===null||typeof $!=="object"&&typeof $!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof D==="function"?$===D:D.has($)},DEA=function(D,$,G){if($!==null&&$!==void 0){if(typeof $!=="object"&&typeof $!=="function")throw TypeError("Object expected.");var Y,H;if(G){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");Y=$[Symbol.asyncDispose]}if(Y===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(Y=$[Symbol.dispose],G)H=Y}if(typeof Y!=="function")throw TypeError("Object not disposable.");if(H)Y=function(){try{H.call(this)}catch(X){return Promise.reject(X)}};D.stack.push({value:$,dispose:Y,async:G})}else if(G)D.stack.push({async:!0});return $};var E=typeof SuppressedError==="function"?SuppressedError:function(D,$,G){var Y=Error(G);return Y.name="SuppressedError",Y.error=D,Y.suppressed=$,Y};$EA=function(D){function $(X){D.error=D.hasError?new E(X,D.error,"An error was suppressed during disposal."):X,D.hasError=!0}var G,Y=0;function H(){while(G=D.stack.pop())try{if(!G.async&&Y===1)return Y=0,D.stack.push(G),Promise.resolve().then(H);if(G.dispose){var X=G.dispose.call(G.value);if(G.async)return Y|=2,Promise.resolve(X).then(H,function(F){return $(F),H()})}else Y|=1}catch(F){$(F)}if(Y===1)return D.hasError?Promise.reject(D.error):Promise.resolve();if(D.hasError)throw D.error}return H()},GEA=function(D,$){if(typeof D==="string"&&/^\.\.?\//.test(D))return D.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(G,Y,H,X,F){return Y?$?".jsx":".js":H&&(!X||!F)?G:H+X+"."+F.toLowerCase()+"js"});return D},A("__extends",xIA),A("__assign",gIA),A("__rest",bIA),A("__decorate",yIA),A("__param",fIA),A("__esDecorate",hIA),A("__runInitializers",uIA),A("__propKey",mIA),A("__setFunctionName",cIA),A("__metadata",lIA),A("__awaiter",dIA),A("__generator",pIA),A("__exportStar",nIA),A("__createBinding",v2),A("__values",k2),A("__read",Gb),A("__spread",iIA),A("__spreadArrays",rIA),A("__spreadArray",oIA),A("__await",xX),A("__asyncGenerator",aIA),A("__asyncDelegator",sIA),A("__asyncValues",tIA),A("__makeTemplateObject",eIA),A("__importStar",AEA),A("__importDefault",QEA),A("__classPrivateFieldGet",BEA),A("__classPrivateFieldSet",IEA),A("__classPrivateFieldIn",EEA),A("__addDisposableResource",DEA),A("__disposeResources",$EA),A("__rewriteRelativeImportExtension",GEA)})});var UEA=x((JEA)=>{Object.defineProperty(JEA,"__esModule",{value:!0});JEA.resolveFetch=void 0;var WuA=(A)=>{if(A)return(...Q)=>A(...Q);return(...Q)=>fetch(...Q)};JEA.resolveFetch=WuA});var Jb=x((WEA)=>{Object.defineProperty(WEA,"__esModule",{value:!0});WEA.FunctionRegion=WEA.FunctionsHttpError=WEA.FunctionsRelayError=WEA.FunctionsFetchError=WEA.FunctionsError=void 0;class DK extends Error{constructor(A,Q="FunctionsError",B){super(A);this.name=Q,this.context=B}toJSON(){return{name:this.name,message:this.message,context:this.context}}}WEA.FunctionsError=DK;class XEA extends DK{constructor(A){super("Failed to send a request to the Edge Function","FunctionsFetchError",A)}}WEA.FunctionsFetchError=XEA;class CEA extends DK{constructor(A){super("Relay Error invoking the Edge Function","FunctionsRelayError",A)}}WEA.FunctionsRelayError=CEA;class FEA extends DK{constructor(A){super("Edge Function returned a non-2xx status code","FunctionsHttpError",A)}}WEA.FunctionsHttpError=FEA;var HEA;(function(A){A.Any="any",A.ApNortheast1="ap-northeast-1",A.ApNortheast2="ap-northeast-2",A.ApSouth1="ap-south-1",A.ApSoutheast1="ap-southeast-1",A.ApSoutheast2="ap-southeast-2",A.CaCentral1="ca-central-1",A.EuCentral1="eu-central-1",A.EuWest1="eu-west-1",A.EuWest2="eu-west-2",A.EuWest3="eu-west-3",A.SaEast1="sa-east-1",A.UsEast1="us-east-1",A.UsWest1="us-west-1",A.UsWest2="us-west-2"})(HEA||(WEA.FunctionRegion=HEA={}))});var NEA=x((ZEA)=>{Object.defineProperty(ZEA,"__esModule",{value:!0});ZEA.FunctionsClient=void 0;var NuA=p4(),wuA=UEA(),gX=Jb();class qEA{constructor(A,{headers:Q={},customFetch:B,region:I=gX.FunctionRegion.Any}={}){this.url=A,this.headers=Q,this.region=I,this.fetch=(0,wuA.resolveFetch)(B)}setAuth(A){this.headers.Authorization=`Bearer ${A}`}invoke(A){return NuA.__awaiter(this,arguments,void 0,function*(Q,B={}){var I;let E,D;try{let{headers:$,method:G,body:Y,signal:H,timeout:X}=B,F={},{region:W}=B;if(!W)W=this.region;let q=new URL(`${this.url}/${Q}`);if(W&&W!=="any")F["x-region"]=W,q.searchParams.set("forceFunctionRegion",W);let Z;if(Y&&($&&!Object.prototype.hasOwnProperty.call($,"Content-Type")||!$))if(typeof Blob<"u"&&Y instanceof Blob||Y instanceof ArrayBuffer)F["Content-Type"]="application/octet-stream",Z=Y;else if(typeof Y==="string")F["Content-Type"]="text/plain",Z=Y;else if(typeof FormData<"u"&&Y instanceof FormData)Z=Y;else F["Content-Type"]="application/json",Z=JSON.stringify(Y);else if(Y&&typeof Y!=="string"&&!(typeof Blob<"u"&&Y instanceof Blob)&&!(Y instanceof ArrayBuffer)&&!(typeof FormData<"u"&&Y instanceof FormData))Z=JSON.stringify(Y);else Z=Y;let M=H;if(X)if(D=new AbortController,E=setTimeout(()=>D.abort(),X),H)M=D.signal,H.addEventListener("abort",()=>D.abort());else M=D.signal;let L=yield this.fetch(q.toString(),{method:G||"POST",headers:Object.assign(Object.assign(Object.assign({},F),this.headers),$),body:Z,signal:M}).catch((S)=>{throw new gX.FunctionsFetchError(S)}),O=L.headers.get("x-relay-error");if(O&&O==="true")throw new gX.FunctionsRelayError(L);if(!L.ok)throw new gX.FunctionsHttpError(L);let T=((I=L.headers.get("Content-Type"))!==null&&I!==void 0?I:"text/plain").split(";")[0].trim(),R;if(T==="application/json")R=yield L.json();else if(T==="application/octet-stream"||T==="application/pdf")R=yield L.blob();else if(T==="text/event-stream")R=L;else if(T==="multipart/form-data")R=yield L.formData();else R=yield L.text();return{data:R,error:null,response:L}}catch($){return{data:null,error:$,response:$ instanceof gX.FunctionsHttpError||$ instanceof gX.FunctionsRelayError?$.context:void 0}}finally{if(E)clearTimeout(E)}})}}ZEA.FunctionsClient=qEA});var wEA=x((j9)=>{Object.defineProperty(j9,"__esModule",{value:!0});j9.FunctionRegion=j9.FunctionsRelayError=j9.FunctionsHttpError=j9.FunctionsFetchError=j9.FunctionsError=j9.FunctionsClient=void 0;var zuA=NEA();Object.defineProperty(j9,"FunctionsClient",{enumerable:!0,get:function(){return zuA.FunctionsClient}});var $K=Jb();Object.defineProperty(j9,"FunctionsError",{enumerable:!0,get:function(){return $K.FunctionsError}});Object.defineProperty(j9,"FunctionsFetchError",{enumerable:!0,get:function(){return $K.FunctionsFetchError}});Object.defineProperty(j9,"FunctionsHttpError",{enumerable:!0,get:function(){return $K.FunctionsHttpError}});Object.defineProperty(j9,"FunctionsRelayError",{enumerable:!0,get:function(){return $K.FunctionsRelayError}});Object.defineProperty(j9,"FunctionRegion",{enumerable:!0,get:function(){return $K.FunctionRegion}})});function LEA(A,Q){return new Promise((B)=>{if(Q===null||Q===void 0?void 0:Q.aborted){B();return}let I=setTimeout(()=>{Q===null||Q===void 0||Q.removeEventListener("abort",E),B()},A);function E(){clearTimeout(I),B()}Q===null||Q===void 0||Q.addEventListener("abort",E)})}function RuA(A,Q,B,I){if(!I||B>=3)return!1;if(!VEA.includes(A))return!1;if(!OuA.includes(Q))return!1;return!0}function GK(A){return GK=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},GK(A)}function juA(A,Q){if(GK(A)!="object"||!A)return A;var B=A[Symbol.toPrimitive];if(B!==void 0){var I=B.call(A,Q||"default");if(GK(I)!="object")return I;throw TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(A)}function PuA(A){var Q=juA(A,"string");return GK(Q)=="symbol"?Q:Q+""}function _uA(A,Q,B){return(Q=PuA(Q))in A?Object.defineProperty(A,Q,{value:B,enumerable:!0,configurable:!0,writable:!0}):A[Q]=B,A}function REA(A,Q){var B=Object.keys(A);if(Object.getOwnPropertySymbols){var I=Object.getOwnPropertySymbols(A);Q&&(I=I.filter(function(E){return Object.getOwnPropertyDescriptor(A,E).enumerable})),B.push.apply(B,I)}return B}function g2(A){for(var Q=1;Q<arguments.length;Q++){var B=arguments[Q]!=null?arguments[Q]:{};Q%2?REA(Object(B),!0).forEach(function(I){_uA(A,I,B[I])}):Object.getOwnPropertyDescriptors?Object.defineProperties(A,Object.getOwnPropertyDescriptors(B)):REA(Object(B)).forEach(function(I){Object.defineProperty(A,I,Object.getOwnPropertyDescriptor(B,I))})}return A}var zEA=(A)=>Math.min(1000*2**A,30000),OuA,VEA,TEA,VuA=class{constructor(A){var Q,B,I,E,D;if(this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=A.method,this.url=A.url,this.headers=new Headers(A.headers),this.schema=A.schema,this.body=A.body,this.shouldThrowOnError=(Q=A.shouldThrowOnError)!==null&&Q!==void 0?Q:!1,this.signal=A.signal,this.isMaybeSingle=(B=A.isMaybeSingle)!==null&&B!==void 0?B:!1,this.shouldStripNulls=(I=A.shouldStripNulls)!==null&&I!==void 0?I:!1,this.urlLengthLimit=(E=A.urlLengthLimit)!==null&&E!==void 0?E:8000,this.retryEnabled=(D=A.retry)!==null&&D!==void 0?D:!0,A.fetch)this.fetch=A.fetch;else this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(A,Q){return this.headers=new Headers(this.headers),this.headers.set(A,Q),this}retry(A){return this.retryEnabled=A,this}then(A,Q){var B=this;if(this.schema===void 0);else if(["GET","HEAD"].includes(this.method))this.headers.set("Accept-Profile",this.schema);else this.headers.set("Content-Profile",this.schema);if(this.method!=="GET"&&this.method!=="HEAD")this.headers.set("Content-Type","application/json");if(this.shouldStripNulls){let $=this.headers.get("Accept");if($==="application/vnd.pgrst.object+json")this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped");else if(!$||$==="application/json")this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let I=this.fetch,D=(async()=>{let $=0;while(!0){let H=new Headers(B.headers);if($>0)H.set("X-Retry-Count",String($));let X;try{X=await I(B.url.toString(),{method:B.method,headers:H,body:JSON.stringify(B.body,(F,W)=>typeof W==="bigint"?W.toString():W),signal:B.signal})}catch(F){if((F===null||F===void 0?void 0:F.name)==="AbortError"||(F===null||F===void 0?void 0:F.code)==="ABORT_ERR")throw F;if(!VEA.includes(B.method))throw F;if(B.retryEnabled&&$<3){let W=zEA($);$++,await LEA(W,B.signal);continue}throw F}if(RuA(B.method,X.status,$,B.retryEnabled)){var G,Y;let F=(G=(Y=X.headers)===null||Y===void 0?void 0:Y.get("Retry-After"))!==null&&G!==void 0?G:null,W=F!==null?Math.max(0,parseInt(F,10)||0)*1000:zEA($);await X.text(),$++,await LEA(W,B.signal);continue}return await B.processResponse(X)}})();if(!this.shouldThrowOnError)D=D.catch(($)=>{var G;let Y="",H="",X="",F=$===null||$===void 0?void 0:$.cause;if(F){var W,q,Z,M;let T=(W=F===null||F===void 0?void 0:F.message)!==null&&W!==void 0?W:"",R=(q=F===null||F===void 0?void 0:F.code)!==null&&q!==void 0?q:"";if(Y=`${(Z=$===null||$===void 0?void 0:$.name)!==null&&Z!==void 0?Z:"FetchError"}: ${$===null||$===void 0?void 0:$.message}`,Y+=`
96
96
 
97
97
  Caused by: ${(M=F===null||F===void 0?void 0:F.name)!==null&&M!==void 0?M:"Error"}: ${T}`,R)Y+=` (${R})`;if(F===null||F===void 0?void 0:F.stack)Y+=`
@@ -817,14 +817,14 @@ All packages are compatible with channel "${$}"`)}return{finalCompatibility:Y.fi
817
817
  `).map((D)=>D.trim()).filter((D)=>D.length>0);if(E.length>0){let D=Wo([...E,...Fo]);return A?.(`Found ${D.length} matching repositories from the GitHub API.`),D}A?.("No matching repositories were returned from the paginated GitHub API. Trying a fallback request.")}else A?.("Paginated GitHub API request failed. Trying a fallback request.");let I=jH(["api",`orgs/${pY}/repos?per_page=100`]);if(I.status!==0)return A?.("Fallback request failed. Using the default repository list instead."),[...pP];try{let E=JSON.parse(I.stdout);if(!Array.isArray(E))return A?.("Fallback response format was invalid. Using the default repository list instead."),[...pP];let D=E.filter(($)=>typeof $==="object"&&$!==null).map(($)=>$.name).filter(($)=>!!$&&$.startsWith(RRA)).map(($)=>`${pY}/${$}`);if(D.length>0){let $=Wo([...D,...Fo]);return A?.(`Found ${$.length} matching repositories from the fallback request.`),$}}catch{return A?.("Fallback response could not be parsed. Using the default repository list instead."),[...pP]}return A?.("No matching repositories were found. Using the default repository list instead."),[...pP]}function dzQ(A,Q){return new Promise((B)=>{let I="",E="",D=!1,$,G=()=>{},Y=(H)=>{if(D)return;D=!0,Q?.removeEventListener("abort",G),B(H)};if(G=()=>{$?.kill("SIGINT"),Y({status:130,stderr:"GitHub command interrupted by user.",stdout:I})},$=xzQ("gh",A,{stdio:["ignore","pipe","pipe"]}),$.stdout?.setEncoding("utf8"),$.stdout?.on("data",(H)=>{I+=H}),$.stderr?.setEncoding("utf8"),$.stderr?.on("data",(H)=>{E+=H}),$.on("error",()=>{Y({status:1,stderr:"`gh` command is not available in PATH.",stdout:""})}),$.on("close",(H)=>{Y({status:H??1,stderr:E,stdout:I})}),Q){if(Q.aborted){G();return}Q.addEventListener("abort",G,{once:!0})}})}function jH(A){try{let Q=gzQ("gh",A,{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{status:Q.status??1,stderr:Q.stderr?.toString()??"",stdout:Q.stdout?.toString()??""}}catch{return{status:1,stderr:"`gh` command is not available in PATH.",stdout:""}}}function jRA(){if(!kRA())throw Error("GitHub CLI (`gh`) is not installed. Install it from https://cli.github.com/");if(!vRA())throw Error("GitHub CLI is not logged in. Run `gh auth login` first.")}async function pzQ(A,Q,B){if(A.length===0)return new Set;let I=new Set;return Q?.(`Checking ${A.length} target repositories against your GitHub stars.`),await PRA(A,Math.min(A.length,8),B,()=>[],async(E)=>{let D=await dzQ(["api","-X","GET",`/user/starred/${E}`],B);if(D.status===0){I.add(FN(E));return}if(D.status===1)return;if(D.status===130&&B?.aborted)throw nP();throw Error(`Unable to check star status for ${E}. ${D.stderr||D.stdout}`.trim())}),Q?.(`Found ${I.size} repositories already starred.`),I}async function PRA(A,Q,B,I,E){let D=0;async function $(){while(!0){SH(B,I());let Y=D;if(D+=1,Y>=A.length)return;await E(A[Y],Y)}}let G=Math.min(Q,A.length);await Promise.all(Array.from({length:G},$))}function nzQ(A,Q,B){let I=Promise.resolve();return async()=>{SH(B);let E,D=I;I=new Promise(($)=>{E=$}),await D,await czQ(uzQ(A,Q),B),E?.()}}function _RA(A){let Q=jH(["api","-X","PUT",`/user/starred/${A}`]);if(Q.status!==0){let B=Q.stderr||Q.stdout||`GitHub returned status ${Q.status}`;throw Error(`Failed to star ${A}: ${B.trim()}`)}return Ko(A),{repository:A,alreadyStarred:!1}}function oP(A){let B=(A?.trim()||TRA).replace(/\.git$/i,"");if(/^https?:\/\//.test(B))try{let I=new URL(B),E=I.hostname.toLowerCase();if(E==="github.com"||E==="www.github.com"){let[D,$]=I.pathname.split("/").filter((G)=>G.length>0);if(D&&$)return`${D}/${$}`}}catch{}if(B.startsWith("git@github.com:")){let[,I]=B.split("git@github.com:");if(I){let[E,D]=I.split("/");if(E&&D)return`${E}/${D}`}}if(B.includes("/")){let[I,E]=B.split("/");if(I&&E)return`${I}/${E}`}return`${pY}/${B}`}function izQ(A){return jH(["repo","view",A,"--json","nameWithOwner"]).status===0}function rzQ(A){let Q=jH(["api","-X","GET",`/user/starred/${A}`]);if(Q.status===0)return!0;if(Q.status===1)return!1;throw Error(`Unable to check star status for ${A}.`)}function kRA(){return jH(["--version"]).status===0}function vRA(){return jH(["auth","status"]).status===0}function J3(A){let Q=oP(A);if(!kRA())return{repository:Q,ghInstalled:!1,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!vRA())return{repository:Q,ghInstalled:!0,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!izQ(Q))return{repository:Q,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!1,starred:!1};return{repository:Q,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!0,starred:rzQ(Q)}}async function Y3(A={}){jRA(),SH(A.signal);let Q=A.repositories?.length?A.repositories:await lzQ(A.onDiscovery,A.signal);A.onDiscovery?.(`Prepared ${Q.length} repositories to process.`);let B=hzQ(A.minDelayMs,A.maxDelayMs),I=Wo(Q),E=mzQ(A.maxConcurrency,fzQ);SH(A.signal);let D=await pzQ(I,A.onDiscovery,A.signal),$=Array.from({length:I.length}),G=()=>$.filter((X)=>!!X),Y=[];for(let X=0;X<I.length;X++){SH(A.signal,G());let F=I[X],W=FN(F);if(G3(F)){let q={repository:F,alreadyStarred:!0,skipped:!0,status:"already_starred"};A.onProgress?.(q),$[X]=q;continue}if(D.has(W)){Ko(F);let q={repository:F,alreadyStarred:!0,skipped:!0,status:"already_starred"};A.onProgress?.(q),$[X]=q;continue}Y.push({index:X,repository:F})}let H=nzQ(B.min,B.max,A.signal);return await PRA(Y,E,A.signal,G,async({index:X,repository:F})=>{await H(),SH(A.signal,G());try{let q={repository:_RA(F).repository,alreadyStarred:!1,skipped:!1,status:"starred"};A.onProgress?.(q),$[X]=q}catch(W){let q={repository:F,alreadyStarred:!1,skipped:!1,status:"failed",error:W instanceof Error?W.message:String(W)};A.onProgress?.(q),$[X]=q}}),G()}function fJ(A){let Q=oP(A);jRA();let B=J3(Q);if(!B.repositoryExists)throw Error(`Cannot star ${Q}: repository is not reachable or does not exist.`);if(B.starred)return Ko(Q),{repository:Q,alreadyStarred:!0};return _RA(Q)}RB();HB();import{homedir as ozQ}from"node:os";import{join as azQ}from"node:path";var aP=azQ(ozQ(),".capgo-prompt-preferences.json");async function xRA(A=aP){try{let Q=await MT(A),B=JSON.parse(Q);if(!B||typeof B!=="object"||Array.isArray(B))return{};return Object.fromEntries(Object.entries(B).filter(([,I])=>typeof I==="boolean"))}catch{return{}}}async function szQ(A,Q=aP){return(await xRA(Q))[A]}async function tzQ(A,Q,B=aP){let I=await xRA(B);I[A]=Q,await e$(B,`${JSON.stringify(I,null,2)}
818
818
  `,{mode:384})}async function ezQ(A,Q,B=aP){try{await tzQ(A,Q,B)}catch(I){z.warn(`Could not save prompt preference: ${TA(I)}`)}}async function qo({preferenceKey:A,message:Q,initialValue:B=!1,rememberMessage:I="Remember this choice on this machine and stop asking again?"}){let E=await szQ(A);if(E!==void 0)return E;let D=await LI({message:Q,initialValue:B});if(lB(D))return!1;let $=await LI({message:I,initialValue:!1});if(!lB($)&&$)await ezQ(A,D);return D}RB();import gRA from"node:process";var A2Q=[{code:"aws:eu-central-1",label:"EU (Frankfurt)"},{code:"gcp:me-central1",label:"Middle East (Riyadh)"},{code:"gcp:asia-east2",label:"Hong Kong"},{code:"aws:ap-northeast-1",label:"Japan (Tokyo)"},{code:"aws:ap-south-1",label:"India (Mumbai)"},{code:"aws:us-east-1",label:"North America (Virginia)"},{code:"gcp:africa-south1",label:"Africa (South Africa)"},{code:"aws:ap-southeast-2",label:"Oceania (Sydney)"},{code:"aws:sa-east-1",label:"South America (São Paulo)"}],Q2Q=60000,B2Q=1000,bRA=20;function I2Q(){if(typeof Intl>"u")return null;return Intl.DateTimeFormat().resolvedOptions().timeZone||null}function E2Q(){let A=I2Q();if(!A)return null;if(/^America\//.test(A))return"aws:us-east-1";if(/^Europe\//.test(A)||/^Atlantic\//.test(A))return"aws:eu-central-1";if(/^Africa\//.test(A))return"gcp:africa-south1";if(/^Asia\//.test(A)){let Q=(A.split("/")[1]??"").toLowerCase();if(["tokyo","osaka","seoul","pyongyang"].includes(Q))return"aws:ap-northeast-1";if(["kolkata","mumbai","calcutta","chennai","bangalore","hyderabad","delhi","dhaka","colombo","karachi"].includes(Q))return"aws:ap-south-1";if(["hong_kong","singapore","manila","jakarta","kuala_lumpur","beijing","shanghai","hongkong","taipei"].includes(Q))return"gcp:asia-east2";if(["sydney","melbourne","canberra","perth","brisbane","darwin","adelaide"].includes(Q))return"aws:ap-southeast-2";return"gcp:asia-east2"}if(/^Pacific\//.test(A)||/^Australia\//.test(A))return"aws:ap-southeast-2";return null}function D2Q(){let A=[...A2Q],Q=E2Q();if(!Q)return A;let B=A.findIndex((E)=>E.code===Q);if(B<0)return A;let[I]=A.splice(B,1);return A.push(I),A}function $2Q(A,Q,B){let I=Math.min(Math.max(A,0),B);return Math.floor(I/B*Q)}function G2Q(A){let Q=Math.min(Math.max(A,0),100),B=Math.round(Q/100*bRA);return`${"█".repeat(B)}${"░".repeat(bRA-B)}`}function J2Q(A){return`${Math.max(0,A)}s`}function sP({interactive:A=gRA.stdout.isTTY&&gRA.stderr.isTTY,totalMs:Q=Q2Q,updateIntervalMs:B=B2Q,title:I="Replicating your bundle in all regions...",completeMessage:E="Your update is now available worldwide."}={}){if(!A||Q<=0)return Promise.resolve();let D=D2Q();if(!D.length)return Promise.resolve();z.info(I),z.info(`Regions: ${D.map((X)=>X.label).join(" • ")}`);let $=hI(),G=Date.now(),Y=D.length,H=null;return new Promise((X)=>{let F=()=>{let W=Date.now()-G,q=Math.max(0,Q-W),Z=$2Q(W,Y,Q),M=Math.min(100,Math.round(W/Q*100)),L=G2Q(M),O=Z<Y?D[Z]?.label||"Finalizing":"Complete",T=`${Z}/${Y} regions updated • ${J2Q(Math.ceil(q/1000))} left • ${L} • Next: ${O}`;$.message(T)};$.start(I),F(),H=setInterval(F,B),setTimeout(()=>{if(H)clearInterval(H);$.stop(E),X()},Q)})}function yRA(A){let Q=A?.autoUpdate;if(Q==="always")return!0;if(typeof Q==="string"||Q===!1)return!1;let B=A?.directUpdate;return B===!0||B==="always"}HB();RB();c$();function fRA(A){try{let Q=hB(A);return U8(S9(Q,"patch"))}catch{let Q=A.match(/^(\d+)\.(\d+)\.(\d+)/);if(Q){let[,B,I,E]=Q;return`${B}.${I}.${Number.parseInt(E)+1}`}return"1.0.1"}}async function hRA(A,Q){let B=fRA(A),I=Q?` for ${Q}`:"",E=await O1({message:`How do you want to handle the version${I}?`,options:[{value:"auto",label:`Auto: Bump patch version (${A} → ${B})`},{value:"manual",label:"Manual: I'll provide the version number"}]});if(lB(E))return null;if(E==="auto")return z.info(`\uD83D\uDD22 Auto-bumped version from ${A} to ${B}`),B;let D=await T9({message:`Current version is ${A}. Enter new version:`,validate:($)=>{if(!$)return"Version is required";if(!/^\d+\.\d+\.\d+/.test($))return"Please enter a valid version (x.y.z)"}});if(lB(D))return null;return D}function uRA(A){let Q=fRA(A);try{let B=hB(A);return[Q,U8(S9(B,"minor")),`${A}-beta.1`,`${A}.1`]}catch{return[Q,`${A}.1`,`${A}-beta.1`,`${A}-rc.1`]}}RB();kI();function Y2Q(A){if(!A.incompatible)return"skip";if(!A.interactive)return"ci-ad";return A.hasCredentials?"prompt-build":"prompt-onboarding"}var U2Q="https://capgo.app/docs/cli/cloud-build/",mRA="https://capgo.app/native-build/",cRA="This update includes native changes. An app store update may be required for these changes to take effect. Capgo Builder can help you build and publish the required native update.";function H2Q(A,Q){let B=String.fromCharCode(27),I=String.fromCharCode(7);return`${B}]8;;${Q}${I}${A}${B}]8;;${I}`}function X2Q(A){let Q=A?"run a native build (npx @capgo/cli build request --platform <ios|android>)":"set up Capgo Builder (npx @capgo/cli build onboarding)";z.warn(`${cRA} To ${Q} — learn more: ${mRA} · docs: ${U2Q}`)}async function lRA(A){try{return await C2Q(A)}catch{return"continue"}}async function C2Q(A){let{hasCredentials:Q}=A,B=Y2Q({incompatible:A.incompatible,interactive:A.interactive,hasCredentials:Q});if(B==="skip")return"continue";let I=Q?"build":"onboarding";if(BB({channel:"bundle",event:"Builder CTA Shown",icon:"\uD83D\uDCE3",apikey:A.apikey,appId:A.appId,orgId:A.orgId,tags:{surface:B==="ci-ad"?"ci":"interactive",mode:I,incompatible_count:A.incompatibleCount}}),B==="ci-ad")return X2Q(Q),"continue";z.info(cRA);let $=await(A.confirm??LI)({message:`${I==="build"?"Start a native build with Capgo Builder now?":"Would you like to configure Capgo Builder now?"}
819
819
  ${H2Q("Learn what Capgo Builder is",mRA)}`,initialValue:!0});if(lB($))return"continue";if($===!0)return BB({channel:"bundle",event:"Builder CTA Accepted",icon:"✅",apikey:A.apikey,appId:A.appId,orgId:A.orgId,tags:{mode:I}}),I==="build"?"launch-build":"launch-onboarding";return BB({channel:"bundle",event:"Builder CTA Declined",icon:"\uD83D\uDEAB",apikey:A.apikey,appId:A.appId,orgId:A.orgId,tags:{mode:I}}),"continue"}import{readdirSync as dRA,readFileSync as F2Q,statSync as W2Q}from"node:fs";import{extname as K2Q,join as q2Q}from"node:path";function Z2Q(A,Q){return F2Q(A,"utf8").includes(Q)}function WN(A,Q){let B=dRA(A);for(let I of B){let E=q2Q(A,I),D=W2Q(E);if(D.isDirectory()){if(WN(E,Q))return!0}else if(D.isFile()&&K2Q(E)===".js"){if(Z2Q(E,Q))return!0}}return!1}function tP(A){if(dRA(A).indexOf("index.html")>-1)return!0;return!1}RB();c$();var eVA=lA(sVA(),1),ATA=lA(bL(),1);import{Buffer as rLQ}from"node:buffer";import{createHash as oLQ}from"node:crypto";import{createReadStream as xo,statSync as aLQ}from"node:fs";import{platform as sLQ}from"node:os";import{join as tLQ,posix as eLQ,win32 as tVA}from"node:path";import{cwd as AOQ}from"node:process";import{buffer as go}from"node:stream/consumers";import{createBrotliCompress as QOQ}from"node:zlib";HB();async function BOQ(A,Q){try{let B=new URL(`${A.hostFilesApi}/files/read/attachments/${encodeURIComponent(Q)}`);return B.searchParams.set("nocache",`${Date.now()}`),(await fetch(B.toString(),{method:"GET",headers:{range:"bytes=0-0","cache-control":"no-cache"}})).ok}catch{return!1}}var IOQ=8192;async function EOQ(A){let Q=kE(AOQ()),B=await AD("@capgo/capacitor-updater",Q,A.packageJson),I;try{I=B?hB(B):void 0}catch{I=void 0}if(!B||!I)return{version:null,supportsBrotliV2:!1};let E=!B$(I,void 0,void 0,MZ);return{version:`${I.major}.${I.minor}.${I.patch}`,supportsBrotliV2:E}}function DOQ(A,Q){if(!Q)return!1;let B=Q.split(",").map((I)=>I.trim()).filter((I)=>!!I);if(B.length===0)return!1;return eVA.isMatch(A,B)}async function $OQ(A,Q,B){let E=aLQ(A).size,D=await go(xo(A));if(E===0)return{buffer:D,useBrotli:!1};if(DOQ(Q,B.noBrotliPatterns))return{buffer:D,useBrotli:!1};if(E<IOQ)return{buffer:D,useBrotli:!1};try{let $=await go(xo(A).pipe(QOQ({})));if($.length>=E-10)return{buffer:D,useBrotli:!1};return{buffer:$,useBrotli:!0}}catch($){return z.warn(`Brotli compression failed for ${A}: ${$}, using original file`),{buffer:D,useBrotli:!1}}}async function QTA(A,Q,B,I,E,D,$=!1){let G=hI();G.start(E!=="v2"?"Generating the update manifest":`Generating the update manifest with ${$?"V3":"V2"} encryption`);let Y=await wXA(A);if(E==="v2")for(let H of Y)H.hash=$?$3(H.hash,D):D3(H.hash,D);return G.stop("Manifest generated successfully"),await JB(Q,{channel:"partial-update",event:"Generate manifest",icon:"\uD83D\uDCC2",org_id:B,tracking_version:2,tags:{"app-id":I},notify:!1}),Y}function GOQ(A){if(sLQ()!=="win32")return A;return tVA.normalize(A).split(tVA.sep).join(eLQ.sep)}function JOQ(A){return A.split("/").map((Q)=>encodeURIComponent(Q)).join("/")}function YOQ(A,Q,B,I,E){let D=oLQ("sha256").update(B).digest("hex"),$=JOQ(I);if(E){let G=rLQ.from(E.ivSessionKey).toString("hex");return`orgs/${A}/apps/${Q}/delta/${G}/${D}_${$}`}return`orgs/${A}/apps/${Q}/delta/${D}_${$}`}async function BTA(A,Q,B,I,E,D,$){let G=hI();G.start("Preparing partial update with TUS protocol");let Y=performance.now(),H=await n4(),X=!!($.partial||$.delta||$.partialOnly||$.deltaOnly),{version:F,supportsBrotliV2:W}=await EOQ($);if(!W)throw Error(`Your project is using an older version of @capgo/capacitor-updater (${F||"unknown"}). To use Delta updates, please upgrade to version ${YT} (v5), ${UT} (v6) or ${MZ} (v7) or higher.`);else if($.disableBrotli)z.info("Brotli compression disabled by user request");else if($.noBrotliPatterns)z.info(`Files matching patterns (${$.noBrotliPatterns}) will be excluded from brotli compression`);let q=Q.filter((O)=>O.file.includes(" "));if(q.length>0)throw Error(`Files with spaces in their names (${q.map((O)=>O.file).join(", ")}). Please rename the files.`);let Z=0,M=Q.length,L=0;try{G.message(`Uploading ${M} files using TUS protocol`);let O=async(c)=>{let a=tLQ(B,c.file),t=GOQ(c.file),l,$A=!1;if($.disableBrotli)l=await go(xo(a)),$A=!1;else{let jA=await $OQ(a,t,$);l=jA.buffer,$A=jA.useBrotli}let o=l;if(D)o=E3(l,D.sessionKey,D.ivSessionKey);let HA=t;if($A)HA=`${t}.br`,L++;let zA=YOQ(E,I,c.hash,HA,D);if(!D&&await BOQ(H,zA))return Z++,Promise.resolve({file_name:HA,s3_path:zA,file_hash:c.hash});return new Promise((jA,s)=>{G.message(`Prepare upload partial file: ${t}`);let _=GY(HA);new ATA.Upload(o,{endpoint:`${H.hostFilesApi}/files/upload/attachments/`,chunkSize:$.tusChunkSize,retryDelays:[0,1000,3000,5000,1e4],removeFingerprintOnSuccess:!0,metadata:{filename:zA,filetype:_},headers:{Authorization:A},onError:(v)=>{let EA=v.toString(),r;try{let OA=EA.match(/response text: (\{.*?\})/);if(OA&&OA[1])r=JSON.parse(OA[1]).moreInfo?.requestId}catch{}let BA=r?` [requestId: ${r}]`:"";z.error(`Failed to upload ${t}: ${EA}${BA}`),s(v)},onProgress(){let v=(Z/M*100).toFixed(2);G.message(`Uploading partial update: ${v}%`)},onSuccess(){Z++,jA({file_name:HA,s3_path:zA,file_hash:c.hash})}}).start()})},T=500,R=[];for(let c=0;c<Q.length;c+=T){let a=Q.slice(c,c+T),t=Math.floor(c/T)+1,l=Math.ceil(Q.length/T);if(l>1)G.message(`Processing batch ${t}/${l} (${a.length} files)`);let $A=await Promise.all(a.map((o)=>O(o)));R.push(...$A)}let j=((performance.now()-Y)/1000).toFixed(2);if(G.stop(`Partial update uploaded successfully \uD83D\uDCAA in (${j} seconds)`),L>0)z.info(`${L} of ${M} files were compressed with brotli and use .br extension`);return await JB(A,{channel:"app",event:`App Partial TUS done${L>0?" with .br extension":""}`,icon:"⏫",org_id:E,tracking_version:2,tags:{"app-id":I},notify:!1}),await JB(A,{channel:"performance",event:"Partial upload performance",icon:"\uD83D\uDE84",org_id:E,tracking_version:2,tags:{"app-id":I,time:j},notify:!1}),R}catch(O){let R=((performance.now()-Y)/1000).toFixed(2);if(G.error(`Failed to upload Partial bundle (after ${R} seconds)`),X)throw z.error(`Error uploading partial update: ${O}`),z.error("Delta/partial upload was explicitly requested but failed. Upload aborted."),O;else return z.info(`Error uploading partial update: ${O}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}function q0(A){throw z.error(A),Error(A)}async function bo(A,Q,B){let{error:I}=await ZXA(A,Q);if(I)q0(`Cannot ${B} bundle ${TA(I)}`)}function XOQ(A){let Q=new UI;Q.headers=["Package","Local","Remote","Status","Details"],Q.theme=UI.roundTheme,Q.rows=[];for(let B of A){let{name:I,localVersion:E,remoteVersion:D}=B,$=IG(B),G=$.compatible?"✅":"❌";Q.rows.push([I,E||"-",D||"-",G,$.message])}z.info(Q.toString())}async function COQ(A,Q){let B=t$("",Q.packageJson),I=Q.bundle||A?.plugins?.CapacitorUpdater?.version||B||`0.0.1-beta.local-${UOQ().split("-")[0]}`;if(!MC.test(I))q0(`Your bundle name ${I}, is not valid it should follow semver convention : https://semver.org/`);return I}function FOQ(A){let Q=A.apikey||vQ();if(!Q)q0("Missing API key, you need to provide an API key to upload your bundle");return Q}function WOQ(A,Q,B){let I=gB(A,B),E=Q.path||B?.webDir;if(!I)q0("Missing argument, you need to provide a appid or be in a capacitor project");if(!E)q0("Missing argument, you need to provide a path (--path), or be in a capacitor project");if(!wN(E))q0(`Path ${E} does not exist, build your app first, or provide a valid path`);return{appid:I,path:E}}function KOQ(A,Q){let B=A.codeCheck;if(typeof B>"u"||B){if(!WN(Q,"notifyAppReady"))q0(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready
820
- If you are sure your app has this code, you can use the --no-code-check option`);if(!tP(Q))q0(`index.html is missing in the root folder of ${Q}`)}}async function qOQ(A,Q,B,I,E,D,$){let{ignoreMetadataCheck:G,autoMinUpdateVersion:Y,minUpdateVersion:H}=B,{data:X,error:F}=await A.from("channels").select("disable_auto_update, version ( id, name, min_update_version, native_packages )").eq("name",I).eq("app_id",E).maybeSingle();if(F)q0(`Cannot load channel ${I} for compatibility checks ${TA(F)}`);let W=X?.version??void 0,q=!!X&&X.disable_auto_update==="version_number",Z,M;if(!F&&X&&X.version&&X.version.native_packages&&!G){let S=hI();S.start(`Checking bundle compatibility with channel ${I}`);let{finalCompatibility:j,localDependencies:c}=await TC(A,E,I,B.packageJson,B.nodeModules);if(M=j,Z=c,M.filter((t)=>!QD(t)).length>0){if(S.error(`Bundle NOT compatible with ${I} channel`),z.warn(""),XOQ(M),z.warn(""),z.warn("An app store update may be required for these changes to take effect."),Y)H=D,z.info(`Auto set min-update-version to ${H}`)}else if(Y)try{let{min_update_version:t}=X.version;if(!t||!MC.test(t))q0("Invalid remote min update version, skipping auto setting compatibility");H=t,S.stop(`Auto set min-update-version to ${H}`)}catch{q0(`Cannot auto set compatibility, invalid data ${X}`)}else S.stop(`Bundle compatible with ${I} channel`)}else if(!G){if(z.warn(`Channel ${I} is new or it's your first upload with compatibility check, it will be ignored this time`),Z=await bl(B.packageJson,B.nodeModules),Y)H=D,z.info(`Auto set min-update-version to ${H}`)}let L=M?void 0:G?"ignore_metadata_check":"no_remote_metadata",O=QRA(M);if(BB({channel:"bundle",event:"Bundle Upload Compatibility Checked",icon:"\uD83E\uDDEA",apikey:B.apikey,appId:E,orgId:$,tags:{result:O.result,incompatible_count:O.incompatibleCount,channel:I,...O.reasons.length>0?{reasons:O.reasons.join(",")}:{},...L?{skip_reason:L}:{}}}),q&&!H&&!G)q0("You need to provide a min-update-version to upload a bundle to this channel");if(H){if(!MC.test(H))q0(`Your minimal version update ${H}, is not valid it should follow semver convention : https://semver.org/`)}let T=Z?new Map(Z.filter((S)=>!!S.native&&S.native!==void 0).map((S)=>[S.name,S])):new Map;return{nativePackages:T.size>0||!B.ignoreMetadataCheck?Array.from(T,([S,j])=>({name:S,version:j.version,...j.ios_checksum&&{ios_checksum:j.ios_checksum},...j.android_checksum&&{android_checksum:j.android_checksum}})):void 0,minUpdateVersion:H,incompatibleCount:O.incompatibleCount,compatibility:{result:O.result,versionOldId:W?.id!=null?String(W.id):void 0,versionOldName:W?.name}}}async function ZOQ(A,Q,B,I=!1,E=!1){let{data:D,error:$}=await A.rpc("exist_app_versions",{appid:Q,name_version:B}).single();if($)q0(`Cannot check if version ${B} already exists ${TA($)}`);if(D){if(I)return z.warn(`Version ${B} already exists - exiting gracefully due to --silent-fail option`),tQ("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(E){z.error(`❌ Version ${B} already exists`);let G=uRA(B);z.info("\uD83D\uDCA1 Here are some suggestions:"),G.forEach((X,F)=>{z.info(` ${F+1}. ${X}`)});let Y=await O1({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${G[0]}`},{value:"suggest2",label:`Use ${G[1]}`},{value:"suggest3",label:`Use ${G[2]}`},{value:"suggest4",label:`Use ${G[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(lB(Y)||Y==="cancel")q0("Upload cancelled by user");let H;if(Y==="custom"){let X=await hRA(B,"upload");if(!X)q0("Upload cancelled by user");H=X}else{let X=Number.parseInt(Y.replace("suggest",""))-1;H=G[X]}return z.info(`\uD83D\uDD04 Retrying with new version: ${H}`),H}q0(`Version ${B} already exists`)}return!1}async function MOQ(A,Q,B,I,E,D,$,G){let Y,H,X="",F=null,W="none",q="",Z="",M=Q.keyV2,L=Q.key===!1,O=hI();O.start(`Zipping bundle from ${A}`),F=await HT(A),O.message("Calculating checksum");let T=kE(yo()),R=await AD("@capgo/capacitor-updater",T,Q.packageJson),S=!1,j;try{j=R?hB(R):void 0}catch{j=void 0}if(!R)q0("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");else if(j)S=!B$(j,YT,UT,MZ);else if(R==="link:@capgo/capacitor-updater"||R==="file:.."||R==="file:../")z.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),S=!0;let c=Q.forceCrc32Checksum===!0,a=!c&&((M||Q.keyDataV2||wN(e4))&&!L||S);if(X=await n9(F,a?"sha256":"crc32"),O.stop(`Checksum ${a?"SHA256":"CRC32"}${c?" (forced)":""}: ${X}`),L)z.info("Encryption ignored");else if((M||wN(e4)||Q.keyDataV2)&&!Q.oldEncryption){let $A=typeof M==="string"?M:e4,o=Q.keyDataV2||"";if(!o&&!wN($A))q0(`Cannot find private key ${$A}`);if(await JB(B,{channel:"app",event:"App encryption v2",icon:"\uD83D\uDD11",org_id:I,tracking_version:2,tags:{"app-id":E},notify:!1},Q.verbose),!o)o=HOQ($A).toString();let HA=j&&!B$(j,"5.30.0","6.30.0","7.30.0");z.info(`Encrypting your bundle with ${HA?"V3":"V2"}`);let{sessionKey:zA,ivSessionKey:jA}=uP(o),s=E3(F,zA,jA);if(X=HA?$3(X,o):D3(X,o),Y=jA,H=zA,W="v2",q=o,G){if(Z=JRA(G),Q.verbose)z.info(`[Verbose] Encryption key_id: ${Z}`)}if(Q.displayIvSession)z.info(`Your Iv Session key is ${Y},
820
+ If you are sure your app has this code, you can use the --no-code-check option`);if(!tP(Q))q0(`index.html is missing in the root folder of ${Q}`)}}async function qOQ(A,Q,B,I,E,D,$){let{ignoreMetadataCheck:G,autoMinUpdateVersion:Y,minUpdateVersion:H}=B,{data:X,error:F}=await A.from("channels").select("disable_auto_update, version ( id, name, min_update_version, native_packages )").eq("name",I).eq("app_id",E).maybeSingle();if(F)q0(`Cannot load channel ${I} for compatibility checks ${TA(F)}`);let W=X?.version??void 0,q=!!X&&X.disable_auto_update==="version_number",Z,M;if(!F&&X&&X.version&&X.version.native_packages&&!G){let S=hI();S.start(`Checking bundle compatibility with channel ${I}`);let{finalCompatibility:j,localDependencies:c}=await TC(A,E,I,B.packageJson,B.nodeModules);if(M=j,Z=c,M.filter((t)=>!QD(t)).length>0){if(S.error(`Bundle NOT compatible with ${I} channel`),z.warn(""),XOQ(M),z.warn(""),z.warn("An app store update may be required for these changes to take effect."),Y)H=D,z.info(`Auto set min-update-version to ${H}`)}else if(Y)try{let{min_update_version:t}=X.version;if(!t||!MC.test(t))q0("Invalid remote min update version, skipping auto setting compatibility");H=t,S.stop(`Auto set min-update-version to ${H}`)}catch{q0(`Cannot auto set compatibility, invalid data ${X}`)}else S.stop(`Bundle compatible with ${I} channel`)}else if(!G){if(z.warn(`Channel ${I} is new or it's your first upload with compatibility check, it will be ignored this time`),Z=await bl(B.packageJson,B.nodeModules),Y)H=D,z.info(`Auto set min-update-version to ${H}`)}let L=M?void 0:G?"ignore_metadata_check":"no_remote_metadata",O=QRA(M);if(BB({channel:"bundle",event:"Bundle Upload Compatibility Checked",icon:"\uD83E\uDDEA",apikey:B.apikey,appId:E,orgId:$,tags:{result:O.result,incompatible_count:O.incompatibleCount,channel:I,channel_name:I,...O.reasons.length>0?{reasons:O.reasons.join(",")}:{},...L?{skip_reason:L}:{}}}),q&&!H&&!G)q0("You need to provide a min-update-version to upload a bundle to this channel");if(H){if(!MC.test(H))q0(`Your minimal version update ${H}, is not valid it should follow semver convention : https://semver.org/`)}let T=Z?new Map(Z.filter((S)=>!!S.native&&S.native!==void 0).map((S)=>[S.name,S])):new Map;return{nativePackages:T.size>0||!B.ignoreMetadataCheck?Array.from(T,([S,j])=>({name:S,version:j.version,...j.ios_checksum&&{ios_checksum:j.ios_checksum},...j.android_checksum&&{android_checksum:j.android_checksum}})):void 0,minUpdateVersion:H,incompatibleCount:O.incompatibleCount,compatibility:{result:O.result,versionOldId:W?.id!=null?String(W.id):void 0,versionOldName:W?.name}}}async function ZOQ(A,Q,B,I=!1,E=!1){let{data:D,error:$}=await A.rpc("exist_app_versions",{appid:Q,name_version:B}).single();if($)q0(`Cannot check if version ${B} already exists ${TA($)}`);if(D){if(I)return z.warn(`Version ${B} already exists - exiting gracefully due to --silent-fail option`),tQ("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(E){z.error(`❌ Version ${B} already exists`);let G=uRA(B);z.info("\uD83D\uDCA1 Here are some suggestions:"),G.forEach((X,F)=>{z.info(` ${F+1}. ${X}`)});let Y=await O1({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${G[0]}`},{value:"suggest2",label:`Use ${G[1]}`},{value:"suggest3",label:`Use ${G[2]}`},{value:"suggest4",label:`Use ${G[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(lB(Y)||Y==="cancel")q0("Upload cancelled by user");let H;if(Y==="custom"){let X=await hRA(B,"upload");if(!X)q0("Upload cancelled by user");H=X}else{let X=Number.parseInt(Y.replace("suggest",""))-1;H=G[X]}return z.info(`\uD83D\uDD04 Retrying with new version: ${H}`),H}q0(`Version ${B} already exists`)}return!1}async function MOQ(A,Q,B,I,E,D,$,G){let Y,H,X="",F=null,W="none",q="",Z="",M=Q.keyV2,L=Q.key===!1,O=hI();O.start(`Zipping bundle from ${A}`),F=await HT(A),O.message("Calculating checksum");let T=kE(yo()),R=await AD("@capgo/capacitor-updater",T,Q.packageJson),S=!1,j;try{j=R?hB(R):void 0}catch{j=void 0}if(!R)q0("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");else if(j)S=!B$(j,YT,UT,MZ);else if(R==="link:@capgo/capacitor-updater"||R==="file:.."||R==="file:../")z.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),S=!0;let c=Q.forceCrc32Checksum===!0,a=!c&&((M||Q.keyDataV2||wN(e4))&&!L||S);if(X=await n9(F,a?"sha256":"crc32"),O.stop(`Checksum ${a?"SHA256":"CRC32"}${c?" (forced)":""}: ${X}`),L)z.info("Encryption ignored");else if((M||wN(e4)||Q.keyDataV2)&&!Q.oldEncryption){let $A=typeof M==="string"?M:e4,o=Q.keyDataV2||"";if(!o&&!wN($A))q0(`Cannot find private key ${$A}`);if(await JB(B,{channel:"app",event:"App encryption v2",icon:"\uD83D\uDD11",org_id:I,tracking_version:2,tags:{"app-id":E},notify:!1},Q.verbose),!o)o=HOQ($A).toString();let HA=j&&!B$(j,"5.30.0","6.30.0","7.30.0");z.info(`Encrypting your bundle with ${HA?"V3":"V2"}`);let{sessionKey:zA,ivSessionKey:jA}=uP(o),s=E3(F,zA,jA);if(X=HA?$3(X,o):D3(X,o),Y=jA,H=zA,W="v2",q=o,G){if(Z=JRA(G),Q.verbose)z.info(`[Verbose] Encryption key_id: ${Z}`)}if(Q.displayIvSession)z.info(`Your Iv Session key is ${Y},
821
821
  keep it safe, you will need it to decrypt your bundle.
822
822
  It will be also visible in your dashboard
823
823
  `);F=s}let t=Math.floor((F?.byteLength??0)/1024/1024),l=Math.floor(D/1024/1024);if(F?.byteLength>D)q0(`The bundle size is ${t} Mb, this is greater than the maximum upload length ${l} Mb, please reduce the size of your bundle`);else if(F?.byteLength>$){if(z.warn(`WARNING !!
824
824
  The bundle size is ${t} Mb, this may take a while to download for users
825
825
  `),z.info(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
826
826
  `),Q.verbose)z.info("[Verbose] Bundle size details:"),z.info(` - Actual size: ${t} MB (${F?.byteLength} bytes)`),z.info(` - Alert threshold: ${Math.floor($/1024/1024)} MB`),z.info(` - Maximum allowed: ${l} MB`),z.info("[Verbose] Sending 'App Too Large' event to analytics...");if(await JB(B,{channel:"app-error",event:"App Too Large",icon:"\uD83D\uDE9B",org_id:I,tracking_version:2,tags:{"app-id":E},notify:!1},Q.verbose),Q.verbose)z.info("[Verbose] Event sent successfully")}else if(Q.verbose)z.info(`[Verbose] Bundle size OK: ${t} MB (under ${Math.floor($/1024/1024)} MB alert threshold)`);if(Q.verbose)z.info("[Verbose] Bundle preparation complete, returning bundle data");return{zipped:F,ivSessionKey:Y,sessionKey:H,checksum:X,encryptionMethod:W,finalKeyData:q,keyId:Z}}async function NOQ(A,Q,B,I,E,D,$,G){let Y=hI();Y.start("Uploading Bundle");let H=performance.now(),X=!1;if($.verbose)z.info("[Verbose] uploadBundleToCapgoCloud called:"),z.info(` - Bundle size: ${Math.floor(D.byteLength/1024)} KB`),z.info(` - App ID: ${B}`),z.info(` - Bundle version: ${I}`),z.info(` - Chunk size: ${Math.floor(G/1024/1024)} MB`);if($.dryUpload){if(Y.stop(`Dry run, bundle not uploaded
827
- Bundle uploaded \uD83D\uDCAA in 0 seconds`),$.verbose)z.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let q=await n4();if($.verbose)z.info("[Verbose] Local config retrieved for upload");if($.multipart!==void 0&&$.multipart||$.tus!==void 0&&$.tus){if($.multipart)z.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else z.info("Uploading bundle with TUS protocol");if($.verbose)z.info("[Verbose] Starting TUS resumable upload..."),z.info(` - Host: ${q.hostWeb}`),z.info(` - Chunk size: ${Math.floor(G/1024/1024)} MB`);if(await zXA(A,D,E,B,I,Y,q,G),X=!0,$.verbose)z.info("[Verbose] TUS upload completed, updating database with R2 path...");let Z=`orgs/${E}/apps/${B}/${I}.zip`,{error:M}=await Q.from("app_versions").update({r2_path:Z}).eq("name",I).eq("app_id",B);if(M){if(z.error(`Cannot finish TUS upload ${TA(M)}`),$.verbose)z.info(`[Verbose] Database update failed: ${TA(M)}`);throw Error("Cannot finish TUS upload")}if($.verbose)z.info(`[Verbose] Database updated with R2 path: ${Z}`)}else{if($.verbose)z.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let Z=await MXA(Q,B,I);if(!Z){if(z.error("Cannot get upload url"),$.verbose)z.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}if($.verbose)z.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),z.info(` - Timeout: ${$.timeout||Pl}ms`),z.info(" - Retry attempts: 5"),z.info(" - Content-Type: application/zip");let M=new AbortController,L=setTimeout(()=>M.abort(),$.timeout||Pl);try{let O=await fetch(Z,{method:"PUT",body:D,headers:{"Content-Type":"application/zip"},signal:M.signal});if(!O.ok)throw Error(`HTTP error! status: ${O.status}`)}finally{clearTimeout(L)}if($.verbose)z.info("[Verbose] HTTP PUT upload completed successfully")}}catch(q){let M=((performance.now()-H)/1000).toFixed(2);if(Y.error(`Failed to upload bundle ( after ${M} seconds)`),$.verbose)z.info(`[Verbose] Upload failed after ${M} seconds`),z.info(`[Verbose] Error type: ${q instanceof Error?"Error":typeof q}`);if(q instanceof Error&&q.message.includes("HTTP error"))try{let L=q.message.match(/status: (\d+)/),O=L?L[1]:"unknown";z.error(`Upload failed with status ${O}: ${q.message}`)}catch{z.error(`Upload failed: ${q.message}`)}else{if($.verbose)z.info(`[Verbose] Non-HTTP error: ${TA(q)}`);if(!$.tus)z.error(`Cannot upload bundle ( try again with --tus option) ${TA(q)}`);else z.error(`Cannot upload bundle please contact support if the issue persists ${TA(q)}`)}if($.verbose)z.info("[Verbose] Cleaning up failed version from database...");if(await vl(Q,B,I),$.verbose)z.info("[Verbose] Failed version cleaned up");throw q instanceof Error?q:Error(String(q))}let W=((performance.now()-H)/1000).toFixed(2);if(Y.stop(`Bundle uploaded \uD83D\uDCAA in (${W} seconds)`),$.verbose)z.info("[Verbose] Upload successful:"),z.info(` - Upload time: ${W} seconds`),z.info(` - Upload method: ${X?"TUS (resumable)":"Standard HTTP PUT"}`),z.info(` - Bundle size: ${Math.floor(D.byteLength/1024)} KB`),z.info("[Verbose] Sending performance event...");if(await JB(A,{channel:"performance",event:X?"TUS upload zip performance":"Upload zip performance",icon:"\uD83D\uDE84",org_id:E,tracking_version:2,tags:{"app-id":B,time:W},notify:!1},$.verbose),$.verbose)z.info("[Verbose] Performance event sent successfully")}async function wOQ(A,Q,B){let{data:I,error:E}=await A.from("channels").select("version ( id, name, deleted )").eq("app_id",Q).eq("name",B);if(E)return z.error(`Cannot delete linked bundle on upload ${TA(E)}`),null;if(I.length===0)return z.warn("No linked bundle found in the channel you are trying to upload to"),null;let D=I[0].version;if(!D)return z.warn("No linked bundle found in the channel you are trying to upload to"),null;if(D.deleted)return z.warn("The linked bundle is already deleted"),null;return D}async function zOQ(A,Q){if(!Q)return;let{error:B}=await A.from("app_versions").update({deleted:!0}).eq("id",Q.id);if(B){z.error(`Cannot delete linked bundle on upload ${TA(B)}`);return}z.info(`Linked bundle ${Q.name} deleted`)}async function LOQ(A,Q,B,I,E,D,$,G,Y,H){let{data:X}=await A.rpc("get_app_versions",{apikey:Q,name_version:I,appid:G}).single();if(!X)q0("Cannot get version id, cannot set channel");if(await OC(A,Q,"app.create_channel",{appId:G})){let{error:W,data:q}=await XT(A,{name:E,app_id:G,created_by:D,version:X,owner_org:$,...H?{allow_device_self_set:!0}:{}});if(W)q0(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${TA(W)}`);let Z=`${Y.hostWeb}/app/${G}/channel/${q.id}`;if(q?.public)z.info("Your update is now available in your public channel \uD83C\uDF89");else if(q?.id)z.info(`Link device to this bundle to try it: ${Z}`);if(B)z.info(`Bundle url: ${Z}`);return!0}return z.warn("The upload key is not allowed to set the version in the channel"),!1}async function OOQ(A,Q,B){let{error:I,data:E}=await Q.from("apps").select("default_upload_channel").eq("app_id",A).single();if(I)throw Error(`Cannot find default upload channel: ${TA(I)}. You can set it here: ${B}/app/${A}/info`);return E.default_upload_channel}async function X3(A,Q,B=!1){if(!B)sQ(`Uploading with CLI version ${fE.version}`);let I,E=KI();await b0();let{s3Region:D,s3Apikey:$,s3Apisecret:G,s3BucketName:Y,s3Endpoint:H,s3Port:X,s3SSL:F}=Q;if(Q.verbose)z.info("[Verbose] Starting upload process with options:"),z.info(` - API key: ${Q.apikey?"provided":"from saved key"}`),z.info(` - Path: ${Q.path||"from capacitor config"}`),z.info(` - Channel: ${Q.channel||"from default upload channel"}`),z.info(` - Bundle: ${Q.bundle||"auto-detected"}`),z.info(` - External: ${Q.external||"false"}`),z.info(` - Encryption: ${Q.keyV2||Q.keyDataV2?"v2":Q.key===!1?"disabled":"auto"}`),z.info(` - Upload method: ${Q.tus?"TUS":Q.zip?"ZIP":"auto"}`),z.info(` - Delta updates: ${Q.delta||Q.partial?"enabled":"disabled"}`);let W=FOQ(Q);if(Q.verbose)z.info("[Verbose] API key retrieved successfully");let q=await rQ();if(Q.verbose)z.info("[Verbose] Capacitor config loaded successfully");let Z=yRA(q?.config?.plugins?.CapacitorUpdater),M=wC({silent:B});if(Z&&Q.delta===void 0){if(M){z.info("\uD83D\uDCA1 Instant updates are enabled in your config"),z.info(" Delta updates send only changed files instead of the full bundle");let bA=await LI({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!lB(bA)&&bA){if(Q.delta=!0,Q.verbose)z.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!B){if(Q.delta!==!1){if(Q.delta=!0,Q.verbose)z.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let L=await YXA();if(Q.verbose)z.info("[Verbose] Remote file config retrieved:"),z.info(` - Max upload length: ${Math.floor(L.maxUploadLength/1024/1024)} MB`),z.info(` - Alert upload size: ${Math.floor(L.alertUploadSize/1024/1024)} MB`),z.info(` - TUS upload: ${L.TUSUpload?"enabled":"disabled"}`),z.info(` - TUS upload forced: ${L.TUSUploadForced?"yes":"no"}`),z.info(` - Partial upload: ${L.partialUpload?"enabled":"disabled"}`),z.info(` - Max chunk size: ${Math.floor(L.maxChunkSize/1024/1024)} MB`);let{appid:O,path:T}=WOQ(A,Q,q.config);if(Q.verbose)z.info(`[Verbose] App ID: ${O}, Build path: ${T}`);let R=await COQ(q.config,Q);if(Q.verbose)z.info(`[Verbose] Bundle version: ${R}`);let S=Q.external?"external":"r2-direct",j="none";if(Q.autoSetBundle){if(await zC({version:R}),Q.verbose)z.info("[Verbose] Auto-set bundle version in capacitor.config.json")}if(KOQ(Q,T),Q.verbose)z.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");z.info(`Upload ${O}@${R} started from path "${T}" to Capgo cloud`);let c=await n4();if(Q.verbose)z.info(`[Verbose] Local config loaded: host=${c.hostWeb}`);if(Q.supaHost&&Q.supaAnon){if(z.info("Using custom supabase instance from provided options"),c.supaHost=Q.supaHost,c.supaKey=Q.supaAnon,Q.verbose)z.info(`[Verbose] Custom Supabase host: ${Q.supaHost}`)}let a=await eQ(W,Q.supaHost,Q.supaAnon);if(Q.verbose)z.info("[Verbose] Supabase client created successfully");await vE(a,O,B);let t=await y0(a,W);if(Q.verbose)z.info(`[Verbose] User verified successfully, user_id: ${t}`);let l=Q.channel?null:await OOQ(O,a,c.hostWeb),$A=Q.channel||l||"production";if(Q.verbose)z.info(`[Verbose] Target channel: ${$A}`);let o=await cI(a,O);if(Q.verbose)z.info(`[Verbose] Organization ID: ${o}`);if(await CXA(a,o,fE.version),Q.verbose)z.info("[Verbose] Remote CLI messages checked");if(await WXA(a,o,W,O,!0),Q.verbose)z.info("[Verbose] Plan validation passed");if(Q.verbose)z.info("[Verbose] Trial check completed");if(Q.verbose)z.info(`[Verbose] Checking compatibility with channel ${$A}...`);let{nativePackages:HA,minUpdateVersion:zA,incompatibleCount:jA,compatibility:s}=await qOQ(a,E,Q,$A,O,R,o),_=s.result==="incompatible";if(_&&!B){let bA=await I1(O)!==null,HQ=await lRA({incompatible:_,interactive:M,hasCredentials:bA,appId:O,orgId:o,apikey:W,incompatibleCount:jA});if(HQ!=="continue")return{success:!0,skipped:!0,reason:"NATIVE_BUILD",builderAction:HQ,bundle:R,checksum:null,encryptionMethod:j,storageProvider:S}}if(Q.verbose)z.info("[Verbose] Compatibility check completed:"),z.info(` - Native packages: ${HA?HA.length:0}`),z.info(` - Min update version: ${zA||"none"}`);if(Q.verbose)z.info(`[Verbose] Checking if version ${R} already exists...`);let P=await ZOQ(a,O,R,Q.versionExistsOk,M);if(Q.verbose)z.info(`[Verbose] Version exists check: ${P?typeof P==="string"?`retry with ${P}`:"yes (skipping)":"no (continuing)"}`);if(P===!0)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:R,checksum:null,encryptionMethod:j,storageProvider:S};if(typeof P==="string")return z.info(`Retrying upload with new version: ${P}`),X3(A,{...Q,bundle:P},B);if(Q.external&&!Q.external.startsWith("https://"))q0(`External link should should start with "https://" current is "${Q.external}"`);if(Q.deleteLinkedBundleOnUpload)z.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),z.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let v={name:R,app_id:O,session_key:void 0,external_url:Q.external,storage_provider:S,min_update_version:zA,native_packages:HA,owner_org:o,user_id:t,checksum:void 0,link:Q.link||null,comment:Q.comment||null,key_id:void 0,cli_version:fE.version},EA=null,r="";if(!Q.external){if(Q.verbose)z.info(`[Verbose] Preparing bundle file from path: ${T}`);let bA=q.config?.plugins?.CapacitorUpdater?.publicKey,{zipped:HQ,ivSessionKey:AQ,checksum:XQ,sessionKey:NQ,encryptionMethod:$B,finalKeyData:WB,keyId:MQ}=await MOQ(T,Q,W,o,O,L.maxUploadLength,L.alertUploadSize,bA);if(v.session_key=AQ,v.checksum=XQ,v.key_id=MQ||void 0,I=NQ,EA=HQ,j=$B,r=WB,Q.verbose)z.info("[Verbose] Bundle prepared:"),z.info(` - Size: ${Math.floor((HQ?.byteLength??0)/1024)} KB`),z.info(` - Checksum: ${XQ}`),z.info(` - Encryption: ${$B}`),z.info(` - IV Session Key: ${AQ?"present":"none"}`),z.info(` - Key ID: ${MQ||"none"}`);if(!Q.ignoreChecksumCheck){if(Q.verbose)z.info("[Verbose] Checking for duplicate checksum...");if(await TXA(a,O,$A,XQ),Q.verbose)z.info("[Verbose] Checksum is unique")}}else{if(Q.verbose)z.info(`[Verbose] Using external URL: ${Q.external}`);if(await JB(W,{channel:"app",event:"App external",icon:"\uD83D\uDCE4",org_id:o,tracking_version:2,tags:{"app-id":O},notify:!1},Q.verbose),v.session_key=Q.ivSessionKey,v.checksum=Q.encryptedChecksum,Q.verbose)z.info("[Verbose] External bundle configured:"),z.info(` - URL: ${Q.external}`),z.info(` - IV Session Key: ${Q.ivSessionKey?"provided":"none"}`),z.info(` - Encrypted Checksum: ${Q.encryptedChecksum?"provided":"none"}`)}if(Q.zip){if(Q.tus=!1,Q.verbose)z.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!L.TUSUpload||Q.external){if(Q.tus=!1,Q.verbose)z.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if(Q.tus=Q.tus||L.TUSUploadForced,Q.verbose)z.info(`[Verbose] Upload method: ${Q.tus?"TUS (resumable)":"Standard"}`);if(!L.partialUpload||Q.external){if(Q.delta=!1,Q.verbose&&Q.external)z.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if(Q.delta=Q.delta||Q.partial||Q.deltaOnly||Q.partialOnly||L.partialUploadForced,Q.verbose)z.info(`[Verbose] Delta updates: ${Q.delta?"enabled":"disabled"}`);if(Q.encryptPartial&&j==="v1")q0("You cannot encrypt the partial update if you are not using the v2 encryption method");let BA="5.30.0",OA="6.30.0",YA="7.30.0",LA=!1;if(Q.delta&&j==="v2"&&!Q.encryptPartial){let bA=kE(yo()),HQ=await AD("@capgo/capacitor-updater",bA,Q.packageJson),AQ;try{AQ=HQ?hB(HQ):void 0}catch{AQ=void 0}if(HQ&&AQ&&PIA(AQ,hB("6.14.4"))){if(z.info(`Auto-enabling partial update encryption for updater version ${AQ} (> 6.14.4)`),Q.verbose)z.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4");Q.encryptPartial=!0}}if(Q.delta&&(Q.encryptPartial||j==="v2")){let bA=kE(yo()),HQ=await AD("@capgo/capacitor-updater",bA,Q.packageJson),AQ;try{AQ=HQ?hB(HQ):void 0}catch{AQ=void 0}if(HQ&&AQ){if(LA=!B$(AQ,BA,OA,YA),Q.verbose&&LA)z.info(`[Verbose] Using hex checksum format for updater version ${AQ}`)}}if(Q.verbose&&Q.delta)z.info("[Verbose] Preparing delta/partial update manifest...");let aA=Q.delta?await QTA(T,W,o,O,Q.encryptPartial?j:"none",r,LA):[];if(Q.verbose&&Q.delta)z.info(`[Verbose] Delta manifest prepared with ${aA.length} files`);if(Q.verbose)z.info("[Verbose] Creating version record in database...");if(await bo(a,v,"add"),Q.verbose)z.info("[Verbose] Version record created successfully");if(Q.dryUpload){if(Q.verbose)z.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!B)tQ("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,bundle:R,checksum:v.checksum??null,encryptionMethod:j,sessionKey:I?I.toString("base64"):void 0,ivSessionKey:typeof v.session_key==="string"?v.session_key:void 0,storageProvider:v.storage_provider,skipped:!0,reason:"DRY_UPLOAD"}}if(Q.tusChunkSize&&Q.tusChunkSize>L.maxChunkSize)z.error(`Chunk size ${Q.tusChunkSize} is greater than the maximum chunk size ${L.maxChunkSize}, using the maximum chunk size`),Q.tusChunkSize=L.maxChunkSize;else if(!Q.tusChunkSize)Q.tusChunkSize=L.maxChunkSize;if(Q.verbose)z.info(`[Verbose] TUS chunk size: ${Math.floor(Q.tusChunkSize/1024/1024)} MB`);if(EA&&(Y||H||D||$||G||X||F)){if(!Y||!H||!D||!$||!G||!X)q0("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(z.info("Uploading to S3"),Q.verbose)z.info("[Verbose] S3 configuration:"),z.info(` - Endpoint: ${H}`),z.info(` - Region: ${D}`),z.info(` - Bucket: ${Y}`),z.info(` - Port: ${X}`),z.info(` - SSL: ${F?"enabled":"disabled"}`);let bA=`${F?"https":"http"}://${H}${X?`:${X}`:""}`,HQ=new dP({endPoint:H,region:D,port:X,pathStyle:!0,bucket:Y,accessKey:$,secretKey:G}),AQ=`${O}-${R}`,XQ=encodeURIComponent(AQ);if(Q.verbose)z.info(`[Verbose] Uploading to S3 as: ${AQ}`);try{await HQ.putObject(AQ,Uint8Array.from(EA)),v.external_url=`${bA}/${XQ}`,v.storage_provider="external",await bo(a,v,"update")}catch(NQ){await vl(a,O,R),q0(`Cannot upload bundle to S3 ${TA(NQ)}`)}if(Q.verbose)z.info(`[Verbose] S3 upload complete, external URL: ${v.external_url}`)}else if(EA){if(!Q.partialOnly&&!Q.deltaOnly){if(Q.verbose)z.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await NOQ(W,a,O,R,o,EA,Q,Q.tusChunkSize)}else if(Q.verbose)z.info("[Verbose] Skipping full bundle upload (delta-only mode)");let bA=null;try{if(Q.dryUpload){if(Q.delta=!1,Q.verbose)z.info("[Verbose] Dry upload mode: skipping delta upload")}let HQ=v.session_key&&Q.encryptPartial&&I?{sessionKey:I,ivSessionKey:v.session_key}:void 0;if(Q.verbose&&Q.delta)z.info("[Verbose] Starting delta/partial file upload..."),z.info(` - Manifest entries: ${aA.length}`),z.info(` - Encryption: ${HQ?"enabled":"disabled"}`);if(bA=Q.delta?await BTA(W,aA,T,O,o,HQ,Q):null,Q.verbose&&bA)z.info(`[Verbose] Delta upload complete with ${bA.length} files`)}catch(HQ){if(!!(Q.partial||Q.delta||Q.partialOnly||Q.deltaOnly))throw HQ;if(z.info(`Failed to upload partial files to capgo cloud. Error: ${TA(HQ)}. This is not a critical error, the bundle has been uploaded without the partial files`),Q.verbose)z.info(`[Verbose] Delta upload error details: ${TA(HQ)}`)}if(v.storage_provider="r2",v.manifest=bA,Q.verbose)z.info("[Verbose] Updating version record with storage provider and manifest...");if(await bo(a,v,"update"),Q.verbose)z.info("[Verbose] Version record updated successfully")}if(Q.verbose)z.info("[Verbose] Checking app permissions...");let kA=await dI(a,W,O,2,!1,!0);if(Q.verbose)z.info("[Verbose] Permissions:"),z.info(` - Upload: ${LC(kA,2)?"yes":"no"}`),z.info(` - Write: ${LC(kA,3)?"yes":"no"}`),z.info(` - Admin: ${LC(kA,4)?"yes":"no"}`);let $Q=Q.deleteLinkedBundleOnUpload&&LC(kA,3),PQ=$Q?await wOQ(a,O,$A):null;if(Q.deleteLinkedBundleOnUpload&&!$Q)z.warn("Cannot delete linked bundle on upload as a upload organization member");let SA=!1;if(LC(kA,3)){if(Q.verbose)z.info(`[Verbose] Setting bundle ${R} to channel ${$A}...`);if(SA=await LOQ(a,W,!!Q.bundleUrl,R,$A,t,o,O,c,Q.selfAssign),Q.verbose)z.info("[Verbose] Channel updated successfully");if($Q){if(Q.verbose)z.info(`[Verbose] Deleting previously linked bundle in channel ${$A}...`);await zOQ(a,PQ)}}else z.warn("Cannot set channel as a upload organization member");if(Q.verbose)z.info("[Verbose] Sending upload event...");if(await JB(W,{channel:"app",event:"App Uploaded",icon:"⏫",org_id:o,tracking_version:2,tags:{"app-id":O,bundle:R},notify:!1},Q.verbose),await JB(W,{channel:"app",event:"Bundle Uploaded",icon:"⏫",org_id:o,tracking_version:2,tags:{"app-id":O,bundle:R},notify:!1,notifyConsole:!0}).catch(()=>{}),s?.result==="incompatible")BB({channel:"bundle",event:"Bundle Incompatible",icon:"\uD83D\uDEAB",apikey:W,appId:O,orgId:o,tags:{source:"upload",channel:$A,channel_overwritten:SA,version_new_name:R,...s.versionOldId?{version_old_id:s.versionOldId}:{},...s.versionOldName?{version_old_name:s.versionOldName}:{}}});let eA={success:!0,bundle:R,checksum:v.checksum??null,encryptionMethod:j,sessionKey:I?I.toString("base64"):void 0,ivSessionKey:typeof v.session_key==="string"?v.session_key:void 0,storageProvider:v.storage_provider};if(Q.verbose)z.info("[Verbose] Upload completed successfully:"),z.info(` - Bundle: ${eA.bundle}`),z.info(` - Checksum: ${eA.checksum}`),z.info(` - Encryption: ${eA.encryptionMethod}`),z.info(` - Storage: ${eA.storageProvider}`);if(M&&!eA.skipped){let bA=Q.showReplicationProgress;if(bA===void 0)bA=await qo({preferenceKey:"uploadShowReplicationProgress",message:"Show Capgo global replication progress for this upload so you can confirm rollout in all regions?",initialValue:!1,rememberMessage:"Remember this replication progress preference for future uploads on this machine?"});if(bA)await sP({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:M})}if(!B&&!eA.skipped)tQ("Time to share your update to the world \uD83C\uDF0D");return eA}function ROQ(A){let Q=A.key===!1,B=A.forceCrc32Checksum===!0,I=A.keyV2||A.keyDataV2||wN(e4);if(A.ivSessionKey&&!A.external)q0("You need to provide an external url if you want to use the --iv-session-key option");if(A.encryptedChecksum&&!A.external)q0("You need to provide an external url if you want to use the --encrypted-checksum option");if((A.partial||A.delta||A.partialOnly||A.deltaOnly)&&A.external)q0("You cannot use the --partial/--delta/--partial-only/--delta-only option with an external url");if(A.tus&&A.external)q0("You cannot use the --tus option with an external url");if(A.dryUpload&&A.external)q0("You cannot use the --dry-upload option with an external url");if(A.multipart&&A.external)q0("You cannot use the --multipart option with an external url");if(A.external&&(A.keyV2||A.keyDataV2))q0("You cannot set a key if you are uploading to an external url");if(A.keyV2&&A.keyDataV2)q0("You cannot set both key-v2 and key-data-v2");if(A.external&&(A.s3Region||A.s3Apikey||A.s3Apisecret||A.s3Endpoint||A.s3BucketName||A.s3Port||A.s3SSL))q0("You cannot set S3 options if you are uploading to an external url, it's automatically handled");if(A.encryptedChecksum&&!A.external)q0("You cannot set the --encrypted-checksum option if you are not uploading to an external url");if(A.minUpdateVersion&&A.autoMinUpdateVersion)q0("You cannot set both min-update-version and auto-min-update-version, use only one of them");if(B&&I&&!Q)q0("You cannot use --force-crc32-checksum when encryption is enabled. Remove the flag or disable encryption.")}async function VOQ(){if(!wC())return;let A=J3();if(G3(A.repository)||!A.ghInstalled||!A.ghLoggedIn||!A.repositoryExists||A.starred)return;if(!await qo({preferenceKey:"uploadStarCapgoRepo",message:`Would you like to star ${A.repository} on GitHub to support Capgo?`,rememberMessage:"Remember this GitHub support preference for future uploads on this machine?"}))return;try{let B=fJ(A.repository);if(B.alreadyStarred)z.info(`\uD83E\uDEF6 ${B.repository} is already starred`);else z.success(`\uD83D\uDE4F Thanks for starring ${B.repository} \uD83C\uDF89`)}catch(B){z.warn(`Cannot star ${A.repository} right now: ${TA(B)}`)}}async function E_(A,Q){try{ROQ(Q);let B=await X3(A,Q);if(!B.skipped)await VOQ();return B}catch(B){let I=B instanceof Error?B.message:String(B),E=TA(B);if(Q.verbose)z.error(`uploadBundle failed:${E}`);else z.error(`uploadBundle failed: ${I}`);let D=I.includes("Cannot upload the same bundle content"),$=wC();if(!Q.versionExistsOk&&$)try{if(D){let G=await O1({message:"Would you like to retry the upload?",options:[{value:"ignore",label:"Retry with --ignore-checksum-check (force upload same content)"},{value:"cancel",label:"Cancel upload"}]});if(lB(G)||G==="cancel")throw B instanceof Error?B:Error(String(B));if(G==="ignore")return z.info("\uD83D\uDD04 Retrying upload with --ignore-checksum-check..."),E_(A,{...Q,ignoreChecksumCheck:!0})}else{let G=await LI({message:"Would you like to retry the upload?"});if(lB(G))throw B instanceof Error?B:Error(String(B));if(G)return z.info("\uD83D\uDD04 Retrying upload..."),E_(A,Q)}}catch{throw B instanceof Error?B:Error(String(B))}throw B instanceof Error?B:Error(String(B))}}async function ITA(A,Q){let B=await E_(A,Q);if(!B?.builderAction)return;if(B.builderAction==="launch-onboarding")await eF({apikey:Q.apikey});else await Kj(A??"",{apikey:Q.apikey,supaHost:Q.supaHost,supaAnon:Q.supaAnon})}RB();c$();kI();n1();Eq();HB();import{randomUUID as TOQ}from"node:crypto";import{existsSync as SOQ,writeFileSync as jOQ}from"node:fs";import{cwd as POQ}from"node:process";var _OQ=20;function kOQ(A){console.log(JSON.stringify(A,null,2))}function zN(A){console.error(TA(A))}async function fo(A,Q,B=!1){let{json:I}=Q,{bundle:E,path:D}=Q,$=!I&&!B;try{if($)await b0();let G=await rQ(),Y=gB(A,G?.config),H=TOQ().split("-")[0],X=t$("",Q.packageJson);if(E=E||X||`0.0.1-beta.local-${H}`,$)sQ(`Zipping ${Y}@${E}`);if(E&&!MC.test(E)){let c=`Your bundle name ${E}, is not valid it should follow semver convention : https://semver.org/`;if(!B)if(I)zN({error:"invalid_semver"});else z.error(c);throw Error("Invalid bundle version format")}if(D=D||G?.config?.webDir,!Y||!E||!D){if(!B)if(I)zN({error:"missing_argument"});else z.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project");throw Error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project")}if($)z.info(`Started from path "${D}"`);if(typeof Q.codeCheck>"u"?!0:Q.codeCheck){if(!WN(D,"notifyAppReady")){if(!B)if(I)zN({error:"notifyAppReady_not_in_source_code"});else z.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready");throw Error("notifyAppReady() is missing in build folder")}if(!tP(D)){if(!B)if(I)zN({error:"index_html_not_found"});else z.error(`index.html is missing in the root folder of ${D}`);throw Error("index.html is missing in root folder")}}let W=await HT(D);if($)z.info(`Zipped ${W.byteLength} bytes`);let q=$?hI():null;if(q)q.start("Calculating checksum");let Z=kE(POQ()),M=await AD("@capgo/capacitor-updater",Z,Q.packageJson);if(!M){if(!B)z.warn("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");throw Error("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager")}let L=!1,O;try{O=M?hB(M):void 0}catch{O=void 0}if(O)L=!B$(O,void 0,void 0,"7.0.0");else if(M==="link:@capgo/capacitor-updater"){if(!B)z.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let T=await n9(W,Q.keyV2||SOQ(e4)||L?"sha256":"crc32");if(q)q.stop(`Checksum ${L?"SHA256":"CRC32"}: ${T}`);let R=Math.floor(W.byteLength/1024/1024);if(R>_OQ&&$)z.warn(`WARNING !!
827
+ Bundle uploaded \uD83D\uDCAA in 0 seconds`),$.verbose)z.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let q=await n4();if($.verbose)z.info("[Verbose] Local config retrieved for upload");if($.multipart!==void 0&&$.multipart||$.tus!==void 0&&$.tus){if($.multipart)z.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else z.info("Uploading bundle with TUS protocol");if($.verbose)z.info("[Verbose] Starting TUS resumable upload..."),z.info(` - Host: ${q.hostWeb}`),z.info(` - Chunk size: ${Math.floor(G/1024/1024)} MB`);if(await zXA(A,D,E,B,I,Y,q,G),X=!0,$.verbose)z.info("[Verbose] TUS upload completed, updating database with R2 path...");let Z=`orgs/${E}/apps/${B}/${I}.zip`,{error:M}=await Q.from("app_versions").update({r2_path:Z}).eq("name",I).eq("app_id",B);if(M){if(z.error(`Cannot finish TUS upload ${TA(M)}`),$.verbose)z.info(`[Verbose] Database update failed: ${TA(M)}`);throw Error("Cannot finish TUS upload")}if($.verbose)z.info(`[Verbose] Database updated with R2 path: ${Z}`)}else{if($.verbose)z.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let Z=await MXA(Q,B,I);if(!Z){if(z.error("Cannot get upload url"),$.verbose)z.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}if($.verbose)z.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),z.info(` - Timeout: ${$.timeout||Pl}ms`),z.info(" - Retry attempts: 5"),z.info(" - Content-Type: application/zip");let M=new AbortController,L=setTimeout(()=>M.abort(),$.timeout||Pl);try{let O=await fetch(Z,{method:"PUT",body:D,headers:{"Content-Type":"application/zip"},signal:M.signal});if(!O.ok)throw Error(`HTTP error! status: ${O.status}`)}finally{clearTimeout(L)}if($.verbose)z.info("[Verbose] HTTP PUT upload completed successfully")}}catch(q){let M=((performance.now()-H)/1000).toFixed(2);if(Y.error(`Failed to upload bundle ( after ${M} seconds)`),$.verbose)z.info(`[Verbose] Upload failed after ${M} seconds`),z.info(`[Verbose] Error type: ${q instanceof Error?"Error":typeof q}`);if(q instanceof Error&&q.message.includes("HTTP error"))try{let L=q.message.match(/status: (\d+)/),O=L?L[1]:"unknown";z.error(`Upload failed with status ${O}: ${q.message}`)}catch{z.error(`Upload failed: ${q.message}`)}else{if($.verbose)z.info(`[Verbose] Non-HTTP error: ${TA(q)}`);if(!$.tus)z.error(`Cannot upload bundle ( try again with --tus option) ${TA(q)}`);else z.error(`Cannot upload bundle please contact support if the issue persists ${TA(q)}`)}if($.verbose)z.info("[Verbose] Cleaning up failed version from database...");if(await vl(Q,B,I),$.verbose)z.info("[Verbose] Failed version cleaned up");throw q instanceof Error?q:Error(String(q))}let W=((performance.now()-H)/1000).toFixed(2);if(Y.stop(`Bundle uploaded \uD83D\uDCAA in (${W} seconds)`),$.verbose)z.info("[Verbose] Upload successful:"),z.info(` - Upload time: ${W} seconds`),z.info(` - Upload method: ${X?"TUS (resumable)":"Standard HTTP PUT"}`),z.info(` - Bundle size: ${Math.floor(D.byteLength/1024)} KB`),z.info("[Verbose] Sending performance event...");if(await JB(A,{channel:"performance",event:X?"TUS upload zip performance":"Upload zip performance",icon:"\uD83D\uDE84",org_id:E,tracking_version:2,tags:{"app-id":B,time:W},notify:!1},$.verbose),$.verbose)z.info("[Verbose] Performance event sent successfully")}async function wOQ(A,Q,B){let{data:I,error:E}=await A.from("channels").select("version ( id, name, deleted )").eq("app_id",Q).eq("name",B);if(E)return z.error(`Cannot delete linked bundle on upload ${TA(E)}`),null;if(I.length===0)return z.warn("No linked bundle found in the channel you are trying to upload to"),null;let D=I[0].version;if(!D)return z.warn("No linked bundle found in the channel you are trying to upload to"),null;if(D.deleted)return z.warn("The linked bundle is already deleted"),null;return D}async function zOQ(A,Q){if(!Q)return;let{error:B}=await A.from("app_versions").update({deleted:!0}).eq("id",Q.id);if(B){z.error(`Cannot delete linked bundle on upload ${TA(B)}`);return}z.info(`Linked bundle ${Q.name} deleted`)}async function LOQ(A,Q,B,I,E,D,$,G,Y,H){let{data:X}=await A.rpc("get_app_versions",{apikey:Q,name_version:I,appid:G}).single();if(!X)q0("Cannot get version id, cannot set channel");if(await OC(A,Q,"app.create_channel",{appId:G})){let{error:W,data:q}=await XT(A,{name:E,app_id:G,created_by:D,version:X,owner_org:$,...H?{allow_device_self_set:!0}:{}});if(W)q0(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${TA(W)}`);let Z=`${Y.hostWeb}/app/${G}/channel/${q.id}`;if(q?.public)z.info("Your update is now available in your public channel \uD83C\uDF89");else if(q?.id)z.info(`Link device to this bundle to try it: ${Z}`);if(B)z.info(`Bundle url: ${Z}`);return!0}return z.warn("The upload key is not allowed to set the version in the channel"),!1}async function OOQ(A,Q,B){let{error:I,data:E}=await Q.from("apps").select("default_upload_channel").eq("app_id",A).single();if(I)throw Error(`Cannot find default upload channel: ${TA(I)}. You can set it here: ${B}/app/${A}/info`);return E.default_upload_channel}async function X3(A,Q,B=!1){if(!B)sQ(`Uploading with CLI version ${fE.version}`);let I,E=KI();await b0();let{s3Region:D,s3Apikey:$,s3Apisecret:G,s3BucketName:Y,s3Endpoint:H,s3Port:X,s3SSL:F}=Q;if(Q.verbose)z.info("[Verbose] Starting upload process with options:"),z.info(` - API key: ${Q.apikey?"provided":"from saved key"}`),z.info(` - Path: ${Q.path||"from capacitor config"}`),z.info(` - Channel: ${Q.channel||"from default upload channel"}`),z.info(` - Bundle: ${Q.bundle||"auto-detected"}`),z.info(` - External: ${Q.external||"false"}`),z.info(` - Encryption: ${Q.keyV2||Q.keyDataV2?"v2":Q.key===!1?"disabled":"auto"}`),z.info(` - Upload method: ${Q.tus?"TUS":Q.zip?"ZIP":"auto"}`),z.info(` - Delta updates: ${Q.delta||Q.partial?"enabled":"disabled"}`);let W=FOQ(Q);if(Q.verbose)z.info("[Verbose] API key retrieved successfully");let q=await rQ();if(Q.verbose)z.info("[Verbose] Capacitor config loaded successfully");let Z=yRA(q?.config?.plugins?.CapacitorUpdater),M=wC({silent:B});if(Z&&Q.delta===void 0){if(M){z.info("\uD83D\uDCA1 Instant updates are enabled in your config"),z.info(" Delta updates send only changed files instead of the full bundle");let bA=await LI({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!lB(bA)&&bA){if(Q.delta=!0,Q.verbose)z.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!B){if(Q.delta!==!1){if(Q.delta=!0,Q.verbose)z.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let L=await YXA();if(Q.verbose)z.info("[Verbose] Remote file config retrieved:"),z.info(` - Max upload length: ${Math.floor(L.maxUploadLength/1024/1024)} MB`),z.info(` - Alert upload size: ${Math.floor(L.alertUploadSize/1024/1024)} MB`),z.info(` - TUS upload: ${L.TUSUpload?"enabled":"disabled"}`),z.info(` - TUS upload forced: ${L.TUSUploadForced?"yes":"no"}`),z.info(` - Partial upload: ${L.partialUpload?"enabled":"disabled"}`),z.info(` - Max chunk size: ${Math.floor(L.maxChunkSize/1024/1024)} MB`);let{appid:O,path:T}=WOQ(A,Q,q.config);if(Q.verbose)z.info(`[Verbose] App ID: ${O}, Build path: ${T}`);let R=await COQ(q.config,Q);if(Q.verbose)z.info(`[Verbose] Bundle version: ${R}`);let S=Q.external?"external":"r2-direct",j="none";if(Q.autoSetBundle){if(await zC({version:R}),Q.verbose)z.info("[Verbose] Auto-set bundle version in capacitor.config.json")}if(KOQ(Q,T),Q.verbose)z.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");z.info(`Upload ${O}@${R} started from path "${T}" to Capgo cloud`);let c=await n4();if(Q.verbose)z.info(`[Verbose] Local config loaded: host=${c.hostWeb}`);if(Q.supaHost&&Q.supaAnon){if(z.info("Using custom supabase instance from provided options"),c.supaHost=Q.supaHost,c.supaKey=Q.supaAnon,Q.verbose)z.info(`[Verbose] Custom Supabase host: ${Q.supaHost}`)}let a=await eQ(W,Q.supaHost,Q.supaAnon);if(Q.verbose)z.info("[Verbose] Supabase client created successfully");await vE(a,O,B);let t=await y0(a,W);if(Q.verbose)z.info(`[Verbose] User verified successfully, user_id: ${t}`);let l=Q.channel?null:await OOQ(O,a,c.hostWeb),$A=Q.channel||l||"production";if(Q.verbose)z.info(`[Verbose] Target channel: ${$A}`);let o=await cI(a,O);if(Q.verbose)z.info(`[Verbose] Organization ID: ${o}`);if(await CXA(a,o,fE.version),Q.verbose)z.info("[Verbose] Remote CLI messages checked");if(await WXA(a,o,W,O,!0),Q.verbose)z.info("[Verbose] Plan validation passed");if(Q.verbose)z.info("[Verbose] Trial check completed");if(Q.verbose)z.info(`[Verbose] Checking compatibility with channel ${$A}...`);let{nativePackages:HA,minUpdateVersion:zA,incompatibleCount:jA,compatibility:s}=await qOQ(a,E,Q,$A,O,R,o),_=s.result==="incompatible";if(_&&!B){let bA=await I1(O)!==null,HQ=await lRA({incompatible:_,interactive:M,hasCredentials:bA,appId:O,orgId:o,apikey:W,incompatibleCount:jA});if(HQ!=="continue")return{success:!0,skipped:!0,reason:"NATIVE_BUILD",builderAction:HQ,bundle:R,checksum:null,encryptionMethod:j,storageProvider:S}}if(Q.verbose)z.info("[Verbose] Compatibility check completed:"),z.info(` - Native packages: ${HA?HA.length:0}`),z.info(` - Min update version: ${zA||"none"}`);if(Q.verbose)z.info(`[Verbose] Checking if version ${R} already exists...`);let P=await ZOQ(a,O,R,Q.versionExistsOk,M);if(Q.verbose)z.info(`[Verbose] Version exists check: ${P?typeof P==="string"?`retry with ${P}`:"yes (skipping)":"no (continuing)"}`);if(P===!0)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:R,checksum:null,encryptionMethod:j,storageProvider:S};if(typeof P==="string")return z.info(`Retrying upload with new version: ${P}`),X3(A,{...Q,bundle:P},B);if(Q.external&&!Q.external.startsWith("https://"))q0(`External link should should start with "https://" current is "${Q.external}"`);if(Q.deleteLinkedBundleOnUpload)z.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),z.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let v={name:R,app_id:O,session_key:void 0,external_url:Q.external,storage_provider:S,min_update_version:zA,native_packages:HA,owner_org:o,user_id:t,checksum:void 0,link:Q.link||null,comment:Q.comment||null,key_id:void 0,cli_version:fE.version},EA=null,r="";if(!Q.external){if(Q.verbose)z.info(`[Verbose] Preparing bundle file from path: ${T}`);let bA=q.config?.plugins?.CapacitorUpdater?.publicKey,{zipped:HQ,ivSessionKey:AQ,checksum:XQ,sessionKey:NQ,encryptionMethod:$B,finalKeyData:WB,keyId:MQ}=await MOQ(T,Q,W,o,O,L.maxUploadLength,L.alertUploadSize,bA);if(v.session_key=AQ,v.checksum=XQ,v.key_id=MQ||void 0,I=NQ,EA=HQ,j=$B,r=WB,Q.verbose)z.info("[Verbose] Bundle prepared:"),z.info(` - Size: ${Math.floor((HQ?.byteLength??0)/1024)} KB`),z.info(` - Checksum: ${XQ}`),z.info(` - Encryption: ${$B}`),z.info(` - IV Session Key: ${AQ?"present":"none"}`),z.info(` - Key ID: ${MQ||"none"}`);if(!Q.ignoreChecksumCheck){if(Q.verbose)z.info("[Verbose] Checking for duplicate checksum...");if(await TXA(a,O,$A,XQ),Q.verbose)z.info("[Verbose] Checksum is unique")}}else{if(Q.verbose)z.info(`[Verbose] Using external URL: ${Q.external}`);if(await JB(W,{channel:"app",event:"App external",icon:"\uD83D\uDCE4",org_id:o,tracking_version:2,tags:{"app-id":O},notify:!1},Q.verbose),v.session_key=Q.ivSessionKey,v.checksum=Q.encryptedChecksum,Q.verbose)z.info("[Verbose] External bundle configured:"),z.info(` - URL: ${Q.external}`),z.info(` - IV Session Key: ${Q.ivSessionKey?"provided":"none"}`),z.info(` - Encrypted Checksum: ${Q.encryptedChecksum?"provided":"none"}`)}if(Q.zip){if(Q.tus=!1,Q.verbose)z.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!L.TUSUpload||Q.external){if(Q.tus=!1,Q.verbose)z.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if(Q.tus=Q.tus||L.TUSUploadForced,Q.verbose)z.info(`[Verbose] Upload method: ${Q.tus?"TUS (resumable)":"Standard"}`);if(!L.partialUpload||Q.external){if(Q.delta=!1,Q.verbose&&Q.external)z.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if(Q.delta=Q.delta||Q.partial||Q.deltaOnly||Q.partialOnly||L.partialUploadForced,Q.verbose)z.info(`[Verbose] Delta updates: ${Q.delta?"enabled":"disabled"}`);if(Q.encryptPartial&&j==="v1")q0("You cannot encrypt the partial update if you are not using the v2 encryption method");let BA="5.30.0",OA="6.30.0",YA="7.30.0",LA=!1;if(Q.delta&&j==="v2"&&!Q.encryptPartial){let bA=kE(yo()),HQ=await AD("@capgo/capacitor-updater",bA,Q.packageJson),AQ;try{AQ=HQ?hB(HQ):void 0}catch{AQ=void 0}if(HQ&&AQ&&PIA(AQ,hB("6.14.4"))){if(z.info(`Auto-enabling partial update encryption for updater version ${AQ} (> 6.14.4)`),Q.verbose)z.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4");Q.encryptPartial=!0}}if(Q.delta&&(Q.encryptPartial||j==="v2")){let bA=kE(yo()),HQ=await AD("@capgo/capacitor-updater",bA,Q.packageJson),AQ;try{AQ=HQ?hB(HQ):void 0}catch{AQ=void 0}if(HQ&&AQ){if(LA=!B$(AQ,BA,OA,YA),Q.verbose&&LA)z.info(`[Verbose] Using hex checksum format for updater version ${AQ}`)}}if(Q.verbose&&Q.delta)z.info("[Verbose] Preparing delta/partial update manifest...");let aA=Q.delta?await QTA(T,W,o,O,Q.encryptPartial?j:"none",r,LA):[];if(Q.verbose&&Q.delta)z.info(`[Verbose] Delta manifest prepared with ${aA.length} files`);if(Q.verbose)z.info("[Verbose] Creating version record in database...");if(await bo(a,v,"add"),Q.verbose)z.info("[Verbose] Version record created successfully");if(Q.dryUpload){if(Q.verbose)z.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!B)tQ("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,bundle:R,checksum:v.checksum??null,encryptionMethod:j,sessionKey:I?I.toString("base64"):void 0,ivSessionKey:typeof v.session_key==="string"?v.session_key:void 0,storageProvider:v.storage_provider,skipped:!0,reason:"DRY_UPLOAD"}}if(Q.tusChunkSize&&Q.tusChunkSize>L.maxChunkSize)z.error(`Chunk size ${Q.tusChunkSize} is greater than the maximum chunk size ${L.maxChunkSize}, using the maximum chunk size`),Q.tusChunkSize=L.maxChunkSize;else if(!Q.tusChunkSize)Q.tusChunkSize=L.maxChunkSize;if(Q.verbose)z.info(`[Verbose] TUS chunk size: ${Math.floor(Q.tusChunkSize/1024/1024)} MB`);if(EA&&(Y||H||D||$||G||X||F)){if(!Y||!H||!D||!$||!G||!X)q0("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(z.info("Uploading to S3"),Q.verbose)z.info("[Verbose] S3 configuration:"),z.info(` - Endpoint: ${H}`),z.info(` - Region: ${D}`),z.info(` - Bucket: ${Y}`),z.info(` - Port: ${X}`),z.info(` - SSL: ${F?"enabled":"disabled"}`);let bA=`${F?"https":"http"}://${H}${X?`:${X}`:""}`,HQ=new dP({endPoint:H,region:D,port:X,pathStyle:!0,bucket:Y,accessKey:$,secretKey:G}),AQ=`${O}-${R}`,XQ=encodeURIComponent(AQ);if(Q.verbose)z.info(`[Verbose] Uploading to S3 as: ${AQ}`);try{await HQ.putObject(AQ,Uint8Array.from(EA)),v.external_url=`${bA}/${XQ}`,v.storage_provider="external",await bo(a,v,"update")}catch(NQ){await vl(a,O,R),q0(`Cannot upload bundle to S3 ${TA(NQ)}`)}if(Q.verbose)z.info(`[Verbose] S3 upload complete, external URL: ${v.external_url}`)}else if(EA){if(!Q.partialOnly&&!Q.deltaOnly){if(Q.verbose)z.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await NOQ(W,a,O,R,o,EA,Q,Q.tusChunkSize)}else if(Q.verbose)z.info("[Verbose] Skipping full bundle upload (delta-only mode)");let bA=null;try{if(Q.dryUpload){if(Q.delta=!1,Q.verbose)z.info("[Verbose] Dry upload mode: skipping delta upload")}let HQ=v.session_key&&Q.encryptPartial&&I?{sessionKey:I,ivSessionKey:v.session_key}:void 0;if(Q.verbose&&Q.delta)z.info("[Verbose] Starting delta/partial file upload..."),z.info(` - Manifest entries: ${aA.length}`),z.info(` - Encryption: ${HQ?"enabled":"disabled"}`);if(bA=Q.delta?await BTA(W,aA,T,O,o,HQ,Q):null,Q.verbose&&bA)z.info(`[Verbose] Delta upload complete with ${bA.length} files`)}catch(HQ){if(!!(Q.partial||Q.delta||Q.partialOnly||Q.deltaOnly))throw HQ;if(z.info(`Failed to upload partial files to capgo cloud. Error: ${TA(HQ)}. This is not a critical error, the bundle has been uploaded without the partial files`),Q.verbose)z.info(`[Verbose] Delta upload error details: ${TA(HQ)}`)}if(v.storage_provider="r2",v.manifest=bA,Q.verbose)z.info("[Verbose] Updating version record with storage provider and manifest...");if(await bo(a,v,"update"),Q.verbose)z.info("[Verbose] Version record updated successfully")}if(Q.verbose)z.info("[Verbose] Checking app permissions...");let kA=await dI(a,W,O,2,!1,!0);if(Q.verbose)z.info("[Verbose] Permissions:"),z.info(` - Upload: ${LC(kA,2)?"yes":"no"}`),z.info(` - Write: ${LC(kA,3)?"yes":"no"}`),z.info(` - Admin: ${LC(kA,4)?"yes":"no"}`);let $Q=Q.deleteLinkedBundleOnUpload&&LC(kA,3),PQ=$Q?await wOQ(a,O,$A):null;if(Q.deleteLinkedBundleOnUpload&&!$Q)z.warn("Cannot delete linked bundle on upload as a upload organization member");let SA=!1;if(LC(kA,3)){if(Q.verbose)z.info(`[Verbose] Setting bundle ${R} to channel ${$A}...`);if(SA=await LOQ(a,W,!!Q.bundleUrl,R,$A,t,o,O,c,Q.selfAssign),Q.verbose)z.info("[Verbose] Channel updated successfully");if($Q){if(Q.verbose)z.info(`[Verbose] Deleting previously linked bundle in channel ${$A}...`);await zOQ(a,PQ)}}else z.warn("Cannot set channel as a upload organization member");if(Q.verbose)z.info("[Verbose] Sending upload event...");if(await JB(W,{channel:"app",event:"App Uploaded",icon:"⏫",org_id:o,tracking_version:2,tags:{"app-id":O,bundle:R},notify:!1},Q.verbose),await JB(W,{channel:"app",event:"Bundle Uploaded",icon:"⏫",org_id:o,tracking_version:2,tags:{"app-id":O,bundle:R},notify:!1,notifyConsole:!0}).catch(()=>{}),s?.result==="incompatible")BB({channel:"bundle",event:"Bundle Incompatible",icon:"\uD83D\uDEAB",apikey:W,appId:O,orgId:o,tags:{source:"upload",channel:$A,channel_name:$A,channel_overwritten:SA,version_new_name:R,...s.versionOldId?{version_old_id:s.versionOldId}:{},...s.versionOldName?{version_old_name:s.versionOldName}:{}}});let eA={success:!0,bundle:R,checksum:v.checksum??null,encryptionMethod:j,sessionKey:I?I.toString("base64"):void 0,ivSessionKey:typeof v.session_key==="string"?v.session_key:void 0,storageProvider:v.storage_provider};if(Q.verbose)z.info("[Verbose] Upload completed successfully:"),z.info(` - Bundle: ${eA.bundle}`),z.info(` - Checksum: ${eA.checksum}`),z.info(` - Encryption: ${eA.encryptionMethod}`),z.info(` - Storage: ${eA.storageProvider}`);if(M&&!eA.skipped){let bA=Q.showReplicationProgress;if(bA===void 0)bA=await qo({preferenceKey:"uploadShowReplicationProgress",message:"Show Capgo global replication progress for this upload so you can confirm rollout in all regions?",initialValue:!1,rememberMessage:"Remember this replication progress preference for future uploads on this machine?"});if(bA)await sP({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:M})}if(!B&&!eA.skipped)tQ("Time to share your update to the world \uD83C\uDF0D");return eA}function ROQ(A){let Q=A.key===!1,B=A.forceCrc32Checksum===!0,I=A.keyV2||A.keyDataV2||wN(e4);if(A.ivSessionKey&&!A.external)q0("You need to provide an external url if you want to use the --iv-session-key option");if(A.encryptedChecksum&&!A.external)q0("You need to provide an external url if you want to use the --encrypted-checksum option");if((A.partial||A.delta||A.partialOnly||A.deltaOnly)&&A.external)q0("You cannot use the --partial/--delta/--partial-only/--delta-only option with an external url");if(A.tus&&A.external)q0("You cannot use the --tus option with an external url");if(A.dryUpload&&A.external)q0("You cannot use the --dry-upload option with an external url");if(A.multipart&&A.external)q0("You cannot use the --multipart option with an external url");if(A.external&&(A.keyV2||A.keyDataV2))q0("You cannot set a key if you are uploading to an external url");if(A.keyV2&&A.keyDataV2)q0("You cannot set both key-v2 and key-data-v2");if(A.external&&(A.s3Region||A.s3Apikey||A.s3Apisecret||A.s3Endpoint||A.s3BucketName||A.s3Port||A.s3SSL))q0("You cannot set S3 options if you are uploading to an external url, it's automatically handled");if(A.encryptedChecksum&&!A.external)q0("You cannot set the --encrypted-checksum option if you are not uploading to an external url");if(A.minUpdateVersion&&A.autoMinUpdateVersion)q0("You cannot set both min-update-version and auto-min-update-version, use only one of them");if(B&&I&&!Q)q0("You cannot use --force-crc32-checksum when encryption is enabled. Remove the flag or disable encryption.")}async function VOQ(){if(!wC())return;let A=J3();if(G3(A.repository)||!A.ghInstalled||!A.ghLoggedIn||!A.repositoryExists||A.starred)return;if(!await qo({preferenceKey:"uploadStarCapgoRepo",message:`Would you like to star ${A.repository} on GitHub to support Capgo?`,rememberMessage:"Remember this GitHub support preference for future uploads on this machine?"}))return;try{let B=fJ(A.repository);if(B.alreadyStarred)z.info(`\uD83E\uDEF6 ${B.repository} is already starred`);else z.success(`\uD83D\uDE4F Thanks for starring ${B.repository} \uD83C\uDF89`)}catch(B){z.warn(`Cannot star ${A.repository} right now: ${TA(B)}`)}}async function E_(A,Q){try{ROQ(Q);let B=await X3(A,Q);if(!B.skipped)await VOQ();return B}catch(B){let I=B instanceof Error?B.message:String(B),E=TA(B);if(Q.verbose)z.error(`uploadBundle failed:${E}`);else z.error(`uploadBundle failed: ${I}`);let D=I.includes("Cannot upload the same bundle content"),$=wC();if(!Q.versionExistsOk&&$)try{if(D){let G=await O1({message:"Would you like to retry the upload?",options:[{value:"ignore",label:"Retry with --ignore-checksum-check (force upload same content)"},{value:"cancel",label:"Cancel upload"}]});if(lB(G)||G==="cancel")throw B instanceof Error?B:Error(String(B));if(G==="ignore")return z.info("\uD83D\uDD04 Retrying upload with --ignore-checksum-check..."),E_(A,{...Q,ignoreChecksumCheck:!0})}else{let G=await LI({message:"Would you like to retry the upload?"});if(lB(G))throw B instanceof Error?B:Error(String(B));if(G)return z.info("\uD83D\uDD04 Retrying upload..."),E_(A,Q)}}catch{throw B instanceof Error?B:Error(String(B))}throw B instanceof Error?B:Error(String(B))}}async function ITA(A,Q){let B=await E_(A,Q);if(!B?.builderAction)return;if(B.builderAction==="launch-onboarding")await eF({apikey:Q.apikey});else await Kj(A??"",{apikey:Q.apikey,supaHost:Q.supaHost,supaAnon:Q.supaAnon})}RB();c$();kI();n1();Eq();HB();import{randomUUID as TOQ}from"node:crypto";import{existsSync as SOQ,writeFileSync as jOQ}from"node:fs";import{cwd as POQ}from"node:process";var _OQ=20;function kOQ(A){console.log(JSON.stringify(A,null,2))}function zN(A){console.error(TA(A))}async function fo(A,Q,B=!1){let{json:I}=Q,{bundle:E,path:D}=Q,$=!I&&!B;try{if($)await b0();let G=await rQ(),Y=gB(A,G?.config),H=TOQ().split("-")[0],X=t$("",Q.packageJson);if(E=E||X||`0.0.1-beta.local-${H}`,$)sQ(`Zipping ${Y}@${E}`);if(E&&!MC.test(E)){let c=`Your bundle name ${E}, is not valid it should follow semver convention : https://semver.org/`;if(!B)if(I)zN({error:"invalid_semver"});else z.error(c);throw Error("Invalid bundle version format")}if(D=D||G?.config?.webDir,!Y||!E||!D){if(!B)if(I)zN({error:"missing_argument"});else z.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project");throw Error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project")}if($)z.info(`Started from path "${D}"`);if(typeof Q.codeCheck>"u"?!0:Q.codeCheck){if(!WN(D,"notifyAppReady")){if(!B)if(I)zN({error:"notifyAppReady_not_in_source_code"});else z.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready");throw Error("notifyAppReady() is missing in build folder")}if(!tP(D)){if(!B)if(I)zN({error:"index_html_not_found"});else z.error(`index.html is missing in the root folder of ${D}`);throw Error("index.html is missing in root folder")}}let W=await HT(D);if($)z.info(`Zipped ${W.byteLength} bytes`);let q=$?hI():null;if(q)q.start("Calculating checksum");let Z=kE(POQ()),M=await AD("@capgo/capacitor-updater",Z,Q.packageJson);if(!M){if(!B)z.warn("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");throw Error("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager")}let L=!1,O;try{O=M?hB(M):void 0}catch{O=void 0}if(O)L=!B$(O,void 0,void 0,"7.0.0");else if(M==="link:@capgo/capacitor-updater"){if(!B)z.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let T=await n9(W,Q.keyV2||SOQ(e4)||L?"sha256":"crc32");if(q)q.stop(`Checksum ${L?"SHA256":"CRC32"}: ${T}`);let R=Math.floor(W.byteLength/1024/1024);if(R>_OQ&&$)z.warn(`WARNING !!
828
828
  The bundle size is ${R} Mb, this may take a while to download for users
829
829
  `),z.warn(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
830
830
  `);let S=$?hI():null,j=Q.name||`${Y}_${E}.zip`;if(S)S.start(`Saving to ${j}`);if(jOQ(j,W),S)S.stop(`Saved to ${j}`);if(BB({channel:"bundle",event:"Bundle Zipped",icon:"\uD83D\uDDDC️",tags:{zip_size_bytes:W.byteLength}}),$)tQ("Done ✅");if(!B&&I)kOQ({bundle:E,filename:j,checksum:T});return{bundle:E,filename:j,checksum:T}}catch(G){if(!B)if(I)zN(G);else z.error(TA(G));throw G instanceof Error?G:Error(String(G))}}async function ETA(A,Q){await fo(A,Q,!1)}RB();HB();async function LN(A,Q,B,I=!1){if(!I)sQ("Create channel");B.apikey=B.apikey||vQ();let E=await rQ(I).catch(()=>{return});if(Q=gB(Q,E?.config),!B.apikey){if(!I)z.error("Missing API key, you need to provide an API key to upload your bundle");throw Error("Missing API key")}if(!Q){if(!I)z.error("Missing argument, you need to provide a appId, or be in a capacitor project");throw Error("Missing appId")}let D=await eQ(B.apikey,B.supaHost,B.supaAnon,I);if(await vE(D,Q,I),await y0(D,B.apikey),await dI(D,B.apikey,Q,4,I,!0),!I)z.info(`Creating channel ${Q}#${A} to Capgo`);let $=await cI(D,Q),G=await y0(D,B.apikey),Y=await pOA(D,{name:A,app_id:Q,version:null,created_by:G,owner_org:$,allow_device_self_set:B.selfAssign??!1,public:B.default??!1});if(Y.error){if(!I)z.error(`Cannot create Channel \uD83D\uDE40
package/dist/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capgo/cli",
3
3
  "type": "module",
4
- "version": "7.119.2",
4
+ "version": "7.120.0",
5
5
  "description": "A CLI to upload to capgo servers",
6
6
  "author": "Martin martin@capgo.app",
7
7
  "license": "Apache 2.0",
package/dist/src/sdk.js CHANGED
@@ -124,7 +124,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
124
124
  `)}),$.__defineSetter__("stack",function(X){return[X].concat($.stack).join(`
125
125
 
126
126
  `)}),$}});var Av=E((da0,Iv)=>{var z4=l("constants"),Vq0=process.cwd,AF=null,Lq0=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!AF)AF=Vq0.call(process);return AF};try{process.cwd()}catch(D){}if(typeof process.chdir==="function"){if(EF=process.chdir,process.chdir=function(D){AF=null,EF.call(process,D)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,EF)}var EF;Iv.exports=Mq0;function Mq0(D){if(z4.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))$(D);if(!D.lutimes)X(D);if(D.chown=F(D.chown),D.fchown=F(D.fchown),D.lchown=F(D.lchown),D.chmod=J(D.chmod),D.fchmod=J(D.fchmod),D.lchmod=J(D.lchmod),D.chownSync=Q(D.chownSync),D.fchownSync=Q(D.fchownSync),D.lchownSync=Q(D.lchownSync),D.chmodSync=Y(D.chmodSync),D.fchmodSync=Y(D.fchmodSync),D.lchmodSync=Y(D.lchmodSync),D.stat=U(D.stat),D.fstat=U(D.fstat),D.lstat=U(D.lstat),D.statSync=Z(D.statSync),D.fstatSync=Z(D.fstatSync),D.lstatSync=Z(D.lstatSync),D.chmod&&!D.lchmod)D.lchmod=function(G,w,q){if(q)process.nextTick(q)},D.lchmodSync=function(){};if(D.chown&&!D.lchown)D.lchown=function(G,w,q,W){if(W)process.nextTick(W)},D.lchownSync=function(){};if(Lq0==="win32")D.rename=typeof D.rename!=="function"?D.rename:function(G){function w(q,W,K){var H=Date.now(),L=0;G(q,W,function M(I){if(I&&(I.code==="EACCES"||I.code==="EPERM"||I.code==="EBUSY")&&Date.now()-H<60000){if(setTimeout(function(){D.stat(W,function(B,N){if(B&&B.code==="ENOENT")G(q,W,M);else K(I)})},L),L<100)L+=10;return}if(K)K(I)})}if(Object.setPrototypeOf)Object.setPrototypeOf(w,G);return w}(D.rename);D.read=typeof D.read!=="function"?D.read:function(G){function w(q,W,K,H,L,M){var I;if(M&&typeof M==="function"){var B=0;I=function(N,z,R){if(N&&N.code==="EAGAIN"&&B<10)return B++,G.call(D,q,W,K,H,L,I);M.apply(this,arguments)}}return G.call(D,q,W,K,H,L,I)}if(Object.setPrototypeOf)Object.setPrototypeOf(w,G);return w}(D.read),D.readSync=typeof D.readSync!=="function"?D.readSync:function(G){return function(w,q,W,K,H){var L=0;while(!0)try{return G.call(D,w,q,W,K,H)}catch(M){if(M.code==="EAGAIN"&&L<10){L++;continue}throw M}}}(D.readSync);function $(G){G.lchmod=function(w,q,W){G.open(w,z4.O_WRONLY|z4.O_SYMLINK,q,function(K,H){if(K){if(W)W(K);return}G.fchmod(H,q,function(L){G.close(H,function(M){if(W)W(L||M)})})})},G.lchmodSync=function(w,q){var W=G.openSync(w,z4.O_WRONLY|z4.O_SYMLINK,q),K=!0,H;try{H=G.fchmodSync(W,q),K=!1}finally{if(K)try{G.closeSync(W)}catch(L){}else G.closeSync(W)}return H}}function X(G){if(z4.hasOwnProperty("O_SYMLINK")&&G.futimes)G.lutimes=function(w,q,W,K){G.open(w,z4.O_SYMLINK,function(H,L){if(H){if(K)K(H);return}G.futimes(L,q,W,function(M){G.close(L,function(I){if(K)K(M||I)})})})},G.lutimesSync=function(w,q,W){var K=G.openSync(w,z4.O_SYMLINK),H,L=!0;try{H=G.futimesSync(K,q,W),L=!1}finally{if(L)try{G.closeSync(K)}catch(M){}else G.closeSync(K)}return H};else if(G.futimes)G.lutimes=function(w,q,W,K){if(K)process.nextTick(K)},G.lutimesSync=function(){}}function J(G){if(!G)return G;return function(w,q,W){return G.call(D,w,q,function(K){if(O(K))K=null;if(W)W.apply(this,arguments)})}}function Y(G){if(!G)return G;return function(w,q){try{return G.call(D,w,q)}catch(W){if(!O(W))throw W}}}function F(G){if(!G)return G;return function(w,q,W,K){return G.call(D,w,q,W,function(H){if(O(H))H=null;if(K)K.apply(this,arguments)})}}function Q(G){if(!G)return G;return function(w,q,W){try{return G.call(D,w,q,W)}catch(K){if(!O(K))throw K}}}function U(G){if(!G)return G;return function(w,q,W){if(typeof q==="function")W=q,q=null;function K(H,L){if(L){if(L.uid<0)L.uid+=4294967296;if(L.gid<0)L.gid+=4294967296}if(W)W.apply(this,arguments)}return q?G.call(D,w,q,K):G.call(D,w,K)}}function Z(G){if(!G)return G;return function(w,q){var W=q?G.call(D,w,q):G.call(D,w);if(W){if(W.uid<0)W.uid+=4294967296;if(W.gid<0)W.gid+=4294967296}return W}}function O(G){if(!G)return!0;if(G.code==="ENOSYS")return!0;var w=!process.getuid||process.getuid()!==0;if(w){if(G.code==="EINVAL"||G.code==="EPERM")return!0}return!1}}});var jv=E((na0,Rv)=>{var Ev=l("stream").Stream;Rv.exports=Iq0;function Iq0(D){return{ReadStream:$,WriteStream:X};function $(J,Y){if(!(this instanceof $))return new $(J,Y);Ev.call(this);var F=this;this.path=J,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,Y=Y||{};var Q=Object.keys(Y);for(var U=0,Z=Q.length;U<Z;U++){var O=Q[U];this[O]=Y[O]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){F._read()});return}D.open(this.path,this.flags,this.mode,function(G,w){if(G){F.emit("error",G),F.readable=!1;return}F.fd=w,F.emit("open",w),F._read()})}function X(J,Y){if(!(this instanceof X))return new X(J,Y);Ev.call(this),this.path=J,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,Y=Y||{};var F=Object.keys(Y);for(var Q=0,U=F.length;Q<U;Q++){var Z=F[Q];this[Z]=Y[Z]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=D.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var Cv=E((la0,Tv)=>{Tv.exports=Eq0;var Aq0=Object.getPrototypeOf||function(D){return D.__proto__};function Eq0(D){if(D===null||typeof D!=="object")return D;if(D instanceof Object)var $={__proto__:Aq0(D)};else var $=Object.create(null);return Object.getOwnPropertyNames(D).forEach(function(X){Object.defineProperty($,X,Object.getOwnPropertyDescriptor(D,X))}),$}});var bD=E((ia0,aq)=>{var uD=l("fs"),Rq0=Av(),jq0=jv(),Tq0=Cv(),RF=l("util"),F1,TF;if(typeof Symbol==="function"&&typeof Symbol.for==="function")F1=Symbol.for("graceful-fs.queue"),TF=Symbol.for("graceful-fs.previous");else F1="___graceful-fs.queue",TF="___graceful-fs.previous";function Cq0(){}function Pv(D,$){Object.defineProperty(D,F1,{get:function(){return $}})}var h8=Cq0;if(RF.debuglog)h8=RF.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))h8=function(){var D=RF.format.apply(RF,arguments);D="GFS4: "+D.split(/\n/).join(`
127
- GFS4: `),console.error(D)};if(!uD[F1]){if(rq=global[F1]||[],Pv(uD,rq),uD.close=function(D){function $(X,J){return D.call(uD,X,function(Y){if(!Y)Sv();if(typeof J==="function")J.apply(this,arguments)})}return Object.defineProperty($,TF,{value:D}),$}(uD.close),uD.closeSync=function(D){function $(X){D.apply(uD,arguments),Sv()}return Object.defineProperty($,TF,{value:D}),$}(uD.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){h8(uD[F1]),l("assert").equal(uD[F1].length,0)})}var rq;if(!global[F1])Pv(global,uD[F1]);aq.exports=tq(Tq0(uD));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!uD.__patched)aq.exports=tq(uD),uD.__patched=!0;function tq(D){Rq0(D),D.gracefulify=tq,D.createReadStream=z,D.createWriteStream=R;var $=D.readFile;D.readFile=X;function X(A,x,P){if(typeof x==="function")P=x,x=null;return g(A,x,P);function g(c,r,f,T){return $(c,r,function(S){if(S&&(S.code==="EMFILE"||S.code==="ENFILE"))C5([g,[c,r,f],S,T||Date.now(),Date.now()]);else if(typeof f==="function")f.apply(this,arguments)})}}var J=D.writeFile;D.writeFile=Y;function Y(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return J(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var F=D.appendFile;if(F)D.appendFile=Q;function Q(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return F(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var U=D.copyFile;if(U)D.copyFile=Z;function Z(A,x,P,g){if(typeof P==="function")g=P,P=0;return c(A,x,P,g);function c(r,f,T,S,u){return U(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var O=D.readdir;D.readdir=w;var G=/^v[0-5]\./;function w(A,x,P){if(typeof x==="function")P=x,x=null;var g=G.test(process.version)?function(f,T,S,u){return O(f,c(f,T,S,u))}:function(f,T,S,u){return O(f,T,c(f,T,S,u))};return g(A,x,P);function c(r,f,T,S){return function(u,k){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))C5([g,[r,f,T],u,S||Date.now(),Date.now()]);else{if(k&&k.sort)k.sort();if(typeof T==="function")T.call(this,u,k)}}}}if(process.version.substr(0,4)==="v0.8"){var q=jq0(D);M=q.ReadStream,B=q.WriteStream}var W=D.ReadStream;if(W)M.prototype=Object.create(W.prototype),M.prototype.open=I;var K=D.WriteStream;if(K)B.prototype=Object.create(K.prototype),B.prototype.open=N;Object.defineProperty(D,"ReadStream",{get:function(){return M},set:function(A){M=A},enumerable:!0,configurable:!0}),Object.defineProperty(D,"WriteStream",{get:function(){return B},set:function(A){B=A},enumerable:!0,configurable:!0});var H=M;Object.defineProperty(D,"FileReadStream",{get:function(){return H},set:function(A){H=A},enumerable:!0,configurable:!0});var L=B;Object.defineProperty(D,"FileWriteStream",{get:function(){return L},set:function(A){L=A},enumerable:!0,configurable:!0});function M(A,x){if(this instanceof M)return W.apply(this,arguments),this;else return M.apply(Object.create(M.prototype),arguments)}function I(){var A=this;_(A.path,A.flags,A.mode,function(x,P){if(x){if(A.autoClose)A.destroy();A.emit("error",x)}else A.fd=P,A.emit("open",P),A.read()})}function B(A,x){if(this instanceof B)return K.apply(this,arguments),this;else return B.apply(Object.create(B.prototype),arguments)}function N(){var A=this;_(A.path,A.flags,A.mode,function(x,P){if(x)A.destroy(),A.emit("error",x);else A.fd=P,A.emit("open",P)})}function z(A,x){return new D.ReadStream(A,x)}function R(A,x){return new D.WriteStream(A,x)}var v=D.open;D.open=_;function _(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return v(r,f,T,function(k,m){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}return D}function C5(D){h8("ENQUEUE",D[0].name,D[1]),uD[F1].push(D),oq()}var jF;function Sv(){var D=Date.now();for(var $=0;$<uD[F1].length;++$)if(uD[F1][$].length>2)uD[F1][$][3]=D,uD[F1][$][4]=D;oq()}function oq(){if(clearTimeout(jF),jF=void 0,uD[F1].length===0)return;var D=uD[F1].shift(),$=D[0],X=D[1],J=D[2],Y=D[3],F=D[4];if(Y===void 0)h8("RETRY",$.name,X),$.apply(null,X);else if(Date.now()-Y>=60000){h8("TIMEOUT",$.name,X);var Q=X.pop();if(typeof Q==="function")Q.call(null,J)}else{var U=Date.now()-F,Z=Math.max(F-Y,1),O=Math.min(Z*1.2,100);if(U>=O)h8("RETRY",$.name,X),$.apply(null,X.concat([Y]));else uD[F1].push(D)}if(jF===void 0)jF=setTimeout(oq,0)}});var xv=E((pa0,uv)=>{function V$(D,$){if(typeof $==="boolean")$={forever:$};if(this._originalTimeouts=JSON.parse(JSON.stringify(D)),this._timeouts=D,this._options=$||{},this._maxRetryTime=$&&$.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}uv.exports=V$;V$.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};V$.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};V$.prototype.retry=function(D){if(this._timeout)clearTimeout(this._timeout);if(!D)return!1;var $=new Date().getTime();if(D&&$-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(D);var X=this._timeouts.shift();if(X===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),X=this._timeouts.shift();else return!1;var J=this,Y=setTimeout(function(){if(J._attempts++,J._operationTimeoutCb){if(J._timeout=setTimeout(function(){J._operationTimeoutCb(J._attempts)},J._operationTimeout),J._options.unref)J._timeout.unref()}J._fn(J._attempts)},X);if(this._options.unref)Y.unref();return!0};V$.prototype.attempt=function(D,$){if(this._fn=D,$){if($.timeout)this._operationTimeout=$.timeout;if($.cb)this._operationTimeoutCb=$.cb}var X=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){X._operationTimeoutCb()},X._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};V$.prototype.try=function(D){console.log("Using RetryOperation.try() is deprecated"),this.attempt(D)};V$.prototype.start=function(D){console.log("Using RetryOperation.start() is deprecated"),this.attempt(D)};V$.prototype.start=V$.prototype.try;V$.prototype.errors=function(){return this._errors};V$.prototype.attempts=function(){return this._attempts};V$.prototype.mainError=function(){if(this._errors.length===0)return null;var D={},$=null,X=0;for(var J=0;J<this._errors.length;J++){var Y=this._errors[J],F=Y.message,Q=(D[F]||0)+1;if(D[F]=Q,Q>=X)$=Y,X=Q}return $}});var _v=E((Pq0)=>{var Sq0=xv();Pq0.operation=function(D){var $=Pq0.timeouts(D);return new Sq0($,{forever:D&&D.forever,unref:D&&D.unref,maxRetryTime:D&&D.maxRetryTime})};Pq0.timeouts=function(D){if(D instanceof Array)return[].concat(D);var $={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var X in D)$[X]=D[X];if($.minTimeout>$.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var J=[];for(var Y=0;Y<$.retries;Y++)J.push(this.createTimeout(Y,$));if(D&&D.forever&&!J.length)J.push(this.createTimeout(Y,$));return J.sort(function(F,Q){return F-Q}),J};Pq0.createTimeout=function(D,$){var X=$.randomize?Math.random()+1:1,J=Math.round(X*$.minTimeout*Math.pow($.factor,D));return J=Math.min(J,$.maxTimeout),J};Pq0.wrap=function(D,$,X){if($ instanceof Array)X=$,$=null;if(!X){X=[];for(var J in D)if(typeof D[J]==="function")X.push(J)}for(var Y=0;Y<X.length;Y++){var F=X[Y],Q=D[F];D[F]=function(Z){var O=Pq0.operation($),G=Array.prototype.slice.call(arguments,1),w=G.pop();G.push(function(q){if(O.retry(q))return;if(q)arguments[0]=O.mainError();w.apply(this,arguments)}),O.attempt(function(){Z.apply(D,G)})}.bind(D,Q),D[F].options=$}}});var fv=E((ta0,CF)=>{CF.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")CF.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")CF.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var uF=E((oa0,P5)=>{var RD=global.process,g8=function(D){return D&&typeof D==="object"&&typeof D.removeListener==="function"&&typeof D.emit==="function"&&typeof D.reallyExit==="function"&&typeof D.listeners==="function"&&typeof D.kill==="function"&&typeof D.pid==="number"&&typeof D.on==="function"};if(!g8(RD))P5.exports=function(){return function(){}};else{if(sq=l("assert"),m8=fv(),eq=/^win/i.test(RD.platform),S5=l("events"),typeof S5!=="function")S5=S5.EventEmitter;if(RD.__signal_exit_emitter__)aD=RD.__signal_exit_emitter__;else aD=RD.__signal_exit_emitter__=new S5,aD.count=0,aD.emitted={};if(!aD.infinite)aD.setMaxListeners(1/0),aD.infinite=!0;P5.exports=function(D,$){if(!g8(global.process))return function(){};if(sq.equal(typeof D,"function","a callback must be provided for exit handler"),c8===!1)SF();var X="exit";if($&&$.alwaysLast)X="afterexit";var J=function(){if(aD.removeListener(X,D),aD.listeners("exit").length===0&&aD.listeners("afterexit").length===0)L2()};return aD.on(X,D),J},L2=function(){if(!c8||!g8(global.process))return;c8=!1,m8.forEach(function($){try{RD.removeListener($,M2[$])}catch(X){}}),RD.emit=I2,RD.reallyExit=PF,aD.count-=1},P5.exports.unload=L2,V4=function($,X,J){if(aD.emitted[$])return;aD.emitted[$]=!0,aD.emit($,X,J)},M2={},m8.forEach(function(D){M2[D]=function(){if(!g8(global.process))return;var X=RD.listeners(D);if(X.length===aD.count){if(L2(),V4("exit",null,D),V4("afterexit",null,D),eq&&D==="SIGHUP")D="SIGINT";RD.kill(RD.pid,D)}}}),P5.exports.signals=function(){return m8},c8=!1,SF=function(){if(c8||!g8(global.process))return;c8=!0,aD.count+=1,m8=m8.filter(function($){try{return RD.on($,M2[$]),!0}catch(X){return!1}}),RD.emit=$W,RD.reallyExit=DW},P5.exports.load=SF,PF=RD.reallyExit,DW=function($){if(!g8(global.process))return;RD.exitCode=$||0,V4("exit",RD.exitCode,null),V4("afterexit",RD.exitCode,null),PF.call(RD,RD.exitCode)},I2=RD.emit,$W=function($,X){if($==="exit"&&g8(global.process)){if(X!==void 0)RD.exitCode=X;var J=I2.apply(this,arguments);return V4("exit",RD.exitCode,null),V4("afterexit",RD.exitCode,null),J}else return I2.apply(this,arguments)}}var sq,m8,eq,S5,aD,L2,V4,M2,c8,SF,PF,DW,I2,$W});var yv=E((kq0,XW)=>{var kv=Symbol();function _q0(D,$,X){let J=$[kv];if(J)return $.stat(D,(F,Q)=>{if(F)return X(F);X(null,Q.mtime,J)});let Y=new Date(Math.ceil(Date.now()/1000)*1000+5);$.utimes(D,Y,Y,(F)=>{if(F)return X(F);$.stat(D,(Q,U)=>{if(Q)return X(Q);let Z=U.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty($,kv,{value:Z}),X(null,U.mtime,Z)})})}function fq0(D){let $=Date.now();if(D==="s")$=Math.ceil($/1000)*1000;return new Date($)}kq0.probe=_q0;kq0.getMtime=fq0});var cv=E((lq0,E2)=>{var hq0=l("path"),FW=bD(),gq0=_v(),mq0=uF(),bv=yv(),k6={};function A2(D,$){return $.lockfilePath||`${D}.lock`}function QW(D,$,X){if(!$.realpath)return X(null,hq0.resolve(D));$.fs.realpath(D,X)}function YW(D,$,X){let J=A2(D,$);$.fs.mkdir(J,(Y)=>{if(!Y)return bv.probe(J,$.fs,(F,Q,U)=>{if(F)return $.fs.rmdir(J,()=>{}),X(F);X(null,Q,U)});if(Y.code!=="EEXIST")return X(Y);if($.stale<=0)return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));$.fs.stat(J,(F,Q)=>{if(F){if(F.code==="ENOENT")return YW(D,{...$,stale:0},X);return X(F)}if(!hv(Q,$))return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));gv(D,$,(U)=>{if(U)return X(U);YW(D,{...$,stale:0},X)})})})}function hv(D,$){return D.mtime.getTime()<Date.now()-$.stale}function gv(D,$,X){$.fs.rmdir(A2(D,$),(J)=>{if(J&&J.code!=="ENOENT")return X(J);X()})}function xF(D,$){let X=k6[D];if(X.updateTimeout)return;if(X.updateDelay=X.updateDelay||$.update,X.updateTimeout=setTimeout(()=>{X.updateTimeout=null,$.fs.stat(X.lockfilePath,(J,Y)=>{let F=X.lastUpdate+$.stale<Date.now();if(J){if(J.code==="ENOENT"||F)return JW(D,X,Object.assign(J,{code:"ECOMPROMISED"}));return X.updateDelay=1000,xF(D,$)}if(X.mtime.getTime()!==Y.mtime.getTime())return JW(D,X,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let U=bv.getMtime(X.mtimePrecision);$.fs.utimes(X.lockfilePath,U,U,(Z)=>{let O=X.lastUpdate+$.stale<Date.now();if(X.released)return;if(Z){if(Z.code==="ENOENT"||O)return JW(D,X,Object.assign(Z,{code:"ECOMPROMISED"}));return X.updateDelay=1000,xF(D,$)}X.mtime=U,X.lastUpdate=Date.now(),X.updateDelay=null,xF(D,$)})})},X.updateDelay),X.updateTimeout.unref)X.updateTimeout.unref()}function JW(D,$,X){if($.released=!0,$.updateTimeout)clearTimeout($.updateTimeout);if(k6[D]===$)delete k6[D];$.options.onCompromised(X)}function cq0(D,$,X){$={stale:1e4,update:null,realpath:!0,retries:0,fs:FW,onCompromised:(J)=>{throw J},...$},$.retries=$.retries||0,$.retries=typeof $.retries==="number"?{retries:$.retries}:$.retries,$.stale=Math.max($.stale||0,2000),$.update=$.update==null?$.stale/2:$.update||0,$.update=Math.max(Math.min($.update,$.stale/2),1000),QW(D,$,(J,Y)=>{if(J)return X(J);let F=gq0.operation($.retries);F.attempt(()=>{YW(Y,$,(Q,U,Z)=>{if(F.retry(Q))return;if(Q)return X(F.mainError());let O=k6[Y]={lockfilePath:A2(Y,$),mtime:U,mtimePrecision:Z,options:$,lastUpdate:Date.now()};xF(Y,$),X(null,(G)=>{if(O.released)return G&&G(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));mv(Y,{...$,realpath:!1},G)})})})})}function mv(D,$,X){$={fs:FW,realpath:!0,...$},QW(D,$,(J,Y)=>{if(J)return X(J);let F=k6[Y];if(!F)return X(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));F.updateTimeout&&clearTimeout(F.updateTimeout),F.released=!0,delete k6[Y],gv(Y,$,X)})}function dq0(D,$,X){$={stale:1e4,realpath:!0,fs:FW,...$},$.stale=Math.max($.stale||0,2000),QW(D,$,(J,Y)=>{if(J)return X(J);$.fs.stat(A2(Y,$),(F,Q)=>{if(F)return F.code==="ENOENT"?X(null,!1):X(F);return X(null,!hv(Q,$))})})}function nq0(){return k6}mq0(()=>{for(let D in k6){let $=k6[D].options;try{$.fs.rmdirSync(A2(D,$))}catch(X){}}});lq0.lock=cq0;lq0.unlock=mv;lq0.check=dq0;lq0.getLocks=nq0});var nv=E((aa0,dv)=>{var oq0=bD();function aq0(D){let $=["mkdir","realpath","stat","rmdir","utimes"],X={...D};return $.forEach((J)=>{X[J]=(...Y)=>{let F=Y.pop(),Q;try{Q=D[`${J}Sync`](...Y)}catch(U){return F(U)}F(null,Q)}}),X}function sq0(D){return(...$)=>new Promise((X,J)=>{$.push((Y,F)=>{if(Y)J(Y);else X(F)}),D(...$)})}function eq0(D){return(...$)=>{let X,J;if($.push((Y,F)=>{X=Y,J=F}),D(...$),X)throw X;return J}}function DW0(D){if(D={...D},D.fs=aq0(D.fs||oq0),typeof D.retries==="number"&&D.retries>0||D.retries&&typeof D.retries.retries==="number"&&D.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return D}dv.exports={toPromise:sq0,toSync:eq0,toSyncOptions:DW0}});var iv=E((sa0,L4)=>{var u5=cv(),{toPromise:vF,toSync:_F,toSyncOptions:UW}=nv();async function lv(D,$){let X=await vF(u5.lock)(D,$);return vF(X)}function $W0(D,$){let X=_F(u5.lock)(D,UW($));return _F(X)}function XW0(D,$){return vF(u5.unlock)(D,$)}function JW0(D,$){return _F(u5.unlock)(D,UW($))}function YW0(D,$){return vF(u5.check)(D,$)}function FW0(D,$){return _F(u5.check)(D,UW($))}L4.exports=lv;L4.exports.lock=lv;L4.exports.unlock=XW0;L4.exports.lockSync=$W0;L4.exports.unlockSync=JW0;L4.exports.check=YW0;L4.exports.checkSync=FW0});var ev=E((av)=>{Object.defineProperty(av,"__esModule",{value:!0});av.canStoreURLs=av.FileUrlStorage=void 0;var pv=l("fs"),QW0=ZW0(Mv()),rv=UW0(iv());function ov(D){if(typeof WeakMap!="function")return null;var $=new WeakMap,X=new WeakMap;return(ov=function(J){return J?X:$})(D)}function UW0(D,$){if(!$&&D&&D.__esModule)return D;if(D===null||typeof D!="object"&&typeof D!="function")return{default:D};var X=ov($);if(X&&X.has(D))return X.get(D);var J={__proto__:null},Y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var F in D)if(F!=="default"&&{}.hasOwnProperty.call(D,F)){var Q=Y?Object.getOwnPropertyDescriptor(D,F):null;Q&&(Q.get||Q.set)?Object.defineProperty(J,F,Q):J[F]=D[F]}return J.default=D,X&&X.set(D,J),J}function ZW0(D){return D&&D.__esModule?D:{default:D}}function R2(D){return R2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},R2(D)}function OW0(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function tv(D,$){for(var X=0;X<$.length;X++){var J=$[X];if(J.enumerable=J.enumerable||!1,J.configurable=!0,"value"in J)J.writable=!0;Object.defineProperty(D,wW0(J.key),J)}}function GW0(D,$,X){if($)tv(D.prototype,$);if(X)tv(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function wW0(D){var $=qW0(D,"string");return R2($)=="symbol"?$:$+""}function qW0(D,$){if(R2(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var J=X.call(D,$||"default");if(R2(J)!="object")return J;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var ea0=av.canStoreURLs=!0,Ds0=av.FileUrlStorage=function(){function D($){OW0(this,D),this.path=$}return GW0(D,[{key:"findAllUploads",value:function(){var X=this;return new Promise(function(J,Y){X._getItems("tus::",function(F,Q){if(F)Y(F);else J(Q)})})}},{key:"findUploadsByFingerprint",value:function(X){var J=this;return new Promise(function(Y,F){J._getItems("tus::".concat(X),function(Q,U){if(Q)F(Q);else Y(U)})})}},{key:"removeUpload",value:function(X){var J=this;return new Promise(function(Y,F){J._removeItem(X,function(Q){if(Q)F(Q);else Y()})})}},{key:"addUpload",value:function(X,J){var Y=this,F=Math.round(Math.random()*1000000000000),Q="tus::".concat(X,"::").concat(F);return new Promise(function(U,Z){Y._setItem(Q,J,function(O){if(O)Z(O);else U(Q)})})}},{key:"_setItem",value:function(X,J,Y){var F=this;rv.lock(this.path,this._lockfileOptions()).then(function(Q){Y=F._releaseAndCb(Q,Y),F._getData(function(U,Z){if(U){Y(U);return}Z[X]=J,F._writeData(Z,function(O){return Y(O)})})}).catch(Y)}},{key:"_getItems",value:function(X,J){this._getData(function(Y,F){if(Y){J(Y);return}var Q=Object.keys(F).filter(function(U){return U.startsWith(X)}).map(function(U){var Z=F[U];return Z.urlStorageKey=U,Z});J(null,Q)})}},{key:"_removeItem",value:function(X,J){var Y=this;rv.lock(this.path,this._lockfileOptions()).then(function(F){J=Y._releaseAndCb(F,J),Y._getData(function(Q,U){if(Q){J(Q);return}delete U[X],Y._writeData(U,function(Z){return J(Z)})})}).catch(J)}},{key:"_lockfileOptions",value:function(){return{realpath:!1,retries:{retries:5,minTimeout:20}}}},{key:"_releaseAndCb",value:function(X,J){return function(Y){if(Y){X().then(function(){return J(Y)}).catch(function(F){return J((0,QW0.default)([Y,F]))});return}X().then(J).catch(J)}}},{key:"_writeData",value:function(X,J){var Y={encoding:"utf8",mode:432,flag:"w"};(0,pv.writeFile)(this.path,JSON.stringify(X),Y,function(F){return J(F)})}},{key:"_getData",value:function(X){(0,pv.readFile)(this.path,"utf8",function(J,Y){if(J){if(J.code==="ENOENT")X(null,{});else X(J);return}try{Y=!Y.trim().length?{}:JSON.parse(Y)}catch(F){X(F);return}X(null,Y)})}}])}()});var kF=E((M4)=>{Object.defineProperty(M4,"__esModule",{value:!0});Object.defineProperty(M4,"DefaultHttpStack",{enumerable:!0,get:function(){return J_.default}});Object.defineProperty(M4,"DetailedError",{enumerable:!0,get:function(){return KW0.default}});Object.defineProperty(M4,"FileUrlStorage",{enumerable:!0,get:function(){return Y_.FileUrlStorage}});Object.defineProperty(M4,"StreamSource",{enumerable:!0,get:function(){return VW0.default}});M4.Upload=void 0;Object.defineProperty(M4,"canStoreURLs",{enumerable:!0,get:function(){return Y_.canStoreURLs}});M4.defaultOptions=void 0;Object.defineProperty(M4,"enableDebugLog",{enumerable:!0,get:function(){return HW0.enableDebugLog}});M4.isSupported=void 0;var KW0=d8(Uq()),HW0=Zq(),BW0=d8(iP()),ZW=d8(Ru()),NW0=d8(lu()),zW0=d8(ou()),J_=d8(qx()),VW0=d8(Vq()),Y_=ev();function d8(D){return D&&D.__esModule?D:{default:D}}function v5(D){return v5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},v5(D)}function LW0(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function D_(D,$){for(var X=0;X<$.length;X++){var J=$[X];if(J.enumerable=J.enumerable||!1,J.configurable=!0,"value"in J)J.writable=!0;Object.defineProperty(D,Q_(J.key),J)}}function MW0(D,$,X){if($)D_(D.prototype,$);if(X)D_(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function IW0(D,$,X){return $=fF($),AW0(D,F_()?Reflect.construct($,X||[],fF(D).constructor):$.apply(D,X))}function AW0(D,$){if($&&(v5($)==="object"||typeof $==="function"))return $;else if($!==void 0)throw TypeError("Derived constructors may only return object or undefined");return EW0(D)}function EW0(D){if(D===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return D}function F_(){try{var D=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch($){}return(F_=function(){return!!D})()}function fF(D){return fF=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(X){return X.__proto__||Object.getPrototypeOf(X)},fF(D)}function RW0(D,$){if(typeof $!=="function"&&$!==null)throw TypeError("Super expression must either be null or a function");if(D.prototype=Object.create($&&$.prototype,{constructor:{value:D,writable:!0,configurable:!0}}),Object.defineProperty(D,"prototype",{writable:!1}),$)OW(D,$)}function OW(D,$){return OW=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(J,Y){return J.__proto__=Y,J},OW(D,$)}function $_(D,$){var X=Object.keys(D);if(Object.getOwnPropertySymbols){var J=Object.getOwnPropertySymbols(D);$&&(J=J.filter(function(Y){return Object.getOwnPropertyDescriptor(D,Y).enumerable})),X.push.apply(X,J)}return X}function x5(D){for(var $=1;$<arguments.length;$++){var X=arguments[$]!=null?arguments[$]:{};$%2?$_(Object(X),!0).forEach(function(J){jW0(D,J,X[J])}):Object.getOwnPropertyDescriptors?Object.defineProperties(D,Object.getOwnPropertyDescriptors(X)):$_(Object(X)).forEach(function(J){Object.defineProperty(D,J,Object.getOwnPropertyDescriptor(X,J))})}return D}function jW0(D,$,X){if($=Q_($),$ in D)Object.defineProperty(D,$,{value:X,enumerable:!0,configurable:!0,writable:!0});else D[$]=X;return D}function Q_(D){var $=TW0(D,"string");return v5($)=="symbol"?$:$+""}function TW0(D,$){if(v5(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var J=X.call(D,$||"default");if(v5(J)!="object")return J;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var X_=M4.defaultOptions=x5(x5({},ZW.default.defaultOptions),{},{httpStack:new J_.default,fileReader:new NW0.default,urlStorage:new BW0.default,fingerprint:zW0.default}),Xs0=M4.Upload=function(D){function $(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return LW0(this,$),J=x5(x5({},X_),J),IW0(this,$,[X,J])}return RW0($,D),MW0($,null,[{key:"terminate",value:function(J){var Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Y=x5(x5({},X_),Y),ZW.default.terminate(J,Y)}}])}(ZW.default),Js0=M4.isSupported=!0});var i1;var n8=p(()=>{i1={name:"@capgo/cli",type:"module",version:"7.119.2",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/capgo/tree/main/cli#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/capgo.git",directory:"cli"},bugs:{url:"https://github.com/Cap-go/capgo/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"bunx --bun supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsgo --project tsconfig.tsgo.json --noEmit",lint:"bun run lint:ox","lint:ox":"oxlint --config ../.oxlintrc.json src","lint:fix":"oxlint --config ../.oxlintrc.json --fix src","check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:android-service-account-validation":"bun test/test-android-service-account-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:build-needed":"bun test/test-build-needed.mjs","test:ci-prompts":"bun test/test-ci-prompts.mjs","test:ci-secrets":"bun test/test-ci-secrets.mjs","test:android-onboarding-progress":"bun test/test-android-onboarding-progress.mjs","test:onboarding-telemetry":"bun test/test-onboarding-telemetry.mjs","test:v2-event-migration":"bun test/test-v2-event-migration.mjs","test:analytics":"bun test/test-analytics.mjs","test:analytics-error-category":"bun test/test-analytics-error-category.mjs","test:analytics-org-resolver":"bun test/test-analytics-org-resolver.mjs","test:supabase-perf":"bun test/test-supabase-perf.mjs","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:onboarding-recovery":"bun test/test-onboarding-recovery.mjs","test:onboarding-progress":"bun test/test-onboarding-progress.mjs","test:onboarding-run-targets":"bun test/test-onboarding-run-targets.mjs","test:run-device-command":"bun test/test-run-device-command.mjs","test:init-app-conflict":"bun test/test-init-app-conflict.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs",test:"bun run build && bun run test:version-detection:setup && bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:android-service-account-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:build-needed && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:mcp-analytics && bun run test:app-created-source && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:build-platform-selection && bun run test:onboarding-recovery && bun run test:onboarding-progress && bun run test:onboarding-run-targets && bun run test:run-device-command && bun run test:init-app-conflict && bun run test:init-guardrails && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:apple-api-import-helpers && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:ai-render-markdown","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^7.0.4","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.6"},devDependencies:{"@antfu/eslint-config":"^9.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.3.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.4.0","@modelcontextprotocol/sdk":"^1.29.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.106.2","@tanstack/intent":"^0.0.41","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.9.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.15","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260526.1","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.17","ci-info":"^4.4.0",commander:"^14.0.3",eslint:"^10.4.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.67.0",partysocket:"^1.1.19",prettyjson:"^1.2.5",tmp:"^0.2.6","tus-js-client":"^4.3.1",typescript:"^6.0.3",ws:"^8.21.0",zod:"^4.4.3"}}});async function yF(D){try{let X=`https://registry.npmjs.org/${encodeURIComponent(D.toLowerCase())}`,J=await fetch(X,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});if(!J.ok)return null;return(await J.json())["dist-tags"]?.latest||null}catch{return null}}async function SW0(){let D=await yF("@capgo/cli")??"",$=D?.split(".")[0]??"";return{currentVersion:i1.version,latestVersion:D,isOutdated:!!D&&D!==i1.version,majorVersion:$}}async function WD(){let{isOutdated:D,currentVersion:$,latestVersion:X,majorVersion:J}=await SW0();if(D)V.warning(`\uD83D\uDEA8 You are using @capgo/cli@${$} it's not the latest version.
127
+ GFS4: `),console.error(D)};if(!uD[F1]){if(rq=global[F1]||[],Pv(uD,rq),uD.close=function(D){function $(X,J){return D.call(uD,X,function(Y){if(!Y)Sv();if(typeof J==="function")J.apply(this,arguments)})}return Object.defineProperty($,TF,{value:D}),$}(uD.close),uD.closeSync=function(D){function $(X){D.apply(uD,arguments),Sv()}return Object.defineProperty($,TF,{value:D}),$}(uD.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){h8(uD[F1]),l("assert").equal(uD[F1].length,0)})}var rq;if(!global[F1])Pv(global,uD[F1]);aq.exports=tq(Tq0(uD));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!uD.__patched)aq.exports=tq(uD),uD.__patched=!0;function tq(D){Rq0(D),D.gracefulify=tq,D.createReadStream=z,D.createWriteStream=R;var $=D.readFile;D.readFile=X;function X(A,x,P){if(typeof x==="function")P=x,x=null;return g(A,x,P);function g(c,r,f,T){return $(c,r,function(S){if(S&&(S.code==="EMFILE"||S.code==="ENFILE"))C5([g,[c,r,f],S,T||Date.now(),Date.now()]);else if(typeof f==="function")f.apply(this,arguments)})}}var J=D.writeFile;D.writeFile=Y;function Y(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return J(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var F=D.appendFile;if(F)D.appendFile=Q;function Q(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return F(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var U=D.copyFile;if(U)D.copyFile=Z;function Z(A,x,P,g){if(typeof P==="function")g=P,P=0;return c(A,x,P,g);function c(r,f,T,S,u){return U(r,f,T,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var O=D.readdir;D.readdir=w;var G=/^v[0-5]\./;function w(A,x,P){if(typeof x==="function")P=x,x=null;var g=G.test(process.version)?function(f,T,S,u){return O(f,c(f,T,S,u))}:function(f,T,S,u){return O(f,T,c(f,T,S,u))};return g(A,x,P);function c(r,f,T,S){return function(u,k){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))C5([g,[r,f,T],u,S||Date.now(),Date.now()]);else{if(k&&k.sort)k.sort();if(typeof T==="function")T.call(this,u,k)}}}}if(process.version.substr(0,4)==="v0.8"){var q=jq0(D);M=q.ReadStream,B=q.WriteStream}var W=D.ReadStream;if(W)M.prototype=Object.create(W.prototype),M.prototype.open=I;var K=D.WriteStream;if(K)B.prototype=Object.create(K.prototype),B.prototype.open=N;Object.defineProperty(D,"ReadStream",{get:function(){return M},set:function(A){M=A},enumerable:!0,configurable:!0}),Object.defineProperty(D,"WriteStream",{get:function(){return B},set:function(A){B=A},enumerable:!0,configurable:!0});var H=M;Object.defineProperty(D,"FileReadStream",{get:function(){return H},set:function(A){H=A},enumerable:!0,configurable:!0});var L=B;Object.defineProperty(D,"FileWriteStream",{get:function(){return L},set:function(A){L=A},enumerable:!0,configurable:!0});function M(A,x){if(this instanceof M)return W.apply(this,arguments),this;else return M.apply(Object.create(M.prototype),arguments)}function I(){var A=this;_(A.path,A.flags,A.mode,function(x,P){if(x){if(A.autoClose)A.destroy();A.emit("error",x)}else A.fd=P,A.emit("open",P),A.read()})}function B(A,x){if(this instanceof B)return K.apply(this,arguments),this;else return B.apply(Object.create(B.prototype),arguments)}function N(){var A=this;_(A.path,A.flags,A.mode,function(x,P){if(x)A.destroy(),A.emit("error",x);else A.fd=P,A.emit("open",P)})}function z(A,x){return new D.ReadStream(A,x)}function R(A,x){return new D.WriteStream(A,x)}var v=D.open;D.open=_;function _(A,x,P,g){if(typeof P==="function")g=P,P=null;return c(A,x,P,g);function c(r,f,T,S,u){return v(r,f,T,function(k,m){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))C5([c,[r,f,T,S],k,u||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}return D}function C5(D){h8("ENQUEUE",D[0].name,D[1]),uD[F1].push(D),oq()}var jF;function Sv(){var D=Date.now();for(var $=0;$<uD[F1].length;++$)if(uD[F1][$].length>2)uD[F1][$][3]=D,uD[F1][$][4]=D;oq()}function oq(){if(clearTimeout(jF),jF=void 0,uD[F1].length===0)return;var D=uD[F1].shift(),$=D[0],X=D[1],J=D[2],Y=D[3],F=D[4];if(Y===void 0)h8("RETRY",$.name,X),$.apply(null,X);else if(Date.now()-Y>=60000){h8("TIMEOUT",$.name,X);var Q=X.pop();if(typeof Q==="function")Q.call(null,J)}else{var U=Date.now()-F,Z=Math.max(F-Y,1),O=Math.min(Z*1.2,100);if(U>=O)h8("RETRY",$.name,X),$.apply(null,X.concat([Y]));else uD[F1].push(D)}if(jF===void 0)jF=setTimeout(oq,0)}});var xv=E((pa0,uv)=>{function V$(D,$){if(typeof $==="boolean")$={forever:$};if(this._originalTimeouts=JSON.parse(JSON.stringify(D)),this._timeouts=D,this._options=$||{},this._maxRetryTime=$&&$.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}uv.exports=V$;V$.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};V$.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};V$.prototype.retry=function(D){if(this._timeout)clearTimeout(this._timeout);if(!D)return!1;var $=new Date().getTime();if(D&&$-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(D);var X=this._timeouts.shift();if(X===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),X=this._timeouts.shift();else return!1;var J=this,Y=setTimeout(function(){if(J._attempts++,J._operationTimeoutCb){if(J._timeout=setTimeout(function(){J._operationTimeoutCb(J._attempts)},J._operationTimeout),J._options.unref)J._timeout.unref()}J._fn(J._attempts)},X);if(this._options.unref)Y.unref();return!0};V$.prototype.attempt=function(D,$){if(this._fn=D,$){if($.timeout)this._operationTimeout=$.timeout;if($.cb)this._operationTimeoutCb=$.cb}var X=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){X._operationTimeoutCb()},X._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};V$.prototype.try=function(D){console.log("Using RetryOperation.try() is deprecated"),this.attempt(D)};V$.prototype.start=function(D){console.log("Using RetryOperation.start() is deprecated"),this.attempt(D)};V$.prototype.start=V$.prototype.try;V$.prototype.errors=function(){return this._errors};V$.prototype.attempts=function(){return this._attempts};V$.prototype.mainError=function(){if(this._errors.length===0)return null;var D={},$=null,X=0;for(var J=0;J<this._errors.length;J++){var Y=this._errors[J],F=Y.message,Q=(D[F]||0)+1;if(D[F]=Q,Q>=X)$=Y,X=Q}return $}});var _v=E((Pq0)=>{var Sq0=xv();Pq0.operation=function(D){var $=Pq0.timeouts(D);return new Sq0($,{forever:D&&D.forever,unref:D&&D.unref,maxRetryTime:D&&D.maxRetryTime})};Pq0.timeouts=function(D){if(D instanceof Array)return[].concat(D);var $={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var X in D)$[X]=D[X];if($.minTimeout>$.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var J=[];for(var Y=0;Y<$.retries;Y++)J.push(this.createTimeout(Y,$));if(D&&D.forever&&!J.length)J.push(this.createTimeout(Y,$));return J.sort(function(F,Q){return F-Q}),J};Pq0.createTimeout=function(D,$){var X=$.randomize?Math.random()+1:1,J=Math.round(X*$.minTimeout*Math.pow($.factor,D));return J=Math.min(J,$.maxTimeout),J};Pq0.wrap=function(D,$,X){if($ instanceof Array)X=$,$=null;if(!X){X=[];for(var J in D)if(typeof D[J]==="function")X.push(J)}for(var Y=0;Y<X.length;Y++){var F=X[Y],Q=D[F];D[F]=function(Z){var O=Pq0.operation($),G=Array.prototype.slice.call(arguments,1),w=G.pop();G.push(function(q){if(O.retry(q))return;if(q)arguments[0]=O.mainError();w.apply(this,arguments)}),O.attempt(function(){Z.apply(D,G)})}.bind(D,Q),D[F].options=$}}});var fv=E((ta0,CF)=>{CF.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")CF.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")CF.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var uF=E((oa0,P5)=>{var RD=global.process,g8=function(D){return D&&typeof D==="object"&&typeof D.removeListener==="function"&&typeof D.emit==="function"&&typeof D.reallyExit==="function"&&typeof D.listeners==="function"&&typeof D.kill==="function"&&typeof D.pid==="number"&&typeof D.on==="function"};if(!g8(RD))P5.exports=function(){return function(){}};else{if(sq=l("assert"),m8=fv(),eq=/^win/i.test(RD.platform),S5=l("events"),typeof S5!=="function")S5=S5.EventEmitter;if(RD.__signal_exit_emitter__)aD=RD.__signal_exit_emitter__;else aD=RD.__signal_exit_emitter__=new S5,aD.count=0,aD.emitted={};if(!aD.infinite)aD.setMaxListeners(1/0),aD.infinite=!0;P5.exports=function(D,$){if(!g8(global.process))return function(){};if(sq.equal(typeof D,"function","a callback must be provided for exit handler"),c8===!1)SF();var X="exit";if($&&$.alwaysLast)X="afterexit";var J=function(){if(aD.removeListener(X,D),aD.listeners("exit").length===0&&aD.listeners("afterexit").length===0)L2()};return aD.on(X,D),J},L2=function(){if(!c8||!g8(global.process))return;c8=!1,m8.forEach(function($){try{RD.removeListener($,M2[$])}catch(X){}}),RD.emit=I2,RD.reallyExit=PF,aD.count-=1},P5.exports.unload=L2,V4=function($,X,J){if(aD.emitted[$])return;aD.emitted[$]=!0,aD.emit($,X,J)},M2={},m8.forEach(function(D){M2[D]=function(){if(!g8(global.process))return;var X=RD.listeners(D);if(X.length===aD.count){if(L2(),V4("exit",null,D),V4("afterexit",null,D),eq&&D==="SIGHUP")D="SIGINT";RD.kill(RD.pid,D)}}}),P5.exports.signals=function(){return m8},c8=!1,SF=function(){if(c8||!g8(global.process))return;c8=!0,aD.count+=1,m8=m8.filter(function($){try{return RD.on($,M2[$]),!0}catch(X){return!1}}),RD.emit=$W,RD.reallyExit=DW},P5.exports.load=SF,PF=RD.reallyExit,DW=function($){if(!g8(global.process))return;RD.exitCode=$||0,V4("exit",RD.exitCode,null),V4("afterexit",RD.exitCode,null),PF.call(RD,RD.exitCode)},I2=RD.emit,$W=function($,X){if($==="exit"&&g8(global.process)){if(X!==void 0)RD.exitCode=X;var J=I2.apply(this,arguments);return V4("exit",RD.exitCode,null),V4("afterexit",RD.exitCode,null),J}else return I2.apply(this,arguments)}}var sq,m8,eq,S5,aD,L2,V4,M2,c8,SF,PF,DW,I2,$W});var yv=E((kq0,XW)=>{var kv=Symbol();function _q0(D,$,X){let J=$[kv];if(J)return $.stat(D,(F,Q)=>{if(F)return X(F);X(null,Q.mtime,J)});let Y=new Date(Math.ceil(Date.now()/1000)*1000+5);$.utimes(D,Y,Y,(F)=>{if(F)return X(F);$.stat(D,(Q,U)=>{if(Q)return X(Q);let Z=U.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty($,kv,{value:Z}),X(null,U.mtime,Z)})})}function fq0(D){let $=Date.now();if(D==="s")$=Math.ceil($/1000)*1000;return new Date($)}kq0.probe=_q0;kq0.getMtime=fq0});var cv=E((lq0,E2)=>{var hq0=l("path"),FW=bD(),gq0=_v(),mq0=uF(),bv=yv(),k6={};function A2(D,$){return $.lockfilePath||`${D}.lock`}function QW(D,$,X){if(!$.realpath)return X(null,hq0.resolve(D));$.fs.realpath(D,X)}function YW(D,$,X){let J=A2(D,$);$.fs.mkdir(J,(Y)=>{if(!Y)return bv.probe(J,$.fs,(F,Q,U)=>{if(F)return $.fs.rmdir(J,()=>{}),X(F);X(null,Q,U)});if(Y.code!=="EEXIST")return X(Y);if($.stale<=0)return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));$.fs.stat(J,(F,Q)=>{if(F){if(F.code==="ENOENT")return YW(D,{...$,stale:0},X);return X(F)}if(!hv(Q,$))return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));gv(D,$,(U)=>{if(U)return X(U);YW(D,{...$,stale:0},X)})})})}function hv(D,$){return D.mtime.getTime()<Date.now()-$.stale}function gv(D,$,X){$.fs.rmdir(A2(D,$),(J)=>{if(J&&J.code!=="ENOENT")return X(J);X()})}function xF(D,$){let X=k6[D];if(X.updateTimeout)return;if(X.updateDelay=X.updateDelay||$.update,X.updateTimeout=setTimeout(()=>{X.updateTimeout=null,$.fs.stat(X.lockfilePath,(J,Y)=>{let F=X.lastUpdate+$.stale<Date.now();if(J){if(J.code==="ENOENT"||F)return JW(D,X,Object.assign(J,{code:"ECOMPROMISED"}));return X.updateDelay=1000,xF(D,$)}if(X.mtime.getTime()!==Y.mtime.getTime())return JW(D,X,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let U=bv.getMtime(X.mtimePrecision);$.fs.utimes(X.lockfilePath,U,U,(Z)=>{let O=X.lastUpdate+$.stale<Date.now();if(X.released)return;if(Z){if(Z.code==="ENOENT"||O)return JW(D,X,Object.assign(Z,{code:"ECOMPROMISED"}));return X.updateDelay=1000,xF(D,$)}X.mtime=U,X.lastUpdate=Date.now(),X.updateDelay=null,xF(D,$)})})},X.updateDelay),X.updateTimeout.unref)X.updateTimeout.unref()}function JW(D,$,X){if($.released=!0,$.updateTimeout)clearTimeout($.updateTimeout);if(k6[D]===$)delete k6[D];$.options.onCompromised(X)}function cq0(D,$,X){$={stale:1e4,update:null,realpath:!0,retries:0,fs:FW,onCompromised:(J)=>{throw J},...$},$.retries=$.retries||0,$.retries=typeof $.retries==="number"?{retries:$.retries}:$.retries,$.stale=Math.max($.stale||0,2000),$.update=$.update==null?$.stale/2:$.update||0,$.update=Math.max(Math.min($.update,$.stale/2),1000),QW(D,$,(J,Y)=>{if(J)return X(J);let F=gq0.operation($.retries);F.attempt(()=>{YW(Y,$,(Q,U,Z)=>{if(F.retry(Q))return;if(Q)return X(F.mainError());let O=k6[Y]={lockfilePath:A2(Y,$),mtime:U,mtimePrecision:Z,options:$,lastUpdate:Date.now()};xF(Y,$),X(null,(G)=>{if(O.released)return G&&G(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));mv(Y,{...$,realpath:!1},G)})})})})}function mv(D,$,X){$={fs:FW,realpath:!0,...$},QW(D,$,(J,Y)=>{if(J)return X(J);let F=k6[Y];if(!F)return X(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));F.updateTimeout&&clearTimeout(F.updateTimeout),F.released=!0,delete k6[Y],gv(Y,$,X)})}function dq0(D,$,X){$={stale:1e4,realpath:!0,fs:FW,...$},$.stale=Math.max($.stale||0,2000),QW(D,$,(J,Y)=>{if(J)return X(J);$.fs.stat(A2(Y,$),(F,Q)=>{if(F)return F.code==="ENOENT"?X(null,!1):X(F);return X(null,!hv(Q,$))})})}function nq0(){return k6}mq0(()=>{for(let D in k6){let $=k6[D].options;try{$.fs.rmdirSync(A2(D,$))}catch(X){}}});lq0.lock=cq0;lq0.unlock=mv;lq0.check=dq0;lq0.getLocks=nq0});var nv=E((aa0,dv)=>{var oq0=bD();function aq0(D){let $=["mkdir","realpath","stat","rmdir","utimes"],X={...D};return $.forEach((J)=>{X[J]=(...Y)=>{let F=Y.pop(),Q;try{Q=D[`${J}Sync`](...Y)}catch(U){return F(U)}F(null,Q)}}),X}function sq0(D){return(...$)=>new Promise((X,J)=>{$.push((Y,F)=>{if(Y)J(Y);else X(F)}),D(...$)})}function eq0(D){return(...$)=>{let X,J;if($.push((Y,F)=>{X=Y,J=F}),D(...$),X)throw X;return J}}function DW0(D){if(D={...D},D.fs=aq0(D.fs||oq0),typeof D.retries==="number"&&D.retries>0||D.retries&&typeof D.retries.retries==="number"&&D.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return D}dv.exports={toPromise:sq0,toSync:eq0,toSyncOptions:DW0}});var iv=E((sa0,L4)=>{var u5=cv(),{toPromise:vF,toSync:_F,toSyncOptions:UW}=nv();async function lv(D,$){let X=await vF(u5.lock)(D,$);return vF(X)}function $W0(D,$){let X=_F(u5.lock)(D,UW($));return _F(X)}function XW0(D,$){return vF(u5.unlock)(D,$)}function JW0(D,$){return _F(u5.unlock)(D,UW($))}function YW0(D,$){return vF(u5.check)(D,$)}function FW0(D,$){return _F(u5.check)(D,UW($))}L4.exports=lv;L4.exports.lock=lv;L4.exports.unlock=XW0;L4.exports.lockSync=$W0;L4.exports.unlockSync=JW0;L4.exports.check=YW0;L4.exports.checkSync=FW0});var ev=E((av)=>{Object.defineProperty(av,"__esModule",{value:!0});av.canStoreURLs=av.FileUrlStorage=void 0;var pv=l("fs"),QW0=ZW0(Mv()),rv=UW0(iv());function ov(D){if(typeof WeakMap!="function")return null;var $=new WeakMap,X=new WeakMap;return(ov=function(J){return J?X:$})(D)}function UW0(D,$){if(!$&&D&&D.__esModule)return D;if(D===null||typeof D!="object"&&typeof D!="function")return{default:D};var X=ov($);if(X&&X.has(D))return X.get(D);var J={__proto__:null},Y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var F in D)if(F!=="default"&&{}.hasOwnProperty.call(D,F)){var Q=Y?Object.getOwnPropertyDescriptor(D,F):null;Q&&(Q.get||Q.set)?Object.defineProperty(J,F,Q):J[F]=D[F]}return J.default=D,X&&X.set(D,J),J}function ZW0(D){return D&&D.__esModule?D:{default:D}}function R2(D){return R2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},R2(D)}function OW0(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function tv(D,$){for(var X=0;X<$.length;X++){var J=$[X];if(J.enumerable=J.enumerable||!1,J.configurable=!0,"value"in J)J.writable=!0;Object.defineProperty(D,wW0(J.key),J)}}function GW0(D,$,X){if($)tv(D.prototype,$);if(X)tv(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function wW0(D){var $=qW0(D,"string");return R2($)=="symbol"?$:$+""}function qW0(D,$){if(R2(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var J=X.call(D,$||"default");if(R2(J)!="object")return J;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var ea0=av.canStoreURLs=!0,Ds0=av.FileUrlStorage=function(){function D($){OW0(this,D),this.path=$}return GW0(D,[{key:"findAllUploads",value:function(){var X=this;return new Promise(function(J,Y){X._getItems("tus::",function(F,Q){if(F)Y(F);else J(Q)})})}},{key:"findUploadsByFingerprint",value:function(X){var J=this;return new Promise(function(Y,F){J._getItems("tus::".concat(X),function(Q,U){if(Q)F(Q);else Y(U)})})}},{key:"removeUpload",value:function(X){var J=this;return new Promise(function(Y,F){J._removeItem(X,function(Q){if(Q)F(Q);else Y()})})}},{key:"addUpload",value:function(X,J){var Y=this,F=Math.round(Math.random()*1000000000000),Q="tus::".concat(X,"::").concat(F);return new Promise(function(U,Z){Y._setItem(Q,J,function(O){if(O)Z(O);else U(Q)})})}},{key:"_setItem",value:function(X,J,Y){var F=this;rv.lock(this.path,this._lockfileOptions()).then(function(Q){Y=F._releaseAndCb(Q,Y),F._getData(function(U,Z){if(U){Y(U);return}Z[X]=J,F._writeData(Z,function(O){return Y(O)})})}).catch(Y)}},{key:"_getItems",value:function(X,J){this._getData(function(Y,F){if(Y){J(Y);return}var Q=Object.keys(F).filter(function(U){return U.startsWith(X)}).map(function(U){var Z=F[U];return Z.urlStorageKey=U,Z});J(null,Q)})}},{key:"_removeItem",value:function(X,J){var Y=this;rv.lock(this.path,this._lockfileOptions()).then(function(F){J=Y._releaseAndCb(F,J),Y._getData(function(Q,U){if(Q){J(Q);return}delete U[X],Y._writeData(U,function(Z){return J(Z)})})}).catch(J)}},{key:"_lockfileOptions",value:function(){return{realpath:!1,retries:{retries:5,minTimeout:20}}}},{key:"_releaseAndCb",value:function(X,J){return function(Y){if(Y){X().then(function(){return J(Y)}).catch(function(F){return J((0,QW0.default)([Y,F]))});return}X().then(J).catch(J)}}},{key:"_writeData",value:function(X,J){var Y={encoding:"utf8",mode:432,flag:"w"};(0,pv.writeFile)(this.path,JSON.stringify(X),Y,function(F){return J(F)})}},{key:"_getData",value:function(X){(0,pv.readFile)(this.path,"utf8",function(J,Y){if(J){if(J.code==="ENOENT")X(null,{});else X(J);return}try{Y=!Y.trim().length?{}:JSON.parse(Y)}catch(F){X(F);return}X(null,Y)})}}])}()});var kF=E((M4)=>{Object.defineProperty(M4,"__esModule",{value:!0});Object.defineProperty(M4,"DefaultHttpStack",{enumerable:!0,get:function(){return J_.default}});Object.defineProperty(M4,"DetailedError",{enumerable:!0,get:function(){return KW0.default}});Object.defineProperty(M4,"FileUrlStorage",{enumerable:!0,get:function(){return Y_.FileUrlStorage}});Object.defineProperty(M4,"StreamSource",{enumerable:!0,get:function(){return VW0.default}});M4.Upload=void 0;Object.defineProperty(M4,"canStoreURLs",{enumerable:!0,get:function(){return Y_.canStoreURLs}});M4.defaultOptions=void 0;Object.defineProperty(M4,"enableDebugLog",{enumerable:!0,get:function(){return HW0.enableDebugLog}});M4.isSupported=void 0;var KW0=d8(Uq()),HW0=Zq(),BW0=d8(iP()),ZW=d8(Ru()),NW0=d8(lu()),zW0=d8(ou()),J_=d8(qx()),VW0=d8(Vq()),Y_=ev();function d8(D){return D&&D.__esModule?D:{default:D}}function v5(D){return v5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},v5(D)}function LW0(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function D_(D,$){for(var X=0;X<$.length;X++){var J=$[X];if(J.enumerable=J.enumerable||!1,J.configurable=!0,"value"in J)J.writable=!0;Object.defineProperty(D,Q_(J.key),J)}}function MW0(D,$,X){if($)D_(D.prototype,$);if(X)D_(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function IW0(D,$,X){return $=fF($),AW0(D,F_()?Reflect.construct($,X||[],fF(D).constructor):$.apply(D,X))}function AW0(D,$){if($&&(v5($)==="object"||typeof $==="function"))return $;else if($!==void 0)throw TypeError("Derived constructors may only return object or undefined");return EW0(D)}function EW0(D){if(D===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return D}function F_(){try{var D=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch($){}return(F_=function(){return!!D})()}function fF(D){return fF=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(X){return X.__proto__||Object.getPrototypeOf(X)},fF(D)}function RW0(D,$){if(typeof $!=="function"&&$!==null)throw TypeError("Super expression must either be null or a function");if(D.prototype=Object.create($&&$.prototype,{constructor:{value:D,writable:!0,configurable:!0}}),Object.defineProperty(D,"prototype",{writable:!1}),$)OW(D,$)}function OW(D,$){return OW=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(J,Y){return J.__proto__=Y,J},OW(D,$)}function $_(D,$){var X=Object.keys(D);if(Object.getOwnPropertySymbols){var J=Object.getOwnPropertySymbols(D);$&&(J=J.filter(function(Y){return Object.getOwnPropertyDescriptor(D,Y).enumerable})),X.push.apply(X,J)}return X}function x5(D){for(var $=1;$<arguments.length;$++){var X=arguments[$]!=null?arguments[$]:{};$%2?$_(Object(X),!0).forEach(function(J){jW0(D,J,X[J])}):Object.getOwnPropertyDescriptors?Object.defineProperties(D,Object.getOwnPropertyDescriptors(X)):$_(Object(X)).forEach(function(J){Object.defineProperty(D,J,Object.getOwnPropertyDescriptor(X,J))})}return D}function jW0(D,$,X){if($=Q_($),$ in D)Object.defineProperty(D,$,{value:X,enumerable:!0,configurable:!0,writable:!0});else D[$]=X;return D}function Q_(D){var $=TW0(D,"string");return v5($)=="symbol"?$:$+""}function TW0(D,$){if(v5(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var J=X.call(D,$||"default");if(v5(J)!="object")return J;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var X_=M4.defaultOptions=x5(x5({},ZW.default.defaultOptions),{},{httpStack:new J_.default,fileReader:new NW0.default,urlStorage:new BW0.default,fingerprint:zW0.default}),Xs0=M4.Upload=function(D){function $(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return LW0(this,$),J=x5(x5({},X_),J),IW0(this,$,[X,J])}return RW0($,D),MW0($,null,[{key:"terminate",value:function(J){var Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Y=x5(x5({},X_),Y),ZW.default.terminate(J,Y)}}])}(ZW.default),Js0=M4.isSupported=!0});var i1;var n8=p(()=>{i1={name:"@capgo/cli",type:"module",version:"7.120.0",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/capgo/tree/main/cli#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/capgo.git",directory:"cli"},bugs:{url:"https://github.com/Cap-go/capgo/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"bunx --bun supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsgo --project tsconfig.tsgo.json --noEmit",lint:"bun run lint:ox","lint:ox":"oxlint --config ../.oxlintrc.json src","lint:fix":"oxlint --config ../.oxlintrc.json --fix src","check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:android-service-account-validation":"bun test/test-android-service-account-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:build-needed":"bun test/test-build-needed.mjs","test:ci-prompts":"bun test/test-ci-prompts.mjs","test:ci-secrets":"bun test/test-ci-secrets.mjs","test:android-onboarding-progress":"bun test/test-android-onboarding-progress.mjs","test:onboarding-telemetry":"bun test/test-onboarding-telemetry.mjs","test:v2-event-migration":"bun test/test-v2-event-migration.mjs","test:analytics":"bun test/test-analytics.mjs","test:analytics-error-category":"bun test/test-analytics-error-category.mjs","test:analytics-org-resolver":"bun test/test-analytics-org-resolver.mjs","test:supabase-perf":"bun test/test-supabase-perf.mjs","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:onboarding-recovery":"bun test/test-onboarding-recovery.mjs","test:onboarding-progress":"bun test/test-onboarding-progress.mjs","test:onboarding-run-targets":"bun test/test-onboarding-run-targets.mjs","test:run-device-command":"bun test/test-run-device-command.mjs","test:init-app-conflict":"bun test/test-init-app-conflict.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs",test:"bun run build && bun run test:version-detection:setup && bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:android-service-account-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:build-needed && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:mcp-analytics && bun run test:app-created-source && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:build-platform-selection && bun run test:onboarding-recovery && bun run test:onboarding-progress && bun run test:onboarding-run-targets && bun run test:run-device-command && bun run test:init-app-conflict && bun run test:init-guardrails && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:apple-api-import-helpers && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:ai-render-markdown","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^7.0.4","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.6"},devDependencies:{"@antfu/eslint-config":"^9.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.3.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.4.0","@modelcontextprotocol/sdk":"^1.29.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.106.2","@tanstack/intent":"^0.0.41","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.9.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.15","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260526.1","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.17","ci-info":"^4.4.0",commander:"^14.0.3",eslint:"^10.4.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.67.0",partysocket:"^1.1.19",prettyjson:"^1.2.5",tmp:"^0.2.6","tus-js-client":"^4.3.1",typescript:"^6.0.3",ws:"^8.21.0",zod:"^4.4.3"}}});async function yF(D){try{let X=`https://registry.npmjs.org/${encodeURIComponent(D.toLowerCase())}`,J=await fetch(X,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});if(!J.ok)return null;return(await J.json())["dist-tags"]?.latest||null}catch{return null}}async function SW0(){let D=await yF("@capgo/cli")??"",$=D?.split(".")[0]??"";return{currentVersion:i1.version,latestVersion:D,isOutdated:!!D&&D!==i1.version,majorVersion:$}}async function WD(){let{isOutdated:D,currentVersion:$,latestVersion:X,majorVersion:J}=await SW0();if(D)V.warning(`\uD83D\uDEA8 You are using @capgo/cli@${$} it's not the latest version.
128
128
  Please use @capgo/cli@${X}" or @capgo/cli@${J} to keep up to date with the latest features and bug fixes.`)}var R1=p(()=>{f0();n8()});async function G_(D,$,X,J,Y,F="✅"){await I0(X,{channel:D,event:J,icon:F,org_id:$,tracking_version:2,...Y?{tags:{"app-id":Y}}:{},notify:!1})}var w_=p(()=>{f0();C6();R1();v0()});var W_=E((Bs0,q_)=>{var _5=1000,f5=_5*60,k5=f5*60,l8=k5*24,PW0=l8*7,uW0=l8*365.25;q_.exports=function(D,$){$=$||{};var X=typeof D;if(X==="string"&&D.length>0)return xW0(D);else if(X==="number"&&isFinite(D))return $.long?_W0(D):vW0(D);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(D))};function xW0(D){if(D=String(D),D.length>100)return;var $=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(D);if(!$)return;var X=parseFloat($[1]),J=($[2]||"ms").toLowerCase();switch(J){case"years":case"year":case"yrs":case"yr":case"y":return X*uW0;case"weeks":case"week":case"w":return X*PW0;case"days":case"day":case"d":return X*l8;case"hours":case"hour":case"hrs":case"hr":case"h":return X*k5;case"minutes":case"minute":case"mins":case"min":case"m":return X*f5;case"seconds":case"second":case"secs":case"sec":case"s":return X*_5;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return X;default:return}}function vW0(D){var $=Math.abs(D);if($>=l8)return Math.round(D/l8)+"d";if($>=k5)return Math.round(D/k5)+"h";if($>=f5)return Math.round(D/f5)+"m";if($>=_5)return Math.round(D/_5)+"s";return D+"ms"}function _W0(D){var $=Math.abs(D);if($>=l8)return bF(D,$,l8,"day");if($>=k5)return bF(D,$,k5,"hour");if($>=f5)return bF(D,$,f5,"minute");if($>=_5)return bF(D,$,_5,"second");return D+" ms"}function bF(D,$,X,J){var Y=$>=X*1.5;return Math.round(D/X)+" "+J+(Y?"s":"")}});var GW=E((Ns0,K_)=>{function fW0(D){X.debug=X,X.default=X,X.coerce=Z,X.disable=Q,X.enable=Y,X.enabled=U,X.humanize=W_(),X.destroy=O,Object.keys(D).forEach((G)=>{X[G]=D[G]}),X.names=[],X.skips=[],X.formatters={};function $(G){let w=0;for(let q=0;q<G.length;q++)w=(w<<5)-w+G.charCodeAt(q),w|=0;return X.colors[Math.abs(w)%X.colors.length]}X.selectColor=$;function X(G){let w,q=null,W,K;function H(...L){if(!H.enabled)return;let M=H,I=Number(new Date),B=I-(w||I);if(M.diff=B,M.prev=w,M.curr=I,w=I,L[0]=X.coerce(L[0]),typeof L[0]!=="string")L.unshift("%O");let N=0;L[0]=L[0].replace(/%([a-zA-Z%])/g,(R,v)=>{if(R==="%%")return"%";N++;let _=X.formatters[v];if(typeof _==="function"){let A=L[N];R=_.call(M,A),L.splice(N,1),N--}return R}),X.formatArgs.call(M,L),(M.log||X.log).apply(M,L)}if(H.namespace=G,H.useColors=X.useColors(),H.color=X.selectColor(G),H.extend=J,H.destroy=X.destroy,Object.defineProperty(H,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(q!==null)return q;if(W!==X.namespaces)W=X.namespaces,K=X.enabled(G);return K},set:(L)=>{q=L}}),typeof X.init==="function")X.init(H);return H}function J(G,w){let q=X(this.namespace+(typeof w>"u"?":":w)+G);return q.log=this.log,q}function Y(G){X.save(G),X.namespaces=G,X.names=[],X.skips=[];let w=(typeof G==="string"?G:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let q of w)if(q[0]==="-")X.skips.push(q.slice(1));else X.names.push(q)}function F(G,w){let q=0,W=0,K=-1,H=0;while(q<G.length)if(W<w.length&&(w[W]===G[q]||w[W]==="*"))if(w[W]==="*")K=W,H=q,W++;else q++,W++;else if(K!==-1)W=K+1,H++,q=H;else return!1;while(W<w.length&&w[W]==="*")W++;return W===w.length}function Q(){let G=[...X.names,...X.skips.map((w)=>"-"+w)].join(",");return X.enable(""),G}function U(G){for(let w of X.skips)if(F(G,w))return!1;for(let w of X.names)if(F(G,w))return!0;return!1}function Z(G){if(G instanceof Error)return G.stack||G.message;return G}function O(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return X.enable(X.load()),X}K_.exports=fW0});var B_=E((H_,hF)=>{H_.formatArgs=yW0;H_.save=bW0;H_.load=hW0;H_.useColors=kW0;H_.storage=gW0();H_.destroy=(()=>{let D=!1;return()=>{if(!D)D=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();H_.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function kW0(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let D;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(D=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(D[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function yW0(D){if(D[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+D[0]+(this.useColors?"%c ":" ")+"+"+hF.exports.humanize(this.diff),!this.useColors)return;let $="color: "+this.color;D.splice(1,0,$,"color: inherit");let X=0,J=0;D[0].replace(/%[a-zA-Z%]/g,(Y)=>{if(Y==="%%")return;if(X++,Y==="%c")J=X}),D.splice(J,0,$)}H_.log=console.debug||console.log||(()=>{});function bW0(D){try{if(D)H_.storage.setItem("debug",D);else H_.storage.removeItem("debug")}catch($){}}function hW0(){let D;try{D=H_.storage.getItem("debug")||H_.storage.getItem("DEBUG")}catch($){}if(!D&&typeof process<"u"&&"env"in process)D=process.env.DEBUG;return D}function gW0(){try{return localStorage}catch(D){}}hF.exports=GW()(H_);var{formatters:mW0}=hF.exports;mW0.j=function(D){try{return JSON.stringify(D)}catch($){return"[UnexpectedJSONParseError]: "+$.message}}});var z_=E((Vs0,N_)=>{N_.exports=(D,$=process.argv)=>{let X=D.startsWith("-")?"":D.length===1?"-":"--",J=$.indexOf(X+D),Y=$.indexOf("--");return J!==-1&&(Y===-1||J<Y)}});var M_=E((Ls0,L_)=>{var tW0=l("os"),V_=l("tty"),L$=z_(),{env:D1}=process,I4;if(L$("no-color")||L$("no-colors")||L$("color=false")||L$("color=never"))I4=0;else if(L$("color")||L$("colors")||L$("color=true")||L$("color=always"))I4=1;if("FORCE_COLOR"in D1)if(D1.FORCE_COLOR==="true")I4=1;else if(D1.FORCE_COLOR==="false")I4=0;else I4=D1.FORCE_COLOR.length===0?1:Math.min(parseInt(D1.FORCE_COLOR,10),3);function wW(D){if(D===0)return!1;return{level:D,hasBasic:!0,has256:D>=2,has16m:D>=3}}function qW(D,$){if(I4===0)return 0;if(L$("color=16m")||L$("color=full")||L$("color=truecolor"))return 3;if(L$("color=256"))return 2;if(D&&!$&&I4===void 0)return 0;let X=I4||0;if(D1.TERM==="dumb")return X;if(process.platform==="win32"){let J=tW0.release().split(".");if(Number(J[0])>=10&&Number(J[2])>=10586)return Number(J[2])>=14931?3:2;return 1}if("CI"in D1){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((J)=>(J in D1))||D1.CI_NAME==="codeship")return 1;return X}if("TEAMCITY_VERSION"in D1)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(D1.TEAMCITY_VERSION)?1:0;if(D1.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in D1){let J=parseInt((D1.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(D1.TERM_PROGRAM){case"iTerm.app":return J>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(D1.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(D1.TERM))return 1;if("COLORTERM"in D1)return 1;return X}function oW0(D){let $=qW(D,D&&D.isTTY);return wW($)}L_.exports={supportsColor:oW0,stdout:wW(qW(!0,V_.isatty(1))),stderr:wW(qW(!0,V_.isatty(2)))}});var R_=E((A_,mF)=>{var aW0=l("tty"),gF=l("util");A_.init=YK0;A_.log=$K0;A_.formatArgs=eW0;A_.save=XK0;A_.load=JK0;A_.useColors=sW0;A_.destroy=gF.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");A_.colors=[6,2,3,4,5,1];try{let D=M_();if(D&&(D.stderr||D).level>=2)A_.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(D){}A_.inspectOpts=Object.keys(process.env).filter((D)=>{return/^debug_/i.test(D)}).reduce((D,$)=>{let X=$.substring(6).toLowerCase().replace(/_([a-z])/g,(Y,F)=>{return F.toUpperCase()}),J=process.env[$];if(/^(yes|on|true|enabled)$/i.test(J))J=!0;else if(/^(no|off|false|disabled)$/i.test(J))J=!1;else if(J==="null")J=null;else J=Number(J);return D[X]=J,D},{});function sW0(){return"colors"in A_.inspectOpts?Boolean(A_.inspectOpts.colors):aW0.isatty(process.stderr.fd)}function eW0(D){let{namespace:$,useColors:X}=this;if(X){let J=this.color,Y="\x1B[3"+(J<8?J:"8;5;"+J),F=` ${Y};1m${$} \x1B[0m`;D[0]=F+D[0].split(`
129
129
  `).join(`
130
130
  `+F),D.push(Y+"m+"+mF.exports.humanize(this.diff)+"\x1B[0m")}else D[0]=DK0()+$+" "+D[0]}function DK0(){if(A_.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function $K0(...D){return process.stderr.write(gF.formatWithOptions(A_.inspectOpts,...D)+`
@@ -586,14 +586,14 @@ All packages are compatible with channel "${Q}"`)}return{finalCompatibility:Z.fi
586
586
  `).map((F)=>F.trim()).filter((F)=>F.length>0);if(Y.length>0){let F=zE([...Y,...NE]);return D?.(`Found ${F.length} matching repositories from the GitHub API.`),F}D?.("No matching repositories were returned from the paginated GitHub API. Trying a fallback request.")}else D?.("Paginated GitHub API request failed. Trying a fallback request.");let J=k9(["api",`orgs/${W8}/repos?per_page=100`]);if(J.status!==0)return D?.("Fallback request failed. Using the default repository list instead."),[...VG];try{let Y=JSON.parse(J.stdout);if(!Array.isArray(Y))return D?.("Fallback response format was invalid. Using the default repository list instead."),[...VG];let F=Y.filter((Q)=>typeof Q==="object"&&Q!==null).map((Q)=>Q.name).filter((Q)=>!!Q&&Q.startsWith(P40)).map((Q)=>`${W8}/${Q}`);if(F.length>0){let Q=zE([...F,...NE]);return D?.(`Found ${Q.length} matching repositories from the fallback request.`),Q}}catch{return D?.("Fallback response could not be parsed. Using the default repository list instead."),[...VG]}return D?.("No matching repositories were found. Using the default repository list instead."),[...VG]}function Fd0(D,$){return new Promise((X)=>{let J="",Y="",F=!1,Q,U=()=>{},Z=(O)=>{if(F)return;F=!0,$?.removeEventListener("abort",U),X(O)};if(U=()=>{Q?.kill("SIGINT"),Z({status:130,stderr:"GitHub command interrupted by user.",stdout:J})},Q=rc0("gh",D,{stdio:["ignore","pipe","pipe"]}),Q.stdout?.setEncoding("utf8"),Q.stdout?.on("data",(O)=>{J+=O}),Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(O)=>{Y+=O}),Q.on("error",()=>{Z({status:1,stderr:"`gh` command is not available in PATH.",stdout:""})}),Q.on("close",(O)=>{Z({status:O??1,stderr:Y,stdout:J})}),$){if($.aborted){U();return}$.addEventListener("abort",U,{once:!0})}})}function k9(D){try{let $=tc0("gh",D,{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{status:$.status??1,stderr:$.stderr?.toString()??"",stdout:$.stdout?.toString()??""}}catch{return{status:1,stderr:"`gh` command is not available in PATH.",stdout:""}}}function k40(){if(!h40())throw Error("GitHub CLI (`gh`) is not installed. Install it from https://cli.github.com/");if(!g40())throw Error("GitHub CLI is not logged in. Run `gh auth login` first.")}async function Qd0(D,$,X){if(D.length===0)return new Set;let J=new Set;return $?.(`Checking ${D.length} target repositories against your GitHub stars.`),await y40(D,Math.min(D.length,8),X,()=>[],async(Y)=>{let F=await Fd0(["api","-X","GET",`/user/starred/${Y}`],X);if(F.status===0){J.add(lJ(Y));return}if(F.status===1)return;if(F.status===130&&X?.aborted)throw LG();throw Error(`Unable to check star status for ${Y}. ${F.stderr||F.stdout}`.trim())}),$?.(`Found ${J.size} repositories already starred.`),J}async function y40(D,$,X,J,Y){let F=0;async function Q(){while(!0){f9(X,J());let Z=F;if(F+=1,Z>=D.length)return;await Y(D[Z],Z)}}let U=Math.min($,D.length);await Promise.all(Array.from({length:U},Q))}function Ud0(D,$,X){let J=Promise.resolve();return async()=>{f9(X);let Y,F=J;J=new Promise((Q)=>{Y=Q}),await F,await Jd0($d0(D,$),X),Y?.()}}function b40(D){let $=k9(["api","-X","PUT",`/user/starred/${D}`]);if($.status!==0){let X=$.stderr||$.stdout||`GitHub returned status ${$.status}`;throw Error(`Failed to star ${D}: ${X.trim()}`)}return VE(D),{repository:D,alreadyStarred:!1}}function MG(D){let X=(D?.trim()||x40).replace(/\.git$/i,"");if(/^https?:\/\//.test(X))try{let J=new URL(X),Y=J.hostname.toLowerCase();if(Y==="github.com"||Y==="www.github.com"){let[F,Q]=J.pathname.split("/").filter((U)=>U.length>0);if(F&&Q)return`${F}/${Q}`}}catch{}if(X.startsWith("git@github.com:")){let[,J]=X.split("git@github.com:");if(J){let[Y,F]=J.split("/");if(Y&&F)return`${Y}/${F}`}}if(X.includes("/")){let[J,Y]=X.split("/");if(J&&Y)return`${J}/${Y}`}return`${W8}/${X}`}function Zd0(D){return k9(["repo","view",D,"--json","nameWithOwner"]).status===0}function Od0(D){let $=k9(["api","-X","GET",`/user/starred/${D}`]);if($.status===0)return!0;if($.status===1)return!1;throw Error(`Unable to check star status for ${D}.`)}function h40(){return k9(["--version"]).status===0}function g40(){return k9(["auth","status"]).status===0}function m40(D){let $=MG(D);if(!h40())return{repository:$,ghInstalled:!1,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!g40())return{repository:$,ghInstalled:!0,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!Zd0($))return{repository:$,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!1,starred:!1};return{repository:$,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!0,starred:Od0($)}}async function c40(D={}){k40(),f9(D.signal);let $=D.repositories?.length?D.repositories:await Yd0(D.onDiscovery,D.signal);D.onDiscovery?.(`Prepared ${$.length} repositories to process.`);let X=Dd0(D.minDelayMs,D.maxDelayMs),J=zE($),Y=Xd0(D.maxConcurrency,ec0);f9(D.signal);let F=await Qd0(J,D.onDiscovery,D.signal),Q=Array.from({length:J.length}),U=()=>Q.filter((G)=>!!G),Z=[];for(let G=0;G<J.length;G++){f9(D.signal,U());let w=J[G],q=lJ(w);if(f40(w)){let W={repository:w,alreadyStarred:!0,skipped:!0,status:"already_starred"};D.onProgress?.(W),Q[G]=W;continue}if(F.has(q)){VE(w);let W={repository:w,alreadyStarred:!0,skipped:!0,status:"already_starred"};D.onProgress?.(W),Q[G]=W;continue}Z.push({index:G,repository:w})}let O=Ud0(X.min,X.max,D.signal);return await y40(Z,Y,D.signal,U,async({index:G,repository:w})=>{await O(),f9(D.signal,U());try{let W={repository:b40(w).repository,alreadyStarred:!1,skipped:!1,status:"starred"};D.onProgress?.(W),Q[G]=W}catch(q){let W={repository:w,alreadyStarred:!1,skipped:!1,status:"failed",error:q instanceof Error?q.message:String(q)};D.onProgress?.(W),Q[G]=W}}),U()}function LE(D){let $=MG(D);k40();let X=m40($);if(!X.repositoryExists)throw Error(`Cannot star ${$}: repository is not reachable or does not exist.`);if(X.starred)return VE($),{repository:$,alreadyStarred:!0};return b40($)}f0();v0();import{homedir as Gd0}from"node:os";import{join as wd0}from"node:path";var IG=wd0(Gd0(),".capgo-prompt-preferences.json");async function d40(D=IG){try{let $=await oO(D),X=JSON.parse($);if(!X||typeof X!=="object"||Array.isArray(X))return{};return Object.fromEntries(Object.entries(X).filter(([,J])=>typeof J==="boolean"))}catch{return{}}}async function qd0(D,$=IG){return(await d40($))[D]}async function Wd0(D,$,X=IG){let J=await d40(X);J[D]=$,await Y3(X,`${JSON.stringify(J,null,2)}
587
587
  `,{mode:384})}async function Kd0(D,$,X=IG){try{await Wd0(D,$,X)}catch(J){V.warn(`Could not save prompt preference: ${a(J)}`)}}async function n40({preferenceKey:D,message:$,initialValue:X=!1,rememberMessage:J="Remember this choice on this machine and stop asking again?"}){let Y=await qd0(D);if(Y!==void 0)return Y;let F=await AD({message:$,initialValue:X});if(y0(F))return!1;let Q=await AD({message:J,initialValue:!1});if(!y0(Q)&&Q)await Kd0(D,F);return F}f0();import l40 from"node:process";var Hd0=[{code:"aws:eu-central-1",label:"EU (Frankfurt)"},{code:"gcp:me-central1",label:"Middle East (Riyadh)"},{code:"gcp:asia-east2",label:"Hong Kong"},{code:"aws:ap-northeast-1",label:"Japan (Tokyo)"},{code:"aws:ap-south-1",label:"India (Mumbai)"},{code:"aws:us-east-1",label:"North America (Virginia)"},{code:"gcp:africa-south1",label:"Africa (South Africa)"},{code:"aws:ap-southeast-2",label:"Oceania (Sydney)"},{code:"aws:sa-east-1",label:"South America (São Paulo)"}],Bd0=60000,Nd0=1000,i40=20;function zd0(){if(typeof Intl>"u")return null;return Intl.DateTimeFormat().resolvedOptions().timeZone||null}function Vd0(){let D=zd0();if(!D)return null;if(/^America\//.test(D))return"aws:us-east-1";if(/^Europe\//.test(D)||/^Atlantic\//.test(D))return"aws:eu-central-1";if(/^Africa\//.test(D))return"gcp:africa-south1";if(/^Asia\//.test(D)){let $=(D.split("/")[1]??"").toLowerCase();if(["tokyo","osaka","seoul","pyongyang"].includes($))return"aws:ap-northeast-1";if(["kolkata","mumbai","calcutta","chennai","bangalore","hyderabad","delhi","dhaka","colombo","karachi"].includes($))return"aws:ap-south-1";if(["hong_kong","singapore","manila","jakarta","kuala_lumpur","beijing","shanghai","hongkong","taipei"].includes($))return"gcp:asia-east2";if(["sydney","melbourne","canberra","perth","brisbane","darwin","adelaide"].includes($))return"aws:ap-southeast-2";return"gcp:asia-east2"}if(/^Pacific\//.test(D)||/^Australia\//.test(D))return"aws:ap-southeast-2";return null}function Ld0(){let D=[...Hd0],$=Vd0();if(!$)return D;let X=D.findIndex((Y)=>Y.code===$);if(X<0)return D;let[J]=D.splice(X,1);return D.push(J),D}function Md0(D,$,X){let J=Math.min(Math.max(D,0),X);return Math.floor(J/X*$)}function Id0(D){let $=Math.min(Math.max(D,0),100),X=Math.round($/100*i40);return`${"█".repeat(X)}${"░".repeat(i40-X)}`}function Ad0(D){return`${Math.max(0,D)}s`}function p40({interactive:D=l40.stdout.isTTY&&l40.stderr.isTTY,totalMs:$=Bd0,updateIntervalMs:X=Nd0,title:J="Replicating your bundle in all regions...",completeMessage:Y="Your update is now available worldwide."}={}){if(!D||$<=0)return Promise.resolve();let F=Ld0();if(!F.length)return Promise.resolve();V.info(J),V.info(`Regions: ${F.map((G)=>G.label).join(" • ")}`);let Q=TD(),U=Date.now(),Z=F.length,O=null;return new Promise((G)=>{let w=()=>{let q=Date.now()-U,W=Math.max(0,$-q),K=Md0(q,Z,$),H=Math.min(100,Math.round(q/$*100)),L=Id0(H),M=K<Z?F[K]?.label||"Finalizing":"Complete",I=`${K}/${Z} regions updated • ${Ad0(Math.ceil(W/1000))} left • ${L} • Next: ${M}`;Q.message(I)};Q.start(J),w(),O=setInterval(w,X),setTimeout(()=>{if(O)clearInterval(O);Q.stop(Y),G()},$)})}function r40(D){let $=D?.autoUpdate;if($==="always")return!0;if(typeof $==="string"||$===!1)return!1;let X=D?.directUpdate;return X===!0||X==="always"}v0();f0();P6();function t40(D){try{let $=UD(D);return x$(P3($,"patch"))}catch{let $=D.match(/^(\d+)\.(\d+)\.(\d+)/);if($){let[,X,J,Y]=$;return`${X}.${J}.${Number.parseInt(Y)+1}`}return"1.0.1"}}async function o40(D,$){let X=t40(D),J=$?` for ${$}`:"",Y=await m1({message:`How do you want to handle the version${J}?`,options:[{value:"auto",label:`Auto: Bump patch version (${D} → ${X})`},{value:"manual",label:"Manual: I'll provide the version number"}]});if(y0(Y))return null;if(Y==="auto")return V.info(`\uD83D\uDD22 Auto-bumped version from ${D} to ${X}`),X;let F=await w4({message:`Current version is ${D}. Enter new version:`,validate:(Q)=>{if(!Q)return"Version is required";if(!/^\d+\.\d+\.\d+/.test(Q))return"Please enter a valid version (x.y.z)"}});if(y0(F))return null;return F}function a40(D){let $=t40(D);try{let X=UD(D);return[$,x$(P3(X,"minor")),`${D}-beta.1`,`${D}.1`]}catch{return[$,`${D}.1`,`${D}-beta.1`,`${D}-rc.1`]}}f0();q1();function Ed0(D){if(!D.incompatible)return"skip";if(!D.interactive)return"ci-ad";return D.hasCredentials?"prompt-build":"prompt-onboarding"}var Rd0="https://capgo.app/docs/cli/cloud-build/",s40="https://capgo.app/native-build/",e40="This update includes native changes. An app store update may be required for these changes to take effect. Capgo Builder can help you build and publish the required native update.";function jd0(D,$){let X=String.fromCharCode(27),J=String.fromCharCode(7);return`${X}]8;;${$}${J}${D}${X}]8;;${J}`}function Td0(D){let $=D?"run a native build (npx @capgo/cli build request --platform <ios|android>)":"set up Capgo Builder (npx @capgo/cli build onboarding)";V.warn(`${e40} To ${$} — learn more: ${s40} · docs: ${Rd0}`)}async function D80(D){try{return await Cd0(D)}catch{return"continue"}}async function Cd0(D){let{hasCredentials:$}=D,X=Ed0({incompatible:D.incompatible,interactive:D.interactive,hasCredentials:$});if(X==="skip")return"continue";let J=$?"build":"onboarding";if(g0({channel:"bundle",event:"Builder CTA Shown",icon:"\uD83D\uDCE3",apikey:D.apikey,appId:D.appId,orgId:D.orgId,tags:{surface:X==="ci-ad"?"ci":"interactive",mode:J,incompatible_count:D.incompatibleCount}}),X==="ci-ad")return Td0($),"continue";V.info(e40);let Q=await(D.confirm??AD)({message:`${J==="build"?"Start a native build with Capgo Builder now?":"Would you like to configure Capgo Builder now?"}
588
588
  ${jd0("Learn what Capgo Builder is",s40)}`,initialValue:!0});if(y0(Q))return"continue";if(Q===!0)return g0({channel:"bundle",event:"Builder CTA Accepted",icon:"✅",apikey:D.apikey,appId:D.appId,orgId:D.orgId,tags:{mode:J}}),J==="build"?"launch-build":"launch-onboarding";return g0({channel:"bundle",event:"Builder CTA Declined",icon:"\uD83D\uDEAB",apikey:D.apikey,appId:D.appId,orgId:D.orgId,tags:{mode:J}}),"continue"}import{readdirSync as $80,readFileSync as Sd0,statSync as Pd0}from"node:fs";import{extname as ud0,join as xd0}from"node:path";function vd0(D,$){return Sd0(D,"utf8").includes($)}function iJ(D,$){let X=$80(D);for(let J of X){let Y=xd0(D,J),F=Pd0(Y);if(F.isDirectory()){if(iJ(Y,$))return!0}else if(F.isFile()&&ud0(Y)===".js"){if(vd0(Y,$))return!0}}return!1}function AG(D){if($80(D).indexOf("index.html")>-1)return!0;return!1}f0();P6();var G90=JD(Z90(),1),w90=JD(kF(),1);import{Buffer as Ol0}from"node:buffer";import{createHash as Gl0}from"node:crypto";import{createReadStream as yE,statSync as wl0}from"node:fs";import{platform as ql0}from"node:os";import{join as Wl0,posix as Kl0,win32 as O90}from"node:path";import{cwd as Hl0}from"node:process";import{buffer as bE}from"node:stream/consumers";import{createBrotliCompress as Bl0}from"node:zlib";v0();async function Nl0(D,$){try{let X=new URL(`${D.hostFilesApi}/files/read/attachments/${encodeURIComponent($)}`);return X.searchParams.set("nocache",`${Date.now()}`),(await fetch(X.toString(),{method:"GET",headers:{range:"bytes=0-0","cache-control":"no-cache"}})).ok}catch{return!1}}var zl0=8192;async function Vl0(D){let $=w1(Hl0()),X=await $$("@capgo/capacitor-updater",$,D.packageJson),J;try{J=X?UD(X):void 0}catch{J=void 0}if(!X||!J)return{version:null,supportsBrotliV2:!1};let Y=!T$(J,void 0,void 0,zJ);return{version:`${J.major}.${J.minor}.${J.patch}`,supportsBrotliV2:Y}}function Ll0(D,$){if(!$)return!1;let X=$.split(",").map((J)=>J.trim()).filter((J)=>!!J);if(X.length===0)return!1;return G90.isMatch(D,X)}async function Ml0(D,$,X){let Y=wl0(D).size,F=await bE(yE(D));if(Y===0)return{buffer:F,useBrotli:!1};if(Ll0($,X.noBrotliPatterns))return{buffer:F,useBrotli:!1};if(Y<zl0)return{buffer:F,useBrotli:!1};try{let Q=await bE(yE(D).pipe(Bl0({})));if(Q.length>=Y-10)return{buffer:F,useBrotli:!1};return{buffer:Q,useBrotli:!0}}catch(Q){return V.warn(`Brotli compression failed for ${D}: ${Q}, using original file`),{buffer:F,useBrotli:!1}}}async function q90(D,$,X,J,Y,F,Q=!1){let U=TD();U.start(Y!=="v2"?"Generating the update manifest":`Generating the update manifest with ${Q?"V3":"V2"} encryption`);let Z=await I00(D);if(Y==="v2")for(let O of Z)O.hash=Q?B3(O.hash,F):H3(O.hash,F);return U.stop("Manifest generated successfully"),await I0($,{channel:"partial-update",event:"Generate manifest",icon:"\uD83D\uDCC2",org_id:X,tracking_version:2,tags:{"app-id":J},notify:!1}),Z}function Il0(D){if(ql0()!=="win32")return D;return O90.normalize(D).split(O90.sep).join(Kl0.sep)}function Al0(D){return D.split("/").map(($)=>encodeURIComponent($)).join("/")}function El0(D,$,X,J,Y){let F=Gl0("sha256").update(X).digest("hex"),Q=Al0(J);if(Y){let U=Ol0.from(Y.ivSessionKey).toString("hex");return`orgs/${D}/apps/${$}/delta/${U}/${F}_${Q}`}return`orgs/${D}/apps/${$}/delta/${F}_${Q}`}async function W90(D,$,X,J,Y,F,Q){let U=TD();U.start("Preparing partial update with TUS protocol");let Z=performance.now(),O=await J6(),G=!!(Q.partial||Q.delta||Q.partialOnly||Q.deltaOnly),{version:w,supportsBrotliV2:q}=await Vl0(Q);if(!q)throw Error(`Your project is using an older version of @capgo/capacitor-updater (${w||"unknown"}). To use Delta updates, please upgrade to version ${RO} (v5), ${jO} (v6) or ${zJ} (v7) or higher.`);else if(Q.disableBrotli)V.info("Brotli compression disabled by user request");else if(Q.noBrotliPatterns)V.info(`Files matching patterns (${Q.noBrotliPatterns}) will be excluded from brotli compression`);let W=$.filter((M)=>M.file.includes(" "));if(W.length>0)throw Error(`Files with spaces in their names (${W.map((M)=>M.file).join(", ")}). Please rename the files.`);let K=0,H=$.length,L=0;try{U.message(`Uploading ${H} files using TUS protocol`);let M=async(R)=>{let v=Wl0(X,R.file),_=Il0(R.file),A,x=!1;if(Q.disableBrotli)A=await bE(yE(v)),x=!1;else{let r=await Ml0(v,_,Q);A=r.buffer,x=r.useBrotli}let P=A;if(F)P=K3(A,F.sessionKey,F.ivSessionKey);let g=_;if(x)g=`${_}.br`,L++;let c=El0(Y,J,R.hash,g,F);if(!F&&await Nl0(O,c))return K++,Promise.resolve({file_name:g,s3_path:c,file_hash:R.hash});return new Promise((r,f)=>{U.message(`Prepare upload partial file: ${_}`);let T=s4(g);new w90.Upload(P,{endpoint:`${O.hostFilesApi}/files/upload/attachments/`,chunkSize:Q.tusChunkSize,retryDelays:[0,1000,3000,5000,1e4],removeFingerprintOnSuccess:!0,metadata:{filename:c,filetype:T},headers:{Authorization:D},onError:(u)=>{let k=u.toString(),m;try{let o=k.match(/response text: (\{.*?\})/);if(o&&o[1])m=JSON.parse(o[1]).moreInfo?.requestId}catch{}let b=m?` [requestId: ${m}]`:"";V.error(`Failed to upload ${_}: ${k}${b}`),f(u)},onProgress(){let u=(K/H*100).toFixed(2);U.message(`Uploading partial update: ${u}%`)},onSuccess(){K++,r({file_name:g,s3_path:c,file_hash:R.hash})}}).start()})},I=500,B=[];for(let R=0;R<$.length;R+=I){let v=$.slice(R,R+I),_=Math.floor(R/I)+1,A=Math.ceil($.length/I);if(A>1)U.message(`Processing batch ${_}/${A} (${v.length} files)`);let x=await Promise.all(v.map((P)=>M(P)));B.push(...x)}let z=((performance.now()-Z)/1000).toFixed(2);if(U.stop(`Partial update uploaded successfully \uD83D\uDCAA in (${z} seconds)`),L>0)V.info(`${L} of ${H} files were compressed with brotli and use .br extension`);return await I0(D,{channel:"app",event:`App Partial TUS done${L>0?" with .br extension":""}`,icon:"⏫",org_id:Y,tracking_version:2,tags:{"app-id":J},notify:!1}),await I0(D,{channel:"performance",event:"Partial upload performance",icon:"\uD83D\uDE84",org_id:Y,tracking_version:2,tags:{"app-id":J,time:z},notify:!1}),B}catch(M){let B=((performance.now()-Z)/1000).toFixed(2);if(U.error(`Failed to upload Partial bundle (after ${B} seconds)`),G)throw V.error(`Error uploading partial update: ${M}`),V.error("Delta/partial upload was explicitly requested but failed. Upload aborted."),M;else return V.info(`Error uploading partial update: ${M}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}function BD(D){throw V.error(D),Error(D)}async function hE(D,$,X){let{error:J}=await V00(D,$);if(J)BD(`Cannot ${X} bundle ${a(J)}`)}function Tl0(D){let $=new vD;$.headers=["Package","Local","Remote","Status","Details"],$.theme=vD.roundTheme,$.rows=[];for(let X of D){let{name:J,localVersion:Y,remoteVersion:F}=X,Q=e4(X),U=Q.compatible?"✅":"❌";$.rows.push([J,Y||"-",F||"-",U,Q.message])}V.info($.toString())}async function Cl0(D,$){let X=a4("",$.packageJson),J=$.bundle||D?.plugins?.CapacitorUpdater?.version||X||`0.0.1-beta.local-${Rl0().split("-")[0]}`;if(!l7.test(J))BD(`Your bundle name ${J}, is not valid it should follow semver convention : https://semver.org/`);return J}function Sl0(D){let $=D.apikey||H0();if(!$)BD("Missing API key, you need to provide an API key to upload your bundle");return $}function Pl0(D,$,X){let J=d0(D,X),Y=$.path||X?.webDir;if(!J)BD("Missing argument, you need to provide a appid or be in a capacitor project");if(!Y)BD("Missing argument, you need to provide a path (--path), or be in a capacitor project");if(!SG(Y))BD(`Path ${Y} does not exist, build your app first, or provide a valid path`);return{appid:J,path:Y}}function ul0(D,$){let X=D.codeCheck;if(typeof X>"u"||X){if(!iJ($,"notifyAppReady"))BD(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready
589
- If you are sure your app has this code, you can use the --no-code-check option`);if(!AG($))BD(`index.html is missing in the root folder of ${$}`)}}async function xl0(D,$,X,J,Y,F,Q){let{ignoreMetadataCheck:U,autoMinUpdateVersion:Z,minUpdateVersion:O}=X,{data:G,error:w}=await D.from("channels").select("disable_auto_update, version ( id, name, min_update_version, native_packages )").eq("name",J).eq("app_id",Y).maybeSingle();if(w)BD(`Cannot load channel ${J} for compatibility checks ${a(w)}`);let q=G?.version??void 0,W=!!G&&G.disable_auto_update==="version_number",K,H;if(!w&&G&&G.version&&G.version.native_packages&&!U){let N=TD();N.start(`Checking bundle compatibility with channel ${J}`);let{finalCompatibility:z,localDependencies:R}=await uO(D,Y,J,X.packageJson,X.nodeModules);if(H=z,K=R,H.filter((_)=>!L6(_)).length>0){if(N.error(`Bundle NOT compatible with ${J} channel`),V.warn(""),Tl0(H),V.warn(""),V.warn("An app store update may be required for these changes to take effect."),Z)O=F,V.info(`Auto set min-update-version to ${O}`)}else if(Z)try{let{min_update_version:_}=G.version;if(!_||!l7.test(_))BD("Invalid remote min update version, skipping auto setting compatibility");O=_,N.stop(`Auto set min-update-version to ${O}`)}catch{BD(`Cannot auto set compatibility, invalid data ${G}`)}else N.stop(`Bundle compatible with ${J} channel`)}else if(!U){if(V.warn(`Channel ${J} is new or it's your first upload with compatibility check, it will be ignored this time`),K=await CI(X.packageJson,X.nodeModules),Z)O=F,V.info(`Auto set min-update-version to ${O}`)}let L=H?void 0:U?"ignore_metadata_check":"no_remote_metadata",M=Z40(H);if(g0({channel:"bundle",event:"Bundle Upload Compatibility Checked",icon:"\uD83E\uDDEA",apikey:X.apikey,appId:Y,orgId:Q,tags:{result:M.result,incompatible_count:M.incompatibleCount,channel:J,...M.reasons.length>0?{reasons:M.reasons.join(",")}:{},...L?{skip_reason:L}:{}}}),W&&!O&&!U)BD("You need to provide a min-update-version to upload a bundle to this channel");if(O){if(!l7.test(O))BD(`Your minimal version update ${O}, is not valid it should follow semver convention : https://semver.org/`)}let I=K?new Map(K.filter((N)=>!!N.native&&N.native!==void 0).map((N)=>[N.name,N])):new Map;return{nativePackages:I.size>0||!X.ignoreMetadataCheck?Array.from(I,([N,z])=>({name:N,version:z.version,...z.ios_checksum&&{ios_checksum:z.ios_checksum},...z.android_checksum&&{android_checksum:z.android_checksum}})):void 0,minUpdateVersion:O,incompatibleCount:M.incompatibleCount,compatibility:{result:M.result,versionOldId:q?.id!=null?String(q.id):void 0,versionOldName:q?.name}}}async function vl0(D,$,X,J=!1,Y=!1){let{data:F,error:Q}=await D.rpc("exist_app_versions",{appid:$,name_version:X}).single();if(Q)BD(`Cannot check if version ${X} already exists ${a(Q)}`);if(F){if(J)return V.warn(`Version ${X} already exists - exiting gracefully due to --silent-fail option`),M0("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(Y){V.error(`❌ Version ${X} already exists`);let U=a40(X);V.info("\uD83D\uDCA1 Here are some suggestions:"),U.forEach((G,w)=>{V.info(` ${w+1}. ${G}`)});let Z=await m1({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${U[0]}`},{value:"suggest2",label:`Use ${U[1]}`},{value:"suggest3",label:`Use ${U[2]}`},{value:"suggest4",label:`Use ${U[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(y0(Z)||Z==="cancel")BD("Upload cancelled by user");let O;if(Z==="custom"){let G=await o40(X,"upload");if(!G)BD("Upload cancelled by user");O=G}else{let G=Number.parseInt(Z.replace("suggest",""))-1;O=U[G]}return V.info(`\uD83D\uDD04 Retrying with new version: ${O}`),O}BD(`Version ${X} already exists`)}return!1}async function _l0(D,$,X,J,Y,F,Q,U){let Z,O,G="",w=null,q="none",W="",K="",H=$.keyV2,L=$.key===!1,M=TD();M.start(`Zipping bundle from ${D}`),w=await TO(D),M.message("Calculating checksum");let I=w1(gE()),B=await $$("@capgo/capacitor-updater",I,$.packageJson),N=!1,z;try{z=B?UD(B):void 0}catch{z=void 0}if(!B)BD("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");else if(z)N=!T$(z,RO,jO,zJ);else if(B==="link:@capgo/capacitor-updater"||B==="file:.."||B==="file:../")V.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),N=!0;let R=$.forceCrc32Checksum===!0,v=!R&&((H||$.keyDataV2||SG(G$))&&!L||N);if(G=await m4(w,v?"sha256":"crc32"),M.stop(`Checksum ${v?"SHA256":"CRC32"}${R?" (forced)":""}: ${G}`),L)V.info("Encryption ignored");else if((H||SG(G$)||$.keyDataV2)&&!$.oldEncryption){let x=typeof H==="string"?H:G$,P=$.keyDataV2||"";if(!P&&!SG(x))BD(`Cannot find private key ${x}`);if(await I0(X,{channel:"app",event:"App encryption v2",icon:"\uD83D\uDD11",org_id:J,tracking_version:2,tags:{"app-id":Y},notify:!1},$.verbose),!P)P=jl0(x).toString();let g=z&&!T$(z,"5.30.0","6.30.0","7.30.0");V.info(`Encrypting your bundle with ${g?"V3":"V2"}`);let{sessionKey:c,ivSessionKey:r}=KG(P),f=K3(w,c,r);if(G=g?B3(G,P):H3(G,P),Z=r,O=c,q="v2",W=P,U){if(K=H40(U),$.verbose)V.info(`[Verbose] Encryption key_id: ${K}`)}if($.displayIvSession)V.info(`Your Iv Session key is ${Z},
589
+ If you are sure your app has this code, you can use the --no-code-check option`);if(!AG($))BD(`index.html is missing in the root folder of ${$}`)}}async function xl0(D,$,X,J,Y,F,Q){let{ignoreMetadataCheck:U,autoMinUpdateVersion:Z,minUpdateVersion:O}=X,{data:G,error:w}=await D.from("channels").select("disable_auto_update, version ( id, name, min_update_version, native_packages )").eq("name",J).eq("app_id",Y).maybeSingle();if(w)BD(`Cannot load channel ${J} for compatibility checks ${a(w)}`);let q=G?.version??void 0,W=!!G&&G.disable_auto_update==="version_number",K,H;if(!w&&G&&G.version&&G.version.native_packages&&!U){let N=TD();N.start(`Checking bundle compatibility with channel ${J}`);let{finalCompatibility:z,localDependencies:R}=await uO(D,Y,J,X.packageJson,X.nodeModules);if(H=z,K=R,H.filter((_)=>!L6(_)).length>0){if(N.error(`Bundle NOT compatible with ${J} channel`),V.warn(""),Tl0(H),V.warn(""),V.warn("An app store update may be required for these changes to take effect."),Z)O=F,V.info(`Auto set min-update-version to ${O}`)}else if(Z)try{let{min_update_version:_}=G.version;if(!_||!l7.test(_))BD("Invalid remote min update version, skipping auto setting compatibility");O=_,N.stop(`Auto set min-update-version to ${O}`)}catch{BD(`Cannot auto set compatibility, invalid data ${G}`)}else N.stop(`Bundle compatible with ${J} channel`)}else if(!U){if(V.warn(`Channel ${J} is new or it's your first upload with compatibility check, it will be ignored this time`),K=await CI(X.packageJson,X.nodeModules),Z)O=F,V.info(`Auto set min-update-version to ${O}`)}let L=H?void 0:U?"ignore_metadata_check":"no_remote_metadata",M=Z40(H);if(g0({channel:"bundle",event:"Bundle Upload Compatibility Checked",icon:"\uD83E\uDDEA",apikey:X.apikey,appId:Y,orgId:Q,tags:{result:M.result,incompatible_count:M.incompatibleCount,channel:J,channel_name:J,...M.reasons.length>0?{reasons:M.reasons.join(",")}:{},...L?{skip_reason:L}:{}}}),W&&!O&&!U)BD("You need to provide a min-update-version to upload a bundle to this channel");if(O){if(!l7.test(O))BD(`Your minimal version update ${O}, is not valid it should follow semver convention : https://semver.org/`)}let I=K?new Map(K.filter((N)=>!!N.native&&N.native!==void 0).map((N)=>[N.name,N])):new Map;return{nativePackages:I.size>0||!X.ignoreMetadataCheck?Array.from(I,([N,z])=>({name:N,version:z.version,...z.ios_checksum&&{ios_checksum:z.ios_checksum},...z.android_checksum&&{android_checksum:z.android_checksum}})):void 0,minUpdateVersion:O,incompatibleCount:M.incompatibleCount,compatibility:{result:M.result,versionOldId:q?.id!=null?String(q.id):void 0,versionOldName:q?.name}}}async function vl0(D,$,X,J=!1,Y=!1){let{data:F,error:Q}=await D.rpc("exist_app_versions",{appid:$,name_version:X}).single();if(Q)BD(`Cannot check if version ${X} already exists ${a(Q)}`);if(F){if(J)return V.warn(`Version ${X} already exists - exiting gracefully due to --silent-fail option`),M0("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(Y){V.error(`❌ Version ${X} already exists`);let U=a40(X);V.info("\uD83D\uDCA1 Here are some suggestions:"),U.forEach((G,w)=>{V.info(` ${w+1}. ${G}`)});let Z=await m1({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${U[0]}`},{value:"suggest2",label:`Use ${U[1]}`},{value:"suggest3",label:`Use ${U[2]}`},{value:"suggest4",label:`Use ${U[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(y0(Z)||Z==="cancel")BD("Upload cancelled by user");let O;if(Z==="custom"){let G=await o40(X,"upload");if(!G)BD("Upload cancelled by user");O=G}else{let G=Number.parseInt(Z.replace("suggest",""))-1;O=U[G]}return V.info(`\uD83D\uDD04 Retrying with new version: ${O}`),O}BD(`Version ${X} already exists`)}return!1}async function _l0(D,$,X,J,Y,F,Q,U){let Z,O,G="",w=null,q="none",W="",K="",H=$.keyV2,L=$.key===!1,M=TD();M.start(`Zipping bundle from ${D}`),w=await TO(D),M.message("Calculating checksum");let I=w1(gE()),B=await $$("@capgo/capacitor-updater",I,$.packageJson),N=!1,z;try{z=B?UD(B):void 0}catch{z=void 0}if(!B)BD("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");else if(z)N=!T$(z,RO,jO,zJ);else if(B==="link:@capgo/capacitor-updater"||B==="file:.."||B==="file:../")V.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),N=!0;let R=$.forceCrc32Checksum===!0,v=!R&&((H||$.keyDataV2||SG(G$))&&!L||N);if(G=await m4(w,v?"sha256":"crc32"),M.stop(`Checksum ${v?"SHA256":"CRC32"}${R?" (forced)":""}: ${G}`),L)V.info("Encryption ignored");else if((H||SG(G$)||$.keyDataV2)&&!$.oldEncryption){let x=typeof H==="string"?H:G$,P=$.keyDataV2||"";if(!P&&!SG(x))BD(`Cannot find private key ${x}`);if(await I0(X,{channel:"app",event:"App encryption v2",icon:"\uD83D\uDD11",org_id:J,tracking_version:2,tags:{"app-id":Y},notify:!1},$.verbose),!P)P=jl0(x).toString();let g=z&&!T$(z,"5.30.0","6.30.0","7.30.0");V.info(`Encrypting your bundle with ${g?"V3":"V2"}`);let{sessionKey:c,ivSessionKey:r}=KG(P),f=K3(w,c,r);if(G=g?B3(G,P):H3(G,P),Z=r,O=c,q="v2",W=P,U){if(K=H40(U),$.verbose)V.info(`[Verbose] Encryption key_id: ${K}`)}if($.displayIvSession)V.info(`Your Iv Session key is ${Z},
590
590
  keep it safe, you will need it to decrypt your bundle.
591
591
  It will be also visible in your dashboard
592
592
  `);w=f}let _=Math.floor((w?.byteLength??0)/1024/1024),A=Math.floor(F/1024/1024);if(w?.byteLength>F)BD(`The bundle size is ${_} Mb, this is greater than the maximum upload length ${A} Mb, please reduce the size of your bundle`);else if(w?.byteLength>Q){if(V.warn(`WARNING !!
593
593
  The bundle size is ${_} Mb, this may take a while to download for users
594
594
  `),V.info(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
595
595
  `),$.verbose)V.info("[Verbose] Bundle size details:"),V.info(` - Actual size: ${_} MB (${w?.byteLength} bytes)`),V.info(` - Alert threshold: ${Math.floor(Q/1024/1024)} MB`),V.info(` - Maximum allowed: ${A} MB`),V.info("[Verbose] Sending 'App Too Large' event to analytics...");if(await I0(X,{channel:"app-error",event:"App Too Large",icon:"\uD83D\uDE9B",org_id:J,tracking_version:2,tags:{"app-id":Y},notify:!1},$.verbose),$.verbose)V.info("[Verbose] Event sent successfully")}else if($.verbose)V.info(`[Verbose] Bundle size OK: ${_} MB (under ${Math.floor(Q/1024/1024)} MB alert threshold)`);if($.verbose)V.info("[Verbose] Bundle preparation complete, returning bundle data");return{zipped:w,ivSessionKey:Z,sessionKey:O,checksum:G,encryptionMethod:q,finalKeyData:W,keyId:K}}async function fl0(D,$,X,J,Y,F,Q,U){let Z=TD();Z.start("Uploading Bundle");let O=performance.now(),G=!1;if(Q.verbose)V.info("[Verbose] uploadBundleToCapgoCloud called:"),V.info(` - Bundle size: ${Math.floor(F.byteLength/1024)} KB`),V.info(` - App ID: ${X}`),V.info(` - Bundle version: ${J}`),V.info(` - Chunk size: ${Math.floor(U/1024/1024)} MB`);if(Q.dryUpload){if(Z.stop(`Dry run, bundle not uploaded
596
- Bundle uploaded \uD83D\uDCAA in 0 seconds`),Q.verbose)V.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let W=await J6();if(Q.verbose)V.info("[Verbose] Local config retrieved for upload");if(Q.multipart!==void 0&&Q.multipart||Q.tus!==void 0&&Q.tus){if(Q.multipart)V.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else V.info("Uploading bundle with TUS protocol");if(Q.verbose)V.info("[Verbose] Starting TUS resumable upload..."),V.info(` - Host: ${W.hostWeb}`),V.info(` - Chunk size: ${Math.floor(U/1024/1024)} MB`);if(await A00(D,F,Y,X,J,Z,W,U),G=!0,Q.verbose)V.info("[Verbose] TUS upload completed, updating database with R2 path...");let K=`orgs/${Y}/apps/${X}/${J}.zip`,{error:H}=await $.from("app_versions").update({r2_path:K}).eq("name",J).eq("app_id",X);if(H){if(V.error(`Cannot finish TUS upload ${a(H)}`),Q.verbose)V.info(`[Verbose] Database update failed: ${a(H)}`);throw Error("Cannot finish TUS upload")}if(Q.verbose)V.info(`[Verbose] Database updated with R2 path: ${K}`)}else{if(Q.verbose)V.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let K=await L00($,X,J);if(!K){if(V.error("Cannot get upload url"),Q.verbose)V.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}if(Q.verbose)V.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),V.info(` - Timeout: ${Q.timeout||RI}ms`),V.info(" - Retry attempts: 5"),V.info(" - Content-Type: application/zip");let H=new AbortController,L=setTimeout(()=>H.abort(),Q.timeout||RI);try{let M=await fetch(K,{method:"PUT",body:F,headers:{"Content-Type":"application/zip"},signal:H.signal});if(!M.ok)throw Error(`HTTP error! status: ${M.status}`)}finally{clearTimeout(L)}if(Q.verbose)V.info("[Verbose] HTTP PUT upload completed successfully")}}catch(W){let H=((performance.now()-O)/1000).toFixed(2);if(Z.error(`Failed to upload bundle ( after ${H} seconds)`),Q.verbose)V.info(`[Verbose] Upload failed after ${H} seconds`),V.info(`[Verbose] Error type: ${W instanceof Error?"Error":typeof W}`);if(W instanceof Error&&W.message.includes("HTTP error"))try{let L=W.message.match(/status: (\d+)/),M=L?L[1]:"unknown";V.error(`Upload failed with status ${M}: ${W.message}`)}catch{V.error(`Upload failed: ${W.message}`)}else{if(Q.verbose)V.info(`[Verbose] Non-HTTP error: ${a(W)}`);if(!Q.tus)V.error(`Cannot upload bundle ( try again with --tus option) ${a(W)}`);else V.error(`Cannot upload bundle please contact support if the issue persists ${a(W)}`)}if(Q.verbose)V.info("[Verbose] Cleaning up failed version from database...");if(await jI($,X,J),Q.verbose)V.info("[Verbose] Failed version cleaned up");throw W instanceof Error?W:Error(String(W))}let q=((performance.now()-O)/1000).toFixed(2);if(Z.stop(`Bundle uploaded \uD83D\uDCAA in (${q} seconds)`),Q.verbose)V.info("[Verbose] Upload successful:"),V.info(` - Upload time: ${q} seconds`),V.info(` - Upload method: ${G?"TUS (resumable)":"Standard HTTP PUT"}`),V.info(` - Bundle size: ${Math.floor(F.byteLength/1024)} KB`),V.info("[Verbose] Sending performance event...");if(await I0(D,{channel:"performance",event:G?"TUS upload zip performance":"Upload zip performance",icon:"\uD83D\uDE84",org_id:Y,tracking_version:2,tags:{"app-id":X,time:q},notify:!1},Q.verbose),Q.verbose)V.info("[Verbose] Performance event sent successfully")}async function kl0(D,$,X){let{data:J,error:Y}=await D.from("channels").select("version ( id, name, deleted )").eq("app_id",$).eq("name",X);if(Y)return V.error(`Cannot delete linked bundle on upload ${a(Y)}`),null;if(J.length===0)return V.warn("No linked bundle found in the channel you are trying to upload to"),null;let F=J[0].version;if(!F)return V.warn("No linked bundle found in the channel you are trying to upload to"),null;if(F.deleted)return V.warn("The linked bundle is already deleted"),null;return F}async function yl0(D,$){if(!$)return;let{error:X}=await D.from("app_versions").update({deleted:!0}).eq("id",$.id);if(X){V.error(`Cannot delete linked bundle on upload ${a(X)}`);return}V.info(`Linked bundle ${$.name} deleted`)}async function bl0(D,$,X,J,Y,F,Q,U,Z,O){let{data:G}=await D.rpc("get_app_versions",{apikey:$,name_version:J,appid:U}).single();if(!G)BD("Cannot get version id, cannot set channel");if(await SO(D,$,"app.create_channel",{appId:U})){let{error:q,data:W}=await CO(D,{name:Y,app_id:U,created_by:F,version:G,owner_org:Q,...O?{allow_device_self_set:!0}:{}});if(q)BD(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${a(q)}`);let K=`${Z.hostWeb}/app/${U}/channel/${W.id}`;if(W?.public)V.info("Your update is now available in your public channel \uD83C\uDF89");else if(W?.id)V.info(`Link device to this bundle to try it: ${K}`);if(X)V.info(`Bundle url: ${K}`);return!0}return V.warn("The upload key is not allowed to set the version in the channel"),!1}async function hl0(D,$,X){let{error:J,data:Y}=await $.from("apps").select("default_upload_channel").eq("app_id",D).single();if(J)throw Error(`Cannot find default upload channel: ${a(J)}. You can set it here: ${X}/app/${D}/info`);return Y.default_upload_channel}async function mE(D,$,X=!1){if(!X)L0(`Uploading with CLI version ${i1.version}`);let J,Y=L9();await WD();let{s3Region:F,s3Apikey:Q,s3Apisecret:U,s3BucketName:Z,s3Endpoint:O,s3Port:G,s3SSL:w}=$;if($.verbose)V.info("[Verbose] Starting upload process with options:"),V.info(` - API key: ${$.apikey?"provided":"from saved key"}`),V.info(` - Path: ${$.path||"from capacitor config"}`),V.info(` - Channel: ${$.channel||"from default upload channel"}`),V.info(` - Bundle: ${$.bundle||"auto-detected"}`),V.info(` - External: ${$.external||"false"}`),V.info(` - Encryption: ${$.keyV2||$.keyDataV2?"v2":$.key===!1?"disabled":"auto"}`),V.info(` - Upload method: ${$.tus?"TUS":$.zip?"ZIP":"auto"}`),V.info(` - Delta updates: ${$.delta||$.partial?"enabled":"disabled"}`);let q=Sl0($);if($.verbose)V.info("[Verbose] API key retrieved successfully");let W=await E0();if($.verbose)V.info("[Verbose] Capacitor config loaded successfully");let K=r40(W?.config?.plugins?.CapacitorUpdater),H=IO({silent:X});if(K&&$.delta===void 0){if(H){V.info("\uD83D\uDCA1 Instant updates are enabled in your config"),V.info(" Delta updates send only changed files instead of the full bundle");let C=await AD({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!y0(C)&&C){if($.delta=!0,$.verbose)V.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!X){if($.delta!==!1){if($.delta=!0,$.verbose)V.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let L=await w00();if($.verbose)V.info("[Verbose] Remote file config retrieved:"),V.info(` - Max upload length: ${Math.floor(L.maxUploadLength/1024/1024)} MB`),V.info(` - Alert upload size: ${Math.floor(L.alertUploadSize/1024/1024)} MB`),V.info(` - TUS upload: ${L.TUSUpload?"enabled":"disabled"}`),V.info(` - TUS upload forced: ${L.TUSUploadForced?"yes":"no"}`),V.info(` - Partial upload: ${L.partialUpload?"enabled":"disabled"}`),V.info(` - Max chunk size: ${Math.floor(L.maxChunkSize/1024/1024)} MB`);let{appid:M,path:I}=Pl0(D,$,W.config);if($.verbose)V.info(`[Verbose] App ID: ${M}, Build path: ${I}`);let B=await Cl0(W.config,$);if($.verbose)V.info(`[Verbose] Bundle version: ${B}`);let N=$.external?"external":"r2-direct",z="none";if($.autoSetBundle){if(await O00({version:B}),$.verbose)V.info("[Verbose] Auto-set bundle version in capacitor.config.json")}if(ul0($,I),$.verbose)V.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");V.info(`Upload ${M}@${B} started from path "${I}" to Capgo cloud`);let R=await J6();if($.verbose)V.info(`[Verbose] Local config loaded: host=${R.hostWeb}`);if($.supaHost&&$.supaAnon){if(V.info("Using custom supabase instance from provided options"),R.supaHost=$.supaHost,R.supaKey=$.supaAnon,$.verbose)V.info(`[Verbose] Custom Supabase host: ${$.supaHost}`)}let v=await T0(q,$.supaHost,$.supaAnon);if($.verbose)V.info("[Verbose] Supabase client created successfully");await sD(v,M,X);let _=await o0(v,q);if($.verbose)V.info(`[Verbose] User verified successfully, user_id: ${_}`);let A=$.channel?null:await hl0(M,v,R.hostWeb),x=$.channel||A||"production";if($.verbose)V.info(`[Verbose] Target channel: ${x}`);let P=await pD(v,M);if($.verbose)V.info(`[Verbose] Organization ID: ${P}`);if(await H00(v,P,i1.version),$.verbose)V.info("[Verbose] Remote CLI messages checked");if(await N00(v,P,q,M,!0),$.verbose)V.info("[Verbose] Plan validation passed");if($.verbose)V.info("[Verbose] Trial check completed");if($.verbose)V.info(`[Verbose] Checking compatibility with channel ${x}...`);let{nativePackages:g,minUpdateVersion:c,incompatibleCount:r,compatibility:f}=await xl0(v,Y,$,x,M,B,P),T=f.result==="incompatible";if(T&&!X){let C=await eO(M)!==null,j=await D80({incompatible:T,interactive:H,hasCredentials:C,appId:M,orgId:P,apikey:q,incompatibleCount:r});if(j!=="continue")return{success:!0,skipped:!0,reason:"NATIVE_BUILD",builderAction:j,bundle:B,checksum:null,encryptionMethod:z,storageProvider:N}}if($.verbose)V.info("[Verbose] Compatibility check completed:"),V.info(` - Native packages: ${g?g.length:0}`),V.info(` - Min update version: ${c||"none"}`);if($.verbose)V.info(`[Verbose] Checking if version ${B} already exists...`);let S=await vl0(v,M,B,$.versionExistsOk,H);if($.verbose)V.info(`[Verbose] Version exists check: ${S?typeof S==="string"?`retry with ${S}`:"yes (skipping)":"no (continuing)"}`);if(S===!0)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:B,checksum:null,encryptionMethod:z,storageProvider:N};if(typeof S==="string")return V.info(`Retrying upload with new version: ${S}`),mE(D,{...$,bundle:S},X);if($.external&&!$.external.startsWith("https://"))BD(`External link should should start with "https://" current is "${$.external}"`);if($.deleteLinkedBundleOnUpload)V.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),V.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let u={name:B,app_id:M,session_key:void 0,external_url:$.external,storage_provider:N,min_update_version:c,native_packages:g,owner_org:P,user_id:_,checksum:void 0,link:$.link||null,comment:$.comment||null,key_id:void 0,cli_version:i1.version},k=null,m="";if(!$.external){if($.verbose)V.info(`[Verbose] Preparing bundle file from path: ${I}`);let C=W.config?.plugins?.CapacitorUpdater?.publicKey,{zipped:j,ivSessionKey:h,checksum:y,sessionKey:w0,encryptionMethod:V0,finalKeyData:j0,keyId:XD}=await _l0(I,$,q,P,M,L.maxUploadLength,L.alertUploadSize,C);if(u.session_key=h,u.checksum=y,u.key_id=XD||void 0,J=w0,k=j,z=V0,m=j0,$.verbose)V.info("[Verbose] Bundle prepared:"),V.info(` - Size: ${Math.floor((j?.byteLength??0)/1024)} KB`),V.info(` - Checksum: ${y}`),V.info(` - Encryption: ${V0}`),V.info(` - IV Session Key: ${h?"present":"none"}`),V.info(` - Key ID: ${XD||"none"}`);if(!$.ignoreChecksumCheck){if($.verbose)V.info("[Verbose] Checking for duplicate checksum...");if(await C00(v,M,x,y),$.verbose)V.info("[Verbose] Checksum is unique")}}else{if($.verbose)V.info(`[Verbose] Using external URL: ${$.external}`);if(await I0(q,{channel:"app",event:"App external",icon:"\uD83D\uDCE4",org_id:P,tracking_version:2,tags:{"app-id":M},notify:!1},$.verbose),u.session_key=$.ivSessionKey,u.checksum=$.encryptedChecksum,$.verbose)V.info("[Verbose] External bundle configured:"),V.info(` - URL: ${$.external}`),V.info(` - IV Session Key: ${$.ivSessionKey?"provided":"none"}`),V.info(` - Encrypted Checksum: ${$.encryptedChecksum?"provided":"none"}`)}if($.zip){if($.tus=!1,$.verbose)V.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!L.TUSUpload||$.external){if($.tus=!1,$.verbose)V.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if($.tus=$.tus||L.TUSUploadForced,$.verbose)V.info(`[Verbose] Upload method: ${$.tus?"TUS (resumable)":"Standard"}`);if(!L.partialUpload||$.external){if($.delta=!1,$.verbose&&$.external)V.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if($.delta=$.delta||$.partial||$.deltaOnly||$.partialOnly||L.partialUploadForced,$.verbose)V.info(`[Verbose] Delta updates: ${$.delta?"enabled":"disabled"}`);if($.encryptPartial&&z==="v1")BD("You cannot encrypt the partial update if you are not using the v2 encryption method");let b="5.30.0",o="6.30.0",n="7.30.0",t=!1;if($.delta&&z==="v2"&&!$.encryptPartial){let C=w1(gE()),j=await $$("@capgo/capacitor-updater",C,$.packageJson),h;try{h=j?UD(j):void 0}catch{h=void 0}if(j&&h&&oR(h,UD("6.14.4"))){if(V.info(`Auto-enabling partial update encryption for updater version ${h} (> 6.14.4)`),$.verbose)V.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4");$.encryptPartial=!0}}if($.delta&&($.encryptPartial||z==="v2")){let C=w1(gE()),j=await $$("@capgo/capacitor-updater",C,$.packageJson),h;try{h=j?UD(j):void 0}catch{h=void 0}if(j&&h){if(t=!T$(h,b,o,n),$.verbose&&t)V.info(`[Verbose] Using hex checksum format for updater version ${h}`)}}if($.verbose&&$.delta)V.info("[Verbose] Preparing delta/partial update manifest...");let K0=$.delta?await q90(I,q,P,M,$.encryptPartial?z:"none",m,t):[];if($.verbose&&$.delta)V.info(`[Verbose] Delta manifest prepared with ${K0.length} files`);if($.verbose)V.info("[Verbose] Creating version record in database...");if(await hE(v,u,"add"),$.verbose)V.info("[Verbose] Version record created successfully");if($.dryUpload){if($.verbose)V.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!X)M0("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,bundle:B,checksum:u.checksum??null,encryptionMethod:z,sessionKey:J?J.toString("base64"):void 0,ivSessionKey:typeof u.session_key==="string"?u.session_key:void 0,storageProvider:u.storage_provider,skipped:!0,reason:"DRY_UPLOAD"}}if($.tusChunkSize&&$.tusChunkSize>L.maxChunkSize)V.error(`Chunk size ${$.tusChunkSize} is greater than the maximum chunk size ${L.maxChunkSize}, using the maximum chunk size`),$.tusChunkSize=L.maxChunkSize;else if(!$.tusChunkSize)$.tusChunkSize=L.maxChunkSize;if($.verbose)V.info(`[Verbose] TUS chunk size: ${Math.floor($.tusChunkSize/1024/1024)} MB`);if(k&&(Z||O||F||Q||U||G||w)){if(!Z||!O||!F||!Q||!U||!G)BD("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(V.info("Uploading to S3"),$.verbose)V.info("[Verbose] S3 configuration:"),V.info(` - Endpoint: ${O}`),V.info(` - Region: ${F}`),V.info(` - Bucket: ${Z}`),V.info(` - Port: ${G}`),V.info(` - SSL: ${w?"enabled":"disabled"}`);let C=`${w?"https":"http"}://${O}${G?`:${G}`:""}`,j=new zG({endPoint:O,region:F,port:G,pathStyle:!0,bucket:Z,accessKey:Q,secretKey:U}),h=`${M}-${B}`,y=encodeURIComponent(h);if($.verbose)V.info(`[Verbose] Uploading to S3 as: ${h}`);try{await j.putObject(h,Uint8Array.from(k)),u.external_url=`${C}/${y}`,u.storage_provider="external",await hE(v,u,"update")}catch(w0){await jI(v,M,B),BD(`Cannot upload bundle to S3 ${a(w0)}`)}if($.verbose)V.info(`[Verbose] S3 upload complete, external URL: ${u.external_url}`)}else if(k){if(!$.partialOnly&&!$.deltaOnly){if($.verbose)V.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await fl0(q,v,M,B,P,k,$,$.tusChunkSize)}else if($.verbose)V.info("[Verbose] Skipping full bundle upload (delta-only mode)");let C=null;try{if($.dryUpload){if($.delta=!1,$.verbose)V.info("[Verbose] Dry upload mode: skipping delta upload")}let j=u.session_key&&$.encryptPartial&&J?{sessionKey:J,ivSessionKey:u.session_key}:void 0;if($.verbose&&$.delta)V.info("[Verbose] Starting delta/partial file upload..."),V.info(` - Manifest entries: ${K0.length}`),V.info(` - Encryption: ${j?"enabled":"disabled"}`);if(C=$.delta?await W90(q,K0,I,M,P,j,$):null,$.verbose&&C)V.info(`[Verbose] Delta upload complete with ${C.length} files`)}catch(j){if(!!($.partial||$.delta||$.partialOnly||$.deltaOnly))throw j;if(V.info(`Failed to upload partial files to capgo cloud. Error: ${a(j)}. This is not a critical error, the bundle has been uploaded without the partial files`),$.verbose)V.info(`[Verbose] Delta upload error details: ${a(j)}`)}if(u.storage_provider="r2",u.manifest=C,$.verbose)V.info("[Verbose] Updating version record with storage provider and manifest...");if(await hE(v,u,"update"),$.verbose)V.info("[Verbose] Version record updated successfully")}if($.verbose)V.info("[Verbose] Checking app permissions...");let $0=await gD(v,q,M,2,!1,!0);if($.verbose)V.info("[Verbose] Permissions:"),V.info(` - Upload: ${i7($0,2)?"yes":"no"}`),V.info(` - Write: ${i7($0,3)?"yes":"no"}`),V.info(` - Admin: ${i7($0,4)?"yes":"no"}`);let R0=$.deleteLinkedBundleOnUpload&&i7($0,3),l0=R0?await kl0(v,M,x):null;if($.deleteLinkedBundleOnUpload&&!R0)V.warn("Cannot delete linked bundle on upload as a upload organization member");let F0=!1;if(i7($0,3)){if($.verbose)V.info(`[Verbose] Setting bundle ${B} to channel ${x}...`);if(F0=await bl0(v,q,!!$.bundleUrl,B,x,_,P,M,R,$.selfAssign),$.verbose)V.info("[Verbose] Channel updated successfully");if(R0){if($.verbose)V.info(`[Verbose] Deleting previously linked bundle in channel ${x}...`);await yl0(v,l0)}}else V.warn("Cannot set channel as a upload organization member");if($.verbose)V.info("[Verbose] Sending upload event...");if(await I0(q,{channel:"app",event:"App Uploaded",icon:"⏫",org_id:P,tracking_version:2,tags:{"app-id":M,bundle:B},notify:!1},$.verbose),await I0(q,{channel:"app",event:"Bundle Uploaded",icon:"⏫",org_id:P,tracking_version:2,tags:{"app-id":M,bundle:B},notify:!1,notifyConsole:!0}).catch(()=>{}),f?.result==="incompatible")g0({channel:"bundle",event:"Bundle Incompatible",icon:"\uD83D\uDEAB",apikey:q,appId:M,orgId:P,tags:{source:"upload",channel:x,channel_overwritten:F0,version_new_name:B,...f.versionOldId?{version_old_id:f.versionOldId}:{},...f.versionOldName?{version_old_name:f.versionOldName}:{}}});let x0={success:!0,bundle:B,checksum:u.checksum??null,encryptionMethod:z,sessionKey:J?J.toString("base64"):void 0,ivSessionKey:typeof u.session_key==="string"?u.session_key:void 0,storageProvider:u.storage_provider};if($.verbose)V.info("[Verbose] Upload completed successfully:"),V.info(` - Bundle: ${x0.bundle}`),V.info(` - Checksum: ${x0.checksum}`),V.info(` - Encryption: ${x0.encryptionMethod}`),V.info(` - Storage: ${x0.storageProvider}`);if(H&&!x0.skipped){let C=$.showReplicationProgress;if(C===void 0)C=await n40({preferenceKey:"uploadShowReplicationProgress",message:"Show Capgo global replication progress for this upload so you can confirm rollout in all regions?",initialValue:!1,rememberMessage:"Remember this replication progress preference for future uploads on this machine?"});if(C)await p40({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:H})}if(!X&&!x0.skipped)M0("Time to share your update to the world \uD83C\uDF0D");return x0}f0();P6();q1();R1();IX();v0();import{randomUUID as gl0}from"node:crypto";import{existsSync as ml0,writeFileSync as cl0}from"node:fs";import{cwd as dl0}from"node:process";var nl0=20;function ll0(D){console.log(JSON.stringify(D,null,2))}function sJ(D){console.error(a(D))}async function K90(D,$,X=!1){let{json:J}=$,{bundle:Y,path:F}=$,Q=!J&&!X;try{if(Q)await WD();let U=await E0(),Z=d0(D,U?.config),O=gl0().split("-")[0],G=a4("",$.packageJson);if(Y=Y||G||`0.0.1-beta.local-${O}`,Q)L0(`Zipping ${Z}@${Y}`);if(Y&&!l7.test(Y)){let R=`Your bundle name ${Y}, is not valid it should follow semver convention : https://semver.org/`;if(!X)if(J)sJ({error:"invalid_semver"});else V.error(R);throw Error("Invalid bundle version format")}if(F=F||U?.config?.webDir,!Z||!Y||!F){if(!X)if(J)sJ({error:"missing_argument"});else V.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project");throw Error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project")}if(Q)V.info(`Started from path "${F}"`);if(typeof $.codeCheck>"u"?!0:$.codeCheck){if(!iJ(F,"notifyAppReady")){if(!X)if(J)sJ({error:"notifyAppReady_not_in_source_code"});else V.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready");throw Error("notifyAppReady() is missing in build folder")}if(!AG(F)){if(!X)if(J)sJ({error:"index_html_not_found"});else V.error(`index.html is missing in the root folder of ${F}`);throw Error("index.html is missing in root folder")}}let q=await TO(F);if(Q)V.info(`Zipped ${q.byteLength} bytes`);let W=Q?TD():null;if(W)W.start("Calculating checksum");let K=w1(dl0()),H=await $$("@capgo/capacitor-updater",K,$.packageJson);if(!H){if(!X)V.warn("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");throw Error("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager")}let L=!1,M;try{M=H?UD(H):void 0}catch{M=void 0}if(M)L=!T$(M,void 0,void 0,"7.0.0");else if(H==="link:@capgo/capacitor-updater"){if(!X)V.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let I=await m4(q,$.keyV2||ml0(G$)||L?"sha256":"crc32");if(W)W.stop(`Checksum ${L?"SHA256":"CRC32"}: ${I}`);let B=Math.floor(q.byteLength/1024/1024);if(B>nl0&&Q)V.warn(`WARNING !!
596
+ Bundle uploaded \uD83D\uDCAA in 0 seconds`),Q.verbose)V.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let W=await J6();if(Q.verbose)V.info("[Verbose] Local config retrieved for upload");if(Q.multipart!==void 0&&Q.multipart||Q.tus!==void 0&&Q.tus){if(Q.multipart)V.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else V.info("Uploading bundle with TUS protocol");if(Q.verbose)V.info("[Verbose] Starting TUS resumable upload..."),V.info(` - Host: ${W.hostWeb}`),V.info(` - Chunk size: ${Math.floor(U/1024/1024)} MB`);if(await A00(D,F,Y,X,J,Z,W,U),G=!0,Q.verbose)V.info("[Verbose] TUS upload completed, updating database with R2 path...");let K=`orgs/${Y}/apps/${X}/${J}.zip`,{error:H}=await $.from("app_versions").update({r2_path:K}).eq("name",J).eq("app_id",X);if(H){if(V.error(`Cannot finish TUS upload ${a(H)}`),Q.verbose)V.info(`[Verbose] Database update failed: ${a(H)}`);throw Error("Cannot finish TUS upload")}if(Q.verbose)V.info(`[Verbose] Database updated with R2 path: ${K}`)}else{if(Q.verbose)V.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let K=await L00($,X,J);if(!K){if(V.error("Cannot get upload url"),Q.verbose)V.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}if(Q.verbose)V.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),V.info(` - Timeout: ${Q.timeout||RI}ms`),V.info(" - Retry attempts: 5"),V.info(" - Content-Type: application/zip");let H=new AbortController,L=setTimeout(()=>H.abort(),Q.timeout||RI);try{let M=await fetch(K,{method:"PUT",body:F,headers:{"Content-Type":"application/zip"},signal:H.signal});if(!M.ok)throw Error(`HTTP error! status: ${M.status}`)}finally{clearTimeout(L)}if(Q.verbose)V.info("[Verbose] HTTP PUT upload completed successfully")}}catch(W){let H=((performance.now()-O)/1000).toFixed(2);if(Z.error(`Failed to upload bundle ( after ${H} seconds)`),Q.verbose)V.info(`[Verbose] Upload failed after ${H} seconds`),V.info(`[Verbose] Error type: ${W instanceof Error?"Error":typeof W}`);if(W instanceof Error&&W.message.includes("HTTP error"))try{let L=W.message.match(/status: (\d+)/),M=L?L[1]:"unknown";V.error(`Upload failed with status ${M}: ${W.message}`)}catch{V.error(`Upload failed: ${W.message}`)}else{if(Q.verbose)V.info(`[Verbose] Non-HTTP error: ${a(W)}`);if(!Q.tus)V.error(`Cannot upload bundle ( try again with --tus option) ${a(W)}`);else V.error(`Cannot upload bundle please contact support if the issue persists ${a(W)}`)}if(Q.verbose)V.info("[Verbose] Cleaning up failed version from database...");if(await jI($,X,J),Q.verbose)V.info("[Verbose] Failed version cleaned up");throw W instanceof Error?W:Error(String(W))}let q=((performance.now()-O)/1000).toFixed(2);if(Z.stop(`Bundle uploaded \uD83D\uDCAA in (${q} seconds)`),Q.verbose)V.info("[Verbose] Upload successful:"),V.info(` - Upload time: ${q} seconds`),V.info(` - Upload method: ${G?"TUS (resumable)":"Standard HTTP PUT"}`),V.info(` - Bundle size: ${Math.floor(F.byteLength/1024)} KB`),V.info("[Verbose] Sending performance event...");if(await I0(D,{channel:"performance",event:G?"TUS upload zip performance":"Upload zip performance",icon:"\uD83D\uDE84",org_id:Y,tracking_version:2,tags:{"app-id":X,time:q},notify:!1},Q.verbose),Q.verbose)V.info("[Verbose] Performance event sent successfully")}async function kl0(D,$,X){let{data:J,error:Y}=await D.from("channels").select("version ( id, name, deleted )").eq("app_id",$).eq("name",X);if(Y)return V.error(`Cannot delete linked bundle on upload ${a(Y)}`),null;if(J.length===0)return V.warn("No linked bundle found in the channel you are trying to upload to"),null;let F=J[0].version;if(!F)return V.warn("No linked bundle found in the channel you are trying to upload to"),null;if(F.deleted)return V.warn("The linked bundle is already deleted"),null;return F}async function yl0(D,$){if(!$)return;let{error:X}=await D.from("app_versions").update({deleted:!0}).eq("id",$.id);if(X){V.error(`Cannot delete linked bundle on upload ${a(X)}`);return}V.info(`Linked bundle ${$.name} deleted`)}async function bl0(D,$,X,J,Y,F,Q,U,Z,O){let{data:G}=await D.rpc("get_app_versions",{apikey:$,name_version:J,appid:U}).single();if(!G)BD("Cannot get version id, cannot set channel");if(await SO(D,$,"app.create_channel",{appId:U})){let{error:q,data:W}=await CO(D,{name:Y,app_id:U,created_by:F,version:G,owner_org:Q,...O?{allow_device_self_set:!0}:{}});if(q)BD(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${a(q)}`);let K=`${Z.hostWeb}/app/${U}/channel/${W.id}`;if(W?.public)V.info("Your update is now available in your public channel \uD83C\uDF89");else if(W?.id)V.info(`Link device to this bundle to try it: ${K}`);if(X)V.info(`Bundle url: ${K}`);return!0}return V.warn("The upload key is not allowed to set the version in the channel"),!1}async function hl0(D,$,X){let{error:J,data:Y}=await $.from("apps").select("default_upload_channel").eq("app_id",D).single();if(J)throw Error(`Cannot find default upload channel: ${a(J)}. You can set it here: ${X}/app/${D}/info`);return Y.default_upload_channel}async function mE(D,$,X=!1){if(!X)L0(`Uploading with CLI version ${i1.version}`);let J,Y=L9();await WD();let{s3Region:F,s3Apikey:Q,s3Apisecret:U,s3BucketName:Z,s3Endpoint:O,s3Port:G,s3SSL:w}=$;if($.verbose)V.info("[Verbose] Starting upload process with options:"),V.info(` - API key: ${$.apikey?"provided":"from saved key"}`),V.info(` - Path: ${$.path||"from capacitor config"}`),V.info(` - Channel: ${$.channel||"from default upload channel"}`),V.info(` - Bundle: ${$.bundle||"auto-detected"}`),V.info(` - External: ${$.external||"false"}`),V.info(` - Encryption: ${$.keyV2||$.keyDataV2?"v2":$.key===!1?"disabled":"auto"}`),V.info(` - Upload method: ${$.tus?"TUS":$.zip?"ZIP":"auto"}`),V.info(` - Delta updates: ${$.delta||$.partial?"enabled":"disabled"}`);let q=Sl0($);if($.verbose)V.info("[Verbose] API key retrieved successfully");let W=await E0();if($.verbose)V.info("[Verbose] Capacitor config loaded successfully");let K=r40(W?.config?.plugins?.CapacitorUpdater),H=IO({silent:X});if(K&&$.delta===void 0){if(H){V.info("\uD83D\uDCA1 Instant updates are enabled in your config"),V.info(" Delta updates send only changed files instead of the full bundle");let C=await AD({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!y0(C)&&C){if($.delta=!0,$.verbose)V.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!X){if($.delta!==!1){if($.delta=!0,$.verbose)V.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let L=await w00();if($.verbose)V.info("[Verbose] Remote file config retrieved:"),V.info(` - Max upload length: ${Math.floor(L.maxUploadLength/1024/1024)} MB`),V.info(` - Alert upload size: ${Math.floor(L.alertUploadSize/1024/1024)} MB`),V.info(` - TUS upload: ${L.TUSUpload?"enabled":"disabled"}`),V.info(` - TUS upload forced: ${L.TUSUploadForced?"yes":"no"}`),V.info(` - Partial upload: ${L.partialUpload?"enabled":"disabled"}`),V.info(` - Max chunk size: ${Math.floor(L.maxChunkSize/1024/1024)} MB`);let{appid:M,path:I}=Pl0(D,$,W.config);if($.verbose)V.info(`[Verbose] App ID: ${M}, Build path: ${I}`);let B=await Cl0(W.config,$);if($.verbose)V.info(`[Verbose] Bundle version: ${B}`);let N=$.external?"external":"r2-direct",z="none";if($.autoSetBundle){if(await O00({version:B}),$.verbose)V.info("[Verbose] Auto-set bundle version in capacitor.config.json")}if(ul0($,I),$.verbose)V.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");V.info(`Upload ${M}@${B} started from path "${I}" to Capgo cloud`);let R=await J6();if($.verbose)V.info(`[Verbose] Local config loaded: host=${R.hostWeb}`);if($.supaHost&&$.supaAnon){if(V.info("Using custom supabase instance from provided options"),R.supaHost=$.supaHost,R.supaKey=$.supaAnon,$.verbose)V.info(`[Verbose] Custom Supabase host: ${$.supaHost}`)}let v=await T0(q,$.supaHost,$.supaAnon);if($.verbose)V.info("[Verbose] Supabase client created successfully");await sD(v,M,X);let _=await o0(v,q);if($.verbose)V.info(`[Verbose] User verified successfully, user_id: ${_}`);let A=$.channel?null:await hl0(M,v,R.hostWeb),x=$.channel||A||"production";if($.verbose)V.info(`[Verbose] Target channel: ${x}`);let P=await pD(v,M);if($.verbose)V.info(`[Verbose] Organization ID: ${P}`);if(await H00(v,P,i1.version),$.verbose)V.info("[Verbose] Remote CLI messages checked");if(await N00(v,P,q,M,!0),$.verbose)V.info("[Verbose] Plan validation passed");if($.verbose)V.info("[Verbose] Trial check completed");if($.verbose)V.info(`[Verbose] Checking compatibility with channel ${x}...`);let{nativePackages:g,minUpdateVersion:c,incompatibleCount:r,compatibility:f}=await xl0(v,Y,$,x,M,B,P),T=f.result==="incompatible";if(T&&!X){let C=await eO(M)!==null,j=await D80({incompatible:T,interactive:H,hasCredentials:C,appId:M,orgId:P,apikey:q,incompatibleCount:r});if(j!=="continue")return{success:!0,skipped:!0,reason:"NATIVE_BUILD",builderAction:j,bundle:B,checksum:null,encryptionMethod:z,storageProvider:N}}if($.verbose)V.info("[Verbose] Compatibility check completed:"),V.info(` - Native packages: ${g?g.length:0}`),V.info(` - Min update version: ${c||"none"}`);if($.verbose)V.info(`[Verbose] Checking if version ${B} already exists...`);let S=await vl0(v,M,B,$.versionExistsOk,H);if($.verbose)V.info(`[Verbose] Version exists check: ${S?typeof S==="string"?`retry with ${S}`:"yes (skipping)":"no (continuing)"}`);if(S===!0)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:B,checksum:null,encryptionMethod:z,storageProvider:N};if(typeof S==="string")return V.info(`Retrying upload with new version: ${S}`),mE(D,{...$,bundle:S},X);if($.external&&!$.external.startsWith("https://"))BD(`External link should should start with "https://" current is "${$.external}"`);if($.deleteLinkedBundleOnUpload)V.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),V.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let u={name:B,app_id:M,session_key:void 0,external_url:$.external,storage_provider:N,min_update_version:c,native_packages:g,owner_org:P,user_id:_,checksum:void 0,link:$.link||null,comment:$.comment||null,key_id:void 0,cli_version:i1.version},k=null,m="";if(!$.external){if($.verbose)V.info(`[Verbose] Preparing bundle file from path: ${I}`);let C=W.config?.plugins?.CapacitorUpdater?.publicKey,{zipped:j,ivSessionKey:h,checksum:y,sessionKey:w0,encryptionMethod:V0,finalKeyData:j0,keyId:XD}=await _l0(I,$,q,P,M,L.maxUploadLength,L.alertUploadSize,C);if(u.session_key=h,u.checksum=y,u.key_id=XD||void 0,J=w0,k=j,z=V0,m=j0,$.verbose)V.info("[Verbose] Bundle prepared:"),V.info(` - Size: ${Math.floor((j?.byteLength??0)/1024)} KB`),V.info(` - Checksum: ${y}`),V.info(` - Encryption: ${V0}`),V.info(` - IV Session Key: ${h?"present":"none"}`),V.info(` - Key ID: ${XD||"none"}`);if(!$.ignoreChecksumCheck){if($.verbose)V.info("[Verbose] Checking for duplicate checksum...");if(await C00(v,M,x,y),$.verbose)V.info("[Verbose] Checksum is unique")}}else{if($.verbose)V.info(`[Verbose] Using external URL: ${$.external}`);if(await I0(q,{channel:"app",event:"App external",icon:"\uD83D\uDCE4",org_id:P,tracking_version:2,tags:{"app-id":M},notify:!1},$.verbose),u.session_key=$.ivSessionKey,u.checksum=$.encryptedChecksum,$.verbose)V.info("[Verbose] External bundle configured:"),V.info(` - URL: ${$.external}`),V.info(` - IV Session Key: ${$.ivSessionKey?"provided":"none"}`),V.info(` - Encrypted Checksum: ${$.encryptedChecksum?"provided":"none"}`)}if($.zip){if($.tus=!1,$.verbose)V.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!L.TUSUpload||$.external){if($.tus=!1,$.verbose)V.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if($.tus=$.tus||L.TUSUploadForced,$.verbose)V.info(`[Verbose] Upload method: ${$.tus?"TUS (resumable)":"Standard"}`);if(!L.partialUpload||$.external){if($.delta=!1,$.verbose&&$.external)V.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if($.delta=$.delta||$.partial||$.deltaOnly||$.partialOnly||L.partialUploadForced,$.verbose)V.info(`[Verbose] Delta updates: ${$.delta?"enabled":"disabled"}`);if($.encryptPartial&&z==="v1")BD("You cannot encrypt the partial update if you are not using the v2 encryption method");let b="5.30.0",o="6.30.0",n="7.30.0",t=!1;if($.delta&&z==="v2"&&!$.encryptPartial){let C=w1(gE()),j=await $$("@capgo/capacitor-updater",C,$.packageJson),h;try{h=j?UD(j):void 0}catch{h=void 0}if(j&&h&&oR(h,UD("6.14.4"))){if(V.info(`Auto-enabling partial update encryption for updater version ${h} (> 6.14.4)`),$.verbose)V.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4");$.encryptPartial=!0}}if($.delta&&($.encryptPartial||z==="v2")){let C=w1(gE()),j=await $$("@capgo/capacitor-updater",C,$.packageJson),h;try{h=j?UD(j):void 0}catch{h=void 0}if(j&&h){if(t=!T$(h,b,o,n),$.verbose&&t)V.info(`[Verbose] Using hex checksum format for updater version ${h}`)}}if($.verbose&&$.delta)V.info("[Verbose] Preparing delta/partial update manifest...");let K0=$.delta?await q90(I,q,P,M,$.encryptPartial?z:"none",m,t):[];if($.verbose&&$.delta)V.info(`[Verbose] Delta manifest prepared with ${K0.length} files`);if($.verbose)V.info("[Verbose] Creating version record in database...");if(await hE(v,u,"add"),$.verbose)V.info("[Verbose] Version record created successfully");if($.dryUpload){if($.verbose)V.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!X)M0("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,bundle:B,checksum:u.checksum??null,encryptionMethod:z,sessionKey:J?J.toString("base64"):void 0,ivSessionKey:typeof u.session_key==="string"?u.session_key:void 0,storageProvider:u.storage_provider,skipped:!0,reason:"DRY_UPLOAD"}}if($.tusChunkSize&&$.tusChunkSize>L.maxChunkSize)V.error(`Chunk size ${$.tusChunkSize} is greater than the maximum chunk size ${L.maxChunkSize}, using the maximum chunk size`),$.tusChunkSize=L.maxChunkSize;else if(!$.tusChunkSize)$.tusChunkSize=L.maxChunkSize;if($.verbose)V.info(`[Verbose] TUS chunk size: ${Math.floor($.tusChunkSize/1024/1024)} MB`);if(k&&(Z||O||F||Q||U||G||w)){if(!Z||!O||!F||!Q||!U||!G)BD("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(V.info("Uploading to S3"),$.verbose)V.info("[Verbose] S3 configuration:"),V.info(` - Endpoint: ${O}`),V.info(` - Region: ${F}`),V.info(` - Bucket: ${Z}`),V.info(` - Port: ${G}`),V.info(` - SSL: ${w?"enabled":"disabled"}`);let C=`${w?"https":"http"}://${O}${G?`:${G}`:""}`,j=new zG({endPoint:O,region:F,port:G,pathStyle:!0,bucket:Z,accessKey:Q,secretKey:U}),h=`${M}-${B}`,y=encodeURIComponent(h);if($.verbose)V.info(`[Verbose] Uploading to S3 as: ${h}`);try{await j.putObject(h,Uint8Array.from(k)),u.external_url=`${C}/${y}`,u.storage_provider="external",await hE(v,u,"update")}catch(w0){await jI(v,M,B),BD(`Cannot upload bundle to S3 ${a(w0)}`)}if($.verbose)V.info(`[Verbose] S3 upload complete, external URL: ${u.external_url}`)}else if(k){if(!$.partialOnly&&!$.deltaOnly){if($.verbose)V.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await fl0(q,v,M,B,P,k,$,$.tusChunkSize)}else if($.verbose)V.info("[Verbose] Skipping full bundle upload (delta-only mode)");let C=null;try{if($.dryUpload){if($.delta=!1,$.verbose)V.info("[Verbose] Dry upload mode: skipping delta upload")}let j=u.session_key&&$.encryptPartial&&J?{sessionKey:J,ivSessionKey:u.session_key}:void 0;if($.verbose&&$.delta)V.info("[Verbose] Starting delta/partial file upload..."),V.info(` - Manifest entries: ${K0.length}`),V.info(` - Encryption: ${j?"enabled":"disabled"}`);if(C=$.delta?await W90(q,K0,I,M,P,j,$):null,$.verbose&&C)V.info(`[Verbose] Delta upload complete with ${C.length} files`)}catch(j){if(!!($.partial||$.delta||$.partialOnly||$.deltaOnly))throw j;if(V.info(`Failed to upload partial files to capgo cloud. Error: ${a(j)}. This is not a critical error, the bundle has been uploaded without the partial files`),$.verbose)V.info(`[Verbose] Delta upload error details: ${a(j)}`)}if(u.storage_provider="r2",u.manifest=C,$.verbose)V.info("[Verbose] Updating version record with storage provider and manifest...");if(await hE(v,u,"update"),$.verbose)V.info("[Verbose] Version record updated successfully")}if($.verbose)V.info("[Verbose] Checking app permissions...");let $0=await gD(v,q,M,2,!1,!0);if($.verbose)V.info("[Verbose] Permissions:"),V.info(` - Upload: ${i7($0,2)?"yes":"no"}`),V.info(` - Write: ${i7($0,3)?"yes":"no"}`),V.info(` - Admin: ${i7($0,4)?"yes":"no"}`);let R0=$.deleteLinkedBundleOnUpload&&i7($0,3),l0=R0?await kl0(v,M,x):null;if($.deleteLinkedBundleOnUpload&&!R0)V.warn("Cannot delete linked bundle on upload as a upload organization member");let F0=!1;if(i7($0,3)){if($.verbose)V.info(`[Verbose] Setting bundle ${B} to channel ${x}...`);if(F0=await bl0(v,q,!!$.bundleUrl,B,x,_,P,M,R,$.selfAssign),$.verbose)V.info("[Verbose] Channel updated successfully");if(R0){if($.verbose)V.info(`[Verbose] Deleting previously linked bundle in channel ${x}...`);await yl0(v,l0)}}else V.warn("Cannot set channel as a upload organization member");if($.verbose)V.info("[Verbose] Sending upload event...");if(await I0(q,{channel:"app",event:"App Uploaded",icon:"⏫",org_id:P,tracking_version:2,tags:{"app-id":M,bundle:B},notify:!1},$.verbose),await I0(q,{channel:"app",event:"Bundle Uploaded",icon:"⏫",org_id:P,tracking_version:2,tags:{"app-id":M,bundle:B},notify:!1,notifyConsole:!0}).catch(()=>{}),f?.result==="incompatible")g0({channel:"bundle",event:"Bundle Incompatible",icon:"\uD83D\uDEAB",apikey:q,appId:M,orgId:P,tags:{source:"upload",channel:x,channel_name:x,channel_overwritten:F0,version_new_name:B,...f.versionOldId?{version_old_id:f.versionOldId}:{},...f.versionOldName?{version_old_name:f.versionOldName}:{}}});let x0={success:!0,bundle:B,checksum:u.checksum??null,encryptionMethod:z,sessionKey:J?J.toString("base64"):void 0,ivSessionKey:typeof u.session_key==="string"?u.session_key:void 0,storageProvider:u.storage_provider};if($.verbose)V.info("[Verbose] Upload completed successfully:"),V.info(` - Bundle: ${x0.bundle}`),V.info(` - Checksum: ${x0.checksum}`),V.info(` - Encryption: ${x0.encryptionMethod}`),V.info(` - Storage: ${x0.storageProvider}`);if(H&&!x0.skipped){let C=$.showReplicationProgress;if(C===void 0)C=await n40({preferenceKey:"uploadShowReplicationProgress",message:"Show Capgo global replication progress for this upload so you can confirm rollout in all regions?",initialValue:!1,rememberMessage:"Remember this replication progress preference for future uploads on this machine?"});if(C)await p40({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:H})}if(!X&&!x0.skipped)M0("Time to share your update to the world \uD83C\uDF0D");return x0}f0();P6();q1();R1();IX();v0();import{randomUUID as gl0}from"node:crypto";import{existsSync as ml0,writeFileSync as cl0}from"node:fs";import{cwd as dl0}from"node:process";var nl0=20;function ll0(D){console.log(JSON.stringify(D,null,2))}function sJ(D){console.error(a(D))}async function K90(D,$,X=!1){let{json:J}=$,{bundle:Y,path:F}=$,Q=!J&&!X;try{if(Q)await WD();let U=await E0(),Z=d0(D,U?.config),O=gl0().split("-")[0],G=a4("",$.packageJson);if(Y=Y||G||`0.0.1-beta.local-${O}`,Q)L0(`Zipping ${Z}@${Y}`);if(Y&&!l7.test(Y)){let R=`Your bundle name ${Y}, is not valid it should follow semver convention : https://semver.org/`;if(!X)if(J)sJ({error:"invalid_semver"});else V.error(R);throw Error("Invalid bundle version format")}if(F=F||U?.config?.webDir,!Z||!Y||!F){if(!X)if(J)sJ({error:"missing_argument"});else V.error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project");throw Error("Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project")}if(Q)V.info(`Started from path "${F}"`);if(typeof $.codeCheck>"u"?!0:$.codeCheck){if(!iJ(F,"notifyAppReady")){if(!X)if(J)sJ({error:"notifyAppReady_not_in_source_code"});else V.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready");throw Error("notifyAppReady() is missing in build folder")}if(!AG(F)){if(!X)if(J)sJ({error:"index_html_not_found"});else V.error(`index.html is missing in the root folder of ${F}`);throw Error("index.html is missing in root folder")}}let q=await TO(F);if(Q)V.info(`Zipped ${q.byteLength} bytes`);let W=Q?TD():null;if(W)W.start("Calculating checksum");let K=w1(dl0()),H=await $$("@capgo/capacitor-updater",K,$.packageJson);if(!H){if(!X)V.warn("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");throw Error("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager")}let L=!1,M;try{M=H?UD(H):void 0}catch{M=void 0}if(M)L=!T$(M,void 0,void 0,"7.0.0");else if(H==="link:@capgo/capacitor-updater"){if(!X)V.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let I=await m4(q,$.keyV2||ml0(G$)||L?"sha256":"crc32");if(W)W.stop(`Checksum ${L?"SHA256":"CRC32"}: ${I}`);let B=Math.floor(q.byteLength/1024/1024);if(B>nl0&&Q)V.warn(`WARNING !!
597
597
  The bundle size is ${B} Mb, this may take a while to download for users
598
598
  `),V.warn(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
599
599
  `);let N=Q?TD():null,z=$.name||`${Z}_${Y}.zip`;if(N)N.start(`Saving to ${z}`);if(cl0(z,q),N)N.stop(`Saved to ${z}`);if(g0({channel:"bundle",event:"Bundle Zipped",icon:"\uD83D\uDDDC️",tags:{zip_size_bytes:q.byteLength}}),Q)M0("Done ✅");if(!X&&J)ll0({bundle:Y,filename:z,checksum:I});return{bundle:Y,filename:z,checksum:I}}catch(U){if(!X)if(J)sJ(U);else V.error(a(U));throw U instanceof Error?U:Error(String(U))}}f0();v0();async function H90(D,$,X,J=!1){if(!J)L0("Create channel");X.apikey=X.apikey||H0();let Y=await E0(J).catch(()=>{return});if($=d0($,Y?.config),!X.apikey){if(!J)V.error("Missing API key, you need to provide an API key to upload your bundle");throw Error("Missing API key")}if(!$){if(!J)V.error("Missing argument, you need to provide a appId, or be in a capacitor project");throw Error("Missing appId")}let F=await T0(X.apikey,X.supaHost,X.supaAnon,J);if(await sD(F,$,J),await o0(F,X.apikey),await gD(F,X.apikey,$,4,J,!0),!J)V.info(`Creating channel ${$}#${D} to Capgo`);let Q=await pD(F,$),U=await o0(F,X.apikey),Z=await x00(F,{name:D,app_id:$,version:null,created_by:U,owner_org:Q,allow_device_self_set:X.selfAssign??!1,public:X.default??!1});if(Z.error){if(!J)V.error(`Cannot create Channel \uD83D\uDE40
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capgo/cli",
3
3
  "type": "module",
4
- "version": "7.119.2",
4
+ "version": "7.120.0",
5
5
  "description": "A CLI to upload to capgo servers",
6
6
  "author": "Martin martin@capgo.app",
7
7
  "license": "Apache 2.0",