@capgo/cli 8.68.1 → 8.69.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
@@ -67,7 +67,7 @@ ${X}
67
67
  `}}}}).prompt();var GB=fA(()=>{AZA();AZA();d7A();h7A();$x=rA(p7A(),1);QZA=gvQ(),hvQ=l6("◆","*"),AfA=l6("■","x"),QfA=l6("▲","x"),$ZA=l6("◇","o"),uvQ=l6("┌","T"),i8=l6("│","|"),jU=l6("└","—"),MXB=l6("┐","T"),OXB=l6("┘","—"),BZA=l6("●",">"),cn=l6("○"," "),LXB=l6("◻","[•]"),NXB=l6("◼","[+]"),CXB=l6("◻","[ ]"),mvQ=l6("▪","•"),VXB=l6("─","-"),RXB=l6("╮","+"),EXB=l6("├","+"),jXB=l6("╯","+"),wXB=l6("╰","+"),PXB=l6("╭","+"),cvQ=l6("●","•"),dvQ=l6("◆","*"),lvQ=l6("▲","!"),pvQ=l6("■","x");_XB=[`${_0("dim","↑/↓")} to navigate`,`${_0("dim","Space:")} select`,`${_0("dim","Enter:")} confirm`],f={message:(A=[],{symbol:Q=_0("gray",i8),secondarySymbol:B=_0("gray",i8),output:$=process.stdout,spacing:J=1,withGuide:Y}={})=>{let Z=[],X=Y??O5.withGuide,G=X?B:"",K=X?`${Q} `:"",W=X?`${B} `:"";for(let U=0;U<J;U++)Z.push(G);let H=Array.isArray(A)?A:A.split(`
68
68
  `);if(H.length>0){let[U,...z]=H;U.length>0?Z.push(`${K}${U}`):Z.push(X?Q:"");for(let D of z)D.length>0?Z.push(`${W}${D}`):Z.push(X?B:"")}$.write(`${Z.join(`
69
69
  `)}
70
- `)},info:(A,Q)=>{f.message(A,{...Q,symbol:_0("blue",cvQ)})},success:(A,Q)=>{f.message(A,{...Q,symbol:_0("green",dvQ)})},step:(A,Q)=>{f.message(A,{...Q,symbol:_0("green",$ZA)})},warn:(A,Q)=>{f.message(A,{...Q,symbol:_0("yellow",lvQ)})},warning:(A,Q)=>{f.warn(A,Q)},error:(A,Q)=>{f.message(A,{...Q,symbol:_0("red",pvQ)})}},TXB={light:l6("─","-"),heavy:l6("━","="),block:l6("█","#")},ovQ=[`${_0("dim","↑/↓")} to navigate`,`${_0("dim","Enter:")} confirm`],SXB=`${_0("gray",i8)} `});var D6;var qX=fA(()=>{D6={name:"@capgo/cli",type:"module",version:"8.68.1",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:"https://github.com/Cap-go/capgo.app",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:notify-app-ready-background":"bun test ./test/test-notify-app-ready-background.mjs ./test/test-background-check-shutdown.mjs","test:bundle":"bun test/test-bundle.mjs","test:bundle-validation":"bun test test/bundle/","test:prescan":"bun test test/prescan/","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:fail-on-incompatible":"bun test/test-fail-on-incompatible.mjs","test:native-dependencies":"bun test/test-native-dependencies.mjs && bun test/test-get-remote-dependencies.mjs","test:package-json-guard":"bun test/test-package-json-guard.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-export":"bun test/test-credentials-export.mjs","test:asc-key-protocol":"bun test/test-asc-key-protocol.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:cli-help":"bun test/test-cli-help.mjs","test:build-cache-payload":"bun test/test-build-cache-payload.mjs","test:build-cancellation":"bun test/test-build-cancellation.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 && bun test/test-android-select-guard.mjs","test:android-keystore-action":"bun test/test-android-keystore-action.mjs","test:android-google-play-action":"bun test/test-android-google-play-action.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:cli-headers":"bun test/test-cli-headers.mjs","test:min-cli-version":"bun test/test-min-cli-version.mjs","test:authenticated-command-invocation":"bun test/test-authenticated-command-invocation.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:preview-qr":"bun test/test-preview-qr.mjs","test:bundle-pages":"bun test test/test-bundle-pages.test.ts","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:mcp-instructions":"bun test/test-mcp-instructions.mjs","test:mcp-stdout-guard":"bun test/test-mcp-stdout-guard.mjs","test:mcp-platform-select":"bun test/test-mcp-platform-select.mjs","test:mcp-explain-scopes":"bun test/test-mcp-explain-scopes.mjs","test:mcp-oauth-reopen":"bun test/test-mcp-oauth-reopen.mjs","test:mcp-broker-oauth":"bun test/test-mcp-broker-oauth.mjs","test:mcp-broker-session":"bun test/test-mcp-broker-session.mjs","test:mcp-credentials-manage":"bun test/test-mcp-credentials-manage.mjs","test:mcp-resume-prompt":"bun test/test-mcp-resume-prompt.mjs","test:mcp-build-job":"bun test/test-mcp-build-job.mjs","test:mcp-build-tools":"bun test/test-mcp-build-tools.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:app-add-exists":"bun test/test-app-add-exists.mjs","test:app-add-getting-started":"bun test/test-app-add-getting-started.mjs","test:app-list-output-text":"bun test/test-app-list-output-text.mjs","test:app-todo":"bun test/test-app-todo.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:cli-recovery":"bun test/test-cli-recovery.mjs","test:create-supabase-client":"bun test/test-create-supabase-client.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:channel-add-exists":"bun test/test-channel-add-exists.mjs","test:wait-log":"bun test/test-wait-log.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:init-upload-recovery":"bun test/test-init-upload-error-gate.mjs && bun test/test-init-upload-monorepo-recovery.mjs","test:init-replay":"bun test/test-init-replay.mjs","test:init-telemetry":"bun test/test-init-telemetry.mjs","test:capacitor-config-target":"bun test/test-capacitor-config-target.mjs","test:builder-app-id-config":"bun test/test-builder-app-id-config.mjs","test:capacitor-config-typescript7":"bun test/test-capacitor-config-typescript7.mjs","test:capacitor-config-native-import":"bun test/test-capacitor-config-native-import.mjs","test:cli-user-error-config":"bun test/test-cli-user-error-config.mjs","test:cordova-upload-mode":"bun test/test-cordova-upload-mode.mjs","test:init-monorepo-targeting":"bun run test:capacitor-config-target && bun run test:builder-app-id-config && bun run test:capacitor-config-typescript7 && bun run test:capacitor-config-native-import && bun run test:cli-user-error-config && bun test/test-init-monorepo-targeting.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:auth-session":"bun test/test-auth-session.mjs","test:mcp":"node test/test-mcp.mjs","test:mcp-no-key-handshake":"node test/test-mcp-no-key-handshake.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:project-type-detection":"bun test/test-project-type-detection.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:helper-dce":"bash scripts/check-helper-dce.sh","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:apple-api-verify-key":"bun test/test-apple-api-verify-key.mjs","test:bundle-id-detector":"bun test/test-bundle-id-detector.mjs","test:apple-api-app-list":"bun test/test-apple-api-app-list.mjs","test:apple-api-cert-create":"bun test/test-apple-api-cert-create.mjs","test:app-verification":"bun test/test-app-verification.mjs","test:pbxproj-parser":"bun test/test-pbxproj-parser.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs","test:self-update":"bun test/test-self-update.mjs","test:update-prompt":"bun test/test-update-prompt.mjs","test:android-tail-engine":"bun test/test-android-tail-engine.mjs","test:android-tail-render":"bun test/test-android-tail-render.mjs","test:android-tail-routing":"bun test/test-android-tail-routing.mjs","test:dev-gate-stripped":"bun test/test-dev-gate-stripped.mjs","test:frame-fit-ios-shared":"bun test/test-frame-fit-ios-shared.mjs","test:ios-confirm-app-id":"bun test/test-ios-confirm-app-id.mjs","test:ios-create-new":"bun test/test-ios-create-new.mjs","test:ios-certificate-action":"bun test/test-ios-certificate-action.mjs","test:ios-profile-action":"bun test/test-ios-profile-action.mjs","test:ios-credential-action":"bun test/test-ios-credential-action.mjs","test:ios-e2e":"bun test/test-ios-e2e.mjs","test:ios-flow-contract":"bun test/test-ios-flow-contract.mjs","test:ios-import-discovery":"bun test/test-ios-import-discovery.mjs","test:ios-import-export":"bun test/test-ios-import-export.mjs","test:ios-import-pickers":"bun test/test-ios-import-pickers.mjs","test:ios-import-recovery":"bun test/test-ios-import-recovery.mjs","test:ios-recovery":"bun test/test-ios-recovery.mjs","test:ios-resume":"bun test/test-ios-resume.mjs","test:ios-tail-handoff":"bun test/test-ios-tail-handoff.mjs","test:ios-tui-render":"bun test/test-ios-tui-render.mjs","test:p8-error":"bun test/test-p8-error.mjs","test:ios-tui-routing":"bun test/test-ios-tui-routing.mjs","test:ios-updater-sync-validation":"bun test/test-ios-updater-sync-validation.mjs","test:ios-verify-app":"bun test/test-ios-verify-app.mjs","test:ios-marketing-version":"bun test/test-ios-marketing-version.mjs","test:android-version":"bun test/test-android-version.mjs","test:platform-flow-contract":"bun test/test-platform-flow-contract.mjs","test:tail-engine-shared":"bun test/test-tail-engine-shared.mjs",test:"bun run build && bun run test:helper-dce && bun run test:version-detection:setup && bun run test:bundle && bun run test:notify-app-ready-background && bun run test:bundle-validation && bun run test:functional && bun run test:semver && bun run test:auto-bump-version && bun run test:auto-bump-ai-diff && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:cordova-upload-mode && bun run test:fail-on-incompatible && bun run test:native-dependencies && bun run test:package-json-guard && bun run test:credentials && bun run test:credentials-export && bun run test:ios-provisioning-map && bun run test:ios-provisioning-command && 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:cli-help && bun run test:build-cache-payload && bun run test:build-cancellation && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:android-keystore-action && bun run test:android-google-play-action && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:cli-headers && bun run test:min-cli-version && bun run test:authenticated-command-invocation && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:preview-qr && bun run test:bundle-pages && bun run test:app-set-options && bun run test:mcp-analytics && bun run test:mcp-instructions && bun run test:mcp-live-update-onboarding && bun run test:mcp-stdout-guard && bun run test:mcp-platform-select && bun run test:mcp-explain-scopes && bun run test:mcp-oauth-reopen && bun run test:mcp-broker-oauth && bun run test:mcp-broker-session && bun run test:mcp-credentials-manage && bun run test:mcp-resume-prompt && bun run test:mcp-build-job && bun run test:mcp-build-tools && bun run test:app-created-source && bun run test:app-add-exists && bun run test:app-add-getting-started && bun run test:app-list-output-text && bun run test:app-todo && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:cli-recovery && bun run test:create-supabase-client && bun run test:build-platform-selection && bun run test:builder-project-discovery && bun run test:builder-app-selection && bun run test:builder-login-gate && 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-monorepo-targeting && bun run test:init-app-conflict && bun run test:channel-list && bun run test:channel-add-exists && bun run test:wait-log && bun run test:init-guardrails && bun run test:init-upload-recovery && bun run test:init-replay && bun run test:init-telemetry && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:mcp-no-key-handshake && bun run test:auth-session && bun run test:version-detection && bun run test:platform-paths && bun run test:project-type-detection && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:asc-key-protocol && bun run test:apple-api-import-helpers && bun run test:apple-api-verify-key && bun run test:bundle-id-detector && bun run test:apple-api-app-list && bun run test:app-verification && bun run test:pbxproj-parser && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:cicd-failure-help && bun run test:ai-sse-parser && bun run test:ai-render-markdown && bun run test:ai-stream-markdown && bun run test:ai-onboarding-mode && bun run test:ai-fit && bun run test:platform-layout && bun run test:frame-fit && bun run test:onboarding-min-size && bun run test:min-size-gate && bun run test:shell-size-gate && bun run test:build-log-sanitize && bun run test:build-output-viewport && bun run test:diff-viewer-viewport && bun run test:build-complete-exit && bun run test:ai-analyze-stream && bun run test:support-mailto && bun run test:support-redact && bun run test:support-internal-log && bun run test:support-help-menu && bun run test:support-contact && bun run test:support-upload-prompt && bun run test:support-bundle-files && bun run test:self-update && bun run test:update-prompt && bun run test:apple-api-cert-create && bun run test:android-tail-engine && bun run test:android-tail-render && bun run test:android-tail-routing && bun run test:dev-gate-stripped && bun run test:frame-fit-ios-shared && bun run test:ios-confirm-app-id && bun run test:ios-create-new && bun run test:ios-certificate-action && bun run test:ios-profile-action && bun run test:ios-credential-action && bun run test:ios-e2e && bun run test:ios-flow-contract && bun run test:ios-import-discovery && bun run test:ios-import-export && bun run test:ios-import-pickers && bun run test:ios-import-recovery && bun run test:ios-recovery && bun run test:ios-resume && bun run test:ios-tail-handoff && bun run test:ios-tui-render && bun run test:p8-error && bun run test:ios-tui-routing && bun run test:ios-updater-sync-validation && bun run test:ios-verify-app && bun run test:ios-marketing-version && bun run test:android-version && bun run test:platform-flow-contract && bun run test:tail-engine-shared && bun run test:prescan && bun run test:android-reporting-api && bun run test:android-gcp && bun run test:android-app-verification && bun run test:android-rename && bun run test:appflow-auth && bun run test:appflow-api-map && bun run test:appflow-validate && bun run test:appflow-flow && bun run test:appflow-gapfill && bun run test:appflow-engine && bun run test:appflow-tail && bun run test:appflow-fetch && bun run test:appflow-sa-decode && bun run test:app-permission-helper && bun run test:2fa-compliance-network && bun run test:organization-set-api-host && bun run test:trial-warning && bun run test:plan-validation","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:builder-project-discovery":"bun test/test-builder-project-discovery.mjs","test:builder-app-selection":"bun test/test-builder-app-selection.mjs","test:builder-login-gate":"bun test/test-builder-login-gate.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:cicd-failure-help":"bun test/test-cicd-failure-help.mjs","test:ai-analyze-stream":"bun test/test-ai-analyze-stream.mjs","test:ai-sse-parser":"bun test/test-ai-sse-parser.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs","test:ai-onboarding-mode":"bun test/test-ai-onboarding-mode.mjs","test:ai-fit":"bun test/test-ai-fit.mjs","test:platform-layout":"bun test/test-platform-layout.mjs","test:frame-fit":"bun test/run-frame-fit.mjs","test:onboarding-min-size":"bun test/test-onboarding-min-size.mjs","test:min-size-gate":"bun test/test-min-size-gate.mjs","test:shell-size-gate":"bun test/test-shell-size-gate.mjs","test:build-log-sanitize":"bun test/test-build-log-sanitize.mjs","test:build-output-viewport":"bun test/test-build-output-viewport.mjs","test:diff-viewer-viewport":"bun test/test-diff-viewer-viewport.mjs","test:build-complete-exit":"bun test/test-build-complete-exit.mjs","test:ai-stream-markdown":"bun test/test-ai-stream-markdown.mjs","test:support-mailto":"bun test/test-support-mailto.mjs","test:support-redact":"bun test/test-support-redact.mjs","test:support-internal-log":"bun test/test-support-internal-log.mjs","test:support-help-menu":"bun test/test-support-help-menu.mjs","test:support-contact":"bun test/test-support-contact.mjs","test:support-upload-prompt":"bun test/test-support-upload-prompt.mjs","test:support-bundle-files":"bun test/test-support-bundle-files.mjs","test:mcp-live-update-onboarding":"bun test/test-mcp-live-update-onboarding.mjs","test:app-set-options":"bun test/test-app-set-options.mjs && bun test/test-app-list-options.mjs","test:android-reporting-api":"bun test/test-android-reporting-api.mjs","test:android-gcp":"bun test/test-android-gcp.mjs","test:android-app-verification":"bun test/test-android-app-verification.mjs","test:android-rename":"bun test/test-android-rename.mjs","test:appflow-auth":"bun test/test-appflow-auth.mjs","test:appflow-api-map":"bun test/test-appflow-api-map.mjs","test:appflow-validate":"bun test/test-appflow-validate.mjs","test:appflow-flow":"bun test/test-appflow-flow.mjs","test:appflow-gapfill":"bun test/test-appflow-gapfill.mjs","test:appflow-engine":"bun test/test-appflow-engine.mjs","test:appflow-tail":"bun test/test-appflow-tail.mjs","test:appflow-fetch":"bun test/test-appflow-fetch.mjs","test:appflow-sa-decode":"bun test/test-appflow-sa-decode.mjs","test:app-permission-helper":"bun test/test-app-permission-helper.mjs","test:2fa-compliance-network":"bun test/test-2fa-compliance-network.mjs","test:organization-set-api-host":"bun test/test-organization-set-api-host.mjs","test:trial-warning":"bun test/test-trial-warning.mjs","test:plan-validation":"bun test/test-plan-validation.mjs","test:auto-bump-version":"bun test/test-auto-bump-version.mjs","test:auto-bump-ai-diff":"bun test/test-auto-bump-ai-diff.mjs","test:ios-provisioning-map":"bun test/test-ios-provisioning-map.mjs","test:ios-provisioning-command":"bun test/test-ios-provisioning-command.mjs","test:channel-list":"bun test/test-channel-list.mjs"},dependencies:{"@inkjs/ui":"^2.0.0","@manypkg/tools":"^2.1.2","@rrweb/types":"^2.1.1","@standard-schema/spec":"^1.1.0","@xmldom/xmldom":"^0.9.10","@xterm/addon-serialize":"^0.14.0","@xterm/headless":"^6.0.0","agent-cli-detector":"^0.1.6","happy-dom":"^20.11.0",ink:"^7.1.1","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.8","rrweb-snapshot":"^2.1.1","string-width":"^8.2.2",typescript:"6.0.3",zod:"^4.5.4"},optionalDependencies:{"@capgo/cli-helper-darwin-arm64":"^1.1.1","@capgo/cli-helper-darwin-x64":"^1.1.1","node-pty":"^1.1.0"},devDependencies:{"@antfu/eslint-config":"^9.2.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.4.2","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.7.0","@modelcontextprotocol/client":"^2.0.0-beta.5","@modelcontextprotocol/server":"^2.0.0-beta.5","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.110.8","@tanstack/intent":"^0.3.6","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^26.1.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.17","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260707.2","@vercel/ncc":"^0.44.1","@vue/compiler-dom":"3.5.40","@xterm/headless":"^6.0.0","adm-zip":"^0.6.0","ci-info":"^4.4.0",commander:"^15.0.0",eslint:"^10.7.0","git-format-staged":"4.0.2",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.75.0",partysocket:"^1.3.0",prettyjson:"^1.2.5",tmp:"^0.2.7","tus-js-client":"^4.3.1",ws:"^8.21.1"}}});function $fQ(A){if(A&&typeof A==="object"&&"status"in A){let Q=A.status;if(typeof Q==="number")return Q}return}function JfQ(A){let Q=[],B=new Set,$=A;if(typeof A==="string")return A;while($){if(typeof $==="string"){Q.push($);break}if(typeof $!=="object")break;if(B.has($))break;if(B.add($),$ instanceof Error){Q.push($.message),$=$.cause;continue}let J=$;if(typeof J.message==="string")Q.push(J.message);$=J.cause}return Q.join(" ")}function YfQ(A){return JfQ(A)}function cL(A){if(A&&typeof A==="object"&&"code"in A){let $=A.code;if(typeof $==="string"&&$.startsWith("commander."))return"commander"}let Q=$fQ(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=YfQ(A).toLowerCase();if(/econnrefused|econnreset|enotfound|eai_again|fetch failed|failed to fetch|connect timeout|und_err/.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 ZfA(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"}import{AsyncLocalStorage as XfQ}from"node:async_hooks";function tn(A,Q){return KfA.run(A,()=>Promise.resolve(Q()))}function GfQ(){return KfA.getStore()}function Jx(){WfA=!0}function HfA(){return WfA}function UfA(A){FfA=A}function GfA(A){try{FfA?.(A)}catch{}}function zfA(A,Q){let B;try{B=new URL(A).pathname}catch{B=A.split("?")[0]}let $="/functions/v1/",J=B.indexOf($);if(J>=0){let K=B.slice(J+$.length),W=0,H=K.length;while(W<H&&K[W]==="/")W+=1;while(H>W&&K[H-1]==="/")H-=1;let U=K.slice(W,H);return U?`${Q} functions:${U}`:`${Q} functions`}let Y="/rest/v1/",Z=B.indexOf(Y),X=Z>=0?B.slice(Z+Y.length):B.replace(/^\//,"");if(X.startsWith("rpc/"))return`rpc:${X.slice(4).split("/")[0]}`;let G=X.split("/")[0]||B;return`${Q} ${G}`}function KfQ(A){let Q=A?.headers;if(!Q)return;let B=Q.get;if(typeof B==="function")return B.call(Q,"capgkey")??void 0;if(Array.isArray(Q))return Q.find(([$])=>$.toLowerCase()==="capgkey")?.[1];return Q.capgkey}function DfA(){return async(Q,B)=>{let $=(B?.method??"GET").toUpperCase(),J=typeof Q==="string"?Q:Q instanceof URL?Q.href:Q.url,Y=GfQ(),Z=KfQ(B),X=Date.now();try{let G=await globalThis.fetch(Q,B);return GfA({url:J,method:$,status:G.status,ok:G.ok,durationMs:Date.now()-X,source:Y,apikey:Z}),G}catch(G){throw GfA({url:J,method:$,status:0,ok:!1,durationMs:Date.now()-X,source:Y,apikey:Z,error:G}),G}}}var KfA,WfA=!1,FfA,qfA=5000;var Yx=fA(()=>{KfA=new XfQ});var FQ;var t1=fA(()=>{FQ=class FQ extends Error{context;constructor(A,Q){super(A);this.name="CliUserError",this.context=Q}}});import{platform as WfQ}from"node:os";import{version as HfQ}from"node:process";function OfA(A){MfA=A}function UfQ(A){for(let Q=0;Q<A.length;Q++)if(A.charCodeAt(Q)>255)return!1;return!0}function IfA(A){if(A.toLowerCase()==="x-capgo-log-token")return"Build log token is missing. Re-run the build command or pass a valid log token.";return"Capgo API key is missing. Run `npx -y @capgo/cli@latest login` or pass `--apikey`."}function qfQ(A){if(A.toLowerCase()==="x-capgo-log-token")return"Build log token contains invalid characters (only ASCII is allowed). Re-run the build command to get a fresh token.";if(A.toLowerCase()==="authorization")return"Authorization header contains invalid characters (only ASCII is allowed). Check your Capgo API key or Supabase anon key configuration.";return"Capgo API key contains invalid characters (only ASCII is allowed). Copy the key from the Capgo dashboard."}function GZA(A,Q){if(Q===void 0||Q===null){if(XZA.has(A.toLowerCase()))throw new FQ(IfA(A));throw new FQ(`HTTP header "${A}" is missing or invalid.`)}if(typeof Q!=="string"){if(XZA.has(A.toLowerCase()))throw new FQ(IfA(A));throw new FQ(`HTTP header "${A}" is missing or invalid.`)}if(!UfQ(Q)){if(XZA.has(A.toLowerCase()))throw new FQ(qfQ(A));throw new FQ(`HTTP header "${A}" contains invalid characters (only ASCII is allowed).`)}return Q}function j4(A){let Q={capgo_api:FfQ,"x-cli-version":D6.version,"x-cli-command":MfA,"x-cli-node":HfQ,"x-cli-os":WfQ()};if(A)for(let[B,$]of Object.entries(A))Q[B]=GZA(B,$);return Q}var FfQ="2025-10-01",MfA="",XZA;var M7=fA(()=>{qX();t1();XZA=new Set(["authorization","capgkey","x-capgo-log-token"])});function $Z(A){let Q=A.length;while(Q>0&&A[Q-1]==="/")Q-=1;return A.slice(0,Q)}import{randomUUID as LfA}from"node:crypto";import{existsSync as zfQ,mkdirSync as DfQ,readFileSync as IfQ,writeFileSync as MfQ}from"node:fs";import{homedir as WZA,platform as OfQ,release as LfQ}from"node:os";import{join as NfA}from"node:path";import{arch as NfQ,cwd as CfA,env as dL,version as CfQ}from"node:process";function K3(A){return A==="1"||A?.toLowerCase()==="true"||A?.toLowerCase()==="yes"}function wfQ(){if(K3(dL.CAPGO_DISABLE_TELEMETRY)||K3(dL.CAPGO_DISABLE_POSTHOG))return;return dL.CAPGO_CLI_POSTHOG_API_KEY?.trim()||dL.POSTHOG_API_KEY?.trim()||RfQ}function PfQ(A){let Q=$Z(A);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 _fQ(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 TfQ(A){let Q=A,B=CfA(),$=WZA();if(B)Q=Q.replaceAll(B,"<cwd>");if($)Q=Q.replaceAll($,"~");return Q}function SfQ(A){let Q=A,B=CfA(),$=WZA();if(B)Q=Q.replaceAll(B,"<cwd>");if($)Q=Q.replaceAll($,"~");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-]+){1,}\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 kfQ(A,Q){let B=A?.split(`
70
+ `)},info:(A,Q)=>{f.message(A,{...Q,symbol:_0("blue",cvQ)})},success:(A,Q)=>{f.message(A,{...Q,symbol:_0("green",dvQ)})},step:(A,Q)=>{f.message(A,{...Q,symbol:_0("green",$ZA)})},warn:(A,Q)=>{f.message(A,{...Q,symbol:_0("yellow",lvQ)})},warning:(A,Q)=>{f.warn(A,Q)},error:(A,Q)=>{f.message(A,{...Q,symbol:_0("red",pvQ)})}},TXB={light:l6("─","-"),heavy:l6("━","="),block:l6("█","#")},ovQ=[`${_0("dim","↑/↓")} to navigate`,`${_0("dim","Enter:")} confirm`],SXB=`${_0("gray",i8)} `});var D6;var qX=fA(()=>{D6={name:"@capgo/cli",type:"module",version:"8.69.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:"https://github.com/Cap-go/capgo.app",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:notify-app-ready-background":"bun test ./test/test-notify-app-ready-background.mjs ./test/test-background-check-shutdown.mjs","test:bundle":"bun test/test-bundle.mjs","test:bundle-validation":"bun test test/bundle/","test:prescan":"bun test test/prescan/","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:fail-on-incompatible":"bun test/test-fail-on-incompatible.mjs","test:native-dependencies":"bun test/test-native-dependencies.mjs && bun test/test-get-remote-dependencies.mjs","test:package-json-guard":"bun test/test-package-json-guard.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-export":"bun test/test-credentials-export.mjs","test:asc-key-protocol":"bun test/test-asc-key-protocol.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:cli-help":"bun test/test-cli-help.mjs","test:build-cache-payload":"bun test/test-build-cache-payload.mjs","test:build-cancellation":"bun test/test-build-cancellation.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 && bun test/test-android-select-guard.mjs","test:android-keystore-action":"bun test/test-android-keystore-action.mjs","test:android-google-play-action":"bun test/test-android-google-play-action.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:cli-headers":"bun test/test-cli-headers.mjs","test:min-cli-version":"bun test/test-min-cli-version.mjs","test:authenticated-command-invocation":"bun test/test-authenticated-command-invocation.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:preview-qr":"bun test/test-preview-qr.mjs","test:bundle-pages":"bun test test/test-bundle-pages.test.ts","test:mcp-analytics":"bun test/test-mcp-analytics.mjs","test:mcp-instructions":"bun test/test-mcp-instructions.mjs","test:mcp-stdout-guard":"bun test/test-mcp-stdout-guard.mjs","test:mcp-platform-select":"bun test/test-mcp-platform-select.mjs","test:mcp-explain-scopes":"bun test/test-mcp-explain-scopes.mjs","test:mcp-oauth-reopen":"bun test/test-mcp-oauth-reopen.mjs","test:mcp-broker-oauth":"bun test/test-mcp-broker-oauth.mjs","test:mcp-broker-session":"bun test/test-mcp-broker-session.mjs","test:mcp-credentials-manage":"bun test/test-mcp-credentials-manage.mjs","test:mcp-resume-prompt":"bun test/test-mcp-resume-prompt.mjs","test:mcp-build-job":"bun test/test-mcp-build-job.mjs","test:mcp-build-tools":"bun test/test-mcp-build-tools.mjs","test:app-created-source":"bun test/test-app-created-source.mjs","test:app-add-exists":"bun test/test-app-add-exists.mjs","test:app-add-getting-started":"bun test/test-app-add-getting-started.mjs","test:app-list-output-text":"bun test/test-app-list-output-text.mjs","test:app-todo":"bun test/test-app-todo.mjs","test:doctor-analytics":"bun test/test-doctor-analytics.mjs","test:posthog-exception":"bun test/test-posthog-exception.mjs","test:cli-recovery":"bun test/test-cli-recovery.mjs","test:create-supabase-client":"bun test/test-create-supabase-client.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:channel-add-exists":"bun test/test-channel-add-exists.mjs","test:wait-log":"bun test/test-wait-log.mjs","test:init-guardrails":"bun test/test-init-guardrails.mjs","test:init-upload-recovery":"bun test/test-init-upload-error-gate.mjs && bun test/test-init-upload-monorepo-recovery.mjs","test:init-replay":"bun test/test-init-replay.mjs","test:init-telemetry":"bun test/test-init-telemetry.mjs","test:capacitor-config-target":"bun test/test-capacitor-config-target.mjs","test:builder-app-id-config":"bun test/test-builder-app-id-config.mjs","test:capacitor-config-typescript7":"bun test/test-capacitor-config-typescript7.mjs","test:capacitor-config-native-import":"bun test/test-capacitor-config-native-import.mjs","test:cli-user-error-config":"bun test/test-cli-user-error-config.mjs","test:cordova-upload-mode":"bun test/test-cordova-upload-mode.mjs","test:init-monorepo-targeting":"bun run test:capacitor-config-target && bun run test:builder-app-id-config && bun run test:capacitor-config-typescript7 && bun run test:capacitor-config-native-import && bun run test:cli-user-error-config && bun test/test-init-monorepo-targeting.mjs","test:prompt-preferences":"bun test/test-prompt-preferences.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:auth-session":"bun test/test-auth-session.mjs","test:mcp":"node test/test-mcp.mjs","test:mcp-no-key-handshake":"node test/test-mcp-no-key-handshake.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:project-type-detection":"bun test/test-project-type-detection.mjs","test:payload-split":"bun test/test-payload-split.mjs","test:macos-signing":"bun test/test-macos-signing.mjs","test:helper-dce":"bash scripts/check-helper-dce.sh","test:apple-api-import-helpers":"bun test/test-apple-api-import-helpers.mjs","test:apple-api-verify-key":"bun test/test-apple-api-verify-key.mjs","test:bundle-id-detector":"bun test/test-bundle-id-detector.mjs","test:apple-api-app-list":"bun test/test-apple-api-app-list.mjs","test:apple-api-cert-create":"bun test/test-apple-api-cert-create.mjs","test:app-verification":"bun test/test-app-verification.mjs","test:pbxproj-parser":"bun test/test-pbxproj-parser.mjs","test:manifest-path-encoding":"bun test/test-manifest-path-encoding.mjs","test:self-update":"bun test/test-self-update.mjs","test:update-prompt":"bun test/test-update-prompt.mjs","test:android-tail-engine":"bun test/test-android-tail-engine.mjs","test:android-tail-render":"bun test/test-android-tail-render.mjs","test:android-tail-routing":"bun test/test-android-tail-routing.mjs","test:dev-gate-stripped":"bun test/test-dev-gate-stripped.mjs","test:frame-fit-ios-shared":"bun test/test-frame-fit-ios-shared.mjs","test:ios-confirm-app-id":"bun test/test-ios-confirm-app-id.mjs","test:ios-create-new":"bun test/test-ios-create-new.mjs","test:ios-certificate-action":"bun test/test-ios-certificate-action.mjs","test:ios-profile-action":"bun test/test-ios-profile-action.mjs","test:ios-credential-action":"bun test/test-ios-credential-action.mjs","test:ios-e2e":"bun test/test-ios-e2e.mjs","test:ios-flow-contract":"bun test/test-ios-flow-contract.mjs","test:ios-import-discovery":"bun test/test-ios-import-discovery.mjs","test:ios-import-export":"bun test/test-ios-import-export.mjs","test:ios-import-pickers":"bun test/test-ios-import-pickers.mjs","test:ios-import-recovery":"bun test/test-ios-import-recovery.mjs","test:ios-recovery":"bun test/test-ios-recovery.mjs","test:ios-resume":"bun test/test-ios-resume.mjs","test:ios-tail-handoff":"bun test/test-ios-tail-handoff.mjs","test:ios-tui-render":"bun test/test-ios-tui-render.mjs","test:p8-error":"bun test/test-p8-error.mjs","test:ios-tui-routing":"bun test/test-ios-tui-routing.mjs","test:ios-updater-sync-validation":"bun test/test-ios-updater-sync-validation.mjs","test:ios-verify-app":"bun test/test-ios-verify-app.mjs","test:ios-marketing-version":"bun test/test-ios-marketing-version.mjs","test:android-version":"bun test/test-android-version.mjs","test:platform-flow-contract":"bun test/test-platform-flow-contract.mjs","test:tail-engine-shared":"bun test/test-tail-engine-shared.mjs",test:"bun run build && bun run test:helper-dce && bun run test:version-detection:setup && bun run test:bundle && bun run test:notify-app-ready-background && bun run test:bundle-validation && bun run test:functional && bun run test:semver && bun run test:auto-bump-version && bun run test:auto-bump-ai-diff && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:cordova-upload-mode && bun run test:fail-on-incompatible && bun run test:native-dependencies && bun run test:package-json-guard && bun run test:credentials && bun run test:credentials-export && bun run test:ios-provisioning-map && bun run test:ios-provisioning-command && 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:cli-help && bun run test:build-cache-payload && bun run test:build-cancellation && bun run test:ci-prompts && bun run test:ci-secrets && bun run test:android-onboarding-progress && bun run test:android-keystore-action && bun run test:android-google-play-action && bun run test:onboarding-telemetry && bun run test:v2-event-migration && bun run test:analytics && bun run test:cli-headers && bun run test:min-cli-version && bun run test:authenticated-command-invocation && bun run test:analytics-error-category && bun run test:analytics-org-resolver && bun run test:supabase-perf && bun run test:preview-qr && bun run test:bundle-pages && bun run test:app-set-options && bun run test:mcp-analytics && bun run test:mcp-instructions && bun run test:mcp-live-update-onboarding && bun run test:mcp-stdout-guard && bun run test:mcp-platform-select && bun run test:mcp-explain-scopes && bun run test:mcp-oauth-reopen && bun run test:mcp-broker-oauth && bun run test:mcp-broker-session && bun run test:mcp-credentials-manage && bun run test:mcp-resume-prompt && bun run test:mcp-build-job && bun run test:mcp-build-tools && bun run test:app-created-source && bun run test:app-add-exists && bun run test:app-add-getting-started && bun run test:app-list-output-text && bun run test:app-todo && bun run test:doctor-analytics && bun run test:posthog-exception && bun run test:cli-recovery && bun run test:create-supabase-client && bun run test:build-platform-selection && bun run test:builder-project-discovery && bun run test:builder-app-selection && bun run test:builder-login-gate && 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-monorepo-targeting && bun run test:init-app-conflict && bun run test:channel-list && bun run test:channel-add-exists && bun run test:wait-log && bun run test:init-guardrails && bun run test:init-upload-recovery && bun run test:init-replay && bun run test:init-telemetry && bun run test:prompt-preferences && bun run test:esm-sdk && bun run test:mcp && bun run test:mcp-no-key-handshake && bun run test:auth-session && bun run test:version-detection && bun run test:platform-paths && bun run test:project-type-detection && bun run test:payload-split && bun run test:manifest-path-encoding && bun run test:macos-signing && bun run test:asc-key-protocol && bun run test:apple-api-import-helpers && bun run test:apple-api-verify-key && bun run test:bundle-id-detector && bun run test:apple-api-app-list && bun run test:app-verification && bun run test:pbxproj-parser && bun run test:ai-log-capture && bun run test:ai-analyze-flow && bun run test:cicd-failure-help && bun run test:ai-sse-parser && bun run test:ai-render-markdown && bun run test:ai-stream-markdown && bun run test:ai-onboarding-mode && bun run test:ai-fit && bun run test:platform-layout && bun run test:frame-fit && bun run test:onboarding-min-size && bun run test:min-size-gate && bun run test:shell-size-gate && bun run test:build-log-sanitize && bun run test:build-output-viewport && bun run test:diff-viewer-viewport && bun run test:build-complete-exit && bun run test:ai-analyze-stream && bun run test:support-mailto && bun run test:support-redact && bun run test:support-internal-log && bun run test:support-help-menu && bun run test:support-contact && bun run test:support-upload-prompt && bun run test:support-bundle-files && bun run test:self-update && bun run test:update-prompt && bun run test:apple-api-cert-create && bun run test:android-tail-engine && bun run test:android-tail-render && bun run test:android-tail-routing && bun run test:dev-gate-stripped && bun run test:frame-fit-ios-shared && bun run test:ios-confirm-app-id && bun run test:ios-create-new && bun run test:ios-certificate-action && bun run test:ios-profile-action && bun run test:ios-credential-action && bun run test:ios-e2e && bun run test:ios-flow-contract && bun run test:ios-import-discovery && bun run test:ios-import-export && bun run test:ios-import-pickers && bun run test:ios-import-recovery && bun run test:ios-recovery && bun run test:ios-resume && bun run test:ios-tail-handoff && bun run test:ios-tui-render && bun run test:p8-error && bun run test:ios-tui-routing && bun run test:ios-updater-sync-validation && bun run test:ios-verify-app && bun run test:ios-marketing-version && bun run test:android-version && bun run test:platform-flow-contract && bun run test:tail-engine-shared && bun run test:prescan && bun run test:android-reporting-api && bun run test:android-gcp && bun run test:android-app-verification && bun run test:android-rename && bun run test:appflow-auth && bun run test:appflow-api-map && bun run test:appflow-validate && bun run test:appflow-flow && bun run test:appflow-gapfill && bun run test:appflow-engine && bun run test:appflow-tail && bun run test:appflow-fetch && bun run test:appflow-sa-decode && bun run test:app-permission-helper && bun run test:2fa-compliance-network && bun run test:organization-set-api-host && bun run test:trial-warning && bun run test:plan-validation","test:build-platform-selection":"bun test/test-build-platform-selection.mjs","test:builder-project-discovery":"bun test/test-builder-project-discovery.mjs","test:builder-app-selection":"bun test/test-builder-app-selection.mjs","test:builder-login-gate":"bun test/test-builder-login-gate.mjs","test:ai-log-capture":"bun test/test-ai-log-capture.mjs","test:ai-analyze-flow":"bun test/test-ai-analyze-flow.mjs","test:cicd-failure-help":"bun test/test-cicd-failure-help.mjs","test:ai-analyze-stream":"bun test/test-ai-analyze-stream.mjs","test:ai-sse-parser":"bun test/test-ai-sse-parser.mjs","test:ai-render-markdown":"bun test/test-ai-render-markdown.mjs","test:ai-onboarding-mode":"bun test/test-ai-onboarding-mode.mjs","test:ai-fit":"bun test/test-ai-fit.mjs","test:platform-layout":"bun test/test-platform-layout.mjs","test:frame-fit":"bun test/run-frame-fit.mjs","test:onboarding-min-size":"bun test/test-onboarding-min-size.mjs","test:min-size-gate":"bun test/test-min-size-gate.mjs","test:shell-size-gate":"bun test/test-shell-size-gate.mjs","test:build-log-sanitize":"bun test/test-build-log-sanitize.mjs","test:build-output-viewport":"bun test/test-build-output-viewport.mjs","test:diff-viewer-viewport":"bun test/test-diff-viewer-viewport.mjs","test:build-complete-exit":"bun test/test-build-complete-exit.mjs","test:ai-stream-markdown":"bun test/test-ai-stream-markdown.mjs","test:support-mailto":"bun test/test-support-mailto.mjs","test:support-redact":"bun test/test-support-redact.mjs","test:support-internal-log":"bun test/test-support-internal-log.mjs","test:support-help-menu":"bun test/test-support-help-menu.mjs","test:support-contact":"bun test/test-support-contact.mjs","test:support-upload-prompt":"bun test/test-support-upload-prompt.mjs","test:support-bundle-files":"bun test/test-support-bundle-files.mjs","test:mcp-live-update-onboarding":"bun test/test-mcp-live-update-onboarding.mjs","test:app-set-options":"bun test/test-app-set-options.mjs && bun test/test-app-list-options.mjs","test:android-reporting-api":"bun test/test-android-reporting-api.mjs","test:android-gcp":"bun test/test-android-gcp.mjs","test:android-app-verification":"bun test/test-android-app-verification.mjs","test:android-rename":"bun test/test-android-rename.mjs","test:appflow-auth":"bun test/test-appflow-auth.mjs","test:appflow-api-map":"bun test/test-appflow-api-map.mjs","test:appflow-validate":"bun test/test-appflow-validate.mjs","test:appflow-flow":"bun test/test-appflow-flow.mjs","test:appflow-gapfill":"bun test/test-appflow-gapfill.mjs","test:appflow-engine":"bun test/test-appflow-engine.mjs","test:appflow-tail":"bun test/test-appflow-tail.mjs","test:appflow-fetch":"bun test/test-appflow-fetch.mjs","test:appflow-sa-decode":"bun test/test-appflow-sa-decode.mjs","test:app-permission-helper":"bun test/test-app-permission-helper.mjs","test:2fa-compliance-network":"bun test/test-2fa-compliance-network.mjs","test:organization-set-api-host":"bun test/test-organization-set-api-host.mjs","test:trial-warning":"bun test/test-trial-warning.mjs","test:plan-validation":"bun test/test-plan-validation.mjs","test:auto-bump-version":"bun test/test-auto-bump-version.mjs","test:auto-bump-ai-diff":"bun test/test-auto-bump-ai-diff.mjs","test:ios-provisioning-map":"bun test/test-ios-provisioning-map.mjs","test:ios-provisioning-command":"bun test/test-ios-provisioning-command.mjs","test:channel-list":"bun test/test-channel-list.mjs"},dependencies:{"@inkjs/ui":"^2.0.0","@manypkg/tools":"^2.1.2","@rrweb/types":"^2.1.1","@standard-schema/spec":"^1.1.0","@xmldom/xmldom":"^0.9.10","@xterm/addon-serialize":"^0.14.0","@xterm/headless":"^6.0.0","agent-cli-detector":"^0.1.6","happy-dom":"^20.11.0",ink:"^7.1.1","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.4.0",qrcode:"^1.5.4",react:"^19.2.8","rrweb-snapshot":"^2.1.1","string-width":"^8.2.2",typescript:"6.0.3",zod:"^4.5.4"},optionalDependencies:{"@capgo/cli-helper-darwin-arm64":"^1.1.1","@capgo/cli-helper-darwin-x64":"^1.1.1","node-pty":"^1.1.0"},devDependencies:{"@antfu/eslint-config":"^9.2.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.6","@capacitor/cli":"^8.4.2","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.7.0","@modelcontextprotocol/client":"^2.0.0-beta.5","@modelcontextprotocol/server":"^2.0.0-beta.5","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.110.8","@tanstack/intent":"^0.3.6","@types/adm-zip":"^0.5.8","@types/jsonwebtoken":"^9.0.10","@types/node":"^26.1.1","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/qrcode":"^1.5.6","@types/react":"^19.2.17","@types/tmp":"^0.2.6","@types/ws":"^8.18.1","@typescript/native-preview":"7.0.0-dev.20260707.2","@vercel/ncc":"^0.44.1","@vue/compiler-dom":"3.5.40","@xterm/headless":"^6.0.0","adm-zip":"^0.6.0","ci-info":"^4.4.0",commander:"^15.0.0",eslint:"^10.7.0","git-format-staged":"4.0.2",husky:"^9.1.7","is-wsl":"^3.1.1",micromatch:"^4.0.8",open:"^11.0.0",oxlint:"^1.75.0",partysocket:"^1.3.0",prettyjson:"^1.2.5",tmp:"^0.2.7","tus-js-client":"^4.3.1",ws:"^8.21.1"}}});function $fQ(A){if(A&&typeof A==="object"&&"status"in A){let Q=A.status;if(typeof Q==="number")return Q}return}function JfQ(A){let Q=[],B=new Set,$=A;if(typeof A==="string")return A;while($){if(typeof $==="string"){Q.push($);break}if(typeof $!=="object")break;if(B.has($))break;if(B.add($),$ instanceof Error){Q.push($.message),$=$.cause;continue}let J=$;if(typeof J.message==="string")Q.push(J.message);$=J.cause}return Q.join(" ")}function YfQ(A){return JfQ(A)}function cL(A){if(A&&typeof A==="object"&&"code"in A){let $=A.code;if(typeof $==="string"&&$.startsWith("commander."))return"commander"}let Q=$fQ(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=YfQ(A).toLowerCase();if(/econnrefused|econnreset|enotfound|eai_again|fetch failed|failed to fetch|connect timeout|und_err/.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 ZfA(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"}import{AsyncLocalStorage as XfQ}from"node:async_hooks";function tn(A,Q){return KfA.run(A,()=>Promise.resolve(Q()))}function GfQ(){return KfA.getStore()}function Jx(){WfA=!0}function HfA(){return WfA}function UfA(A){FfA=A}function GfA(A){try{FfA?.(A)}catch{}}function zfA(A,Q){let B;try{B=new URL(A).pathname}catch{B=A.split("?")[0]}let $="/functions/v1/",J=B.indexOf($);if(J>=0){let K=B.slice(J+$.length),W=0,H=K.length;while(W<H&&K[W]==="/")W+=1;while(H>W&&K[H-1]==="/")H-=1;let U=K.slice(W,H);return U?`${Q} functions:${U}`:`${Q} functions`}let Y="/rest/v1/",Z=B.indexOf(Y),X=Z>=0?B.slice(Z+Y.length):B.replace(/^\//,"");if(X.startsWith("rpc/"))return`rpc:${X.slice(4).split("/")[0]}`;let G=X.split("/")[0]||B;return`${Q} ${G}`}function KfQ(A){let Q=A?.headers;if(!Q)return;let B=Q.get;if(typeof B==="function")return B.call(Q,"capgkey")??void 0;if(Array.isArray(Q))return Q.find(([$])=>$.toLowerCase()==="capgkey")?.[1];return Q.capgkey}function DfA(){return async(Q,B)=>{let $=(B?.method??"GET").toUpperCase(),J=typeof Q==="string"?Q:Q instanceof URL?Q.href:Q.url,Y=GfQ(),Z=KfQ(B),X=Date.now();try{let G=await globalThis.fetch(Q,B);return GfA({url:J,method:$,status:G.status,ok:G.ok,durationMs:Date.now()-X,source:Y,apikey:Z}),G}catch(G){throw GfA({url:J,method:$,status:0,ok:!1,durationMs:Date.now()-X,source:Y,apikey:Z,error:G}),G}}}var KfA,WfA=!1,FfA,qfA=5000;var Yx=fA(()=>{KfA=new XfQ});var FQ;var t1=fA(()=>{FQ=class FQ extends Error{context;constructor(A,Q){super(A);this.name="CliUserError",this.context=Q}}});import{platform as WfQ}from"node:os";import{version as HfQ}from"node:process";function OfA(A){MfA=A}function UfQ(A){for(let Q=0;Q<A.length;Q++)if(A.charCodeAt(Q)>255)return!1;return!0}function IfA(A){if(A.toLowerCase()==="x-capgo-log-token")return"Build log token is missing. Re-run the build command or pass a valid log token.";return"Capgo API key is missing. Run `npx -y @capgo/cli@latest login` or pass `--apikey`."}function qfQ(A){if(A.toLowerCase()==="x-capgo-log-token")return"Build log token contains invalid characters (only ASCII is allowed). Re-run the build command to get a fresh token.";if(A.toLowerCase()==="authorization")return"Authorization header contains invalid characters (only ASCII is allowed). Check your Capgo API key or Supabase anon key configuration.";return"Capgo API key contains invalid characters (only ASCII is allowed). Copy the key from the Capgo dashboard."}function GZA(A,Q){if(Q===void 0||Q===null){if(XZA.has(A.toLowerCase()))throw new FQ(IfA(A));throw new FQ(`HTTP header "${A}" is missing or invalid.`)}if(typeof Q!=="string"){if(XZA.has(A.toLowerCase()))throw new FQ(IfA(A));throw new FQ(`HTTP header "${A}" is missing or invalid.`)}if(!UfQ(Q)){if(XZA.has(A.toLowerCase()))throw new FQ(qfQ(A));throw new FQ(`HTTP header "${A}" contains invalid characters (only ASCII is allowed).`)}return Q}function j4(A){let Q={capgo_api:FfQ,"x-cli-version":D6.version,"x-cli-command":MfA,"x-cli-node":HfQ,"x-cli-os":WfQ()};if(A)for(let[B,$]of Object.entries(A))Q[B]=GZA(B,$);return Q}var FfQ="2025-10-01",MfA="",XZA;var M7=fA(()=>{qX();t1();XZA=new Set(["authorization","capgkey","x-capgo-log-token"])});function $Z(A){let Q=A.length;while(Q>0&&A[Q-1]==="/")Q-=1;return A.slice(0,Q)}import{randomUUID as LfA}from"node:crypto";import{existsSync as zfQ,mkdirSync as DfQ,readFileSync as IfQ,writeFileSync as MfQ}from"node:fs";import{homedir as WZA,platform as OfQ,release as LfQ}from"node:os";import{join as NfA}from"node:path";import{arch as NfQ,cwd as CfA,env as dL,version as CfQ}from"node:process";function K3(A){return A==="1"||A?.toLowerCase()==="true"||A?.toLowerCase()==="yes"}function wfQ(){if(K3(dL.CAPGO_DISABLE_TELEMETRY)||K3(dL.CAPGO_DISABLE_POSTHOG))return;return dL.CAPGO_CLI_POSTHOG_API_KEY?.trim()||dL.POSTHOG_API_KEY?.trim()||RfQ}function PfQ(A){let Q=$Z(A);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 _fQ(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 TfQ(A){let Q=A,B=CfA(),$=WZA();if(B)Q=Q.replaceAll(B,"<cwd>");if($)Q=Q.replaceAll($,"~");return Q}function SfQ(A){let Q=A,B=CfA(),$=WZA();if(B)Q=Q.replaceAll(B,"<cwd>");if($)Q=Q.replaceAll($,"~");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-]+){1,}\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 kfQ(A,Q){let B=A?.split(`
71
71
  `).slice(1).map(($)=>{let J=$.trim(),Y=J.startsWith("at ")?J.slice(3):J,Z=Q,X=Y,G=Y.lastIndexOf(" (");if(G!==-1&&Y.endsWith(")"))Z=Y.slice(0,G).trim()||Q,X=Y.slice(G+2,-1);else{let H=Y.lastIndexOf(" "),U=H===-1?"":Y.slice(H+1);if(/:\d+:\d+$/.test(U))Z=Y.slice(0,H).trim()||Q,X=U}let K=X.lastIndexOf(":"),W=K===-1?-1:X.lastIndexOf(":",K-1);if(K===-1||W===-1)return{function:Q,platform:"custom",lang:"javascript"};return{function:Z,filename:TfQ(X.slice(0,W)),lineno:Number.parseInt(X.slice(W+1,K),10),colno:Number.parseInt(X.slice(K+1),10),platform:"custom",lang:"javascript"}}).filter(Boolean);return B&&B.length>0?B:[{function:Q,platform:"custom",lang:"javascript"}]}function bfQ(A){if(!A||typeof A!=="object"||!("code"in A))return;let{code:Q}=A;return typeof Q==="string"?Q:void 0}function vfQ(A){if(!A||typeof A!=="object")return;let Q=A;if(typeof Q.status==="number")return Q.status;if(typeof Q.statusCode==="number")return Q.statusCode;let B=Q.context&&typeof Q.context==="object"?Q.context.status:void 0;return typeof B==="number"?B:void 0}function ffQ(A){let Q=(A instanceof Error?A.message:typeof A==="string"?A:"").toLowerCase();if(xfQ.some((B)=>Q.includes(B)))return!0;return vfQ(A)===401}function Zx(A){if(A instanceof FQ){if(jfQ.has(A.message))return!0;return!1}if(ffQ(A))return!1;return!bfQ(A)?.startsWith("commander.")}function en(A){let Q=[],B=A;while(B?.parent){let $=B.name();if($)Q.push($);B=B.parent}return Q.reverse().join(" ")||"unknown"}function gfQ(A=NfA(WZA(),".capgo-credentials")){if(KZA)return KZA;let Q=NfA(A,"install-id"),B;try{let $=zfQ(Q)?IfQ(Q,"utf8").trim():"";if($)B=$;else B=LfA(),DfQ(A,{recursive:!0}),MfQ(Q,B,{encoding:"utf8",mode:384})}catch{B=LfA()}return KZA=B,B}async function Xx(A){let Q=wfQ();if(!Q)return!1;let B=dL.CAPGO_CLI_POSTHOG_API_HOST?.trim()||dL.POSTHOG_API_HOST?.trim()||VfQ,$;try{$=PfQ(B)}catch{return!1}let J=_fQ(A.error),Y=SfQ(J.message),Z=gfQ(),X=kfQ(J.stack,A.functionName),G=[A.functionName,A.kind,J.name||"Error",String(A.status??1)].join(":"),K={token:Q,event:"$exception",properties:{distinct_id:Z,$exception_list:[{type:J.name||"Error",value:Y,mechanism:{handled:!0,synthetic:!1},stacktrace:{type:"raw",frames:X}}],$exception_fingerprint:G,architecture:NfQ,cli_version:D6.version,error_kind:A.kind,function_name:A.functionName,is_ci:Boolean(dL.CI),node_version:CfQ,os_platform:OfQ(),os_release:LfQ(),runtime:"cli",status:A.status},timestamp:new Date().toISOString()};try{let W=new AbortController,H=setTimeout(()=>W.abort(),EfQ);try{return(await fetch($,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K),signal:W.signal})).ok}finally{clearTimeout(H)}}catch{return!1}}var VfQ="https://eu.i.posthog.com/i/v0/e/",RfQ="phc_NXDyDajQaTQVwb25DEhIVZfxVUn4R0Y348Z7vWYHZUi",EfQ=1500,HZA="iOS sync validation failed. Delete your iOS folder, then rerun the add and sync commands above and retry.",jfQ,xfQ,KZA;var eE=fA(()=>{qX();t1();jfQ=new Set([HZA]);xfQ=["invalid_apikey","invalid apikey","no_key_provided","no key provided","invalid api key or insufficient permissions","does not exist, run first"]});import{existsSync as zX}from"fs";var lH=(A=".",Q="unknown")=>{let B=`${A}/bun.lockb`,$=`${A}/bun.lock`,J=`${A}/pnpm-lock.yaml`,Y=`${A}/shrinkwrap.yaml`,Z=`${A}/yarn.lock`,X=`${A}/package-lock.json`,G=`${A}/npm-shrinkwrap.json`;if(zX(B)||zX($))return"bun";if(zX(J)||zX(Y))return"pnpm";if(zX(Z))return"yarn";if(zX(X)||zX(G))return"npm";return Q},fD=(A=lH(),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"}},Ar=(A=".",Q="npx")=>{let B=`${A}/bun.lockb`,$=`${A}/bun.lock`,J=`${A}/pnpm-lock.yaml`,Y=`${A}/shrinkwrap.yaml`,Z=`${A}/yarn.lock`,X=`${A}/package-lock.json`,G=`${A}/npm-shrinkwrap.json`;if(zX(B)||zX($))return"bunx";if(zX(J)||zX(Y))return"pnpm exec";if(zX(Z))return"yarn dlx";if(zX(X)||zX(G))return"npx";return Q};var Gx=()=>{};function Qr(A,Q){if(isNaN(A)||isNaN(Q))throw Error("Cannot compare against non-numbers");return A===Q?0:A<Q?-1:1}function EfA(A=[],Q=[]){if(A.length&&!Q.length)return-1;if(!A.length&&Q.length)return 1;return 0}function Br(A=[],Q=[]){let B=Math.max(A.length,Q.length);for(let $=0;$<B;$++){let J=A[$],Y=Q[$];if(J===void 0&&Y===void 0)return 0;if(Y===void 0)return 1;if(J===void 0)return-1;if(typeof J==="string"&&typeof Y==="number")return 1;if(typeof J==="number"&&typeof Y==="string")return-1;if(J<Y)return-1;if(J>Y)return 1}return 0}function UZA(A){return typeof A==="number"&&!Number.isNaN(A)&&(!Number.isFinite(A)||0<=A&&A<=Number.MAX_SAFE_INTEGER)}function DX(A){return A.split(".").filter(Boolean).map((Q)=>{if(mfQ.test(Q)){let B=Number(Q);if(UZA(B))return B}return Q})}function pH(A){return A.split(".").filter(Boolean)}function Jr(A,Q){let B=Number(A);if(!UZA(B))throw TypeError(Q);return B}function PU(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 Aj="0|[1-9]\\d*",yfQ="\\d*[a-zA-Z-][a-zA-Z0-9-]*",hfQ,VfA,jfA,RfA="[0-9A-Za-z-]+",wfA,PfA,_fA,TfA="(?:<|>)?=?",ufQ="x|X|\\*",FZA,$r,SfA,kfA,qZA=256,mfQ;var NG=fA(()=>{hfQ=`(?<major>${Aj})\\.(?<minor>${Aj})\\.(?<patch>${Aj})`,VfA=`(?:${Aj}|${yfQ})`,jfA=`(?:-(?<prerelease>${VfA}(?:\\.${VfA})*))`,wfA=`(?:\\+(?<buildmetadata>${RfA}(?:\\.${RfA})*))`,PfA=`v?${hfQ}${jfA}?${wfA}?`,_fA=new RegExp(`^${PfA}$`),FZA=`${Aj}|${ufQ}`,$r=`[v=\\s]*(?<major>${FZA})(?:\\.(?<minor>${FZA})(?:\\.(?<patch>${FZA})${jfA}?${wfA}?)?)?`,SfA=new RegExp(`^(?<operator>~>?|\\^|${TfA})\\s*${$r}$`),kfA=new RegExp(`^(?<operator>${TfA})\\s*(${PfA})$|^$`);mfQ=new RegExp(`^${Aj}$`)});function JZ(A,Q){if(A===Q)return 0;return Qr(A.major,Q.major)||Qr(A.minor,Q.minor)||Qr(A.patch,Q.patch)||EfA(A.prerelease,Q.prerelease)||Br(A.prerelease,Q.prerelease)}var wK=fA(()=>{NG()});function bfA(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(Br(A.prerelease,Q.prerelease)!==0)return"prerelease"}var xfA=fA(()=>{NG()});function zZA(A){return A.toFixed(0)}function PY(A){let Q=zZA(A.major),B=zZA(A.minor),$=zZA(A.patch),J=A.prerelease?.join(".")??"",Y=A.build?.join(".")??"";return[[`${Q}.${B}.${$}`,J].filter((G)=>G).join("-"),Y].filter((G)=>G).join("+")}function cfQ(A,Q){if(PU(Q))return!0;let B=JZ(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 Yr(A,Q){for(let B of Q)if(!cfQ(A,B))return!1;if(!A.prerelease?.length)return!0;for(let B of Q){if(PU(B))continue;if(!B.prerelease?.length)continue;let{major:$,minor:J,patch:Y}=B;if(A.major===$&&A.minor===J&&A.patch===Y)return!0}return!1}var Zr=fA(()=>{NG();wK()});function Kx(A,Q){return Q.some((B)=>Yr(A,B))}var Wx=fA(()=>{Zr()});function dfQ(A=[]){let Q=[...A],B=Q.length;while(B>=0){let $=Q[B];if(typeof $==="number"){Q[B]=$+1;break}B-=1}if(B===-1)Q.push(0);return Q}function Hx(A=[],Q){let B=dfQ(A);if(!Q)return B;let $=DX(Q);if($.every((J)=>typeof J==="string")){if($.every((J,Y)=>J===B[Y])&&typeof B[$.length]==="number")return B;$=[...$,0]}return $}function gD(A,Q,B={}){let $=B.build!==void 0?pH(B.build):A.build??[];switch(Q){case"premajor":return{major:A.major+1,minor:0,patch:0,prerelease:Hx(A.prerelease,B.prerelease),build:$};case"preminor":return{major:A.major,minor:A.minor+1,patch:0,prerelease:Hx(A.prerelease,B.prerelease),build:$};case"prepatch":return{major:A.major,minor:A.minor,patch:A.patch+1,prerelease:Hx(A.prerelease,B.prerelease),build:$};case"prerelease":{let Y=(A.prerelease??[]).length===0?A.patch+1:A.patch;return{major:A.major,minor:A.minor,patch:Y,prerelease:Hx(A.prerelease,B.prerelease),build:$}}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:$};case"minor":{let Y=(A.prerelease??[]).length===0||A.patch!==0?A.minor+1:A.minor;return{major:A.major,minor:Y,patch:0,prerelease:[],build:$}}case"patch":{let Y=(A.prerelease??[]).length===0?A.patch+1:A.patch;return{major:A.major,minor:A.minor,patch:Y,prerelease:[],build:$}}case"pre":return{major:A.major,minor:A.minor,patch:A.patch,prerelease:Hx(A.prerelease,B.prerelease),build:$};default:throw TypeError(`Cannot increment version: invalid argument ${Q}`)}}var vfA=fA(()=>{NG()});var Xr,Qj;var Fx=fA(()=>{Xr={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},Qj={operator:void 0,...Xr}});var DZA=fA(()=>{Fx();NG()});function IZA(A,Q){return JZ(A,Q)>0}var MZA=fA(()=>{wK()});var ffA=fA(()=>{Wx();MZA()});function O7(A,Q){return JZ(A,Q)<0}var OZA=fA(()=>{wK()});var gfA=fA(()=>{Wx();OZA()});function lfQ(A){let B=A.match(kfA)?.groups;if(!B)return null;let{operator:$}=B;return{operator:$||void 0,...Xr}}function z$(A){return!A||A.toLowerCase()==="x"||A==="*"}function pfQ(A){if(z$(A.major))return;if(z$(A.minor))return{operator:">=",major:+A.major,minor:0,patch:0,prerelease:[],build:[]};if(z$(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?DX(A.prerelease):[],build:[]}}function ifQ(A){if(z$(A.major))return;if(z$(A.minor))return{operator:"<",major:+A.major+1,minor:0,patch:0,prerelease:[],build:[]};if(z$(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:DX(A.prerelease),build:[]};return{operator:"<=",major:+A.major,minor:+A.minor,patch:+A.patch,prerelease:[],build:[]}}function nfQ(A){let Q=A.match(new RegExp(`^${$r}`)),B=Q?.groups;if(!B)return null;let $=Q[0].length,J=A.slice($).match(/^\s+-\s+/);if(!J)return null;let Y=J[0].length,X=A.slice($+Y).match(new RegExp(`^${$r}\\s*$`))?.groups,G=pfQ(B),K=ifQ(X);return[G,K].filter(Boolean)}function rfQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[Qj];if(B)return[{operator:">=",major:J,minor:0,patch:0},{operator:"<",major:J+1,minor:0,patch:0}];if($){if(J===0)return[{operator:">=",major:J,minor:Y,patch:0},{operator:"<",major:J,minor:Y+1,patch:0}];return[{operator:">=",major:J,minor:Y,patch:0},{operator:"<",major:J+1,minor:0,patch:0}]}let X=DX(A.prerelease??"");if(J===0){if(Y===0)return[{operator:">=",major:J,minor:Y,patch:Z,prerelease:X},{operator:"<",major:J,minor:Y,patch:Z+1}];return[{operator:">=",major:J,minor:Y,patch:Z,prerelease:X},{operator:"<",major:J,minor:Y+1,patch:0}]}return[{operator:">=",major:J,minor:Y,patch:Z,prerelease:X},{operator:"<",major:J+1,minor:0,patch:0}]}function afQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[Qj];if(B)return[{operator:">=",major:J,minor:0,patch:0},{operator:"<",major:J+1,minor:0,patch:0}];if($)return[{operator:">=",major:J,minor:Y,patch:0},{operator:"<",major:J,minor:Y+1,patch:0}];let X=DX(A.prerelease??"");return[{operator:">=",major:J,minor:Y,patch:Z,prerelease:X},{operator:"<",major:J,minor:Y+1,patch:0}]}function ofQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[{operator:"<",major:0,minor:0,patch:0}];if(B){if($)return[{operator:"<",major:J,minor:0,patch:0}];return[{operator:"<",major:J,minor:0,patch:0}]}if($)return[{operator:"<",major:J,minor:Y,patch:0}];let X=DX(A.prerelease??""),G=pH(A.build??"");return[{operator:"<",major:J,minor:Y,patch:Z,prerelease:X,build:G}]}function sfQ(A){let Q=z$(A.minor),B=z$(A.patch),$=+A.major,J=+A.minor,Y=+A.patch;if(Q)return[{operator:"<",major:$+1,minor:0,patch:0}];if(B)return[{operator:"<",major:$,minor:J+1,patch:0}];let Z=DX(A.prerelease??""),X=pH(A.build??"");return[{operator:"<=",major:$,minor:J,patch:Y,prerelease:Z,build:X}]}function tfQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[{operator:"<",major:0,minor:0,patch:0}];if(B)return[{operator:">=",major:J+1,minor:0,patch:0}];if($)return[{operator:">=",major:J,minor:Y+1,patch:0}];let X=DX(A.prerelease??""),G=pH(A.build??"");return[{operator:">",major:J,minor:Y,patch:Z,prerelease:X,build:G}]}function efQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[Qj];if(B)return[{operator:">=",major:J,minor:0,patch:0}];if($)return[{operator:">=",major:J,minor:Y,patch:0}];let X=DX(A.prerelease??""),G=pH(A.build??"");return[{operator:">=",major:J,minor:Y,patch:Z,prerelease:X,build:G}]}function AgQ(A){let Q=z$(A.major),B=z$(A.minor),$=z$(A.patch),J=+A.major,Y=+A.minor,Z=+A.patch;if(Q)return[Qj];if(B)return[{operator:">=",major:J,minor:0,patch:0},{operator:"<",major:J+1,minor:0,patch:0}];if($)return[{operator:">=",major:J,minor:Y,patch:0},{operator:"<",major:J,minor:Y+1,patch:0}];let X=DX(A.prerelease??""),G=pH(A.build??"");return[{operator:A.operator==="="?"=":void 0,major:J,minor:Y,patch:Z,prerelease:X,build:G}]}function QgQ(A){let Q=A.match(SfA)?.groups;if(!Q)return lfQ(A);switch(Q.operator){case"^":return rfQ(Q);case"~":case"~>":return afQ(Q);case"<":return ofQ(Q);case"<=":return sfQ(Q);case">":return tfQ(Q);case">=":return efQ(Q);default:return AgQ(Q)}}function BgQ(A){return A.split(/\s+/).flatMap(QgQ)}function Gr(A){let Q=A.replaceAll(/(?<=[<>=~^])(\s+)/g,"").split(/\s*\|\|\s*/).map((B)=>nfQ(B)||BgQ(B));if(Q.some((B)=>B.includes(null)))throw TypeError(`Cannot parse version range: range "${A}" is invalid`);return Q}var LZA=fA(()=>{NG();Fx()});function Z1(A){if(typeof A!=="string")throw TypeError(`Cannot parse version as version must be a string: received ${typeof A}`);if(A.length>qZA)throw TypeError(`Cannot parse version as version length is too long: length is ${A.length}, max length is ${qZA}`);A=A.trim();let Q=A.match(_fA)?.groups;if(!Q)throw TypeError(`Cannot parse version: ${A}`);let B=Jr(Q.major,`Cannot parse version ${A}: invalid major version`),$=Jr(Q.minor,`Cannot parse version ${A}: invalid minor version`),J=Jr(Q.patch,`Cannot parse version ${A}: invalid patch version`),Y=Q.prerelease?DX(Q.prerelease):[],Z=Q.buildmetadata?pH(Q.buildmetadata):[];return{major:B,minor:$,patch:J,prerelease:Y,build:Z}}var Kr=fA(()=>{NG();NG()});function yfA(A,Q){let B=A.operator,$=Q.operator;if(B===void 0){if(PU(A))return!0;return Kx(A,[[Q]])}if($===void 0){if(PU(Q))return!0;return Kx(Q,[[A]])}let J=JZ(A,Q);return(B===">="||B===">")&&($===">="||$===">")||(B==="<="||B==="<")&&($==="<="||$==="<")||J===0&&((B===">="||B==="<=")&&($===">="||$==="<="))||J===-1&&(B===">="||B===">")&&($==="<="||$==="<")||J===1&&(B==="<="||B==="<")&&($===">="||$===">")}function $gQ(A){return A.every((Q)=>{return Q.some((B)=>JgQ(B))})}function JgQ(A){for(let Q=0;Q<A.length-1;Q++){let B=A[Q];for(let $ of A.slice(Q+1))if(!yfA(B,$))return!1}return!0}function hfA(A,Q){return $gQ([A,Q])&&A.some((B)=>{return Q.some(($)=>{return B.every((J)=>{return $.every((Y)=>yfA(J,Y))})})})}var ufA=fA(()=>{NG();wK();Wx()});var mfA=fA(()=>{LZA()});var cfA=fA(()=>{Fx();Fx();DZA()});function yD(A){try{return Z1(A),!0}catch{return!1}}var dfA=fA(()=>{Kr()});var lfA=fA(()=>{Kr()});var pfA=fA(()=>{NG()});var ifA=fA(()=>{wK()});var nfA=fA(()=>{wK()});var rfA=fA(()=>{Zr();NG();wK()});function NZA(A,Q){return JZ(A,Q)>=0}var afA=fA(()=>{wK()});var ofA=fA(()=>{Zr();NG();wK()});var sfA=fA(()=>{wK()});var PK=fA(()=>{wK();xfA();Wx();vfA();DZA();ffA();gfA();LZA();Kr();ufA();mfA();cfA();dfA();lfA();pfA();ifA();nfA();MZA();rfA();afA();OZA();ofA();sfA()});var IX=$A((IWB,Fr)=>{var tfA,efA,AgA,QgA,BgA,$gA,JgA,YgA,ZgA,XgA,GgA,KgA,WgA,Wr,CZA,HgA,FgA,UgA,Bj,qgA,zgA,DgA,IgA,MgA,OgA,LgA,NgA,CgA,Hr,VgA,RgA,EgA;(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($){A(B(Q,B($)))});else if(typeof Fr==="object"&&typeof IWB==="object")A(B(Q,B(IWB)));else A(B(Q));function B($,J){if($!==Q)if(typeof Object.create==="function")Object.defineProperty($,"__esModule",{value:!0});else $.__esModule=!0;return function(Y,Z){return $[Y]=J?J(Y,Z):Z}}})(function(A){var Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Y,Z){Y.__proto__=Z}||function(Y,Z){for(var X in Z)if(Object.prototype.hasOwnProperty.call(Z,X))Y[X]=Z[X]};tfA=function(Y,Z){if(typeof Z!=="function"&&Z!==null)throw TypeError("Class extends value "+String(Z)+" is not a constructor or null");Q(Y,Z);function X(){this.constructor=Y}Y.prototype=Z===null?Object.create(Z):(X.prototype=Z.prototype,new X)},efA=Object.assign||function(Y){for(var Z,X=1,G=arguments.length;X<G;X++){Z=arguments[X];for(var K in Z)if(Object.prototype.hasOwnProperty.call(Z,K))Y[K]=Z[K]}return Y},AgA=function(Y,Z){var X={};for(var G in Y)if(Object.prototype.hasOwnProperty.call(Y,G)&&Z.indexOf(G)<0)X[G]=Y[G];if(Y!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var K=0,G=Object.getOwnPropertySymbols(Y);K<G.length;K++)if(Z.indexOf(G[K])<0&&Object.prototype.propertyIsEnumerable.call(Y,G[K]))X[G[K]]=Y[G[K]]}return X},QgA=function(Y,Z,X,G){var K=arguments.length,W=K<3?Z:G===null?G=Object.getOwnPropertyDescriptor(Z,X):G,H;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")W=Reflect.decorate(Y,Z,X,G);else for(var U=Y.length-1;U>=0;U--)if(H=Y[U])W=(K<3?H(W):K>3?H(Z,X,W):H(Z,X))||W;return K>3&&W&&Object.defineProperty(Z,X,W),W},BgA=function(Y,Z){return function(X,G){Z(X,G,Y)}},$gA=function(Y,Z,X,G,K,W){function H(E){if(E!==void 0&&typeof E!=="function")throw TypeError("Function expected");return E}var U=G.kind,z=U==="getter"?"get":U==="setter"?"set":"value",D=!Z&&Y?G.static?Y:Y.prototype:null,I=Z||(D?Object.getOwnPropertyDescriptor(D,G.name):{}),M,N=!1;for(var V=X.length-1;V>=0;V--){var L={};for(var C in G)L[C]=C==="access"?{}:G[C];for(var C in G.access)L.access[C]=G.access[C];L.addInitializer=function(E){if(N)throw TypeError("Cannot add initializers after decoration has completed");W.push(H(E||null))};var R=(0,X[V])(U==="accessor"?{get:I.get,set:I.set}:I[z],L);if(U==="accessor"){if(R===void 0)continue;if(R===null||typeof R!=="object")throw TypeError("Object expected");if(M=H(R.get))I.get=M;if(M=H(R.set))I.set=M;if(M=H(R.init))K.unshift(M)}else if(M=H(R))if(U==="field")K.unshift(M);else I[z]=M}if(D)Object.defineProperty(D,G.name,I);N=!0},JgA=function(Y,Z,X){var G=arguments.length>2;for(var K=0;K<Z.length;K++)X=G?Z[K].call(Y,X):Z[K].call(Y);return G?X:void 0},YgA=function(Y){return typeof Y==="symbol"?Y:"".concat(Y)},ZgA=function(Y,Z,X){if(typeof Z==="symbol")Z=Z.description?"[".concat(Z.description,"]"):"";return Object.defineProperty(Y,"name",{configurable:!0,value:X?"".concat(X," ",Z):Z})},XgA=function(Y,Z){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(Y,Z)},GgA=function(Y,Z,X,G){function K(W){return W instanceof X?W:new X(function(H){H(W)})}return new(X||(X=Promise))(function(W,H){function U(I){try{D(G.next(I))}catch(M){H(M)}}function z(I){try{D(G.throw(I))}catch(M){H(M)}}function D(I){I.done?W(I.value):K(I.value).then(U,z)}D((G=G.apply(Y,Z||[])).next())})},KgA=function(Y,Z){var X={label:0,sent:function(){if(W[0]&1)throw W[1];return W[1]},trys:[],ops:[]},G,K,W,H=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return H.next=U(0),H.throw=U(1),H.return=U(2),typeof Symbol==="function"&&(H[Symbol.iterator]=function(){return this}),H;function U(D){return function(I){return z([D,I])}}function z(D){if(G)throw TypeError("Generator is already executing.");while(H&&(H=0,D[0]&&(X=0)),X)try{if(G=1,K&&(W=D[0]&2?K.return:D[0]?K.throw||((W=K.return)&&W.call(K),0):K.next)&&!(W=W.call(K,D[1])).done)return W;if(K=0,W)D=[D[0]&2,W.value];switch(D[0]){case 0:case 1:W=D;break;case 4:return X.label++,{value:D[1],done:!1};case 5:X.label++,K=D[1],D=[0];continue;case 7:D=X.ops.pop(),X.trys.pop();continue;default:if((W=X.trys,!(W=W.length>0&&W[W.length-1]))&&(D[0]===6||D[0]===2)){X=0;continue}if(D[0]===3&&(!W||D[1]>W[0]&&D[1]<W[3])){X.label=D[1];break}if(D[0]===6&&X.label<W[1]){X.label=W[1],W=D;break}if(W&&X.label<W[2]){X.label=W[2],X.ops.push(D);break}if(W[2])X.ops.pop();X.trys.pop();continue}D=Z.call(Y,X)}catch(I){D=[6,I],K=0}finally{G=W=0}if(D[0]&5)throw D[1];return{value:D[0]?D[1]:void 0,done:!0}}},WgA=function(Y,Z){for(var X in Y)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))Hr(Z,Y,X)},Hr=Object.create?function(Y,Z,X,G){if(G===void 0)G=X;var K=Object.getOwnPropertyDescriptor(Z,X);if(!K||("get"in K?!Z.__esModule:K.writable||K.configurable))K={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty(Y,G,K)}:function(Y,Z,X,G){if(G===void 0)G=X;Y[G]=Z[X]},Wr=function(Y){var Z=typeof Symbol==="function"&&Symbol.iterator,X=Z&&Y[Z],G=0;if(X)return X.call(Y);if(Y&&typeof Y.length==="number")return{next:function(){if(Y&&G>=Y.length)Y=void 0;return{value:Y&&Y[G++],done:!Y}}};throw TypeError(Z?"Object is not iterable.":"Symbol.iterator is not defined.")},CZA=function(Y,Z){var X=typeof Symbol==="function"&&Y[Symbol.iterator];if(!X)return Y;var G=X.call(Y),K,W=[],H;try{while((Z===void 0||Z-- >0)&&!(K=G.next()).done)W.push(K.value)}catch(U){H={error:U}}finally{try{if(K&&!K.done&&(X=G.return))X.call(G)}finally{if(H)throw H.error}}return W},HgA=function(){for(var Y=[],Z=0;Z<arguments.length;Z++)Y=Y.concat(CZA(arguments[Z]));return Y},FgA=function(){for(var Y=0,Z=0,X=arguments.length;Z<X;Z++)Y+=arguments[Z].length;for(var G=Array(Y),K=0,Z=0;Z<X;Z++)for(var W=arguments[Z],H=0,U=W.length;H<U;H++,K++)G[K]=W[H];return G},UgA=function(Y,Z,X){if(X||arguments.length===2){for(var G=0,K=Z.length,W;G<K;G++)if(W||!(G in Z)){if(!W)W=Array.prototype.slice.call(Z,0,G);W[G]=Z[G]}}return Y.concat(W||Array.prototype.slice.call(Z))},Bj=function(Y){return this instanceof Bj?(this.v=Y,this):new Bj(Y)},qgA=function(Y,Z,X){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var G=X.apply(Y,Z||[]),K,W=[];return K=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),U("next"),U("throw"),U("return",H),K[Symbol.asyncIterator]=function(){return this},K;function H(V){return function(L){return Promise.resolve(L).then(V,M)}}function U(V,L){if(G[V]){if(K[V]=function(C){return new Promise(function(R,E){W.push([V,C,R,E])>1||z(V,C)})},L)K[V]=L(K[V])}}function z(V,L){try{D(G[V](L))}catch(C){N(W[0][3],C)}}function D(V){V.value instanceof Bj?Promise.resolve(V.value.v).then(I,M):N(W[0][2],V)}function I(V){z("next",V)}function M(V){z("throw",V)}function N(V,L){if(V(L),W.shift(),W.length)z(W[0][0],W[0][1])}},zgA=function(Y){var Z,X;return Z={},G("next"),G("throw",function(K){throw K}),G("return"),Z[Symbol.iterator]=function(){return this},Z;function G(K,W){Z[K]=Y[K]?function(H){return(X=!X)?{value:Bj(Y[K](H)),done:!1}:W?W(H):H}:W}},DgA=function(Y){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var Z=Y[Symbol.asyncIterator],X;return Z?Z.call(Y):(Y=typeof Wr==="function"?Wr(Y):Y[Symbol.iterator](),X={},G("next"),G("throw"),G("return"),X[Symbol.asyncIterator]=function(){return this},X);function G(W){X[W]=Y[W]&&function(H){return new Promise(function(U,z){H=Y[W](H),K(U,z,H.done,H.value)})}}function K(W,H,U,z){Promise.resolve(z).then(function(D){W({value:D,done:U})},H)}},IgA=function(Y,Z){if(Object.defineProperty)Object.defineProperty(Y,"raw",{value:Z});else Y.raw=Z;return Y};var B=Object.create?function(Y,Z){Object.defineProperty(Y,"default",{enumerable:!0,value:Z})}:function(Y,Z){Y.default=Z},$=function(Y){return $=Object.getOwnPropertyNames||function(Z){var X=[];for(var G in Z)if(Object.prototype.hasOwnProperty.call(Z,G))X[X.length]=G;return X},$(Y)};MgA=function(Y){if(Y&&Y.__esModule)return Y;var Z={};if(Y!=null){for(var X=$(Y),G=0;G<X.length;G++)if(X[G]!=="default")Hr(Z,Y,X[G])}return B(Z,Y),Z},OgA=function(Y){return Y&&Y.__esModule?Y:{default:Y}},LgA=function(Y,Z,X,G){if(X==="a"&&!G)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?Y!==Z||!G:!Z.has(Y))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?G:X==="a"?G.call(Y):G?G.value:Z.get(Y)},NgA=function(Y,Z,X,G,K){if(G==="m")throw TypeError("Private method is not writable");if(G==="a"&&!K)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?Y!==Z||!K:!Z.has(Y))throw TypeError("Cannot write private member to an object whose class did not declare it");return G==="a"?K.call(Y,X):K?K.value=X:Z.set(Y,X),X},CgA=function(Y,Z){if(Z===null||typeof Z!=="object"&&typeof Z!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof Y==="function"?Z===Y:Y.has(Z)},VgA=function(Y,Z,X){if(Z!==null&&Z!==void 0){if(typeof Z!=="object"&&typeof Z!=="function")throw TypeError("Object expected.");var G,K;if(X){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");G=Z[Symbol.asyncDispose]}if(G===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(G=Z[Symbol.dispose],X)K=G}if(typeof G!=="function")throw TypeError("Object not disposable.");if(K)G=function(){try{K.call(this)}catch(W){return Promise.reject(W)}};Y.stack.push({value:Z,dispose:G,async:X})}else if(X)Y.stack.push({async:!0});return Z};var J=typeof SuppressedError==="function"?SuppressedError:function(Y,Z,X){var G=Error(X);return G.name="SuppressedError",G.error=Y,G.suppressed=Z,G};RgA=function(Y){function Z(W){Y.error=Y.hasError?new J(W,Y.error,"An error was suppressed during disposal."):W,Y.hasError=!0}var X,G=0;function K(){while(X=Y.stack.pop())try{if(!X.async&&G===1)return G=0,Y.stack.push(X),Promise.resolve().then(K);if(X.dispose){var W=X.dispose.call(X.value);if(X.async)return G|=2,Promise.resolve(W).then(K,function(H){return Z(H),K()})}else G|=1}catch(H){Z(H)}if(G===1)return Y.hasError?Promise.reject(Y.error):Promise.resolve();if(Y.hasError)throw Y.error}return K()},EgA=function(Y,Z){if(typeof Y==="string"&&/^\.\.?\//.test(Y))return Y.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(X,G,K,W,H){return G?Z?".jsx":".js":K&&(!W||!H)?X:K+W+"."+H.toLowerCase()+"js"});return Y},A("__extends",tfA),A("__assign",efA),A("__rest",AgA),A("__decorate",QgA),A("__param",BgA),A("__esDecorate",$gA),A("__runInitializers",JgA),A("__propKey",YgA),A("__setFunctionName",ZgA),A("__metadata",XgA),A("__awaiter",GgA),A("__generator",KgA),A("__exportStar",WgA),A("__createBinding",Hr),A("__values",Wr),A("__read",CZA),A("__spread",HgA),A("__spreadArrays",FgA),A("__spreadArray",UgA),A("__await",Bj),A("__asyncGenerator",qgA),A("__asyncDelegator",zgA),A("__asyncValues",DgA),A("__makeTemplateObject",IgA),A("__importStar",MgA),A("__importDefault",OgA),A("__classPrivateFieldGet",LgA),A("__classPrivateFieldSet",NgA),A("__classPrivateFieldIn",CgA),A("__addDisposableResource",VgA),A("__disposeResources",RgA),A("__rewriteRelativeImportExtension",EgA)})});var PgA=$A((jgA)=>{Object.defineProperty(jgA,"__esModule",{value:!0});jgA.resolveFetch=void 0;var YgQ=(A)=>{if(A)return(...Q)=>A(...Q);return(...Q)=>fetch(...Q)};jgA.resolveFetch=YgQ});var VZA=$A((bgA)=>{Object.defineProperty(bgA,"__esModule",{value:!0});bgA.FunctionRegion=bgA.FunctionsHttpError=bgA.FunctionsRelayError=bgA.FunctionsFetchError=bgA.FunctionsError=void 0;class Ux 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}}}bgA.FunctionsError=Ux;class TgA extends Ux{constructor(A){super("Failed to send a request to the Edge Function","FunctionsFetchError",A)}}bgA.FunctionsFetchError=TgA;class SgA extends Ux{constructor(A){super("Relay Error invoking the Edge Function","FunctionsRelayError",A)}}bgA.FunctionsRelayError=SgA;class kgA extends Ux{constructor(A){super("Edge Function returned a non-2xx status code","FunctionsHttpError",A)}}bgA.FunctionsHttpError=kgA;var _gA;(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"})(_gA||(bgA.FunctionRegion=_gA={}))});var ygA=$A((fgA)=>{Object.defineProperty(fgA,"__esModule",{value:!0});fgA.FunctionsClient=void 0;var WgQ=IX(),HgQ=PgA(),$j=VZA();class vgA{constructor(A,{headers:Q={},customFetch:B,region:$=$j.FunctionRegion.Any}={}){this.url=A,this.headers=Q,this.region=$,this.fetch=(0,HgQ.resolveFetch)(B)}setAuth(A){this.headers.Authorization=`Bearer ${A}`}invoke(A){return WgQ.__awaiter(this,arguments,void 0,function*(Q,B={}){var $,J;let Y,Z,X;try{let{headers:G,method:K,body:W,signal:H,timeout:U}=B,z={},{region:D}=B;if(!D)D=this.region;let I=new URL(`${this.url}/${Q}`);if(D&&D!=="any")z["x-region"]=D,I.searchParams.set("forceFunctionRegion",D);let M,N=!!G&&Object.keys(G).some((w)=>w.toLowerCase()==="content-type");if(W&&!N)if(typeof Blob<"u"&&W instanceof Blob||W instanceof ArrayBuffer)z["Content-Type"]="application/octet-stream",M=W;else if(typeof W==="string")z["Content-Type"]="text/plain",M=W;else if(typeof FormData<"u"&&W instanceof FormData)M=W;else z["Content-Type"]="application/json",M=JSON.stringify(W);else if(W&&typeof W!=="string"&&!(typeof Blob<"u"&&W instanceof Blob)&&!(W instanceof ArrayBuffer)&&!(typeof FormData<"u"&&W instanceof FormData))M=JSON.stringify(W);else M=W;let V=H;if(U)if(Z=new AbortController,Y=setTimeout(()=>Z.abort(),U),H)V=Z.signal,X=()=>Z.abort(),H.addEventListener("abort",X);else V=Z.signal;let L=yield this.fetch(I.toString(),{method:K||"POST",headers:Object.assign(Object.assign(Object.assign({},z),this.headers),G),body:M,signal:V}).catch((w)=>{throw new $j.FunctionsFetchError(w)}),C=L.headers.get("x-relay-error");if(C&&C==="true")throw new $j.FunctionsRelayError(L);if(!L.ok)throw new $j.FunctionsHttpError(L);let R=(($=L.headers.get("Content-Type"))!==null&&$!==void 0?$:"text/plain").split(";")[0].trim().toLowerCase(),E;if(R==="application/json")E=yield L.json();else if(R==="application/octet-stream"||R==="application/pdf")E=yield L.blob();else if(R==="text/event-stream")E=L;else if(R==="multipart/form-data")E=yield L.formData();else E=yield L.text();return{data:E,error:null,response:L}}catch(G){return{data:null,error:G,response:G instanceof $j.FunctionsHttpError||G instanceof $j.FunctionsRelayError?G.context:void 0}}finally{if(Y)clearTimeout(Y);if(X)(J=B.signal)===null||J===void 0||J.removeEventListener("abort",X)}})}}fgA.FunctionsClient=vgA});var hgA=$A((hD)=>{Object.defineProperty(hD,"__esModule",{value:!0});hD.FunctionRegion=hD.FunctionsRelayError=hD.FunctionsHttpError=hD.FunctionsFetchError=hD.FunctionsError=hD.FunctionsClient=void 0;var FgQ=ygA();Object.defineProperty(hD,"FunctionsClient",{enumerable:!0,get:function(){return FgQ.FunctionsClient}});var qx=VZA();Object.defineProperty(hD,"FunctionsError",{enumerable:!0,get:function(){return qx.FunctionsError}});Object.defineProperty(hD,"FunctionsFetchError",{enumerable:!0,get:function(){return qx.FunctionsFetchError}});Object.defineProperty(hD,"FunctionsHttpError",{enumerable:!0,get:function(){return qx.FunctionsHttpError}});Object.defineProperty(hD,"FunctionsRelayError",{enumerable:!0,get:function(){return qx.FunctionsRelayError}});Object.defineProperty(hD,"FunctionRegion",{enumerable:!0,get:function(){return qx.FunctionRegion}})});function mgA(A,Q){return new Promise((B)=>{if(Q===null||Q===void 0?void 0:Q.aborted){B();return}let $=setTimeout(()=>{Q===null||Q===void 0||Q.removeEventListener("abort",J),B()},A);function J(){clearTimeout($),B()}Q===null||Q===void 0||Q.addEventListener("abort",J)})}function zgQ(A,Q,B,$){if(!$||B>=3)return!1;if(!lgA.includes(A))return!1;if(!qgQ.includes(Q))return!1;return!0}function zx(A){return zx=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},zx(A)}function OgQ(A,Q){if(zx(A)!="object"||!A)return A;var B=A[Symbol.toPrimitive];if(B!==void 0){var $=B.call(A,Q||"default");if(zx($)!="object")return $;throw TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(A)}function LgQ(A){var Q=OgQ(A,"string");return zx(Q)=="symbol"?Q:Q+""}function NgQ(A,Q,B){return(Q=LgQ(Q))in A?Object.defineProperty(A,Q,{value:B,enumerable:!0,configurable:!0,writable:!0}):A[Q]=B,A}function dgA(A,Q){var B=Object.keys(A);if(Object.getOwnPropertySymbols){var $=Object.getOwnPropertySymbols(A);Q&&($=$.filter(function(J){return Object.getOwnPropertyDescriptor(A,J).enumerable})),B.push.apply(B,$)}return B}function Ur(A){for(var Q=1;Q<arguments.length;Q++){var B=arguments[Q]!=null?arguments[Q]:{};Q%2?dgA(Object(B),!0).forEach(function($){NgQ(A,$,B[$])}):Object.getOwnPropertyDescriptors?Object.defineProperties(A,Object.getOwnPropertyDescriptors(B)):dgA(Object(B)).forEach(function($){Object.defineProperty(A,$,Object.getOwnPropertyDescriptor(B,$))})}return A}var ugA=(A)=>Math.min(1000*2**A,30000),qgQ,lgA,RZA,DgQ=class{constructor(A){var Q,B,$,J,Y;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=($=A.shouldStripNulls)!==null&&$!==void 0?$:!1,this.urlLengthLimit=(J=A.urlLengthLimit)!==null&&J!==void 0?J:8000,this.retryEnabled=(Y=A.retry)!==null&&Y!==void 0?Y:!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 Z=this.headers.get("Accept");if(Z==="application/vnd.pgrst.object+json")this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped");else if(!Z||Z==="application/json")this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let $=this.fetch,Y=(async()=>{let Z=0;while(!0){let K={};if(B.headers.forEach((H,U)=>{K[U]=H}),Z>0)K["X-Retry-Count"]=String(Z);let W;try{W=await $(B.url.toString(),{method:B.method,headers:K,body:JSON.stringify(B.body,(H,U)=>typeof U==="bigint"?U.toString():U),signal:B.signal})}catch(H){if((H===null||H===void 0?void 0:H.name)==="AbortError"||(H===null||H===void 0?void 0:H.code)==="ABORT_ERR")throw H;if(!lgA.includes(B.method))throw H;if(B.retryEnabled&&Z<3){let U=ugA(Z);Z++,await mgA(U,B.signal);continue}throw H}if(zgQ(B.method,W.status,Z,B.retryEnabled)){var X,G;let H=(X=(G=W.headers)===null||G===void 0?void 0:G.get("Retry-After"))!==null&&X!==void 0?X:null,U=H!==null?Math.max(0,parseInt(H,10)||0)*1000:ugA(Z);await W.text(),Z++,await mgA(U,B.signal);continue}return await B.processResponse(W)}})();if(!this.shouldThrowOnError)Y=Y.catch((Z)=>{var X;let G="",K="",W="",H=Z===null||Z===void 0?void 0:Z.cause;if(H){var U,z,D,I;let V=(U=H===null||H===void 0?void 0:H.message)!==null&&U!==void 0?U:"",L=(z=H===null||H===void 0?void 0:H.code)!==null&&z!==void 0?z:"";if(G=`${(D=Z===null||Z===void 0?void 0:Z.name)!==null&&D!==void 0?D:"FetchError"}: ${Z===null||Z===void 0?void 0:Z.message}`,G+=`
72
72
 
73
73
  Caused by: ${(I=H===null||H===void 0?void 0:H.name)!==null&&I!==void 0?I:"Error"}: ${V}`,L)G+=` (${L})`;if(H===null||H===void 0?void 0:H.stack)G+=`
@@ -1423,7 +1423,7 @@ ${yjA(Q)};
1423
1423
  ${lAB}
1424
1424
 
1425
1425
  Docs: ${gjA}`);let Z=await s1({message:"Have you added notifyAppReady() and rebuilt your app?"});if(EB(Z)||!Z)continue;if(mW(Q,"notifyAppReady"))return R0({channel:"bundle",event:"CLI Recovered Missing NotifyAppReady",tags:{recovery:"manual"}}),"recovered";f.warn("notifyAppReady() is still missing in the build folder. Rebuild, or choose another option.");continue}if(Y==="skip"){f.warn("Skipping notifyAppReady check. Without this call, Capgo may roll back downloaded updates."),f.warn(`Learn more: ${gjA}`);let Z=await s1({message:"Continue without notifyAppReady()?",initialValue:!1});if(EB(Z)||!Z)continue;return R0({channel:"bundle",event:"CLI Skipped NotifyAppReady Check",tags:{}}),"skipped"}if(Y==="patch-build"){let Z=tAB(Q);if(!Z){f.warn("Could not patch the build folder automatically. The app bundle must already include CapacitorUpdater, or patch the source and rebuild.");continue}if(!mW(Q,"notifyAppReady")){f.warn(`Patched ${Z}, but notifyAppReady() is still missing. Try another option.`);continue}return f.success(`Added notifyAppReady() to ${Z}`),R0({channel:"bundle",event:"CLI Recovered Missing NotifyAppReady",tags:{recovery:"patch-build"}}),"recovered"}if(Y==="patch-source")try{let Z=await eAB(L1(hjA()));if(!Z){f.warn("Could not find your app entry file automatically.");continue}f.success(`Added notifyAppReady() to ${Z}`),f.info("Rebuild your web assets, then retry zip/upload.");let X=await s1({message:"Have you rebuilt your app into the build folder?"});if(EB(X)||!X)continue;if(mW(Q,"notifyAppReady"))return R0({channel:"bundle",event:"CLI Recovered Missing NotifyAppReady",tags:{recovery:"patch-source"}}),"recovered";f.warn("notifyAppReady() is still missing in the build folder after rebuild.")}catch(Z){f.error(uA(Z))}}}t1();V0();var AQB={invoke:async(A,Q)=>lB(A,Q),formatError:IZ};async function tLQ(A,Q,B=AQB){let{data:$,error:J}=await B.invoke("private/config",{apikey:A.apikey,method:"GET",supaHost:A.supaHost,supaAnon:A.supaAnon});if(J||!$?.useNewFinalizeBundleUpload){await Q();return}let Y=A.reporter.spinner();Y.start("Finalizing bundle upload...");let{error:Z}=await B.invoke("private/finalize_bundle_upload",{apikey:A.apikey,body:{app_id:A.appId,name:A.bundle},supaHost:A.supaHost,supaAnon:A.supaAnon});if(Z){let X=`Cannot finalize bundle upload: ${await B.formatError(Z)}`;throw Y.error(X),new FQ(X)}Y.stop("Bundle upload finalized")}t1();V0();function QQB(A){let Q=A.appId?.trim()||"<appId>",B=A.path?.trim()||"www",$=A.channel?.trim()||"<channel>";return`npx @capgo/cli@latest bundle upload ${Q} --mode cordova --path ${B} --channel ${$}`}function BQB(A){return[Nt,"If this is a Cordova project (config.xml / plugin.xml and a www folder), retry with:",QQB(A)].join(`
1426
- `)}function $QB(A,Q){if(A instanceof FQ&&A.message===Nt)throw new FQ(BQB({appId:Q.appId,path:Q.path,channel:Q.channel}));throw A}async function eLQ(A,Q={}){if(uF(A.mode))return pLQ({path:A.path,appId:Q.appId});try{return await h0()}catch(B){$QB(B,{appId:Q.appId,path:A.path,channel:A.channel})}}PK();M7();var GCQ=rA(ZCQ(),1),KCQ=rA(za(),1);import{Buffer as b0B}from"node:buffer";import{createHash as x0B}from"node:crypto";import{createReadStream as $wA,statSync as v0B}from"node:fs";import{platform as f0B}from"node:os";import{join as g0B,posix as y0B,win32 as XCQ}from"node:path";import{cwd as h0B}from"node:process";import{buffer as JwA}from"node:stream/consumers";import{createBrotliCompress as u0B}from"node:zlib";t1();V0();La();var gz={info:(A)=>NJ().info(A),warn:(A)=>NJ().warn(A),error:(A)=>NJ().error(A)};async function m0B(A,Q){try{let B=new URL(`${A.hostFilesApi}/files/read/attachments/${encodeURIComponent(Q)}`);B.searchParams.set("nocache",`${Date.now()}`);let $=await fetch(B.toString(),{method:"GET",headers:j4({range:"bytes=0-0","cache-control":"no-cache"})});return{exists:$.ok,receipt:$.headers.get("X-Capgo-Manifest-Size-Receipt")??void 0}}catch{return{exists:!1}}}var c0B=8192;async function d0B(A){let Q=L1(h0B()),B=await DZ("@capgo/capacitor-updater",Q,A.packageJson),$;try{$=B?Z1(B):void 0}catch{$=void 0}if(!B||!$)return{version:null,supportsBrotliV2:!1};let J=!yK($,void 0,void 0,yf);return{version:`${$.major}.${$.minor}.${$.patch}`,supportsBrotliV2:J}}function l0B(A,Q){if(!Q)return!1;let B=Q.split(",").map(($)=>$.trim()).filter(($)=>!!$);if(B.length===0)return!1;return GCQ.isMatch(A,B)}async function p0B(A,Q,B){let J=v0B(A).size,Y=await JwA($wA(A));if(J===0)return{buffer:Y,useBrotli:!1};if(l0B(Q,B.noBrotliPatterns))return{buffer:Y,useBrotli:!1};if(J<c0B)return{buffer:Y,useBrotli:!1};try{let Z=await JwA($wA(A).pipe(u0B({})));if(Z.length>=J-10)return{buffer:Y,useBrotli:!1};return{buffer:Z,useBrotli:!0}}catch(Z){return gz.warn(`Brotli compression failed for ${A}: ${Z}, using original file`),{buffer:Y,useBrotli:!1}}}async function WCQ(A,Q,B,$,J,Y,Z=!1){let X=NJ().spinner();X.start(J!=="v2"?"Generating the update manifest":`Generating the update manifest with ${Z?"V3":"V2"} encryption`);let G=await Rt(A);if(J==="v2")for(let K of G)K.hash=Z?$k(K.hash,Y):Bk(K.hash,Y);return X.stop("Manifest generated successfully"),await _B(Q,{channel:"partial-update",event:"Generate manifest",org_id:B,tracking_version:2,tags:{"app-id":$}}),G}function i0B(A){if(f0B()!=="win32")return A;return XCQ.normalize(A).split(XCQ.sep).join(y0B.sep)}function n0B(A){return A.split("/").map((Q)=>encodeURIComponent(Q)).join("/")}function r0B(A,Q,B,$,J){let Y=x0B("sha256").update(B).digest("hex"),Z=n0B($);if(J){let X=b0B.from(J.ivSessionKey).toString("hex");return`orgs/${A}/apps/${Q}/delta/${X}/${Y}_${Z}`}return`orgs/${A}/apps/${Q}/delta/${Y}_${Z}`}async function HCQ(A,Q,B,$,J,Y,Z){let X=NJ().spinner();X.start("Preparing partial update with TUS protocol");let G=performance.now(),K=await LJ(),W=!!Z.userRequestedDelta,{version:H,supportsBrotliV2:U}=await d0B(Z);if(!U)throw new FQ(`Your project is using an older version of @capgo/capacitor-updater (${H||"unknown"}). To use Delta updates, please upgrade to version ${Ct} (v5), ${Vt} (v6) or ${yf} (v7) or higher.`);else if(Z.disableBrotli)gz.info("Brotli compression disabled by user request");else if(Z.noBrotliPatterns)gz.info(`Files matching patterns (${Z.noBrotliPatterns}) will be excluded from brotli compression`);let z=Q.filter((N)=>N.file.includes(" "));if(z.length>0)throw new FQ(`Files with spaces in their names (${z.map((N)=>N.file).join(", ")}). Please rename the files.`);if(Q.length>vf)throw new FQ(Lt(Q.length));let D=0,I=Q.length,M=0;try{X.message(`Uploading ${I} files using TUS protocol`);let N=async(E)=>{let w=g0B(B,E.file),S=i0B(E.file),h,k=!1;if(Z.disableBrotli)h=await JwA($wA(w)),k=!1;else{let n=await p0B(w,S,Z);h=n.buffer,k=n.useBrotli}let v=h;if(Y)v=Qk(h,Y.sessionKey,Y.ivSessionKey);let g=S;if(k)g=`${S}.br`,M++;let a=r0B(J,$,E.hash,g,Y),t=!Y?await m0B(K,a):{exists:!1};if(t.exists)return D++,Promise.resolve({file_name:g,s3_path:a,file_hash:E.hash,file_size_receipt:t.receipt});return new Promise((n,l)=>{X.message(`Prepare upload partial file: ${S}`);let c=oN(g);new KCQ.Upload(v,{endpoint:`${K.hostFilesApi}/files/upload/attachments/`,chunkSize:Z.tusChunkSize,retryDelays:[...xf],removeFingerprintOnSuccess:!0,metadata:{filename:a,filetype:c},headers:j4({Authorization:A}),onError:(d)=>{let b=d.toString();if(TqA(d)){gz.error(`Failed to upload ${S}: ${b}`),l(Error(hf($)));return}let m;try{let y=b.match(/response text: (\{.*?\})/);if(y&&y[1])m=JSON.parse(y[1]).moreInfo?.requestId}catch{}let QA=m?` [requestId: ${m}]`:"";gz.error(`Failed to upload ${S}: ${b}${QA}`),l(d)},onProgress(){let d=(D/I*100).toFixed(2);X.message(`Uploading partial update: ${d}%`)},onSuccess({lastResponse:d}){D++,n({file_name:g,s3_path:a,file_hash:E.hash,file_size_receipt:d.getHeader("X-Capgo-Manifest-Size-Receipt")??void 0})}}).start()})},V=500,L=[];for(let E=0;E<Q.length;E+=V){let w=Q.slice(E,E+V),S=Math.floor(E/V)+1,h=Math.ceil(Q.length/V);if(h>1)X.message(`Processing batch ${S}/${h} (${w.length} files)`);let k=await Promise.all(w.map((v)=>N(v)));L.push(...k)}if(L.some((E)=>!E.file_size_receipt))L.forEach((E)=>delete E.file_size_receipt);let R=((performance.now()-G)/1000).toFixed(2);if(X.stop(`Partial update uploaded successfully \uD83D\uDCAA in (${R} seconds)`),M>0)gz.info(`${M} of ${I} files were compressed with brotli and use .br extension`);return await _B(A,{channel:"app",event:`App Partial TUS done${M>0?" with .br extension":""}`,org_id:J,tracking_version:2,tags:{"app-id":$}}),await _B(A,{channel:"performance",event:"Partial upload performance",org_id:J,tracking_version:2,tags:{"app-id":$,time:R}}),L}catch(N){let L=((performance.now()-G)/1000).toFixed(2);if(X.error(`Failed to upload Partial bundle (after ${L} seconds)`),W)throw gz.error(`Error uploading partial update: ${N}`),gz.error("Delta/partial upload was explicitly requested but failed. Upload aborted."),N;else return gz.info(`Error uploading partial update: ${N}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}La();function YwA(A){if(!A)return[];let Q=A.split(",").map((B)=>B.trim()).filter(Boolean);return Array.from(new Set(Q))}function Ik(A){return A.join(", ")}function FCQ(A,Q,B){let $=[],J=[];for(let Y of A){if(B.get(Y)===Q){$.push(Y);continue}J.push(Y)}return{channelsAlreadyCurrent:$,channelsToAssign:J}}var GwA="Upload cancelled by user",_A={info:(A)=>NJ().info(A),warn:(A)=>NJ().warn(A),error:(A)=>NJ().error(A),success:(A)=>NJ().success(A)};function VB(A){throw _A.error(A),new FQ(A)}async function Z$A(A,Q){let B=await gf(A);VB(B||await Q())}function KwA(){throw _A.warn(GwA),new FQ(GwA)}class WwA extends FQ{}async function ZwA(A,Q,B){let{error:$}=await YeA(A,Q);if($)VB(`Cannot ${B} bundle ${uA($)}`)}function s0B(A){let Q=A.map((B)=>{let $=Z2(B);return[B.name,B.localVersion||"-",B.remoteVersion||"-",$.compatible?"✅":"❌",$.message]});_A.info(fG({headers:["Package","Local","Remote","Status","Details"],rows:Q}))}async function t0B(A,Q){let B=RX("",Q.packageJson),$=Q.bundle||A?.plugins?.CapacitorUpdater?.version||B||`0.0.1-beta.local-${a0B().split("-")[0]}`;if(!rN.test($))VB(`Your bundle name ${$}, is not valid it should follow semver convention : https://semver.org/`);return $}function e0B(A){let Q=A.apikey||x0();if(!Q)VB("Missing API key, you need to provide an API key to upload your bundle");return Q}async function ABB(A,Q,B,$){let J=await a6A({explicitAppId:A,config:B,apikey:Q.apikey||x0(!0),packageJsonPaths:Hk(Q.packageJson),interactive:$,supaHost:Q.supaHost,supaAnon:Q.supaAnon}),Y=Q.path||B?.webDir||(uF(Q.mode)?s6A:void 0);if(!J)VB(uF(Q.mode)?"Missing appId. Pass it on the command line or set id in config.xml / plugin.xml":"Missing argument, you need to provide a appid or be in a capacitor project");if(!Y)VB(uF(Q.mode)?`Missing upload path. Pass --path or use the default Cordova web dir (${s6A})`:"Missing argument, you need to provide a path (--path), or be in a capacitor project");if(!pl(Y))VB(`Path ${Y} does not exist, build your app first, or provide a valid path`);return{appid:J,path:Y}}async function QBB(A,Q,B){if(A.codeCheck===!1||A.ignoreNotifyAppReady)return;if(!mW(Q,"notifyAppReady")){if(await A$A({webDir:Q,interactive:B})==="skipped")return}if(!mW(Q,"notifyAppReady"))throw _A.error(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugins/updater/notifyappready
1426
+ `)}function $QB(A,Q){if(A instanceof FQ&&A.message===Nt)throw new FQ(BQB({appId:Q.appId,path:Q.path,channel:Q.channel}));throw A}async function eLQ(A,Q={}){if(uF(A.mode))return pLQ({path:A.path,appId:Q.appId});try{return await h0()}catch(B){$QB(B,{appId:Q.appId,path:A.path,channel:A.channel})}}PK();M7();var GCQ=rA(ZCQ(),1),KCQ=rA(za(),1);import{Buffer as b0B}from"node:buffer";import{createHash as x0B}from"node:crypto";import{createReadStream as $wA,statSync as v0B}from"node:fs";import{platform as f0B}from"node:os";import{join as g0B,posix as y0B,win32 as XCQ}from"node:path";import{cwd as h0B}from"node:process";import{buffer as JwA}from"node:stream/consumers";import{createBrotliCompress as u0B}from"node:zlib";t1();V0();La();var gz={info:(A)=>NJ().info(A),warn:(A)=>NJ().warn(A),error:(A)=>NJ().error(A)};async function m0B(A,Q){try{let B=new URL(`${A.hostFilesApi}/files/read/attachments/${encodeURIComponent(Q)}`);B.searchParams.set("nocache",`${Date.now()}`);let $=await fetch(B.toString(),{method:"GET",headers:j4({range:"bytes=0-0","cache-control":"no-cache"})});return{exists:$.ok,receipt:$.headers.get("X-Capgo-Manifest-Size-Receipt")??void 0}}catch{return{exists:!1}}}var c0B=8192;async function d0B(A){let Q=L1(h0B()),B=await DZ("@capgo/capacitor-updater",Q,A.packageJson),$;try{$=B?Z1(B):void 0}catch{$=void 0}if(!B||!$)return{version:null,supportsBrotliV2:!1};let J=!yK($,void 0,void 0,yf);return{version:`${$.major}.${$.minor}.${$.patch}`,supportsBrotliV2:J}}function l0B(A,Q){if(!Q)return!1;let B=Q.split(",").map(($)=>$.trim()).filter(($)=>!!$);if(B.length===0)return!1;return GCQ.isMatch(A,B)}async function p0B(A,Q,B){let J=v0B(A).size,Y=await JwA($wA(A));if(J===0)return{buffer:Y,useBrotli:!1};if(l0B(Q,B.noBrotliPatterns))return{buffer:Y,useBrotli:!1};if(J<c0B)return{buffer:Y,useBrotli:!1};try{let Z=await JwA($wA(A).pipe(u0B({})));if(Z.length>=J-10)return{buffer:Y,useBrotli:!1};return{buffer:Z,useBrotli:!0}}catch(Z){return gz.warn(`Brotli compression failed for ${A}: ${Z}, using original file`),{buffer:Y,useBrotli:!1}}}async function WCQ(A,Q,B,$,J,Y,Z=!1){let X=NJ().spinner();X.start(J!=="v2"?"Generating the update manifest":`Generating the update manifest with ${Z?"V3":"V2"} encryption`);let G=await Rt(A);if(J==="v2")for(let K of G)K.hash=Z?$k(K.hash,Y):Bk(K.hash,Y);return X.stop("Manifest generated successfully"),await _B(Q,{channel:"partial-update",event:"Generate manifest",org_id:B,tracking_version:2,tags:{"app-id":$}}),G}function i0B(A){if(f0B()!=="win32")return A;return XCQ.normalize(A).split(XCQ.sep).join(y0B.sep)}function n0B(A){return A.split("/").map((Q)=>encodeURIComponent(Q)).join("/")}function r0B(A,Q,B,$,J){let Y=x0B("sha256").update(B).digest("hex"),Z=n0B($);if(J){let X=b0B.from(J.ivSessionKey).toString("hex");return`orgs/${A}/apps/${Q}/delta/${X}/${Y}_${Z}`}return`orgs/${A}/apps/${Q}/delta/${Y}_${Z}`}async function HCQ(A,Q,B,$,J,Y,Z){let X=NJ().spinner();X.start("Preparing delta update with TUS protocol");let G=performance.now(),K=await LJ(),W=!!Z.userRequestedDelta,{version:H,supportsBrotliV2:U}=await d0B(Z);if(!U)throw new FQ(`Your project is using an older version of @capgo/capacitor-updater (${H||"unknown"}). To use Delta updates, please upgrade to version ${Ct} (v5), ${Vt} (v6) or ${yf} (v7) or higher.`);else if(Z.disableBrotli)gz.info("Brotli compression disabled by user request");else if(Z.noBrotliPatterns)gz.info(`Files matching patterns (${Z.noBrotliPatterns}) will be excluded from brotli compression`);let z=Q.filter((N)=>N.file.includes(" "));if(z.length>0)throw new FQ(`Files with spaces in their names (${z.map((N)=>N.file).join(", ")}). Please rename the files.`);if(Q.length>vf)throw new FQ(Lt(Q.length));let D=0,I=Q.length,M=0;try{X.message(`Uploading ${I} files using TUS protocol`);let N=async(E)=>{let w=g0B(B,E.file),S=i0B(E.file),h,k=!1;if(Z.disableBrotli)h=await JwA($wA(w)),k=!1;else{let n=await p0B(w,S,Z);h=n.buffer,k=n.useBrotli}let v=h;if(Y)v=Qk(h,Y.sessionKey,Y.ivSessionKey);let g=S;if(k)g=`${S}.br`,M++;let a=r0B(J,$,E.hash,g,Y),t=!Y?await m0B(K,a):{exists:!1};if(t.exists)return D++,Promise.resolve({file_name:g,s3_path:a,file_hash:E.hash,file_size_receipt:t.receipt});return new Promise((n,l)=>{X.message(`Prepare upload delta file: ${S}`);let c=oN(g);new KCQ.Upload(v,{endpoint:`${K.hostFilesApi}/files/upload/attachments/`,chunkSize:Z.tusChunkSize,retryDelays:[...xf],removeFingerprintOnSuccess:!0,metadata:{filename:a,filetype:c},headers:j4({Authorization:A}),onError:(d)=>{let b=d.toString();if(TqA(d)){gz.error(`Failed to upload ${S}: ${b}`),l(Error(hf($)));return}let m;try{let y=b.match(/response text: (\{.*?\})/);if(y&&y[1])m=JSON.parse(y[1]).moreInfo?.requestId}catch{}let QA=m?` [requestId: ${m}]`:"";gz.error(`Failed to upload ${S}: ${b}${QA}`),l(d)},onProgress(){let d=(D/I*100).toFixed(2);X.message(`Uploading delta update: ${d}%`)},onSuccess({lastResponse:d}){D++,n({file_name:g,s3_path:a,file_hash:E.hash,file_size_receipt:d.getHeader("X-Capgo-Manifest-Size-Receipt")??void 0})}}).start()})},V=500,L=[];for(let E=0;E<Q.length;E+=V){let w=Q.slice(E,E+V),S=Math.floor(E/V)+1,h=Math.ceil(Q.length/V);if(h>1)X.message(`Processing batch ${S}/${h} (${w.length} files)`);let k=await Promise.all(w.map((v)=>N(v)));L.push(...k)}if(L.some((E)=>!E.file_size_receipt))L.forEach((E)=>delete E.file_size_receipt);let R=((performance.now()-G)/1000).toFixed(2);if(X.stop(`Delta update uploaded successfully \uD83D\uDCAA in (${R} seconds)`),M>0)gz.info(`${M} of ${I} files were compressed with brotli and use .br extension`);return await _B(A,{channel:"app",event:`App Partial TUS done${M>0?" with .br extension":""}`,org_id:J,tracking_version:2,tags:{"app-id":$}}),await _B(A,{channel:"performance",event:"Partial upload performance",org_id:J,tracking_version:2,tags:{"app-id":$,time:R}}),L}catch(N){let L=((performance.now()-G)/1000).toFixed(2);if(X.error(`Failed to upload delta update (after ${L} seconds)`),W)throw gz.error(`Error uploading delta update: ${N}`),gz.error("Delta upload was explicitly requested but failed. Upload aborted."),N;else return gz.info(`Error uploading delta update: ${N}, This is not a critical error, the bundle has been uploaded without the delta files`),null}}La();function YwA(A){if(!A)return[];let Q=A.split(",").map((B)=>B.trim()).filter(Boolean);return Array.from(new Set(Q))}function Ik(A){return A.join(", ")}function FCQ(A,Q,B){let $=[],J=[];for(let Y of A){if(B.get(Y)===Q){$.push(Y);continue}J.push(Y)}return{channelsAlreadyCurrent:$,channelsToAssign:J}}var GwA="Upload cancelled by user",_A={info:(A)=>NJ().info(A),warn:(A)=>NJ().warn(A),error:(A)=>NJ().error(A),success:(A)=>NJ().success(A)};function VB(A){throw _A.error(A),new FQ(A)}async function Z$A(A,Q){let B=await gf(A);VB(B||await Q())}function KwA(){throw _A.warn(GwA),new FQ(GwA)}class WwA extends FQ{}async function ZwA(A,Q,B){let{error:$}=await YeA(A,Q);if($)VB(`Cannot ${B} bundle ${uA($)}`)}function s0B(A){let Q=A.map((B)=>{let $=Z2(B);return[B.name,B.localVersion||"-",B.remoteVersion||"-",$.compatible?"✅":"❌",$.message]});_A.info(fG({headers:["Package","Local","Remote","Status","Details"],rows:Q}))}async function t0B(A,Q){let B=RX("",Q.packageJson),$=Q.bundle||A?.plugins?.CapacitorUpdater?.version||B||`0.0.1-beta.local-${a0B().split("-")[0]}`;if(!rN.test($))VB(`Your bundle name ${$}, is not valid it should follow semver convention : https://semver.org/`);return $}function e0B(A){let Q=A.apikey||x0();if(!Q)VB("Missing API key, you need to provide an API key to upload your bundle");return Q}async function ABB(A,Q,B,$){let J=await a6A({explicitAppId:A,config:B,apikey:Q.apikey||x0(!0),packageJsonPaths:Hk(Q.packageJson),interactive:$,supaHost:Q.supaHost,supaAnon:Q.supaAnon}),Y=Q.path||B?.webDir||(uF(Q.mode)?s6A:void 0);if(!J)VB(uF(Q.mode)?"Missing appId. Pass it on the command line or set id in config.xml / plugin.xml":"Missing argument, you need to provide a appid or be in a capacitor project");if(!Y)VB(uF(Q.mode)?`Missing upload path. Pass --path or use the default Cordova web dir (${s6A})`:"Missing argument, you need to provide a path (--path), or be in a capacitor project");if(!pl(Y))VB(`Path ${Y} does not exist, build your app first, or provide a valid path`);return{appid:J,path:Y}}async function QBB(A,Q,B){if(A.codeCheck===!1||A.ignoreNotifyAppReady)return;if(!mW(Q,"notifyAppReady")){if(await A$A({webDir:Q,interactive:B})==="skipped")return}if(!mW(Q,"notifyAppReady"))throw _A.error(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugins/updater/notifyappready
1427
1427
  If you are sure your app has this code, you can use the --no-code-check or --ignore-notify-app-ready option`),Error(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugins/updater/notifyappready
1428
1428
  If you are sure your app has this code, you can use the --no-code-check or --ignore-notify-app-ready option`.trim());if(!Kk(Q))VB(`index.html is missing in the root folder of ${Q}`)}async function BBB(A,Q,B,$,J,Y,Z){let{ignoreMetadataCheck:X,autoMinUpdateVersion:G,minUpdateVersion:K}=B,{data:W,error:H}=await A.from("channels").select("disable_auto_update, version ( id, name, min_update_version, native_packages )").eq("name",$).eq("app_id",J).maybeSingle();if(H)VB(`Cannot load channel ${$} for compatibility checks ${uA(H)}`);let U=W?.version??void 0,z=!!W&&W.disable_auto_update==="version_number",D,I;if(!H&&W&&W.version&&W.version.native_packages&&!X){let C=NJ().spinner();C.start(`Checking bundle compatibility with channel ${$}`);let{finalCompatibility:R,localDependencies:E}=await aw(A,J,$,B.packageJson,B.nodeModules);if(I=R,D=E,I.filter((S)=>!R7(S)).length>0){if(C.error(`Bundle NOT compatible with ${$} channel`),_A.warn(""),s0B(I),_A.warn(""),_A.warn("An app store update may be required for these changes to take effect."),G)K=Y,_A.info(`Auto set min-update-version to ${K}`)}else if(G)try{let{min_update_version:S}=W.version;if(!S||!rN.test(S))VB("Invalid remote min update version, skipping auto setting compatibility");K=S,C.stop(`Auto set min-update-version to ${K}`)}catch{VB(`Cannot auto set compatibility, invalid data ${W}`)}else C.stop(`Bundle compatible with ${$} channel`)}else if(!X){if(_A.warn(`Channel ${$} is new or it's your first upload with compatibility check, it will be ignored this time`),D=await bqA(B.packageJson,B.nodeModules),G)K=Y,_A.info(`Auto set min-update-version to ${K}`)}let M=I?void 0:X?"ignore_metadata_check":"no_remote_metadata",N=ROQ(I);if(R0({channel:"bundle",event:"Bundle Upload Compatibility Checked",apikey:B.apikey,appId:J,orgId:Z,tags:{result:N.result,incompatible_count:N.incompatibleCount,channel:$,channel_name:$,...N.reasons.length>0?{reasons:N.reasons.join(",")}:{},...M?{skip_reason:M}:{}}}),z&&!K&&!X)VB("You need to provide a min-update-version to upload a bundle to this channel");if(K){if(!rN.test(K))VB(`Your minimal version update ${K}, is not valid it should follow semver convention : https://semver.org/`)}let V=D?new Map(D.filter((C)=>!!C.native&&C.native!==void 0).map((C)=>[C.name,C])):new Map;return{nativePackages:V.size>0||!B.ignoreMetadataCheck?Array.from(V,([C,R])=>({name:C,version:R.version,requested_version:R.requested_version,...R.ios_checksum&&{ios_checksum:R.ios_checksum},...R.android_checksum&&{android_checksum:R.android_checksum}})):void 0,minUpdateVersion:K,incompatibleCount:N.incompatibleCount,compatibility:{result:N.result,versionOldId:U?.id!=null?String(U.id):void 0,versionOldName:U?.name}}}async function $BB(A,Q,B,$=!1,J=!1){let{data:Y,error:Z}=await A.rpc("exist_app_versions",{appid:Q,name_version:B}).single();if(Z)VB(`Cannot check if version ${B} already exists ${uA(Z)}`);if(Y){if($)return _A.warn(`Version ${B} already exists - exiting gracefully due to --version-exists-ok option`),NJ().outro("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(J){_A.error(`❌ Version ${B} already exists`);let X=_LQ(B);_A.info("\uD83D\uDCA1 Here are some suggestions:"),X.forEach((W,H)=>{_A.info(` ${H+1}. ${W}`)});let G=await _6({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${X[0]}`},{value:"suggest2",label:`Use ${X[1]}`},{value:"suggest3",label:`Use ${X[2]}`},{value:"suggest4",label:`Use ${X[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(EB(G)||typeof G!=="string"||G==="cancel")KwA();let K;if(G==="custom"){let W=await PLQ(B,"upload");if(!W)KwA();K=W}else{let W=Number.parseInt(G.replace("suggest",""))-1;K=X[W]}return _A.info(`\uD83D\uDD04 Retrying with new version: ${K}`),K}VB(`Version ${B} already exists`)}return!1}function JBB(A){let Q;for(let{minUpdateVersion:B}of A){if(!B)continue;if(!Q||NZA(Z1(B),Z1(Q)))Q=B}return Q}async function YBB(A,Q,B,$){let J=new Map;for(let X of B){let G=NJ().spinner();G.start(`Checking bundle checksum compatibility with channel ${X}`);let K=await qeA(A,Q,X);if(J.set(X,K),!K){G.stop(`No checksum found for channel ${X}, the bundle will be uploaded`);continue}if(K===$){G.stop(`Channel ${X} already has this bundle checksum`);continue}G.stop(`Checksum compatible with ${X} channel`)}let{channelsAlreadyCurrent:Y,channelsToAssign:Z}=FCQ(B,$,J);if(Z.length===0){let X=Ik(B);throw _A.error(`Cannot upload the same bundle content.
1429
1429
  Current bundle checksum matches remote bundle for channel${B.length>1?"s":""} ${X}
@@ -1435,7 +1435,7 @@ PS: You can ignore this check with "--ignore-checksum-check"`),Error("Cannot upl
1435
1435
  The bundle size is ${k} Mb, this may take a while to download for users
1436
1436
  `),_A.info(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
1437
1437
  `),Q.verbose)_A.info("[Verbose] Bundle size details:"),_A.info(` - Actual size: ${k} MB (${H?.byteLength} bytes)`),_A.info(` - Alert threshold: ${Math.floor(Z/1024/1024)} MB`),_A.info(` - Maximum allowed: ${v} MB`),_A.info("[Verbose] Sending 'App Too Large' event to analytics...");if(await _B(B,{channel:"app-error",event:"App Too Large",org_id:$,tracking_version:2,tags:{"app-id":J,size_mb:k}},Q.verbose),Q.verbose)_A.info("[Verbose] Event sent successfully")}else if(Q.verbose)_A.info(`[Verbose] Bundle size OK: ${k} MB (under ${Math.floor(Z/1024/1024)} MB alert threshold)`);if(Q.verbose)_A.info("[Verbose] Bundle preparation complete, returning bundle data");return{zipped:H,ivSessionKey:G,sessionKey:K,checksum:W,encryptionMethod:U,finalKeyData:z,keyId:D}}async function FBB(A,Q,B,$,J,Y,Z,X){let G=NJ().spinner();G.start("Uploading Bundle");let K=performance.now(),W=!1;if(Z.verbose)_A.info("[Verbose] uploadBundleToCapgoCloud called:"),_A.info(` - Bundle size: ${Math.floor(Y.byteLength/1024)} KB`),_A.info(` - App ID: ${B}`),_A.info(` - Bundle version: ${$}`),_A.info(` - Chunk size: ${Math.floor(X/1024/1024)} MB`);if(Z.dryUpload){if(G.stop(`Dry run, bundle not uploaded
1438
- Bundle uploaded \uD83D\uDCAA in 0 seconds`),Z.verbose)_A.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let z=await LJ();if(Z.verbose)_A.info("[Verbose] Local config retrieved for upload");if(Z.multipart!==void 0&&Z.multipart||Z.tus!==void 0&&Z.tus){if(Z.multipart)_A.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else _A.info("Uploading bundle with TUS protocol");if(Z.verbose)_A.info("[Verbose] Starting TUS resumable upload..."),_A.info(` - Host: ${z.hostWeb}`),_A.info(` - Chunk size: ${Math.floor(X/1024/1024)} MB`);if(await GeA(A,Y,J,B,$,G,z,X),W=!0,Z.verbose)_A.info("[Verbose] TUS upload completed, updating database with R2 path...");let D=`orgs/${J}/apps/${B}/${$}.zip`,{error:I}=await Q.from("app_versions").update({r2_path:D}).eq("name",$).eq("app_id",B);if(I){if(_A.error(`Cannot finish TUS upload ${uA(I)}`),Z.verbose)_A.info(`[Verbose] Database update failed: ${uA(I)}`);throw Error("Cannot finish TUS upload")}if(Z.verbose)_A.info(`[Verbose] Database updated with R2 path: ${D}`)}else{if(Z.verbose)_A.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let D=await ZeA(A,B,$,Z);if(!D){if(_A.error("Cannot get upload url"),Z.verbose)_A.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}let I=Z.timeout||rtA;if(Z.verbose)_A.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),_A.info(` - Timeout: ${I}ms`),_A.info(" - Retry attempts: 0 (standard upload does not retry, use --tus for resumable retries)"),_A.info(" - Content-Type: application/zip");let M=new AbortController,N=setTimeout(()=>M.abort(),I);try{let V=await fetch(D,{method:"PUT",body:Y,headers:{"Content-Type":"application/zip"},signal:M.signal});if(!V.ok)throw Error(`HTTP error! status: ${V.status}`)}catch(V){if(M.signal.aborted||V?.name==="AbortError"){let L=Error(atA(I));throw L.name=wqA,L}throw V}finally{clearTimeout(N)}if(Z.verbose)_A.info("[Verbose] HTTP PUT upload completed successfully")}}catch(z){let I=((performance.now()-K)/1000).toFixed(2);if(G.error(`Failed to upload bundle ( after ${I} seconds)`),Z.verbose)_A.info(`[Verbose] Upload failed after ${I} seconds`),_A.info(`[Verbose] Error type: ${z instanceof Error?"Error":typeof z}`);if(z instanceof Error&&z.name===wqA)_A.error(z.message);else if(z instanceof Error&&z.message.includes("HTTP error"))try{let M=z.message.match(/status: (\d+)/),N=M?M[1]:"unknown";_A.error(`Upload failed with status ${N}: ${z.message}`)}catch{_A.error(`Upload failed: ${z.message}`)}else{if(Z.verbose)_A.info(`[Verbose] Non-HTTP error: ${uA(z)}`);if(!Z.tus)_A.error(`Cannot upload bundle ( try again with --tus option) ${uA(z)}`);else _A.error(`Cannot upload bundle please contact support if the issue persists ${uA(z)}`)}if(Z.verbose)_A.info("[Verbose] Cleaning up failed version from database...");try{if(await jt(A,B,$,Z),Z.verbose)_A.info("[Verbose] Failed version cleaned up")}catch(M){_A.error(`Cleanup of the incomplete version failed (${uA(M)}); delete bundle ${$} manually before retrying.`)}throw z instanceof Error?z:Error(String(z))}let U=((performance.now()-K)/1000).toFixed(2);if(G.stop(`Bundle uploaded \uD83D\uDCAA in (${U} seconds)`),Z.verbose)_A.info("[Verbose] Upload successful:"),_A.info(` - Upload time: ${U} seconds`),_A.info(` - Upload method: ${W?"TUS (resumable)":"Standard HTTP PUT"}`),_A.info(` - Bundle size: ${Math.floor(Y.byteLength/1024)} KB`),_A.info("[Verbose] Sending performance event...");if(await _B(A,{channel:"performance",event:W?"TUS upload zip performance":"Upload zip performance",org_id:J,tracking_version:2,tags:{"app-id":B,time:U}},Z.verbose),Z.verbose)_A.info("[Verbose] Performance event sent successfully")}function UBB(A){if(A.rollout==null&&A.rolloutPercentageBps==null)return;if(A.rolloutPercentageBps!=null)return A.rolloutPercentageBps;return Math.round((A.rollout??0)*100)}function UCQ(A){return`${Number((A/100).toFixed(2))}%`}async function MCQ(A,Q,B,$){let{data:J}=await A.rpc("get_app_versions",{apikey:Q,name_version:$,appid:B}).single();if(!J)VB("Cannot get version id, cannot set channel");return J}async function qBB(A,Q,B){let{data:$,error:J}=await A.rpc("exist_app_versions",{appid:Q,name_version:B}).single();if(J)VB(`Cannot check if version ${B} already exists ${uA(J)}`);return!!$}async function zBB(A,Q){let{data:B,error:$}=await A.from("app_versions").select("name").eq("app_id",Q).order("created_at",{ascending:!1}).limit(1).maybeSingle();if($)return _A.warn(`Cannot fetch latest remote version ${uA($)}`),null;return B?.name??null}async function qCQ(A,Q,B,$,J){let Y=B;for(let Z=0;Z<100;Z++){if(!await qBB(A,Q,Y)){if(Y!==J)_A.info(`\uD83D\uDD22 Auto-bumped (${$}) version from ${J} to ${Y}`);return Y}Y=r6A(Y,$)}VB(`Could not find a free ${$}-bumped version after 100 attempts (started from ${J})`)}async function DBB(A,Q,B,$,J){let Y=B[0],X=(await OCQ(A,Q,Y))?.name??null;if(X)_A.info(`\uD83D\uDCE6 Auto-bump base from channel ${Y}: ${X}`);else if(X=await zBB(A,Q),X)_A.info(`\uD83D\uDCE6 Auto-bump base from latest remote app version: ${X}`);if(!X)return _A.info(`ℹ️ No remote versions found for auto-bump, keeping local version ${$}`),qCQ(A,Q,$,J,$);let G=r6A(X,J);return qCQ(A,Q,G,J,X)}async function OCQ(A,Q,B){let{data:$,error:J}=await A.from("channels").select("version:app_versions!channels_version_fkey( id, name, deleted )").eq("app_id",Q).eq("name",B);if(J)return _A.error(`Cannot delete linked bundle on upload ${uA(J)}`),null;if($.length===0)return _A.warn("No linked bundle found in the channel you are trying to upload to"),null;let Y=$[0].version;if(!Y)return _A.warn("No linked bundle found in the channel you are trying to upload to"),null;if(Y.deleted)return _A.warn("The linked bundle is already deleted"),null;return Y}async function IBB(A,Q){if(!Q)return;let{error:B}=await A.from("app_versions").update({deleted:!0}).eq("id",Q.id);if(B){_A.error(`Cannot delete linked bundle on upload ${uA(B)}`);return}_A.info(`Linked bundle ${Q.name} deleted`)}async function HwA(A,Q,B,$=!0){let{data:J,error:Y}=await A.from("channels").select("id, public, version, rollout_version, rollout_enabled, rollout_percentage_bps").eq("app_id",Q).eq("name",B).maybeSingle();if(Y&&$)VB(`Cannot check channel ${B}: ${uA(Y)}`);return J}async function MBB(A,Q,B,$,J=!1,Y,Z=!1){let X=new Map,G=Y!=null||Z;for(let K of new Set($)){let W=await HwA(A,B,K);if(W){if(X.set(K,W),!await VJ(A,Q,"channel.promote_bundle",{appId:B,channelId:W.id}))VB("Cannot set channel because this API key lacks channel.promote_bundle for the target channel");if(J||G){if(!await VJ(A,Q,"channel.update_settings",{appId:B,channelId:W.id}))VB(J?"Cannot enable device self-assign because this API key lacks channel.update_settings":"Cannot set rollout because this API key lacks channel.update_settings for the target channel")}if(G&&!W.version)VB(`Cannot set rollout, channel ${K} needs a stable bundle before using progressive rollout`);if(Z&&W.rollout_version==null)VB(`Cannot advance rollout, channel ${K} has no rollout target to promote to stable`);if(Z&&Y==null&&!((W.rollout_percentage_bps??0)>0))VB(`Cannot advance rollout, channel ${K} has no rollout percentage to reuse. Pass --rollout or --rollout-percentage-bps`);continue}if(G)VB(`Cannot set rollout, channel ${K} must already exist with a stable bundle`);if(!await VJ(A,Q,"app.create_channel",{appId:B}))VB("Cannot create target channel because this API key lacks app.create_channel");X.set(K,null)}return X}async function FwA(A){let Q=A?.context;if(Q?.json)try{return JSON.stringify(await Q.json())}catch{}return uA(A)}async function zCQ(A,Q,B,$,J,Y,Z){let{error:X}=await lB("bundle",{apikey:A,method:"PUT",body:{app_id:Q,version_id:B,channel_id:$.id},supaHost:Z?.supaHost,supaAnon:Z?.supaAnon});if(X)await Z$A(X,async()=>`Cannot set channel because this API key does not have the required RBAC permission. ${await FwA(X)}`);let G=`${J.hostWeb}/app/${Q}/channel/${$.id}`;if($.rollout_enabled&&$.rollout_version!=null)_A.warn("This channel has an active progressive rollout. Linking this bundle as the stable version resets that rollout, so devices receive the new bundle instead of the previous rollout target.");else if($.public)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${G}`);if(Y)_A.info(`Bundle url: ${G}`);return!0}async function OBB(A,Q,B,$,J,Y,Z,X,G,K,W=!1,H,U){let z=K!==null&&await VJ(A,Q,"channel.promote_bundle",{appId:X,channelId:K.id}),D=K===null&&await VJ(A,Q,"app.create_channel",{appId:X});if(K&&!z){if(W)VB("Cannot set channel because this API key lacks channel.promote_bundle for the target channel");return _A.warn("Cannot set channel because this API key lacks channel.promote_bundle for the target channel"),!1}if(K&&z){let M=await MCQ(A,Q,X,$);if(H){if(!await VJ(A,Q,"channel.update_settings",{appId:X,channelId:K.id}))return _A.warn("Cannot enable device self-assign because this API key lacks channel.update_settings"),zCQ(Q,X,M,K,G,B,U)}if(!H)return zCQ(Q,X,M,K,G,B,U);let{error:N,data:V}=await WeA(A,{name:J,app_id:X,created_by:Y,version:M,owner_org:Z,...H?{allow_device_self_set:!0}:{}});if(N)await Z$A(N,()=>`Cannot set channel because this API key does not have the required RBAC permission. ${uA(N)}`);if(V?.id){let L=`${G.hostWeb}/app/${X}/channel/${V.id}`;if(K.rollout_enabled&&K.rollout_version!=null)_A.warn("This channel has an active progressive rollout. Linking this bundle as the stable version resets that rollout, so devices receive the new bundle instead of the previous rollout target.");else if(V.public)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${L}`);if(B)_A.info(`Bundle url: ${L}`)}return!0}if(D){let{error:M,data:N}=await lB("channel",{apikey:Q,method:"POST",body:{app_id:X,channel:J,version:$,...H?{allow_device_self_set:!0}:{}},supaHost:U?.supaHost,supaAnon:U?.supaAnon});if(M)await Z$A(M,async()=>`Cannot create channel and set its bundle because this API key does not have the required RBAC permission. ${await FwA(M)}`);let V=N,L=Number(V?.id),C=V?.public===!0;if(!Number.isSafeInteger(L)||typeof V?.public!=="boolean"){let E=await HwA(A,X,J,!1),w=Number(E?.id);if(!Number.isSafeInteger(w)){if(!Number.isSafeInteger(L))return _A.info("Your update is now available \uD83C\uDF89"),!0}else L=w,C=E?.public===!0}let R=`${G.hostWeb}/app/${X}/channel/${L}`;if(C)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${R}`);if(B)_A.info(`Bundle url: ${R}`);return!0}let I="Cannot create target channel because this API key lacks app.create_channel";if(W)VB(I);return _A.warn(I),!1}async function LBB(A,Q,B,$,J,Y,Z,X,G,K,W,H,U=!1){if(!X)VB(`Cannot set rollout, channel ${J} must already exist with a stable bundle`);if(!X.version)VB(`Cannot set rollout, channel ${J} needs a stable bundle before using progressive rollout`);if(U&&X.rollout_version==null)VB(`Cannot advance rollout, channel ${J} has no rollout target to promote to stable`);let z=await MCQ(A,Q,Y,$),[D,I]=await Promise.all([VJ(A,Q,"channel.promote_bundle",{appId:Y,channelId:X.id}),VJ(A,Q,"channel.update_settings",{appId:Y,channelId:X.id})]);if(!D)VB("Cannot set rollout because this API key lacks channel.promote_bundle for the target channel");if(!I)VB("Cannot set rollout because this API key lacks channel.update_settings for the target channel");let M=X.rollout_version===z&&G>0,{error:N}=await lB("channel",{apikey:Q,method:"POST",body:{app_id:Y,channel:J,rolloutVersion:$,rolloutPercentageBps:G,rolloutEnabled:G>0,...U?{advanceRollout:!0}:{},...M?{rolloutPaused:!1}:{},...K!=null?{rolloutCacheTtlSeconds:K}:{},...W?{allow_device_self_set:!0}:{}},supaHost:H?.supaHost,supaAnon:H?.supaAnon});if(N)await Z$A(N,async()=>`Cannot set rollout in channel ${await FwA(N)}`);let V=`${Z.hostWeb}/app/${Y}/channel/${X.id}`;if(U)_A.info(`Promoted the previous rollout to stable on ${J} and set @${$} as the new rollout target (${UCQ(G)})`);else _A.info(`Set ${Y} channel ${J} rollout target to @${$} (${UCQ(G)})`);if(B)_A.info(`Bundle url: ${V}`);return!0}async function NBB(A,Q,B){let{error:$,data:J}=await Q.from("apps").select("default_upload_channel").eq("app_id",A).single();if($)throw Error(`Cannot find default upload channel: ${uA($)}. You can set it here: ${B}/app/${A}/info`);return J.default_upload_channel}async function mO(A,Q,B=!1,$){return eXA($,()=>CBB(A,Q,B))}async function CBB(A,Q,B){if(!B)NJ().intro(`Uploading with CLI version ${D6.version}`);let $,J=x4();await l4(NJ());let{s3Region:Y,s3Apikey:Z,s3Apisecret:X,s3BucketName:G,s3Endpoint:K,s3Port:W,s3SSL:H}=Q;if(Q.verbose)_A.info("[Verbose] Starting upload process with options:"),_A.info(` - API key: ${Q.apikey?"provided":"from saved key"}`),_A.info(` - Path: ${Q.path||"from capacitor config"}`),_A.info(` - Channel: ${Q.channel||"from default upload channel"}`),_A.info(` - Bundle: ${Q.bundle||"auto-detected"}`),_A.info(` - External: ${Q.external||"false"}`),_A.info(` - Encryption: ${Q.keyV2||Q.keyDataV2?"v2":Q.key===!1?"disabled":"auto"}`),_A.info(` - Upload method: ${Q.tus?"TUS":Q.zip?"ZIP":"auto"}`),_A.info(` - Delta updates: ${Q.delta||Q.partial?"enabled":"disabled"}`);let U=e0B(Q);if(Q.verbose)_A.info("[Verbose] API key retrieved successfully");let z=await eLQ(Q,{appId:A});if(Q.verbose)_A.info(uF(Q.mode)?`[Verbose] Cordova project config resolved (webDir: ${z.config.webDir})`:"[Verbose] Capacitor config loaded successfully");Q.userRequestedDelta=!!(Q.partial||Q.delta||Q.partialOnly||Q.deltaOnly);let D=jLQ(z?.config?.plugins?.CapacitorUpdater),I=a9({silent:B});if(D&&Q.delta===void 0){if(I){_A.info("\uD83D\uDCA1 Instant updates are enabled in your config"),_A.info(" Delta updates send only changed files instead of the full bundle");let B0=await s1({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!EB(B0)&&B0){if(Q.delta=!0,Q.verbose)_A.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!B){if(Q.delta!==!1){if(Q.delta=!0,Q.verbose)_A.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let M=await etA();if(Q.verbose)_A.info("[Verbose] Remote file config retrieved:"),_A.info(` - Max upload length: ${Math.floor(M.maxUploadLength/1024/1024)} MB`),_A.info(` - Alert upload size: ${Math.floor(M.alertUploadSize/1024/1024)} MB`),_A.info(` - TUS upload: ${M.TUSUpload?"enabled":"disabled"}`),_A.info(` - TUS upload forced: ${M.TUSUploadForced?"yes":"no"}`),_A.info(` - Partial upload: ${M.partialUpload?"enabled":"disabled"}`),_A.info(` - Max chunk size: ${Math.floor(M.maxChunkSize/1024/1024)} MB`);let{appid:N,path:V}=await ABB(A,Q,z.config,I);if(Q.verbose)_A.info(`[Verbose] App ID: ${N}, Build path: ${V}`);if(_R(Q.autoBump)&&Q.bundle)VB("Cannot use --bundle (-b) and --auto-bump together. Omit --bundle to auto-increment from the latest remote version.");let L=await t0B(z.config,Q);if(Q.verbose)_A.info(`[Verbose] Bundle version: ${L}`);let C=Q.external?"external":"r2-direct",R="none";if(await QBB(Q,V,I),Q.verbose)_A.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");let E=await LJ();if(Q.verbose)_A.info(`[Verbose] Local config loaded: host=${E.hostWeb}`);if(Q.supaHost&&Q.supaAnon){if(_A.info("Using custom supabase instance from provided options"),E.supaHost=Q.supaHost,E.supaKey=Q.supaAnon,Q.verbose)_A.info(`[Verbose] Custom Supabase host: ${Q.supaHost}`)}let w=await IB(U,Q.supaHost,Q.supaAnon);if(Q.verbose)_A.info("[Verbose] Supabase client created successfully");if(await Y$(w,N,B),await x6(w,U,N,"app.upload_bundle",B,!0),Q.verbose)_A.info("[Verbose] App exists and API key has app.upload_bundle permission");let S=await $8(w,U);if(Q.verbose)_A.info(`[Verbose] User verified successfully, user_id: ${S}`);let h=YwA(Q.channel);if(Q.channel!==void 0&&h.length===0)VB("Missing channel name, pass one channel or a comma-separated list with --channel");let k=h.length>0?null:await NBB(N,w,E.hostWeb),v=h.length>0?h:YwA(k||"production");if(v.length===0)VB("Cannot resolve target channel");let g=Ik(v),a=v,t=UBB(Q);if(Q.verbose)_A.info(`[Verbose] Target channel${v.length>1?"s":""}: ${g}`);let n=await G9(U,N,{supaHost:Q.supaHost,supaAnon:Q.supaAnon});if(Q.verbose)_A.info(`[Verbose] Organization ID: ${n}`);if(await QeA(w,n,D6.version),Q.verbose)_A.info("[Verbose] Remote CLI messages checked");if(await BeA(w,n,N,!0),Q.verbose)_A.info("[Verbose] Plan validation passed");if(Q.verbose)_A.info("[Verbose] Trial check completed");let l=_R(Q.autoBump);if(l){let B0;if(l==="ai"){let u0=await TLQ({supabase:w,appid:N,channels:v,path:V,apikey:U,options:{supaHost:Q.supaHost,supaAnon:Q.supaAnon}});_A.info(`\uD83E\uDD16 AI auto-bump chose ${u0.level}: ${u0.reason}`),B0=u0.level}else B0=l;if(Q.verbose)_A.info(`[Verbose] Resolving auto-bump (${B0}) version from channel/app remote versions...`);if(L=await DBB(w,N,v,L,B0),Q.verbose)_A.info(`[Verbose] Bundle version after auto-bump: ${L}`)}if(Q.autoSetBundle){if(uF(Q.mode))_A.warn("--auto-set-bundle is not supported in Cordova mode (no capacitor.config to update)");else if(await NI({version:L}),Q.verbose)_A.info(`[Verbose] Auto-set bundle version in ${z.path}`)}if(_A.info(`Upload ${N}@${L} started from path "${V}" to Capgo cloud`),Q.verbose)_A.info(`[Verbose] Checking if version ${L} already exists...`);let c=await $BB(w,N,L,Q.versionExistsOk,I);if(Q.verbose)_A.info(`[Verbose] Version exists check: ${c?typeof c==="string"?`retry with ${c}`:"yes (skipping)":"no (continuing)"}`);if(c===!0)return{success:!0,appId:N,skipped:!0,reason:"VERSION_EXISTS",bundle:L,checksum:null,encryptionMethod:R,storageProvider:C};if(typeof c==="string")return _A.info(`Retrying upload with new version: ${c}`),mO(A,{...Q,bundle:c,autoBump:void 0},B);if(Q.external&&!Q.external.startsWith("https://"))VB(`External link should should start with "https://" current is "${Q.external}"`);let x=null,d="",b;if(!Q.external){if(Q.verbose)_A.info(`[Verbose] Preparing bundle file from path: ${V}`);let B0=z.config?.plugins?.CapacitorUpdater?.publicKey;if(b=await HBB(V,Q,U,n,N,M.maxUploadLength,M.alertUploadSize,B0),$=b.sessionKey,x=b.zipped,R=b.encryptionMethod,d=b.finalKeyData,Q.verbose)_A.info("[Verbose] Bundle prepared:"),_A.info(` - Size: ${Math.floor((b.zipped?.byteLength??0)/1024)} KB`),_A.info(` - Checksum: ${b.checksum}`),_A.info(` - Encryption: ${b.encryptionMethod}`),_A.info(` - IV Session Key: ${b.ivSessionKey?"present":"none"}`),_A.info(` - Key ID: ${b.keyId||"none"}`);if(!Q.ignoreChecksumCheck&&t==null&&!Q.rolloutAdvance){if(Q.verbose)_A.info("[Verbose] Checking for duplicate checksum...");if(a=await YBB(w,N,v,b.checksum),Q.verbose)_A.info("[Verbose] Checksum is unique or already satisfied across target channels")}}let m=Ik(a);if(Q.verbose)_A.info(`[Verbose] Checking compatibility with channel${a.length>1?"s":""} ${m}...`);let QA=[];for(let B0 of a){let u0=await BBB(w,J,Q,B0,N,L,n);QA.push({channel:B0,...u0})}let y=QA.find((B0)=>B0.nativePackages)?.nativePackages,s=JBB(QA),BA=QA.filter((B0)=>B0.compatibility.result==="incompatible"),zA=BA.length>0,YA=BA.reduce((B0,u0)=>Math.max(B0,u0.incompatibleCount),0),CA=Ik(BA.map((B0)=>B0.channel)),HA=()=>{let B0=CA||m;R0({channel:"bundle",event:"Bundle Upload Blocked",apikey:Q.apikey,appId:N,orgId:n,tags:{reason:"incompatible",channel:B0,channel_name:B0,channel_names:B0,channel_count:BA.length||a.length,incompatible_count:YA,interactive:I}});let sB=`Upload aborted: bundle is incompatible with ${BA.length===1?"channel":"channels"} "${B0}" (${YA} native package(s) changed). A native build / app-store update is required. Run a native build with Capgo Builder (https://capgo.app/docs/cli/cloud-build/), or remove --fail-on-incompatible to upload anyway.`;throw _A.error(sB),new WwA(sB)};if(zA&&!B&&!Q.acceptIncompatible){if(Q.failOnIncompatible&&!I)HA();let B0=await p4(N)!==null,u0=await bLQ({incompatible:zA,interactive:I,hasCredentials:B0,appId:N,orgId:n,apikey:U,incompatibleCount:YA});if(u0==="abort")KwA();if(u0!=="continue")return{success:!0,appId:N,skipped:!0,reason:"NATIVE_BUILD",builderAction:u0,bundle:L,checksum:null,encryptionMethod:R,storageProvider:C};if(SLQ({incompatible:zA,failOnIncompatible:!!Q.failOnIncompatible,interactive:I,builderAction:u0}))HA()}else if(zA&&Q.acceptIncompatible&&!B)_A.warn("Proceeding because --accept-incompatible was set. The incompatible-bundle crash warning will not be emailed.");if(Q.verbose)_A.info("[Verbose] Compatibility check completed:"),_A.info(` - Native packages: ${y?y.length:0}`),_A.info(` - Min update version: ${s||"none"}`);if(Q.deleteLinkedBundleOnUpload)_A.warn(`Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the target channel${a.length>1?"s":""}: ${m}.`),_A.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let MA=a.length>0,PA=MA?await MBB(w,U,N,a,!!Q.selfAssign,t,!!Q.rolloutAdvance):new Map,JA={name:L,app_id:N,session_key:Q.external?Q.ivSessionKey:b?.ivSessionKey,external_url:Q.external,storage_provider:C,min_update_version:s,native_packages:y,owner_org:n,user_id:S,checksum:Q.external?Q.encryptedChecksum:b?.checksum,link:Q.link||null,comment:Q.comment||null,key_id:b?.keyId||void 0,cli_version:D6.version};if(Q.external){if(Q.verbose)_A.info(`[Verbose] Using external URL: ${Q.external}`);if(await _B(U,{channel:"app",event:"App external",org_id:n,tracking_version:2,tags:{"app-id":N}},Q.verbose),Q.verbose)_A.info("[Verbose] External bundle configured:"),_A.info(` - URL: ${Q.external}`),_A.info(` - IV Session Key: ${Q.ivSessionKey?"provided":"none"}`),_A.info(` - Encrypted Checksum: ${Q.encryptedChecksum?"provided":"none"}`)}if(Q.zip){if(Q.tus=!1,Q.verbose)_A.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!M.TUSUpload||Q.external){if(Q.tus=!1,Q.verbose)_A.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if(Q.tus=Q.tus||M.TUSUploadForced,Q.verbose)_A.info(`[Verbose] Upload method: ${Q.tus?"TUS (resumable)":"Standard"}`);if(!M.partialUpload||Q.external){if(Q.delta=!1,Q.verbose&&Q.external)_A.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if(Q.delta=Q.delta||Q.partial||Q.deltaOnly||Q.partialOnly||M.partialUploadForced,Q.verbose)_A.info(`[Verbose] Delta updates: ${Q.delta?"enabled":"disabled"}`);if(Q.encryptPartial&&R==="v1")VB("You cannot encrypt the partial update if you are not using the v2 encryption method");let wA="5.30.0",RA="6.30.0",LA="7.30.0",hQ=!1;if(Q.delta&&R==="v2"&&!Q.encryptPartial){let B0=L1(XwA()),u0=await DZ("@capgo/capacitor-updater",B0,Q.packageJson),sB;try{sB=u0?Z1(u0):void 0}catch{sB=void 0}if(u0&&sB&&NZA(sB,Z1("6.14.4"))){if(_A.info(`Auto-enabling partial update encryption for updater version ${sB} (> 6.14.4)`),Q.verbose)_A.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4");Q.encryptPartial=!0}}if(Q.delta&&(Q.encryptPartial||R==="v2")){let B0=L1(XwA()),u0=await DZ("@capgo/capacitor-updater",B0,Q.packageJson),sB;try{sB=u0?Z1(u0):void 0}catch{sB=void 0}if(u0&&sB){if(hQ=!yK(sB,wA,RA,LA),Q.verbose&&hQ)_A.info(`[Verbose] Using hex checksum format for updater version ${sB}`)}}if(Q.verbose&&Q.delta)_A.info("[Verbose] Preparing delta/partial update manifest...");let RQ=Q.delta?await WCQ(V,U,n,N,Q.encryptPartial?R:"none",d,hQ):[];if(Q.verbose&&Q.delta)_A.info(`[Verbose] Delta manifest prepared with ${RQ.length} files`);if(Q.delta&&RQ.length>vf)VB(Lt(RQ.length));if(Q.verbose)_A.info("[Verbose] Creating version record in database...");if(await ZwA(w,JA,"add"),Q.verbose)_A.info("[Verbose] Version record created successfully");if(Q.dryUpload){if(Q.verbose)_A.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!B)NJ().outro("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,appId:N,bundle:L,checksum:JA.checksum??null,encryptionMethod:R,sessionKey:$?$.toString("base64"):void 0,ivSessionKey:typeof JA.session_key==="string"?JA.session_key:void 0,storageProvider:JA.storage_provider,reason:"DRY_UPLOAD"}}if(Q.tusChunkSize&&Q.tusChunkSize>M.maxChunkSize)_A.error(`Chunk size ${Q.tusChunkSize} is greater than the maximum chunk size ${M.maxChunkSize}, using the maximum chunk size`),Q.tusChunkSize=M.maxChunkSize;else if(!Q.tusChunkSize)Q.tusChunkSize=M.maxChunkSize;if(Q.verbose)_A.info(`[Verbose] TUS chunk size: ${Math.floor(Q.tusChunkSize/1024/1024)} MB`);if(x&&ZBB(Q)){if(!G||!K||!Y||!Z||!X||!W)VB("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(_A.info("Uploading to S3"),Q.verbose)_A.info("[Verbose] S3 configuration:"),_A.info(` - Endpoint: ${K}`),_A.info(` - Region: ${Y}`),_A.info(` - Bucket: ${G}`),_A.info(` - Port: ${W}`),_A.info(` - SSL: ${H?"enabled":"disabled"}`);let B0=`${H?"https":"http"}://${K}${W?`:${W}`:""}`,u0=new m6A({endPoint:K,region:Y,port:W,pathStyle:!0,bucket:G,accessKey:Z,secretKey:X}),sB=`${N}-${L}`,WB=encodeURIComponent(sB);if(Q.verbose)_A.info(`[Verbose] Uploading to S3 as: ${sB}`);try{await u0.putObject(sB,Uint8Array.from(x)),JA.external_url=`${B0}/${WB}`,JA.storage_provider="external",await ZwA(w,JA,"update")}catch(J1){try{await jt(U,N,L,Q)}catch(C1){VB(`Cannot upload bundle to S3 ${uA(J1)}. Cleanup of the incomplete version also failed (${uA(C1)}); delete bundle ${L} manually before retrying.`)}VB(`Cannot upload bundle to S3 ${uA(J1)}`)}if(Q.verbose)_A.info(`[Verbose] S3 upload complete, external URL: ${JA.external_url}`)}else if(x){if(DCQ(Q)){if(Q.verbose)_A.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await FBB(U,w,N,L,n,x,Q,Q.tusChunkSize)}else if(Q.verbose)_A.info("[Verbose] Skipping full bundle upload (delta-only mode)");let B0=null;try{if(Q.dryUpload){if(Q.delta=!1,Q.verbose)_A.info("[Verbose] Dry upload mode: skipping delta upload")}let u0=JA.session_key&&Q.encryptPartial&&$?{sessionKey:$,ivSessionKey:JA.session_key}:void 0;if(Q.verbose&&Q.delta)_A.info("[Verbose] Starting delta/partial file upload..."),_A.info(` - Manifest entries: ${RQ.length}`),_A.info(` - Encryption: ${u0?"enabled":"disabled"}`);if(B0=Q.delta?await HCQ(U,RQ,V,N,n,u0,Q):null,Q.verbose&&B0)_A.info(`[Verbose] Delta upload complete with ${B0.length} files`)}catch(u0){if(Q.userRequestedDelta)throw u0;if(_A.info(`Failed to upload partial files to capgo cloud. Error: ${uA(u0)}. This is not a critical error, the bundle has been uploaded without the partial files`),Q.verbose)_A.info(`[Verbose] Delta upload error details: ${uA(u0)}`)}if(B0?.length){if(Q.verbose)_A.info(`[Verbose] Writing ${B0.length} manifest rows via set_manifest...`);try{await KeA(U,N,L,B0,Q)}catch(u0){try{await jt(U,N,L,Q)}catch(sB){VB(`Cannot set bundle manifest ${uA(u0)}. Cleanup of the incomplete version also failed (${uA(sB)}); delete bundle ${L} manually before retrying.`)}VB(`Cannot set bundle manifest ${uA(u0)}`)}if(Q.verbose)_A.info("[Verbose] Manifest rows written (sizes filled by backend from R2)")}if(JA.storage_provider="r2",JA.manifest=null,Q.verbose)_A.info("[Verbose] Updating version record with storage provider...");if(await tLQ({apikey:U,appId:N,bundle:L,supaHost:Q.supaHost,supaAnon:Q.supaAnon,reporter:NJ()},async()=>{await ZwA(w,JA,"update")}),Q.verbose)_A.info("[Verbose] Version record updated successfully")}let $0=await VJ(w,U,"bundle.delete",{appId:N});if(Q.verbose)_A.info("[Verbose] Permissions:"),_A.info(" - app.upload_bundle: yes"),_A.info(` - bundle.delete: ${$0?"yes":"no"}`),_A.info(" - channel permissions: checked per target channel");let vQ=Q.deleteLinkedBundleOnUpload&&$0,E0=vQ?await Promise.all(a.map(async(B0)=>({channel:B0,version:await OCQ(w,N,B0)}))):[];if(Q.deleteLinkedBundleOnUpload&&!vQ)_A.warn("Cannot delete linked bundle on upload because this API key lacks bundle.delete");let v0=new Set(a).size,BB=new Set;for(let B0 of a){if(Q.verbose)_A.info(`[Verbose] Setting bundle ${L} to channel ${B0}...`);let u0=PA.has(B0)?PA.get(B0)??null:await HwA(w,N,B0),sB=Q.rolloutAdvance||t!=null,WB=u0?.rollout_percentage_bps,J1=t??WB??0;if(Q.rolloutAdvance&&t==null&&!((WB??0)>0))VB(`Cannot advance rollout, channel ${B0} has no rollout percentage to reuse. Pass --rollout or --rollout-percentage-bps`);let C1=sB?await LBB(w,U,!!Q.bundleUrl,L,B0,N,E,u0,J1,Q.rolloutCacheTtlSeconds,Q.selfAssign,Q,!!Q.rolloutAdvance):await OBB(w,U,!!Q.bundleUrl,L,B0,S,n,N,E,u0,MA,Q.selfAssign,Q);if(C1)BB.add(B0);if(Q.verbose)_A.info(`[Verbose] Channel ${B0} ${C1?"updated successfully":"was not updated"}`)}if(vQ){let B0=new Set;for(let u0 of E0){if(!BB.has(u0.channel))continue;if(!u0.version||B0.has(u0.version.id))continue;if(Q.verbose)_A.info(`[Verbose] Deleting previously linked bundle in channel ${u0.channel}...`);await IBB(w,u0.version),B0.add(u0.version.id)}}if(BB.size===0)_A.warn("Cannot set channel because this API key lacks the required RBAC permission");if(MA&&BB.size!==v0)VB("Cannot complete upload because one or more target channels were not updated");if(Q.verbose)_A.info("[Verbose] Sending upload event...");await _B(U,{channel:"app",event:"App Uploaded",org_id:n,tracking_version:2,tags:{"app-id":N,bundle:L}},Q.verbose),await _B(U,{channel:"app",event:"Bundle Uploaded",org_id:n,tracking_version:2,tags:{"app-id":N,bundle:L},notifyConsole:!0}).catch(()=>{});for(let B0 of QA){if(B0.compatibility.result!=="incompatible")continue;R0({channel:"bundle",event:"Bundle Incompatible",apikey:U,appId:N,orgId:n,tags:{source:"upload",channel:B0.channel,channel_name:B0.channel,channel_overwritten:BB.has(B0.channel),version_new_name:L,...B0.compatibility.versionOldId?{version_old_id:B0.compatibility.versionOldId}:{},...B0.compatibility.versionOldName?{version_old_name:B0.compatibility.versionOldName}:{},...Q.acceptIncompatible?{incompatibility_accepted:!0}:{}}})}let vB={success:!0,appId:N,bundle:L,updatedChannels:Array.from(BB),checksum:JA.checksum??null,encryptionMethod:R,sessionKey:$?$.toString("base64"):void 0,ivSessionKey:typeof JA.session_key==="string"?JA.session_key:void 0,storageProvider:JA.storage_provider};if(Q.verbose)_A.info("[Verbose] Upload completed successfully:"),_A.info(` - Bundle: ${vB.bundle}`),_A.info(` - Checksum: ${vB.checksum}`),_A.info(` - Encryption: ${vB.encryptionMethod}`),_A.info(` - Storage: ${vB.storageProvider}`);if(I&&!vB.skipped){let B0=Q.showReplicationProgress;if(B0===void 0)B0=await SjA({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(B0)await n6A({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:I})}if(!B&&!vB.skipped)NJ().outro("Time to share your update to the world \uD83C\uDF0D");return vB}function VBB(A){let Q=A.key===!1,B=A.rollout!=null||A.rolloutPercentageBps!=null||A.rolloutAdvance===!0,$=A.forceCrc32Checksum===!0,J=A.keyV2||A.keyDataV2||pl(R5);if(A.ivSessionKey&&!A.external)VB("You need to provide an external url if you want to use the --iv-session-key option");if(A.encryptedChecksum&&!A.external)VB("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)VB("You cannot use the --partial/--delta/--partial-only/--delta-only option with an external url");if(A.tus&&A.external)VB("You cannot use the --tus option with an external url");if(A.dryUpload&&A.external)VB("You cannot use the --dry-upload option with an external url");if(A.multipart&&A.external)VB("You cannot use the --multipart option with an external url");if(A.external&&(A.keyV2||A.keyDataV2))VB("You cannot set a key if you are uploading to an external url");if(A.keyV2&&A.keyDataV2)VB("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))VB("You cannot set S3 options if you are uploading to an external url, it's automatically handled");if(A.encryptedChecksum&&!A.external)VB("You cannot set the --encrypted-checksum option if you are not uploading to an external url");if(A.minUpdateVersion&&A.autoMinUpdateVersion)VB("You cannot set both min-update-version and auto-min-update-version, use only one of them");if(A.rollout!=null&&(!Number.isFinite(A.rollout)||A.rollout<0||A.rollout>100))VB("Rollout percentage must be between 0 and 100");if(A.rolloutPercentageBps!=null&&(!Number.isInteger(A.rolloutPercentageBps)||A.rolloutPercentageBps<0||A.rolloutPercentageBps>1e4))VB("Rollout percentage basis points must be between 0 and 10000");if(A.rolloutCacheTtlSeconds!=null&&(!Number.isInteger(A.rolloutCacheTtlSeconds)||A.rolloutCacheTtlSeconds<60||A.rolloutCacheTtlSeconds>31536000))VB("Rollout cache TTL seconds must be between 60 and 31536000");if(B&&A.dryUpload)VB("You cannot use --rollout or --rollout-advance with --dry-upload because dry upload does not update channels");if(B&&A.deleteLinkedBundleOnUpload)VB("You cannot use --rollout or --rollout-advance with --delete-linked-bundle-on-upload because rollout needs the stable channel bundle as fallback");if($&&J&&!Q)VB("You cannot use --force-crc32-checksum when encryption is enabled. Remove the flag or disable encryption.");if(A.failOnIncompatible&&A.ignoreMetadataCheck)VB("You cannot use --fail-on-incompatible together with --ignore-metadata-check — the metadata check is exactly what --fail-on-incompatible enforces. Remove one of them.");if(A.acceptIncompatible&&A.failOnIncompatible)VB("You cannot use --accept-incompatible together with --fail-on-incompatible — one continues despite a mismatch, the other refuses it. Remove one of them.");if(A.acceptIncompatible&&A.ignoreMetadataCheck)VB("You cannot use --accept-incompatible together with --ignore-metadata-check — accepting a mismatch requires running the compatibility check. Remove one of them.")}async function RBB(){if(!a9())return;let A=Xk();if(Zk(A.repository)||!A.ghInstalled||!A.ghLoggedIn||!A.repositoryExists||A.starred)return;if(!await SjA({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=fz(A.repository);if(B.alreadyStarred)_A.info(`\uD83E\uDEF6 ${B.repository} is already starred`);else _A.success(`\uD83D\uDE4F Thanks for starring ${B.repository} \uD83C\uDF89`)}catch(B){_A.warn(`Cannot star ${A.repository} right now: ${uA(B)}`)}}async function X$A(A,Q){return eXA(Oa,()=>EBB(A,Q))}async function EBB(A,Q){try{VBB(Q);let B=await mO(A,Q);if(!B.skipped)await RBB();return B}catch(B){let $=B instanceof Error?B.message:String(B),J=uA(B);if($===GwA)throw B instanceof Error?B:Error(String(B));if(Q.verbose)_A.error(`uploadBundle failed:${J}`);else _A.error(`uploadBundle failed: ${$}`);if(B instanceof WwA)throw B;let Y=$.includes("Cannot upload the same bundle content"),Z=a9();if(!Q.versionExistsOk&&Z)try{if(Y){let X=await _6({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(EB(X)||X==="cancel")throw B instanceof Error?B:Error(String(B));if(X==="ignore")return _A.info("\uD83D\uDD04 Retrying upload with --ignore-checksum-check..."),X$A(A,{...Q,ignoreChecksumCheck:!0})}else{let X=await s1({message:"Would you like to retry the upload?"});if(EB(X))throw B instanceof Error?B:Error(String(B));if(X)return _A.info("\uD83D\uDD04 Retrying upload..."),X$A(A,Q)}}catch{throw B instanceof Error?B:Error(String(B))}throw B instanceof Error?B:Error(String(B))}}function LCQ(A,Q){return{apikey:A.apikey,bundle:Q,supaAnon:A.supaAnon,supaHost:A.supaHost}}async function NCQ(A,Q){let B=await X$A(A,Q),$=B?.appId||A;if(Q.qrPreview&&B?.bundle&&B.reason!=="DRY_UPLOAD"&&!B.builderAction)await g6A($,void 0,LCQ(Q,B.bundle));if(Q.sendUpdateNotification&&B?.success&&!B.skipped&&B.updatedChannels?.length&&!B.builderAction)try{await v6A({appId:$,apikey:Q.apikey,channels:B.updatedChannels,verbose:Q.verbose})}catch{}if(!B?.builderAction)return;if(B.builderAction==="launch-onboarding")await oS({apikey:Q.apikey});else await m4A($,{apikey:Q.apikey,supaHost:Q.supaHost,supaAnon:Q.supaAnon})}GB();PK();v4();OJ();Nv();V0();import{randomUUID as yBB}from"node:crypto";import{existsSync as hBB,writeFileSync as uBB}from"node:fs";import{cwd as mBB}from"node:process";import{existsSync as CCQ,readFileSync as UwA}from"node:fs";import{createRequire as jBB}from"node:module";import{dirname as qwA,join as wBB}from"node:path";import PBB from"node:process";var tX="@capgo/capacitor-updater",cF="@capacitor/splash-screen";function _BB(A){if(!CCQ(A))return null;try{return JSON.parse(UwA(A,"utf-8"))}catch{return null}}function TBB(A,Q){let B=_BB(A);if(!B)return{version:null,section:null};let $=["dependencies","devDependencies","optionalDependencies"];for(let J of $){let Y=B[J];if(!Y||!Object.hasOwn(Y,Q))continue;let Z=Y[Q];return{version:typeof Z==="string"?Z:String(Z),section:J}}return{version:null,section:null}}function SBB(A,Q){let $=qwA(A);while(!0){let J=wBB($,"node_modules",Q,"package.json");if(CCQ(J))try{let Z=JSON.parse(UwA(J,"utf-8"));if(typeof Z.version==="string")return Z.version}catch{return null}let Y=qwA($);if(Y===$)break;$=Y}if(!PBB.versions.pnp)return null;try{let Y=jBB(A).resolve(`${Q}/package.json`),Z=JSON.parse(UwA(Y,"utf-8"));if(typeof Z.version==="string")return Z.version}catch{return null}return null}function VCQ(A,Q){let B=qwA(A),$=TBB(A,Q),J=SBB(A,Q),Y=[];if(!$.version)Y.push(`Missing ${Q} in ${A}`);if(!J)Y.push(`Cannot resolve ${Q} from ${B}/node_modules`);return{packageJsonPath:A,projectDir:B,declaredVersion:$.version,declaredIn:$.section,installedVersion:J,ready:Y.length===0,details:Y}}function XK(A){return VCQ(A,tX)}function zwA(A){return VCQ(A,cF)}GB();import{spawnSync as kBB}from"node:child_process";import{existsSync as ECQ,statSync as bBB}from"node:fs";import{dirname as xBB,join as vBB,resolve as jCQ}from"node:path";import{cwd as RCQ}from"node:process";V0();function DwA(A){return`0.0.1-beta.local-${A}`}function IwA(A){let Q=L1(RCQ()),B=Hk(A);if(B?.length)for(let $ of B)for(let J of[RCQ(),Q]){let Y=jCQ(J,$);if(ECQ(Y))return Y}return vBB(Q,"package.json")}function fBB(A){return A?.trim()||"latest"}function gBB(A,Q,B){let $=`${tX}@${Q}`,J=A.installCommand.split(/\s+/).filter(Boolean),Y=J[0];if(!Y)return null;if(!B?.trim())switch(A.pm){case"yarn":return{command:"yarn",args:["add",$]};case"bun":return{command:"bun",args:["add",$]};case"pnpm":return{command:"pnpm",args:["add",$]};default:return{command:Y,args:[...J.slice(1),$]}}if(A.pm==="yarn"||A.pm==="bun")return{command:Y,args:J.slice(1)};return{command:Y,args:[...J.slice(1),"--force",$]}}async function wCQ(A,Q){f.warn(`Bundle version "${A}" is not valid semver (https://semver.org/).`);let B=await s1({message:`Use local fallback version ${Q} instead?`,initialValue:!0});if(EB(B)||!B)return null;return f.info(`Using bundle version ${Q}`),Q}async function PCQ(A){let Q=await LG({message:A,validate:(B)=>{let $=B?.trim();if(!$)return"Value is required";let J=jCQ($);if(!ECQ(J))return`Path does not exist: ${J}`;if(!bBB(J).isDirectory())return`Path is not a directory: ${J}`}});if(EB(Q))return null;return Q.trim()}async function _CQ(A){let Q=IwA(A),B=XK(Q);if(B.ready)return!0;f.warn(`Cannot find ${tX} in node_modules.`);let $=await s1({message:`Install ${tX} now?`,initialValue:!0});if(EB($)||!$)return!1;let J=x4(),Y=fBB(B.declaredVersion),Z=gBB(J,Y,B.declaredVersion);if(!Z)return!1;if(kBB(Z.command,Z.args,{cwd:xBB(Q),stdio:"inherit",shell:!1}).status!==0)return!1;return XK(Q).ready}t1();var cBB=20;function dBB(A){console.log(JSON.stringify(A,null,2))}function Mk(A){console.error(uA(A))}function lBB(A){if(A.context?.message)Mk({error:A.message,message:A.context.message});else Mk({error:A.message})}async function MwA(A,Q,B=!1){let{json:$}=Q,{bundle:J,path:Y}=Q,Z=!$&&!B;try{if(Z)await l4();let X=await h0(),G=a9({silent:$||B}),K=await a6A({explicitAppId:A,config:X?.config,packageJsonPaths:Hk(Q.packageJson),interactive:G,json:$}),W=yBB().split("-")[0],H=RX("",Q.packageJson);if(J=J||H||DwA(W),Z)r0(`Zipping ${K??"app"}@${J}`);if(J&&!rN.test(J)){if(G){let h=await wCQ(J,DwA(W));if(h)J=h}if(!rN.test(J)){let h=`Your bundle name ${J}, is not valid it should follow semver convention : https://semver.org/`;if(!B)if($)Mk({error:"invalid_semver"});else f.error(h);throw Error("Invalid bundle version format")}}if(Y=Y||X?.config?.webDir,!Y&&G){let h=await PCQ("Enter the path to your built web assets (webDir):");if(h)Y=h}if(!K||!J||!Y){if(!B)if($)Mk({error:"missing_argument"});else f.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)f.info(`Started from path "${Y}"`);if(Q.codeCheck!==!1&&!Q.ignoreNotifyAppReady){if(!mW(Y,"notifyAppReady"))if(G){if(await A$A({webDir:Y,interactive:G,json:$})!=="skipped"&&!mW(Y,"notifyAppReady"))throw new FQ("notifyAppReady() is missing in build folder")}else throw $?new FQ("notifyAppReady_not_in_source_code",{message:e6A(Y)}):new FQ(e6A(Y));if(!Kk(Y)){if(!B)if($)Mk({error:"index_html_not_found"});else f.error(`index.html is missing in the root folder of ${Y}`);throw Error("index.html is missing in root folder")}}let z=await Et(Y);if(Z)f.info(`Zipped ${z.byteLength} bytes`);let D=Z?n8():null;if(D)D.start("Calculating checksum");let I=L1(mBB()),M=IwA(Q.packageJson),N=XK(M);if(!N.ready&&G&&await _CQ(Q.packageJson))N=XK(M);if(!N.ready){if(!B)f.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 V=await DZ("@capgo/capacitor-updater",I,Q.packageJson),L=!1,C;try{C=V?Z1(V):void 0}catch{C=void 0}if(C)L=!yK(C,void 0,void 0,"7.0.0");else if(V==="link:@capgo/capacitor-updater"){if(!B)f.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let R=await $I(z,Q.keyV2||hBB(R5)||L?"sha256":"crc32");if(D)D.stop(`Checksum ${L?"SHA256":"CRC32"}: ${R}`);let E=Math.floor(z.byteLength/1024/1024);if(E>cBB&&Z)f.warn(`WARNING !!
1438
+ Bundle uploaded \uD83D\uDCAA in 0 seconds`),Z.verbose)_A.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let z=await LJ();if(Z.verbose)_A.info("[Verbose] Local config retrieved for upload");if(Z.multipart!==void 0&&Z.multipart||Z.tus!==void 0&&Z.tus){if(Z.multipart)_A.info("Uploading bundle with multipart is deprecated, we upload with TUS instead");else _A.info("Uploading bundle with TUS protocol");if(Z.verbose)_A.info("[Verbose] Starting TUS resumable upload..."),_A.info(` - Host: ${z.hostWeb}`),_A.info(` - Chunk size: ${Math.floor(X/1024/1024)} MB`);if(await GeA(A,Y,J,B,$,G,z,X),W=!0,Z.verbose)_A.info("[Verbose] TUS upload completed, updating database with R2 path...");let D=`orgs/${J}/apps/${B}/${$}.zip`,{error:I}=await Q.from("app_versions").update({r2_path:D}).eq("name",$).eq("app_id",B);if(I){if(_A.error(`Cannot finish TUS upload ${uA(I)}`),Z.verbose)_A.info(`[Verbose] Database update failed: ${uA(I)}`);throw Error("Cannot finish TUS upload")}if(Z.verbose)_A.info(`[Verbose] Database updated with R2 path: ${D}`)}else{if(Z.verbose)_A.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let D=await ZeA(A,B,$,Z);if(!D){if(_A.error("Cannot get upload url"),Z.verbose)_A.info("[Verbose] Failed to retrieve presigned upload URL from database");throw Error("Cannot get upload url")}let I=Z.timeout||rtA;if(Z.verbose)_A.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),_A.info(` - Timeout: ${I}ms`),_A.info(" - Retry attempts: 0 (standard upload does not retry, use --tus for resumable retries)"),_A.info(" - Content-Type: application/zip");let M=new AbortController,N=setTimeout(()=>M.abort(),I);try{let V=await fetch(D,{method:"PUT",body:Y,headers:{"Content-Type":"application/zip"},signal:M.signal});if(!V.ok)throw Error(`HTTP error! status: ${V.status}`)}catch(V){if(M.signal.aborted||V?.name==="AbortError"){let L=Error(atA(I));throw L.name=wqA,L}throw V}finally{clearTimeout(N)}if(Z.verbose)_A.info("[Verbose] HTTP PUT upload completed successfully")}}catch(z){let I=((performance.now()-K)/1000).toFixed(2);if(G.error(`Failed to upload bundle ( after ${I} seconds)`),Z.verbose)_A.info(`[Verbose] Upload failed after ${I} seconds`),_A.info(`[Verbose] Error type: ${z instanceof Error?"Error":typeof z}`);if(z instanceof Error&&z.name===wqA)_A.error(z.message);else if(z instanceof Error&&z.message.includes("HTTP error"))try{let M=z.message.match(/status: (\d+)/),N=M?M[1]:"unknown";_A.error(`Upload failed with status ${N}: ${z.message}`)}catch{_A.error(`Upload failed: ${z.message}`)}else{if(Z.verbose)_A.info(`[Verbose] Non-HTTP error: ${uA(z)}`);if(!Z.tus)_A.error(`Cannot upload bundle ( try again with --tus option) ${uA(z)}`);else _A.error(`Cannot upload bundle please contact support if the issue persists ${uA(z)}`)}if(Z.verbose)_A.info("[Verbose] Cleaning up failed version from database...");try{if(await jt(A,B,$,Z),Z.verbose)_A.info("[Verbose] Failed version cleaned up")}catch(M){_A.error(`Cleanup of the incomplete version failed (${uA(M)}); delete bundle ${$} manually before retrying.`)}throw z instanceof Error?z:Error(String(z))}let U=((performance.now()-K)/1000).toFixed(2);if(G.stop(`Bundle uploaded \uD83D\uDCAA in (${U} seconds)`),Z.verbose)_A.info("[Verbose] Upload successful:"),_A.info(` - Upload time: ${U} seconds`),_A.info(` - Upload method: ${W?"TUS (resumable)":"Standard HTTP PUT"}`),_A.info(` - Bundle size: ${Math.floor(Y.byteLength/1024)} KB`),_A.info("[Verbose] Sending performance event...");if(await _B(A,{channel:"performance",event:W?"TUS upload zip performance":"Upload zip performance",org_id:J,tracking_version:2,tags:{"app-id":B,time:U}},Z.verbose),Z.verbose)_A.info("[Verbose] Performance event sent successfully")}function UBB(A){if(A.rollout==null&&A.rolloutPercentageBps==null)return;if(A.rolloutPercentageBps!=null)return A.rolloutPercentageBps;return Math.round((A.rollout??0)*100)}function UCQ(A){return`${Number((A/100).toFixed(2))}%`}async function MCQ(A,Q,B,$){let{data:J}=await A.rpc("get_app_versions",{apikey:Q,name_version:$,appid:B}).single();if(!J)VB("Cannot get version id, cannot set channel");return J}async function qBB(A,Q,B){let{data:$,error:J}=await A.rpc("exist_app_versions",{appid:Q,name_version:B}).single();if(J)VB(`Cannot check if version ${B} already exists ${uA(J)}`);return!!$}async function zBB(A,Q){let{data:B,error:$}=await A.from("app_versions").select("name").eq("app_id",Q).order("created_at",{ascending:!1}).limit(1).maybeSingle();if($)return _A.warn(`Cannot fetch latest remote version ${uA($)}`),null;return B?.name??null}async function qCQ(A,Q,B,$,J){let Y=B;for(let Z=0;Z<100;Z++){if(!await qBB(A,Q,Y)){if(Y!==J)_A.info(`\uD83D\uDD22 Auto-bumped (${$}) version from ${J} to ${Y}`);return Y}Y=r6A(Y,$)}VB(`Could not find a free ${$}-bumped version after 100 attempts (started from ${J})`)}async function DBB(A,Q,B,$,J){let Y=B[0],X=(await OCQ(A,Q,Y))?.name??null;if(X)_A.info(`\uD83D\uDCE6 Auto-bump base from channel ${Y}: ${X}`);else if(X=await zBB(A,Q),X)_A.info(`\uD83D\uDCE6 Auto-bump base from latest remote app version: ${X}`);if(!X)return _A.info(`ℹ️ No remote versions found for auto-bump, keeping local version ${$}`),qCQ(A,Q,$,J,$);let G=r6A(X,J);return qCQ(A,Q,G,J,X)}async function OCQ(A,Q,B){let{data:$,error:J}=await A.from("channels").select("version:app_versions!channels_version_fkey( id, name, deleted )").eq("app_id",Q).eq("name",B);if(J)return _A.error(`Cannot delete linked bundle on upload ${uA(J)}`),null;if($.length===0)return _A.warn("No linked bundle found in the channel you are trying to upload to"),null;let Y=$[0].version;if(!Y)return _A.warn("No linked bundle found in the channel you are trying to upload to"),null;if(Y.deleted)return _A.warn("The linked bundle is already deleted"),null;return Y}async function IBB(A,Q){if(!Q)return;let{error:B}=await A.from("app_versions").update({deleted:!0}).eq("id",Q.id);if(B){_A.error(`Cannot delete linked bundle on upload ${uA(B)}`);return}_A.info(`Linked bundle ${Q.name} deleted`)}async function HwA(A,Q,B,$=!0){let{data:J,error:Y}=await A.from("channels").select("id, public, version, rollout_version, rollout_enabled, rollout_percentage_bps").eq("app_id",Q).eq("name",B).maybeSingle();if(Y&&$)VB(`Cannot check channel ${B}: ${uA(Y)}`);return J}async function MBB(A,Q,B,$,J=!1,Y,Z=!1){let X=new Map,G=Y!=null||Z;for(let K of new Set($)){let W=await HwA(A,B,K);if(W){if(X.set(K,W),!await VJ(A,Q,"channel.promote_bundle",{appId:B,channelId:W.id}))VB("Cannot set channel because this API key lacks channel.promote_bundle for the target channel");if(J||G){if(!await VJ(A,Q,"channel.update_settings",{appId:B,channelId:W.id}))VB(J?"Cannot enable device self-assign because this API key lacks channel.update_settings":"Cannot set rollout because this API key lacks channel.update_settings for the target channel")}if(G&&!W.version)VB(`Cannot set rollout, channel ${K} needs a stable bundle before using progressive rollout`);if(Z&&W.rollout_version==null)VB(`Cannot advance rollout, channel ${K} has no rollout target to promote to stable`);if(Z&&Y==null&&!((W.rollout_percentage_bps??0)>0))VB(`Cannot advance rollout, channel ${K} has no rollout percentage to reuse. Pass --rollout or --rollout-percentage-bps`);continue}if(G)VB(`Cannot set rollout, channel ${K} must already exist with a stable bundle`);if(!await VJ(A,Q,"app.create_channel",{appId:B}))VB("Cannot create target channel because this API key lacks app.create_channel");X.set(K,null)}return X}async function FwA(A){let Q=A?.context;if(Q?.json)try{return JSON.stringify(await Q.json())}catch{}return uA(A)}async function zCQ(A,Q,B,$,J,Y,Z){let{error:X}=await lB("bundle",{apikey:A,method:"PUT",body:{app_id:Q,version_id:B,channel_id:$.id},supaHost:Z?.supaHost,supaAnon:Z?.supaAnon});if(X)await Z$A(X,async()=>`Cannot set channel because this API key does not have the required RBAC permission. ${await FwA(X)}`);let G=`${J.hostWeb}/app/${Q}/channel/${$.id}`;if($.rollout_enabled&&$.rollout_version!=null)_A.warn("This channel has an active progressive rollout. Linking this bundle as the stable version resets that rollout, so devices receive the new bundle instead of the previous rollout target.");else if($.public)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${G}`);if(Y)_A.info(`Bundle url: ${G}`);return!0}async function OBB(A,Q,B,$,J,Y,Z,X,G,K,W=!1,H,U){let z=K!==null&&await VJ(A,Q,"channel.promote_bundle",{appId:X,channelId:K.id}),D=K===null&&await VJ(A,Q,"app.create_channel",{appId:X});if(K&&!z){if(W)VB("Cannot set channel because this API key lacks channel.promote_bundle for the target channel");return _A.warn("Cannot set channel because this API key lacks channel.promote_bundle for the target channel"),!1}if(K&&z){let M=await MCQ(A,Q,X,$);if(H){if(!await VJ(A,Q,"channel.update_settings",{appId:X,channelId:K.id}))return _A.warn("Cannot enable device self-assign because this API key lacks channel.update_settings"),zCQ(Q,X,M,K,G,B,U)}if(!H)return zCQ(Q,X,M,K,G,B,U);let{error:N,data:V}=await WeA(A,{name:J,app_id:X,created_by:Y,version:M,owner_org:Z,...H?{allow_device_self_set:!0}:{}});if(N)await Z$A(N,()=>`Cannot set channel because this API key does not have the required RBAC permission. ${uA(N)}`);if(V?.id){let L=`${G.hostWeb}/app/${X}/channel/${V.id}`;if(K.rollout_enabled&&K.rollout_version!=null)_A.warn("This channel has an active progressive rollout. Linking this bundle as the stable version resets that rollout, so devices receive the new bundle instead of the previous rollout target.");else if(V.public)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${L}`);if(B)_A.info(`Bundle url: ${L}`)}return!0}if(D){let{error:M,data:N}=await lB("channel",{apikey:Q,method:"POST",body:{app_id:X,channel:J,version:$,...H?{allow_device_self_set:!0}:{}},supaHost:U?.supaHost,supaAnon:U?.supaAnon});if(M)await Z$A(M,async()=>`Cannot create channel and set its bundle because this API key does not have the required RBAC permission. ${await FwA(M)}`);let V=N,L=Number(V?.id),C=V?.public===!0;if(!Number.isSafeInteger(L)||typeof V?.public!=="boolean"){let E=await HwA(A,X,J,!1),w=Number(E?.id);if(!Number.isSafeInteger(w)){if(!Number.isSafeInteger(L))return _A.info("Your update is now available \uD83C\uDF89"),!0}else L=w,C=E?.public===!0}let R=`${G.hostWeb}/app/${X}/channel/${L}`;if(C)_A.info("Your update is now available in your public channel \uD83C\uDF89");else _A.info(`Link device to this bundle to try it: ${R}`);if(B)_A.info(`Bundle url: ${R}`);return!0}let I="Cannot create target channel because this API key lacks app.create_channel";if(W)VB(I);return _A.warn(I),!1}async function LBB(A,Q,B,$,J,Y,Z,X,G,K,W,H,U=!1){if(!X)VB(`Cannot set rollout, channel ${J} must already exist with a stable bundle`);if(!X.version)VB(`Cannot set rollout, channel ${J} needs a stable bundle before using progressive rollout`);if(U&&X.rollout_version==null)VB(`Cannot advance rollout, channel ${J} has no rollout target to promote to stable`);let z=await MCQ(A,Q,Y,$),[D,I]=await Promise.all([VJ(A,Q,"channel.promote_bundle",{appId:Y,channelId:X.id}),VJ(A,Q,"channel.update_settings",{appId:Y,channelId:X.id})]);if(!D)VB("Cannot set rollout because this API key lacks channel.promote_bundle for the target channel");if(!I)VB("Cannot set rollout because this API key lacks channel.update_settings for the target channel");let M=X.rollout_version===z&&G>0,{error:N}=await lB("channel",{apikey:Q,method:"POST",body:{app_id:Y,channel:J,rolloutVersion:$,rolloutPercentageBps:G,rolloutEnabled:G>0,...U?{advanceRollout:!0}:{},...M?{rolloutPaused:!1}:{},...K!=null?{rolloutCacheTtlSeconds:K}:{},...W?{allow_device_self_set:!0}:{}},supaHost:H?.supaHost,supaAnon:H?.supaAnon});if(N)await Z$A(N,async()=>`Cannot set rollout in channel ${await FwA(N)}`);let V=`${Z.hostWeb}/app/${Y}/channel/${X.id}`;if(U)_A.info(`Promoted the previous rollout to stable on ${J} and set @${$} as the new rollout target (${UCQ(G)})`);else _A.info(`Set ${Y} channel ${J} rollout target to @${$} (${UCQ(G)})`);if(B)_A.info(`Bundle url: ${V}`);return!0}async function NBB(A,Q,B){let{error:$,data:J}=await Q.from("apps").select("default_upload_channel").eq("app_id",A).single();if($)throw Error(`Cannot find default upload channel: ${uA($)}. You can set it here: ${B}/app/${A}/info`);return J.default_upload_channel}async function mO(A,Q,B=!1,$){return eXA($,()=>CBB(A,Q,B))}async function CBB(A,Q,B){if(!B)NJ().intro(`Uploading with CLI version ${D6.version}`);let $,J=x4();await l4(NJ());let{s3Region:Y,s3Apikey:Z,s3Apisecret:X,s3BucketName:G,s3Endpoint:K,s3Port:W,s3SSL:H}=Q;if(Q.verbose)_A.info("[Verbose] Starting upload process with options:"),_A.info(` - API key: ${Q.apikey?"provided":"from saved key"}`),_A.info(` - Path: ${Q.path||"from capacitor config"}`),_A.info(` - Channel: ${Q.channel||"from default upload channel"}`),_A.info(` - Bundle: ${Q.bundle||"auto-detected"}`),_A.info(` - External: ${Q.external||"false"}`),_A.info(` - Encryption: ${Q.keyV2||Q.keyDataV2?"v2":Q.key===!1?"disabled":"auto"}`),_A.info(` - Upload method: ${Q.tus?"TUS":Q.zip?"ZIP":"auto"}`),_A.info(` - Delta updates: ${Q.delta||Q.partial?"enabled":"disabled"}`);let U=e0B(Q);if(Q.verbose)_A.info("[Verbose] API key retrieved successfully");let z=await eLQ(Q,{appId:A});if(Q.verbose)_A.info(uF(Q.mode)?`[Verbose] Cordova project config resolved (webDir: ${z.config.webDir})`:"[Verbose] Capacitor config loaded successfully");Q.userRequestedDelta=!!(Q.partial||Q.delta||Q.partialOnly||Q.deltaOnly);let D=jLQ(z?.config?.plugins?.CapacitorUpdater),I=a9({silent:B});if(D&&Q.delta===void 0){if(I){_A.info("\uD83D\uDCA1 Instant updates are enabled in your config"),_A.info(" Delta updates send only changed files instead of the full bundle");let B0=await s1({message:"Enable delta updates for this upload? (Recommended with instant updates)",initialValue:!0});if(!EB(B0)&&B0){if(Q.delta=!0,Q.verbose)_A.info("[Verbose] Delta updates auto-enabled due to instant update configuration")}}else if(!B){if(Q.delta!==!1){if(Q.delta=!0,Q.verbose)_A.info("[Verbose] Delta updates auto-enabled in CI/CD mode due to instant update configuration")}}}let M=await etA();if(Q.verbose)_A.info("[Verbose] Remote file config retrieved:"),_A.info(` - Max upload length: ${Math.floor(M.maxUploadLength/1024/1024)} MB`),_A.info(` - Alert upload size: ${Math.floor(M.alertUploadSize/1024/1024)} MB`),_A.info(` - TUS upload: ${M.TUSUpload?"enabled":"disabled"}`),_A.info(` - TUS upload forced: ${M.TUSUploadForced?"yes":"no"}`),_A.info(` - Delta upload: ${M.partialUpload?"enabled":"disabled"}`),_A.info(` - Max chunk size: ${Math.floor(M.maxChunkSize/1024/1024)} MB`);let{appid:N,path:V}=await ABB(A,Q,z.config,I);if(Q.verbose)_A.info(`[Verbose] App ID: ${N}, Build path: ${V}`);if(_R(Q.autoBump)&&Q.bundle)VB("Cannot use --bundle (-b) and --auto-bump together. Omit --bundle to auto-increment from the latest remote version.");let L=await t0B(z.config,Q);if(Q.verbose)_A.info(`[Verbose] Bundle version: ${L}`);let C=Q.external?"external":"r2-direct",R="none";if(await QBB(Q,V,I),Q.verbose)_A.info("[Verbose] Code check passed (notifyAppReady found and index.html present)");let E=await LJ();if(Q.verbose)_A.info(`[Verbose] Local config loaded: host=${E.hostWeb}`);if(Q.supaHost&&Q.supaAnon){if(_A.info("Using custom supabase instance from provided options"),E.supaHost=Q.supaHost,E.supaKey=Q.supaAnon,Q.verbose)_A.info(`[Verbose] Custom Supabase host: ${Q.supaHost}`)}let w=await IB(U,Q.supaHost,Q.supaAnon);if(Q.verbose)_A.info("[Verbose] Supabase client created successfully");if(await Y$(w,N,B),await x6(w,U,N,"app.upload_bundle",B,!0),Q.verbose)_A.info("[Verbose] App exists and API key has app.upload_bundle permission");let S=await $8(w,U);if(Q.verbose)_A.info(`[Verbose] User verified successfully, user_id: ${S}`);let h=YwA(Q.channel);if(Q.channel!==void 0&&h.length===0)VB("Missing channel name, pass one channel or a comma-separated list with --channel");let k=h.length>0?null:await NBB(N,w,E.hostWeb),v=h.length>0?h:YwA(k||"production");if(v.length===0)VB("Cannot resolve target channel");let g=Ik(v),a=v,t=UBB(Q);if(Q.verbose)_A.info(`[Verbose] Target channel${v.length>1?"s":""}: ${g}`);let n=await G9(U,N,{supaHost:Q.supaHost,supaAnon:Q.supaAnon});if(Q.verbose)_A.info(`[Verbose] Organization ID: ${n}`);if(await QeA(w,n,D6.version),Q.verbose)_A.info("[Verbose] Remote CLI messages checked");if(await BeA(w,n,N,!0),Q.verbose)_A.info("[Verbose] Plan validation passed");if(Q.verbose)_A.info("[Verbose] Trial check completed");let l=_R(Q.autoBump);if(l){let B0;if(l==="ai"){let u0=await TLQ({supabase:w,appid:N,channels:v,path:V,apikey:U,options:{supaHost:Q.supaHost,supaAnon:Q.supaAnon}});_A.info(`\uD83E\uDD16 AI auto-bump chose ${u0.level}: ${u0.reason}`),B0=u0.level}else B0=l;if(Q.verbose)_A.info(`[Verbose] Resolving auto-bump (${B0}) version from channel/app remote versions...`);if(L=await DBB(w,N,v,L,B0),Q.verbose)_A.info(`[Verbose] Bundle version after auto-bump: ${L}`)}if(Q.autoSetBundle){if(uF(Q.mode))_A.warn("--auto-set-bundle is not supported in Cordova mode (no capacitor.config to update)");else if(await NI({version:L}),Q.verbose)_A.info(`[Verbose] Auto-set bundle version in ${z.path}`)}if(_A.info(`Upload ${N}@${L} started from path "${V}" to Capgo cloud`),Q.verbose)_A.info(`[Verbose] Checking if version ${L} already exists...`);let c=await $BB(w,N,L,Q.versionExistsOk,I);if(Q.verbose)_A.info(`[Verbose] Version exists check: ${c?typeof c==="string"?`retry with ${c}`:"yes (skipping)":"no (continuing)"}`);if(c===!0)return{success:!0,appId:N,skipped:!0,reason:"VERSION_EXISTS",bundle:L,checksum:null,encryptionMethod:R,storageProvider:C};if(typeof c==="string")return _A.info(`Retrying upload with new version: ${c}`),mO(A,{...Q,bundle:c,autoBump:void 0},B);if(Q.external&&!Q.external.startsWith("https://"))VB(`External link should should start with "https://" current is "${Q.external}"`);let x=null,d="",b;if(!Q.external){if(Q.verbose)_A.info(`[Verbose] Preparing bundle file from path: ${V}`);let B0=z.config?.plugins?.CapacitorUpdater?.publicKey;if(b=await HBB(V,Q,U,n,N,M.maxUploadLength,M.alertUploadSize,B0),$=b.sessionKey,x=b.zipped,R=b.encryptionMethod,d=b.finalKeyData,Q.verbose)_A.info("[Verbose] Bundle prepared:"),_A.info(` - Size: ${Math.floor((b.zipped?.byteLength??0)/1024)} KB`),_A.info(` - Checksum: ${b.checksum}`),_A.info(` - Encryption: ${b.encryptionMethod}`),_A.info(` - IV Session Key: ${b.ivSessionKey?"present":"none"}`),_A.info(` - Key ID: ${b.keyId||"none"}`);if(!Q.ignoreChecksumCheck&&t==null&&!Q.rolloutAdvance){if(Q.verbose)_A.info("[Verbose] Checking for duplicate checksum...");if(a=await YBB(w,N,v,b.checksum),Q.verbose)_A.info("[Verbose] Checksum is unique or already satisfied across target channels")}}let m=Ik(a);if(Q.verbose)_A.info(`[Verbose] Checking compatibility with channel${a.length>1?"s":""} ${m}...`);let QA=[];for(let B0 of a){let u0=await BBB(w,J,Q,B0,N,L,n);QA.push({channel:B0,...u0})}let y=QA.find((B0)=>B0.nativePackages)?.nativePackages,s=JBB(QA),BA=QA.filter((B0)=>B0.compatibility.result==="incompatible"),zA=BA.length>0,YA=BA.reduce((B0,u0)=>Math.max(B0,u0.incompatibleCount),0),CA=Ik(BA.map((B0)=>B0.channel)),HA=()=>{let B0=CA||m;R0({channel:"bundle",event:"Bundle Upload Blocked",apikey:Q.apikey,appId:N,orgId:n,tags:{reason:"incompatible",channel:B0,channel_name:B0,channel_names:B0,channel_count:BA.length||a.length,incompatible_count:YA,interactive:I}});let sB=`Upload aborted: bundle is incompatible with ${BA.length===1?"channel":"channels"} "${B0}" (${YA} native package(s) changed). A native build / app-store update is required. Run a native build with Capgo Builder (https://capgo.app/docs/cli/cloud-build/), or remove --fail-on-incompatible to upload anyway.`;throw _A.error(sB),new WwA(sB)};if(zA&&!B&&!Q.acceptIncompatible){if(Q.failOnIncompatible&&!I)HA();let B0=await p4(N)!==null,u0=await bLQ({incompatible:zA,interactive:I,hasCredentials:B0,appId:N,orgId:n,apikey:U,incompatibleCount:YA});if(u0==="abort")KwA();if(u0!=="continue")return{success:!0,appId:N,skipped:!0,reason:"NATIVE_BUILD",builderAction:u0,bundle:L,checksum:null,encryptionMethod:R,storageProvider:C};if(SLQ({incompatible:zA,failOnIncompatible:!!Q.failOnIncompatible,interactive:I,builderAction:u0}))HA()}else if(zA&&Q.acceptIncompatible&&!B)_A.warn("Proceeding because --accept-incompatible was set. The incompatible-bundle crash warning will not be emailed.");if(Q.verbose)_A.info("[Verbose] Compatibility check completed:"),_A.info(` - Native packages: ${y?y.length:0}`),_A.info(` - Min update version: ${s||"none"}`);if(Q.deleteLinkedBundleOnUpload)_A.warn(`Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the target channel${a.length>1?"s":""}: ${m}.`),_A.warn("Please make sure you want to do this, if you are not sure, please do not use this option.");let MA=a.length>0,PA=MA?await MBB(w,U,N,a,!!Q.selfAssign,t,!!Q.rolloutAdvance):new Map,JA={name:L,app_id:N,session_key:Q.external?Q.ivSessionKey:b?.ivSessionKey,external_url:Q.external,storage_provider:C,min_update_version:s,native_packages:y,owner_org:n,user_id:S,checksum:Q.external?Q.encryptedChecksum:b?.checksum,link:Q.link||null,comment:Q.comment||null,key_id:b?.keyId||void 0,cli_version:D6.version};if(Q.external){if(Q.verbose)_A.info(`[Verbose] Using external URL: ${Q.external}`);if(await _B(U,{channel:"app",event:"App external",org_id:n,tracking_version:2,tags:{"app-id":N}},Q.verbose),Q.verbose)_A.info("[Verbose] External bundle configured:"),_A.info(` - URL: ${Q.external}`),_A.info(` - IV Session Key: ${Q.ivSessionKey?"provided":"none"}`),_A.info(` - Encrypted Checksum: ${Q.encryptedChecksum?"provided":"none"}`)}if(Q.zip){if(Q.tus=!1,Q.verbose)_A.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")}else if(!M.TUSUpload||Q.external){if(Q.tus=!1,Q.verbose)_A.info("[Verbose] Upload method: Standard (TUS not available or external URL)")}else if(Q.tus=Q.tus||M.TUSUploadForced,Q.verbose)_A.info(`[Verbose] Upload method: ${Q.tus?"TUS (resumable)":"Standard"}`);if(!M.partialUpload||Q.external){if(Q.delta=!1,Q.verbose&&Q.external)_A.info("[Verbose] Delta updates disabled (not available with external URLs)")}else if(Q.delta=Q.delta||Q.partial||Q.deltaOnly||Q.partialOnly||M.partialUploadForced,Q.verbose)_A.info(`[Verbose] Delta updates: ${Q.delta?"enabled":"disabled"}`);if(Q.encryptDelta=Q.encryptDelta||Q.encryptPartial,Q.encryptDelta&&R!=="v2")VB("You cannot encrypt the delta update if you are not using the v2 encryption method");let wA="5.30.0",RA="6.30.0",LA="7.30.0",hQ=!1;if(Q.delta&&R==="v2"&&!Q.encryptDelta){let B0=L1(XwA()),u0=await DZ("@capgo/capacitor-updater",B0,Q.packageJson),sB;try{sB=u0?Z1(u0):void 0}catch{sB=void 0}if(u0&&sB&&NZA(sB,Z1("6.14.4"))){if(_A.info(`Auto-enabling delta update encryption for updater version ${sB} (>= 6.14.4)`),Q.verbose)_A.info("[Verbose] Delta encryption auto-enabled for updater >= 6.14.4");Q.encryptDelta=!0}}if(Q.delta&&(Q.encryptDelta||R==="v2")){let B0=L1(XwA()),u0=await DZ("@capgo/capacitor-updater",B0,Q.packageJson),sB;try{sB=u0?Z1(u0):void 0}catch{sB=void 0}if(u0&&sB){if(hQ=!yK(sB,wA,RA,LA),Q.verbose&&hQ)_A.info(`[Verbose] Using hex checksum format for updater version ${sB}`)}}if(Q.verbose&&Q.delta)_A.info("[Verbose] Preparing delta update manifest...");let RQ=Q.delta?await WCQ(V,U,n,N,Q.encryptDelta?R:"none",d,hQ):[];if(Q.verbose&&Q.delta)_A.info(`[Verbose] Delta manifest prepared with ${RQ.length} files`);if(Q.delta&&RQ.length>vf)VB(Lt(RQ.length));if(Q.verbose)_A.info("[Verbose] Creating version record in database...");if(await ZwA(w,JA,"add"),Q.verbose)_A.info("[Verbose] Version record created successfully");if(Q.dryUpload){if(Q.verbose)_A.info("[Verbose] Dry upload mode: skipping bundle publishing and channel assignment");if(!B)NJ().outro("Dry upload saved bundle metadata without uploading files or updating channels");return{success:!0,appId:N,bundle:L,checksum:JA.checksum??null,encryptionMethod:R,sessionKey:$?$.toString("base64"):void 0,ivSessionKey:typeof JA.session_key==="string"?JA.session_key:void 0,storageProvider:JA.storage_provider,reason:"DRY_UPLOAD"}}if(Q.tusChunkSize&&Q.tusChunkSize>M.maxChunkSize)_A.error(`Chunk size ${Q.tusChunkSize} is greater than the maximum chunk size ${M.maxChunkSize}, using the maximum chunk size`),Q.tusChunkSize=M.maxChunkSize;else if(!Q.tusChunkSize)Q.tusChunkSize=M.maxChunkSize;if(Q.verbose)_A.info(`[Verbose] TUS chunk size: ${Math.floor(Q.tusChunkSize/1024/1024)} MB`);if(x&&ZBB(Q)){if(!G||!K||!Y||!Z||!X||!W)VB("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret");if(_A.info("Uploading to S3"),Q.verbose)_A.info("[Verbose] S3 configuration:"),_A.info(` - Endpoint: ${K}`),_A.info(` - Region: ${Y}`),_A.info(` - Bucket: ${G}`),_A.info(` - Port: ${W}`),_A.info(` - SSL: ${H?"enabled":"disabled"}`);let B0=`${H?"https":"http"}://${K}${W?`:${W}`:""}`,u0=new m6A({endPoint:K,region:Y,port:W,pathStyle:!0,bucket:G,accessKey:Z,secretKey:X}),sB=`${N}-${L}`,WB=encodeURIComponent(sB);if(Q.verbose)_A.info(`[Verbose] Uploading to S3 as: ${sB}`);try{await u0.putObject(sB,Uint8Array.from(x)),JA.external_url=`${B0}/${WB}`,JA.storage_provider="external",await ZwA(w,JA,"update")}catch(J1){try{await jt(U,N,L,Q)}catch(C1){VB(`Cannot upload bundle to S3 ${uA(J1)}. Cleanup of the incomplete version also failed (${uA(C1)}); delete bundle ${L} manually before retrying.`)}VB(`Cannot upload bundle to S3 ${uA(J1)}`)}if(Q.verbose)_A.info(`[Verbose] S3 upload complete, external URL: ${JA.external_url}`)}else if(x){if(DCQ(Q)){if(Q.verbose)_A.info("[Verbose] Starting full bundle upload to Capgo Cloud...");await FBB(U,w,N,L,n,x,Q,Q.tusChunkSize)}else if(Q.verbose)_A.info("[Verbose] Skipping full bundle upload (delta-only mode)");let B0=null;try{if(Q.dryUpload){if(Q.delta=!1,Q.verbose)_A.info("[Verbose] Dry upload mode: skipping delta upload")}let u0=JA.session_key&&Q.encryptDelta&&$?{sessionKey:$,ivSessionKey:JA.session_key}:void 0;if(Q.verbose&&Q.delta)_A.info("[Verbose] Starting delta file upload..."),_A.info(` - Manifest entries: ${RQ.length}`),_A.info(` - Encryption: ${u0?"enabled":"disabled"}`);if(B0=Q.delta?await HCQ(U,RQ,V,N,n,u0,Q):null,Q.verbose&&B0)_A.info(`[Verbose] Delta upload complete with ${B0.length} files`)}catch(u0){if(Q.userRequestedDelta)throw u0;if(_A.info(`Failed to upload delta files to capgo cloud. Error: ${uA(u0)}. This is not a critical error, the bundle has been uploaded without the delta files`),Q.verbose)_A.info(`[Verbose] Delta upload error details: ${uA(u0)}`)}if(B0?.length){if(Q.verbose)_A.info(`[Verbose] Writing ${B0.length} manifest rows via set_manifest...`);try{await KeA(U,N,L,B0,Q)}catch(u0){try{await jt(U,N,L,Q)}catch(sB){VB(`Cannot set bundle manifest ${uA(u0)}. Cleanup of the incomplete version also failed (${uA(sB)}); delete bundle ${L} manually before retrying.`)}VB(`Cannot set bundle manifest ${uA(u0)}`)}if(Q.verbose)_A.info("[Verbose] Manifest rows written (sizes filled by backend from R2)")}if(JA.storage_provider="r2",JA.manifest=null,Q.verbose)_A.info("[Verbose] Updating version record with storage provider...");if(await tLQ({apikey:U,appId:N,bundle:L,supaHost:Q.supaHost,supaAnon:Q.supaAnon,reporter:NJ()},async()=>{await ZwA(w,JA,"update")}),Q.verbose)_A.info("[Verbose] Version record updated successfully")}let $0=await VJ(w,U,"bundle.delete",{appId:N});if(Q.verbose)_A.info("[Verbose] Permissions:"),_A.info(" - app.upload_bundle: yes"),_A.info(` - bundle.delete: ${$0?"yes":"no"}`),_A.info(" - channel permissions: checked per target channel");let vQ=Q.deleteLinkedBundleOnUpload&&$0,E0=vQ?await Promise.all(a.map(async(B0)=>({channel:B0,version:await OCQ(w,N,B0)}))):[];if(Q.deleteLinkedBundleOnUpload&&!vQ)_A.warn("Cannot delete linked bundle on upload because this API key lacks bundle.delete");let v0=new Set(a).size,BB=new Set;for(let B0 of a){if(Q.verbose)_A.info(`[Verbose] Setting bundle ${L} to channel ${B0}...`);let u0=PA.has(B0)?PA.get(B0)??null:await HwA(w,N,B0),sB=Q.rolloutAdvance||t!=null,WB=u0?.rollout_percentage_bps,J1=t??WB??0;if(Q.rolloutAdvance&&t==null&&!((WB??0)>0))VB(`Cannot advance rollout, channel ${B0} has no rollout percentage to reuse. Pass --rollout or --rollout-percentage-bps`);let C1=sB?await LBB(w,U,!!Q.bundleUrl,L,B0,N,E,u0,J1,Q.rolloutCacheTtlSeconds,Q.selfAssign,Q,!!Q.rolloutAdvance):await OBB(w,U,!!Q.bundleUrl,L,B0,S,n,N,E,u0,MA,Q.selfAssign,Q);if(C1)BB.add(B0);if(Q.verbose)_A.info(`[Verbose] Channel ${B0} ${C1?"updated successfully":"was not updated"}`)}if(vQ){let B0=new Set;for(let u0 of E0){if(!BB.has(u0.channel))continue;if(!u0.version||B0.has(u0.version.id))continue;if(Q.verbose)_A.info(`[Verbose] Deleting previously linked bundle in channel ${u0.channel}...`);await IBB(w,u0.version),B0.add(u0.version.id)}}if(BB.size===0)_A.warn("Cannot set channel because this API key lacks the required RBAC permission");if(MA&&BB.size!==v0)VB("Cannot complete upload because one or more target channels were not updated");if(Q.verbose)_A.info("[Verbose] Sending upload event...");await _B(U,{channel:"app",event:"App Uploaded",org_id:n,tracking_version:2,tags:{"app-id":N,bundle:L}},Q.verbose),await _B(U,{channel:"app",event:"Bundle Uploaded",org_id:n,tracking_version:2,tags:{"app-id":N,bundle:L},notifyConsole:!0}).catch(()=>{});for(let B0 of QA){if(B0.compatibility.result!=="incompatible")continue;R0({channel:"bundle",event:"Bundle Incompatible",apikey:U,appId:N,orgId:n,tags:{source:"upload",channel:B0.channel,channel_name:B0.channel,channel_overwritten:BB.has(B0.channel),version_new_name:L,...B0.compatibility.versionOldId?{version_old_id:B0.compatibility.versionOldId}:{},...B0.compatibility.versionOldName?{version_old_name:B0.compatibility.versionOldName}:{},...Q.acceptIncompatible?{incompatibility_accepted:!0}:{}}})}let vB={success:!0,appId:N,bundle:L,updatedChannels:Array.from(BB),checksum:JA.checksum??null,encryptionMethod:R,sessionKey:$?$.toString("base64"):void 0,ivSessionKey:typeof JA.session_key==="string"?JA.session_key:void 0,storageProvider:JA.storage_provider};if(Q.verbose)_A.info("[Verbose] Upload completed successfully:"),_A.info(` - Bundle: ${vB.bundle}`),_A.info(` - Checksum: ${vB.checksum}`),_A.info(` - Encryption: ${vB.encryptionMethod}`),_A.info(` - Storage: ${vB.storageProvider}`);if(I&&!vB.skipped){let B0=Q.showReplicationProgress;if(B0===void 0)B0=await SjA({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(B0)await n6A({title:"Replicating your bundle in all regions to guarantee fast updates.",completeMessage:"Replication complete. Your update is now globally available.",interactive:I})}if(!B&&!vB.skipped)NJ().outro("Time to share your update to the world \uD83C\uDF0D");return vB}function VBB(A){let Q=A.key===!1,B=A.rollout!=null||A.rolloutPercentageBps!=null||A.rolloutAdvance===!0,$=A.forceCrc32Checksum===!0,J=A.keyV2||A.keyDataV2||pl(R5);if(A.ivSessionKey&&!A.external)VB("You need to provide an external url if you want to use the --iv-session-key option");if(A.encryptedChecksum&&!A.external)VB("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)VB("You cannot use delta upload options (--delta/--delta-only, or deprecated --partial/--partial-only) with an external url");if(A.tus&&A.external)VB("You cannot use the --tus option with an external url");if(A.dryUpload&&A.external)VB("You cannot use the --dry-upload option with an external url");if(A.multipart&&A.external)VB("You cannot use the --multipart option with an external url");if(A.external&&(A.keyV2||A.keyDataV2))VB("You cannot set a key if you are uploading to an external url");if(A.keyV2&&A.keyDataV2)VB("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))VB("You cannot set S3 options if you are uploading to an external url, it's automatically handled");if(A.encryptedChecksum&&!A.external)VB("You cannot set the --encrypted-checksum option if you are not uploading to an external url");if(A.minUpdateVersion&&A.autoMinUpdateVersion)VB("You cannot set both min-update-version and auto-min-update-version, use only one of them");if(A.rollout!=null&&(!Number.isFinite(A.rollout)||A.rollout<0||A.rollout>100))VB("Rollout percentage must be between 0 and 100");if(A.rolloutPercentageBps!=null&&(!Number.isInteger(A.rolloutPercentageBps)||A.rolloutPercentageBps<0||A.rolloutPercentageBps>1e4))VB("Rollout percentage basis points must be between 0 and 10000");if(A.rolloutCacheTtlSeconds!=null&&(!Number.isInteger(A.rolloutCacheTtlSeconds)||A.rolloutCacheTtlSeconds<60||A.rolloutCacheTtlSeconds>31536000))VB("Rollout cache TTL seconds must be between 60 and 31536000");if(B&&A.dryUpload)VB("You cannot use --rollout or --rollout-advance with --dry-upload because dry upload does not update channels");if(B&&A.deleteLinkedBundleOnUpload)VB("You cannot use --rollout or --rollout-advance with --delete-linked-bundle-on-upload because rollout needs the stable channel bundle as fallback");if($&&J&&!Q)VB("You cannot use --force-crc32-checksum when encryption is enabled. Remove the flag or disable encryption.");if(A.failOnIncompatible&&A.ignoreMetadataCheck)VB("You cannot use --fail-on-incompatible together with --ignore-metadata-check — the metadata check is exactly what --fail-on-incompatible enforces. Remove one of them.");if(A.acceptIncompatible&&A.failOnIncompatible)VB("You cannot use --accept-incompatible together with --fail-on-incompatible — one continues despite a mismatch, the other refuses it. Remove one of them.");if(A.acceptIncompatible&&A.ignoreMetadataCheck)VB("You cannot use --accept-incompatible together with --ignore-metadata-check — accepting a mismatch requires running the compatibility check. Remove one of them.")}async function RBB(){if(!a9())return;let A=Xk();if(Zk(A.repository)||!A.ghInstalled||!A.ghLoggedIn||!A.repositoryExists||A.starred)return;if(!await SjA({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=fz(A.repository);if(B.alreadyStarred)_A.info(`\uD83E\uDEF6 ${B.repository} is already starred`);else _A.success(`\uD83D\uDE4F Thanks for starring ${B.repository} \uD83C\uDF89`)}catch(B){_A.warn(`Cannot star ${A.repository} right now: ${uA(B)}`)}}async function X$A(A,Q){return eXA(Oa,()=>EBB(A,Q))}async function EBB(A,Q){try{VBB(Q);let B=await mO(A,Q);if(!B.skipped)await RBB();return B}catch(B){let $=B instanceof Error?B.message:String(B),J=uA(B);if($===GwA)throw B instanceof Error?B:Error(String(B));if(Q.verbose)_A.error(`uploadBundle failed:${J}`);else _A.error(`uploadBundle failed: ${$}`);if(B instanceof WwA)throw B;let Y=$.includes("Cannot upload the same bundle content"),Z=a9();if(!Q.versionExistsOk&&Z)try{if(Y){let X=await _6({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(EB(X)||X==="cancel")throw B instanceof Error?B:Error(String(B));if(X==="ignore")return _A.info("\uD83D\uDD04 Retrying upload with --ignore-checksum-check..."),X$A(A,{...Q,ignoreChecksumCheck:!0})}else{let X=await s1({message:"Would you like to retry the upload?"});if(EB(X))throw B instanceof Error?B:Error(String(B));if(X)return _A.info("\uD83D\uDD04 Retrying upload..."),X$A(A,Q)}}catch{throw B instanceof Error?B:Error(String(B))}throw B instanceof Error?B:Error(String(B))}}function LCQ(A,Q){return{apikey:A.apikey,bundle:Q,supaAnon:A.supaAnon,supaHost:A.supaHost}}async function NCQ(A,Q){let B=await X$A(A,Q),$=B?.appId||A;if(Q.qrPreview&&B?.bundle&&B.reason!=="DRY_UPLOAD"&&!B.builderAction)await g6A($,void 0,LCQ(Q,B.bundle));if(Q.sendUpdateNotification&&B?.success&&!B.skipped&&B.updatedChannels?.length&&!B.builderAction)try{await v6A({appId:$,apikey:Q.apikey,channels:B.updatedChannels,verbose:Q.verbose})}catch{}if(!B?.builderAction)return;if(B.builderAction==="launch-onboarding")await oS({apikey:Q.apikey});else await m4A($,{apikey:Q.apikey,supaHost:Q.supaHost,supaAnon:Q.supaAnon})}GB();PK();v4();OJ();Nv();V0();import{randomUUID as yBB}from"node:crypto";import{existsSync as hBB,writeFileSync as uBB}from"node:fs";import{cwd as mBB}from"node:process";import{existsSync as CCQ,readFileSync as UwA}from"node:fs";import{createRequire as jBB}from"node:module";import{dirname as qwA,join as wBB}from"node:path";import PBB from"node:process";var tX="@capgo/capacitor-updater",cF="@capacitor/splash-screen";function _BB(A){if(!CCQ(A))return null;try{return JSON.parse(UwA(A,"utf-8"))}catch{return null}}function TBB(A,Q){let B=_BB(A);if(!B)return{version:null,section:null};let $=["dependencies","devDependencies","optionalDependencies"];for(let J of $){let Y=B[J];if(!Y||!Object.hasOwn(Y,Q))continue;let Z=Y[Q];return{version:typeof Z==="string"?Z:String(Z),section:J}}return{version:null,section:null}}function SBB(A,Q){let $=qwA(A);while(!0){let J=wBB($,"node_modules",Q,"package.json");if(CCQ(J))try{let Z=JSON.parse(UwA(J,"utf-8"));if(typeof Z.version==="string")return Z.version}catch{return null}let Y=qwA($);if(Y===$)break;$=Y}if(!PBB.versions.pnp)return null;try{let Y=jBB(A).resolve(`${Q}/package.json`),Z=JSON.parse(UwA(Y,"utf-8"));if(typeof Z.version==="string")return Z.version}catch{return null}return null}function VCQ(A,Q){let B=qwA(A),$=TBB(A,Q),J=SBB(A,Q),Y=[];if(!$.version)Y.push(`Missing ${Q} in ${A}`);if(!J)Y.push(`Cannot resolve ${Q} from ${B}/node_modules`);return{packageJsonPath:A,projectDir:B,declaredVersion:$.version,declaredIn:$.section,installedVersion:J,ready:Y.length===0,details:Y}}function XK(A){return VCQ(A,tX)}function zwA(A){return VCQ(A,cF)}GB();import{spawnSync as kBB}from"node:child_process";import{existsSync as ECQ,statSync as bBB}from"node:fs";import{dirname as xBB,join as vBB,resolve as jCQ}from"node:path";import{cwd as RCQ}from"node:process";V0();function DwA(A){return`0.0.1-beta.local-${A}`}function IwA(A){let Q=L1(RCQ()),B=Hk(A);if(B?.length)for(let $ of B)for(let J of[RCQ(),Q]){let Y=jCQ(J,$);if(ECQ(Y))return Y}return vBB(Q,"package.json")}function fBB(A){return A?.trim()||"latest"}function gBB(A,Q,B){let $=`${tX}@${Q}`,J=A.installCommand.split(/\s+/).filter(Boolean),Y=J[0];if(!Y)return null;if(!B?.trim())switch(A.pm){case"yarn":return{command:"yarn",args:["add",$]};case"bun":return{command:"bun",args:["add",$]};case"pnpm":return{command:"pnpm",args:["add",$]};default:return{command:Y,args:[...J.slice(1),$]}}if(A.pm==="yarn"||A.pm==="bun")return{command:Y,args:J.slice(1)};return{command:Y,args:[...J.slice(1),"--force",$]}}async function wCQ(A,Q){f.warn(`Bundle version "${A}" is not valid semver (https://semver.org/).`);let B=await s1({message:`Use local fallback version ${Q} instead?`,initialValue:!0});if(EB(B)||!B)return null;return f.info(`Using bundle version ${Q}`),Q}async function PCQ(A){let Q=await LG({message:A,validate:(B)=>{let $=B?.trim();if(!$)return"Value is required";let J=jCQ($);if(!ECQ(J))return`Path does not exist: ${J}`;if(!bBB(J).isDirectory())return`Path is not a directory: ${J}`}});if(EB(Q))return null;return Q.trim()}async function _CQ(A){let Q=IwA(A),B=XK(Q);if(B.ready)return!0;f.warn(`Cannot find ${tX} in node_modules.`);let $=await s1({message:`Install ${tX} now?`,initialValue:!0});if(EB($)||!$)return!1;let J=x4(),Y=fBB(B.declaredVersion),Z=gBB(J,Y,B.declaredVersion);if(!Z)return!1;if(kBB(Z.command,Z.args,{cwd:xBB(Q),stdio:"inherit",shell:!1}).status!==0)return!1;return XK(Q).ready}t1();var cBB=20;function dBB(A){console.log(JSON.stringify(A,null,2))}function Mk(A){console.error(uA(A))}function lBB(A){if(A.context?.message)Mk({error:A.message,message:A.context.message});else Mk({error:A.message})}async function MwA(A,Q,B=!1){let{json:$}=Q,{bundle:J,path:Y}=Q,Z=!$&&!B;try{if(Z)await l4();let X=await h0(),G=a9({silent:$||B}),K=await a6A({explicitAppId:A,config:X?.config,packageJsonPaths:Hk(Q.packageJson),interactive:G,json:$}),W=yBB().split("-")[0],H=RX("",Q.packageJson);if(J=J||H||DwA(W),Z)r0(`Zipping ${K??"app"}@${J}`);if(J&&!rN.test(J)){if(G){let h=await wCQ(J,DwA(W));if(h)J=h}if(!rN.test(J)){let h=`Your bundle name ${J}, is not valid it should follow semver convention : https://semver.org/`;if(!B)if($)Mk({error:"invalid_semver"});else f.error(h);throw Error("Invalid bundle version format")}}if(Y=Y||X?.config?.webDir,!Y&&G){let h=await PCQ("Enter the path to your built web assets (webDir):");if(h)Y=h}if(!K||!J||!Y){if(!B)if($)Mk({error:"missing_argument"});else f.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)f.info(`Started from path "${Y}"`);if(Q.codeCheck!==!1&&!Q.ignoreNotifyAppReady){if(!mW(Y,"notifyAppReady"))if(G){if(await A$A({webDir:Y,interactive:G,json:$})!=="skipped"&&!mW(Y,"notifyAppReady"))throw new FQ("notifyAppReady() is missing in build folder")}else throw $?new FQ("notifyAppReady_not_in_source_code",{message:e6A(Y)}):new FQ(e6A(Y));if(!Kk(Y)){if(!B)if($)Mk({error:"index_html_not_found"});else f.error(`index.html is missing in the root folder of ${Y}`);throw Error("index.html is missing in root folder")}}let z=await Et(Y);if(Z)f.info(`Zipped ${z.byteLength} bytes`);let D=Z?n8():null;if(D)D.start("Calculating checksum");let I=L1(mBB()),M=IwA(Q.packageJson),N=XK(M);if(!N.ready&&G&&await _CQ(Q.packageJson))N=XK(M);if(!N.ready){if(!B)f.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 V=await DZ("@capgo/capacitor-updater",I,Q.packageJson),L=!1,C;try{C=V?Z1(V):void 0}catch{C=void 0}if(C)L=!yK(C,void 0,void 0,"7.0.0");else if(V==="link:@capgo/capacitor-updater"){if(!B)f.warn("Using local @capgo/capacitor-updater. Assuming v7");L=!0}let R=await $I(z,Q.keyV2||hBB(R5)||L?"sha256":"crc32");if(D)D.stop(`Checksum ${L?"SHA256":"CRC32"}: ${R}`);let E=Math.floor(z.byteLength/1024/1024);if(E>cBB&&Z)f.warn(`WARNING !!
1439
1439
  The bundle size is ${E} Mb, this may take a while to download for users
1440
1440
  `),f.warn(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
1441
1441
  `);let w=Z?n8():null,S=Q.name||`${K}_${J}.zip`;if(w)w.start(`Saving to ${S}`);if(uBB(S,z),w)w.stop(`Saved to ${S}`);if(R0({channel:"bundle",event:"Bundle Zipped",tags:{zip_size_bytes:z.byteLength}}),Z)$B("Done ✅");if(!B&&$)dBB({bundle:J,filename:S,checksum:R});return{bundle:J,filename:S,checksum:R}}catch(X){if(!B)if($)if(X instanceof FQ)lBB(X);else Mk(X);else f.error(uA(X));throw X instanceof Error?X:Error(String(X))}}async function TCQ(A,Q){await MwA(A,Q,!1)}GB();v4();function G$A(A){return(()=>{if(A instanceof Error)return A.message;if(A&&typeof A==="object"){let B=A;return[B.message,B.details,B.hint,B.code].filter(($)=>typeof $==="string"||typeof $==="number").join(" ")}return String(A)})().toLowerCase().includes("unique_name_app_id")}t1();V0();async function pBB(A,Q,B){let{data:$,error:J}=await eS(A,Q,B);if(!J&&$)return!0;if(J?.code==="PGRST116")return!1;return null}async function iBB(A,Q={}){if(!G$A(A.createError))return"not_duplicate";let B=await(Q.isChannelReadableByCaller??pBB)(A.supabase,A.appId,A.channelName);if(B===!0)return"duplicate_readable";if(B===!1)return"duplicate_inaccessible";throw Error("Cannot verify channel access for this API key. Grant app.read_channels or channel.read, then retry.")}async function bR(A,Q,B,$=!1){if(!$)r0("Create channel");B.apikey=B.apikey||x0();let J=await h0($).catch(()=>{return});if(Q=y1(Q,J?.config),!B.apikey){if(!$)f.error("Missing API key, you need to provide an API key to upload your bundle");throw Error("Missing API key")}if(!Q){if(!$)f.error("Missing argument, you need to provide a appId, or be in a capacitor project");throw new FQ("Missing appId")}let Y=await IB(B.apikey,B.supaHost,B.supaAnon,$);if(await Y$(Y,Q,$),await $8(Y,B.apikey),await x6(Y,B.apikey,Q,"app.create_channel",$,!0),!$)f.info(`Creating channel ${Q}#${A} to Capgo`);let Z=await G9(B.apikey,Q,{supaHost:B.supaHost,supaAnon:B.supaAnon}),X=await zOQ({apikey:B.apikey,silent:$,supaHost:B.supaHost,supaAnon:B.supaAnon},{channel:A,app_id:Q,version:null,allow_device_self_set:B.selfAssign??!1,public:B.default??!1});if(X.error){let K=await IZ(X.error),W;try{W=await iBB({createError:K,supabase:Y,appId:Q,channelName:A})}catch(U){let z=uA(U);if(!$)f.error(`Cannot create Channel \uD83D\uDE40
@@ -1943,7 +1943,7 @@ External option: Store only a URL link (useful for apps >200MB or privacy requir
1943
1943
  Capgo never inspects external content. Add encryption for trustless security.
1944
1944
 
1945
1945
  Example: npx @capgo/cli@latest bundle upload com.example.app --path ./dist --channel production,beta
1946
- Cordova example: npx @capgo/cli@latest bundle upload com.example.app --mode cordova --path www --channel production`).action(NCQ).option("-a, --apikey <apikey>",SQ.apikey).addOption(new n5("--mode <framework>",SQ.mode).choices([...Fk])).option("-p, --path <path>","Path of the folder to upload, if not provided it will use the webDir set in capacitor.config (or www with --mode cordova)").option("-c, --channel <channel>","Channel to link to. Use commas for multiple channels, for example production,beta").option("--rollout <rollout>","Set the uploaded bundle as this channel's rollout target at a percentage from 0 to 100",(A)=>Number.parseFloat(A)).option("--rollout-percentage-bps <rolloutPercentageBps>","Set the uploaded bundle rollout percentage in basis points from 0 to 10000",(A)=>Number.parseInt(A,10)).option("--rollout-advance","Promote the current rollout target to stable, then set the uploaded bundle as the new rollout. Reuses the previous percentage unless --rollout or --rollout-percentage-bps is also set").option("--rollout-cache-ttl-seconds <rolloutCacheTtlSeconds>","Cloudflare rollout decision cache TTL in seconds",(A)=>Number.parseInt(A,10)).option("-e, --external <url>","Link to external URL instead of upload to Capgo Cloud").option("--iv-session-key <key>","Set the IV and session key for bundle URL external").option("--s3-region <region>","Region for your S3 bucket").option("--s3-apikey <apikey>","API key for your S3 endpoint").option("--s3-apisecret <apisecret>","API secret for your S3 endpoint").option("--s3-endpoint <s3Endpoint>","URL of S3 endpoint").option("--s3-bucket-name <bucketName>","Name for your AWS S3 bucket").option("--s3-port <port>","Port for your S3 endpoint").option("--no-s3-ssl","Disable SSL for S3 upload").option("--key-v2 <key>","Custom path for private signing key (v2 system)").option("--key-data-v2 <keyDataV2>","Private signing key (v2 system)").option("--bundle-url","Prints bundle URL into stdout").option("--no-key","Ignore signing key and send clear update").option("--no-code-check","Ignore checking if notifyAppReady() is called in source code and index present in root folder").option("--ignore-notify-app-ready",SQ.ignoreNotifyAppReady).option("--display-iv-session","Show in the console the IV and session key used to encrypt the update").option("-b, --bundle <bundle>","Bundle version number of the bundle to upload").option("--link <link>","Link to external resource (e.g. GitHub release)").option("--comment <comment>","Comment about this version, could be a release note, a commit hash, a commit message, etc.").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel").option("--auto-min-update-version","Set the min update version based on native packages").option("--ignore-metadata-check","Ignores the metadata (node_modules) check when uploading").option("--fail-on-incompatible","Fail the upload (exit non-zero) instead of uploading when the bundle is incompatible with the channel's current native packages. In an interactive terminal you can still choose a native build; declining fails. Cannot be combined with --ignore-metadata-check or --accept-incompatible.").option("--accept-incompatible",`${SQ.acceptIncompatible} Cannot be combined with --fail-on-incompatible or --ignore-metadata-check.`).option("--ignore-checksum-check","Ignores the checksum check when uploading").option("--force-crc32-checksum","Force CRC32 checksum for upload (override auto-detection)").option("--timeout <timeout>","Timeout for the upload process in seconds").option("--multipart","[DEPRECATED] Use --tus instead. Uses multipart protocol for S3 uploads").option("--zip","Upload the bundle using zip to Capgo cloud (legacy)").option("--tus","Upload the bundle using TUS to Capgo cloud").option("--tus-chunk-size <tusChunkSize>","Chunk size in bytes for TUS resumable uploads (default: auto)").option("--partial","[DEPRECATED] Use --delta instead. Upload incremental updates").option("--partial-only","[DEPRECATED] Use --delta-only instead. Upload only incremental updates, skip full bundle").option("--delta","Upload delta updates (only changed files) for instant, super-fast updates instead of big zip downloads. Capgo refuses delta uploads over 10,000 files (delta tracks each file); use --no-delta for a full zip, or reduce files in your web build.").option("--delta-only","Upload only delta updates without full bundle for maximum speed (useful for large apps)").option("--no-delta","Disable delta updates even if instant updates are enabled").option("--encrypted-checksum <encryptedChecksum>","An encrypted checksum (signature). Used only when uploading an external bundle.").option("--auto-set-bundle","Set the bundle version in Capacitor config").addOption(new n5("--auto-bump [level]","Auto-increment bundle version from the latest remote channel/app version. Level: major, minor (default), patch|fix, metadata (prerelease), or ai").preset("minor").argParser((A)=>{let Q=_R(A);if(!Q)throw new vD(`Invalid --auto-bump level "${A}". Allowed: major, minor, patch, fix, metadata, ai.`);return Q})).option("--capacitor-config <path>",SQ.capacitorConfig).option("--dry-upload","Dry upload the bundle process: add the row in database without uploading files or updating channels (Used by Capgo for internal testing)").option("--package-json <packageJson>",SQ.packageJson).option("--node-modules <nodeModules>",SQ.nodeModules).option("--encrypt-partial","Encrypt delta update files (auto-enabled for updater > 6.14.4)").option("--delete-linked-bundle-on-upload","Locates the currently linked bundle in the channel you are trying to upload to, and deletes it").option("--no-brotli-patterns <patterns>",'Files to exclude from Brotli compression (comma-separated globs, e.g., "*.jpg,*.png")').option("--disable-brotli","Completely disable brotli compression even if updater version supports it").option("--version-exists-ok","Exit successfully if bundle version already exists, useful for CI/CD workflows with monorepos").option("--self-assign","Allow devices to auto-join this channel (updates channel setting)").option("--qr-preview","Print a terminal QR code for this bundle preview after upload").option("--send-update-notification","Send a native update-check notification to devices after updating linked channel bundles").option("--supa-host <supaHost>",SQ.supaHost).option("--supa-anon <supaAnon>",SQ.supaAnon).option("--verbose",SQ.verbose);BD.command("compatibility [appId]").description(`\uD83E\uDDEA Check compatibility of a bundle with a specific channel in Capgo Cloud to ensure updates are safe.
1946
+ Cordova example: npx @capgo/cli@latest bundle upload com.example.app --mode cordova --path www --channel production`).action(NCQ).option("-a, --apikey <apikey>",SQ.apikey).addOption(new n5("--mode <framework>",SQ.mode).choices([...Fk])).option("-p, --path <path>","Path of the folder to upload, if not provided it will use the webDir set in capacitor.config (or www with --mode cordova)").option("-c, --channel <channel>","Channel to link to. Use commas for multiple channels, for example production,beta").option("--rollout <rollout>","Set the uploaded bundle as this channel's rollout target at a percentage from 0 to 100",(A)=>Number.parseFloat(A)).option("--rollout-percentage-bps <rolloutPercentageBps>","Set the uploaded bundle rollout percentage in basis points from 0 to 10000",(A)=>Number.parseInt(A,10)).option("--rollout-advance","Promote the current rollout target to stable, then set the uploaded bundle as the new rollout. Reuses the previous percentage unless --rollout or --rollout-percentage-bps is also set").option("--rollout-cache-ttl-seconds <rolloutCacheTtlSeconds>","Cloudflare rollout decision cache TTL in seconds",(A)=>Number.parseInt(A,10)).option("-e, --external <url>","Link to external URL instead of upload to Capgo Cloud").option("--iv-session-key <key>","Set the IV and session key for bundle URL external").option("--s3-region <region>","Region for your S3 bucket").option("--s3-apikey <apikey>","API key for your S3 endpoint").option("--s3-apisecret <apisecret>","API secret for your S3 endpoint").option("--s3-endpoint <s3Endpoint>","URL of S3 endpoint").option("--s3-bucket-name <bucketName>","Name for your AWS S3 bucket").option("--s3-port <port>","Port for your S3 endpoint").option("--no-s3-ssl","Disable SSL for S3 upload").option("--key-v2 <key>","Custom path for private signing key (v2 system)").option("--key-data-v2 <keyDataV2>","Private signing key (v2 system)").option("--bundle-url","Prints bundle URL into stdout").option("--no-key","Ignore signing key and send clear update").option("--no-code-check","Ignore checking if notifyAppReady() is called in source code and index present in root folder").option("--ignore-notify-app-ready",SQ.ignoreNotifyAppReady).option("--display-iv-session","Show in the console the IV and session key used to encrypt the update").option("-b, --bundle <bundle>","Bundle version number of the bundle to upload").option("--link <link>","Link to external resource (e.g. GitHub release)").option("--comment <comment>","Comment about this version, could be a release note, a commit hash, a commit message, etc.").option("--min-update-version <minUpdateVersion>","Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel").option("--auto-min-update-version","Set the min update version based on native packages").option("--ignore-metadata-check","Ignores the metadata (node_modules) check when uploading").option("--fail-on-incompatible","Fail the upload (exit non-zero) instead of uploading when the bundle is incompatible with the channel's current native packages. In an interactive terminal you can still choose a native build; declining fails. Cannot be combined with --ignore-metadata-check or --accept-incompatible.").option("--accept-incompatible",`${SQ.acceptIncompatible} Cannot be combined with --fail-on-incompatible or --ignore-metadata-check.`).option("--ignore-checksum-check","Ignores the checksum check when uploading").option("--force-crc32-checksum","Force CRC32 checksum for upload (override auto-detection)").option("--timeout <timeout>","Timeout for the upload process in seconds").option("--multipart","[DEPRECATED] Use --tus instead. Uses multipart protocol for S3 uploads").option("--zip","Upload the bundle using zip to Capgo cloud (legacy)").option("--tus","Upload the bundle using TUS to Capgo cloud").option("--tus-chunk-size <tusChunkSize>","Chunk size in bytes for TUS resumable uploads (default: auto)").option("--partial","[DEPRECATED] Use --delta instead. Upload incremental updates").option("--partial-only","[DEPRECATED] Use --delta-only instead. Upload only incremental updates, skip full bundle").option("--delta","Upload delta updates (only changed files) for instant, super-fast updates instead of big zip downloads. Capgo refuses delta uploads over 10,000 files (delta tracks each file); use --no-delta for a full zip, or reduce files in your web build.").option("--delta-only","Upload only delta updates without full bundle for maximum speed (useful for large apps)").option("--no-delta","Disable delta updates even if instant updates are enabled").option("--encrypted-checksum <encryptedChecksum>","An encrypted checksum (signature). Used only when uploading an external bundle.").option("--auto-set-bundle","Set the bundle version in Capacitor config").addOption(new n5("--auto-bump [level]","Auto-increment bundle version from the latest remote channel/app version. Level: major, minor (default), patch|fix, metadata (prerelease), or ai").preset("minor").argParser((A)=>{let Q=_R(A);if(!Q)throw new vD(`Invalid --auto-bump level "${A}". Allowed: major, minor, patch, fix, metadata, ai.`);return Q})).option("--capacitor-config <path>",SQ.capacitorConfig).option("--dry-upload","Dry upload the bundle process: add the row in database without uploading files or updating channels (Used by Capgo for internal testing)").option("--package-json <packageJson>",SQ.packageJson).option("--node-modules <nodeModules>",SQ.nodeModules).option("--encrypt-delta","Encrypt delta update files (auto-enabled for updater >= 6.14.4)").option("--encrypt-partial","[DEPRECATED] Use --encrypt-delta instead. Encrypt delta update files").option("--delete-linked-bundle-on-upload","Locates the currently linked bundle in the channel you are trying to upload to, and deletes it").option("--no-brotli-patterns <patterns>",'Files to exclude from Brotli compression (comma-separated globs, e.g., "*.jpg,*.png")').option("--disable-brotli","Completely disable brotli compression even if updater version supports it").option("--version-exists-ok","Exit successfully if bundle version already exists, useful for CI/CD workflows with monorepos").option("--self-assign","Allow devices to auto-join this channel (updates channel setting)").option("--qr-preview","Print a terminal QR code for this bundle preview after upload").option("--send-update-notification","Send a native update-check notification to devices after updating linked channel bundles").option("--supa-host <supaHost>",SQ.supaHost).option("--supa-anon <supaAnon>",SQ.supaAnon).option("--verbose",SQ.verbose);BD.command("compatibility [appId]").description(`\uD83E\uDDEA Check compatibility of a bundle with a specific channel in Capgo Cloud to ensure updates are safe.
1947
1947
 
1948
1948
  Example: npx @capgo/cli@latest bundle compatibility com.example.app --channel production`).action(VOQ).option("-a, --apikey <apikey>",SQ.apikey).option("-c, --channel <channel>","Channel to check the compatibility with").option("--text","Output text instead of emojis").option("--package-json <packageJson>",SQ.packageJson).option("--node-modules <nodeModules>",SQ.nodeModules).option("--supa-host <supaHost>",SQ.supaHost).option("--supa-anon <supaAnon>",SQ.supaAnon);BD.command("releaseType [appId]").description(`\uD83E\uDDED Print "native" or "OTA" based on compatibility with a channel's latest metadata.
1949
1949