@allscale/cli 0.1.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.
Files changed (38) hide show
  1. package/README.md +482 -0
  2. package/bin/dev.js +11 -0
  3. package/bin/run-oclif.js +69 -0
  4. package/bin/run.js +6 -0
  5. package/dist/commands/build-info.js +16 -0
  6. package/dist/commands/claim-link/claim.js +17 -0
  7. package/dist/commands/claim-link/create.js +75 -0
  8. package/dist/commands/claim-link/get.js +18 -0
  9. package/dist/commands/claim-link/list.js +18 -0
  10. package/dist/commands/claim-link/preview.js +18 -0
  11. package/dist/commands/claim-link/status.js +17 -0
  12. package/dist/commands/describe.js +16 -0
  13. package/dist/commands/device-login.js +40 -0
  14. package/dist/commands/invoice/get.js +18 -0
  15. package/dist/commands/invoice/list.js +19 -0
  16. package/dist/commands/invoice/pay.js +66 -0
  17. package/dist/commands/invoice/received.js +19 -0
  18. package/dist/commands/invoice/send.js +167 -0
  19. package/dist/commands/invoice/sent.js +18 -0
  20. package/dist/commands/invoice/update.js +18 -0
  21. package/dist/commands/logout.js +17 -0
  22. package/dist/commands/operations.js +16 -0
  23. package/dist/commands/otp-login.js +23 -0
  24. package/dist/commands/otp-send.js +17 -0
  25. package/dist/commands/payout/send.js +23 -0
  26. package/dist/commands/payout/status.js +18 -0
  27. package/dist/commands/scope.js +22 -0
  28. package/dist/commands/store/create.js +28 -0
  29. package/dist/commands/transaction/get.js +18 -0
  30. package/dist/commands/transaction/list.js +18 -0
  31. package/dist/commands/wallet/list.js +18 -0
  32. package/dist/commands/wallet/send.js +63 -0
  33. package/dist/commands/whoami.js +18 -0
  34. package/dist/hooks/version-suffix.js +2 -0
  35. package/dist/index.js +17 -0
  36. package/dist/lib/help.js +3 -0
  37. package/oclif.manifest.json +3329 -0
  38. package/package.json +135 -0
@@ -0,0 +1,16 @@
1
+ "use strict";var Ye=Object.create;var U=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var ze=(e,n)=>{for(var t in n)U(e,t,{get:n[t],enumerable:!0})},pe=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of je(n))!Ke.call(e,a)&&a!==t&&U(e,a,{get:()=>n[a],enumerable:!(i=He(n,a))||i.enumerable});return e};var y=(e,n,t)=>(t=e!=null?Ye(qe(e)):{},pe(n||!e||!e.__esModule?U(t,"default",{value:e,enumerable:!0}):t,e)),We=e=>pe(U({},"__esModule",{value:!0}),e);var Vn={};ze(Vn,{default:()=>V});module.exports=We(Vn);var f=require("@oclif/core");var ce="public",me="https://app.allscale.io";var fe=["https://app.allscale.io"];var G="Override the API base URL (public builds accept only https://app.allscale.io)";var M="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function ye(e){try{let n=new URL(e);return n.username.length>0||n.password.length>0?null:n.protocol==="https:"?n:null}catch{return null}}function Ae(e){return ye(e)!==null}function J(e){let n=ye(e);return n!==null&&fe.includes(n.origin)}function C(){return"".trim()||void 0}function b(){return"public"}function _e(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function Le(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return Y()}function Y(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let i=JSON.parse(e);if(!Array.isArray(i))return[];let a=[];for(let o of i){if(typeof o!="object"||o===null)continue;let{base:r,key:s,keyId:u}=o;if(typeof r!="string"||r.trim().length===0||typeof s!="string"||s.trim().length===0)continue;let m=typeof u=="string"?u.trim():"";a.push({base:r.trim(),key:s,keyId:m.length>0?m:"cli-1"})}return a}catch{return[]}let n=process.env.ALLSCALE_SIGNING_KEY??"",t=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(n.trim().length>0&&t.length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:t,key:n,keyId:i&&i.length>0?i:"cli-1"}]}return[]}var Te="allscale device-login";var Ze={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},Xe=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function q(e){return(typeof e=="string"?e:String(e??"")).replace(Xe,"")}var Qe=64;function H(e,n=new Map,t=0){if(typeof e=="string")return q(e);if(e===null||typeof e!="object")return e;let i=n.get(e);if(i!==void 0)return i;if(t>=Qe)return e;if(Array.isArray(e)){let r=[];n.set(e,r);for(let s of e)r.push(H(s,n,t+1));return r}let a=Object.getPrototypeOf(e);if(a!==Object.prototype&&a!==null)return e;let o={};n.set(e,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{value:H(s,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var d=class extends Error{code;details;constructor(n,t,i){super(q(t)),this.code=n,this.details=i&&H(i),this.name="AllscaleError"}get exitCode(){return Ze[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Se(e){if(e instanceof d)return e;if(e instanceof Error){if(tn(e)){let n=on(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new d("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new d("internal",e.message,{name:e.name})}return new d("internal","Unknown error",{value:String(e)})}var en=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),nn=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function tn(e){if(an(e))return!0;let n=e.name??"";return en.has(n)?n==="CLIError"?j(e,"parse")||ge(e.message):!0:ge(e.message)}function an(e){if(!j(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&j(e,"parse")}function ge(e){return e?q(e).split(`
2
+ `).some(n=>nn.some(t=>t.test(n.trim()))):!1}function j(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function on(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function ke(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var l=y(require("fs")),P=y(require("path")),Ie=y(require("crypto"));var rn="...<truncated>",sn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,ln=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Q=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,K=String.raw`(?:proxy[_-]?)?authorization`,dn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${K}"|'${K}'|${K})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Q}`,"gi"),un=/\b(https?:\/\/)[^\s/?#]+@/gi,z=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,pn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${z}"|'${z}'|${z})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Q}`,"gi"),W=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,cn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${W}"|'${W}'|${W})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Q}`,"g");function he(e){return e.replace(un,"$1<redacted>@").replace(sn,"<redacted-jwt>").replace(dn,"$1$2$3<redacted>").replace(pn,"$1$2<redacted>").replace(cn,"$1$2<redacted>").replace(ln,"Bearer <redacted>")}function Ne(e){let n="";for(let t of e){let i=t.codePointAt(0),a=i<=8||i>=11&&i<=12||i>=14&&i<=31||i>=127&&i<=159;n+=a?`\\u${i.toString(16).padStart(4,"0")}`:t}return n}function Ce(e,n,t=rn){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let s="",u=0;for(let m of t){let A=Buffer.byteLength(m,"utf8");if(u+A>n)break;s+=m,u+=A}return s}let a=n-i,o="",r=0;for(let s of e){let u=Buffer.byteLength(s,"utf8");if(r+u>a)break;o+=s,r+=u}return`${o}${t}`}function c(e,n=16384){return Ce(Ne(he(e)),n)}var Z=100,mn=8,fn=8*1024;function B(){return{remaining:fn}}function X(e,n){let t=Math.min(16384,n.remaining),i=Ce(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function _(e,n,t=0,i={}){if(t>mn)return X("<truncated>",n);if(typeof e=="string"){let a=he(e);return X(i.escapeControls?Ne(a):a,n)}if(Array.isArray(e)){let a=e.slice(0,Z),o=a.map(r=>_(r,n,t+1,i));return e.length>a.length&&o.push(X(`<${e.length-a.length} more items truncated>`,n)),o}if(e!==null&&typeof e=="object"){let a=Object.create(null),o=Object.entries(e);for(let[r,s]of o.slice(0,Z))a[r]=_(s,n,t+1,i);return o.length>Z&&(a.output_truncated=!0),a}return e}var ee=require("process");var ne=!1;function te(e){ne=e}function Ee(){return ne}var be="1";function T(e,n){if(ne){let t={...e};delete t.version;let i=B(),a={event:t.event,...t},o=_(a,i,0,{escapeControls:!0}),r=JSON.stringify({version:be,...o});Buffer.byteLength(r,"utf8")+1>65536&&(r=JSON.stringify({version:be,event:o.event,output_truncated:!0})),ee.stderr.write(`${r}
4
+ `)}else ee.stderr.write(n)}var Oe="2",g=null,p=null,S=!1;function yn(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let n=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(n){let t=new Date().toISOString().replace(/[:.]/g,"-"),i=Ie.randomBytes(4).toString("hex");return P.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var ie=64*1024*1024,An=null;function Re(){if(S)return;let e=yn();if(!e)return;g=null;let n=null;try{if((An??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let t=P.dirname(e);if(l.mkdirSync(t,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let s=l.statSync(t),u=s.mode&511;if(!s.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let i=l.constants.O_NOFOLLOW??0;n=l.openSync(e,l.constants.O_APPEND|l.constants.O_CREAT|l.constants.O_WRONLY|(l.constants.O_NONBLOCK??0)|i,384);let a=l.fstatSync(n),o=l.lstatSync(e);if(!a.isFile()||o.isSymbolicLink()||o.dev!==a.dev||o.ino!==a.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&a.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let r=a.mode&511;if((r&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${r.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);l.fchmodSync(n,384)}catch(t){if(n!==null)try{l.closeSync(n)}catch{}T({event:"sidecar_disabled",reason:"open_failed",detail:c(`sidecar path '${e}' could not be opened safely (${t.message})`)},`${c(`[allscale] sidecar path '${e}' could not be opened safely (${t.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}g=e,p=n,S=!0}var _n=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Ln(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return _n.some(t=>t.test(n))}function Tn(e){try{let n=new URL(e),t=n.username.length>0||n.password.length>0;t&&(n.username="",n.password="");let i=n.pathname;n.pathname=gn(n.pathname);let a=t;n.pathname!==i&&(a=!0);for(let[o]of n.searchParams)Ln(o)&&(n.searchParams.set(o,"<redacted>"),a=!0);return a?n.toString():e}catch{return e}}function gn(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Sn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Tn(e.url)}:e}function kn(e){let n=new Date().toISOString(),t=e,{type:i,...a}=t,o=_(a,B()),r=JSON.stringify({version:Oe,timestamp:n,type:i,...o});return Buffer.byteLength(r,"utf8")+1>65536&&(r=JSON.stringify({version:Oe,timestamp:n,type:i,output_truncated:!0})),r}function E(e){if(!S||!g||p===null)return;let n=Sn(e),t=kn(n);try{if(l.fstatSync(p).size+Buffer.byteLength(t,"utf8")+1>ie){S=!1;try{l.closeSync(p)}catch{}p=null,T({event:"sidecar_disabled",reason:"size_limit",...g===null?{}:{path:c(g)},max_bytes:ie},`${c(`[allscale] sidecar exceeded ${ie} bytes; disabling it for the rest of this run. Rotate or remove ${g}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}l.appendFileSync(p,`${t}
7
+ `)}catch(i){if(S=!1,p!==null){try{l.closeSync(p)}catch{}p=null}try{T({event:"sidecar_disabled",reason:"write_failed",detail:c(i.message)},`${c(`[allscale] sidecar write failed (${i.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}function we(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function v(){if(S=!1,p!==null){try{l.closeSync(p)}catch{}p=null}}function Ue(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||we()||!n}var O=C()??me,I={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function x(e){return Ae(e)?new URL(e).origin:null}function h(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Be(){let e=process.env[I.TOKEN]?.trim();return e&&e.length>0?e:void 0}function ae(){let e=process.env[I.PROFILE]?.trim();return e&&e.length>0?e:void 0}function D(){let e=process.env[I.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Pe(){let e=process.env[I.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ve(){let e=process.env[I.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function xe(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:a}=e;if(C()===void 0&&O!==""&&"".length!==0&&!t&&a!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${O} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
11
+ the old default rather than a deliberate choice.
12
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
+ To move to production, run: ${Te} --api-base ${O}
14
+ `}var N=y(require("fs")),De=y(require("os")),oe=y(require("path")),re=y(require("@iarna/toml"));var Cn=".allscale",bn="config.toml";function En(){return oe.join(De.homedir(),Cn)}function On(){return oe.join(En(),bn)}function Fe(){let e=On();if(!N.existsSync(e))return{};let n=N.readFileSync(e,"utf-8");try{return re.parse(n)}catch(t){throw new d("internal",`Failed to parse ${e}: ${t.message}`)}}function $e(e,n){return e.profile?.[n]}function Ve(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new d("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function se(e){if(!J(e))throw new d("input.invalid",`Refusing to send credentials to API base ${h(e)}. `+M)}function Ge(e){let n=C();if(n===void 0||_e(e))return;let t=x(e),i=Le();if(i.length>0){let o=i.map(s=>x(s.base)).filter(s=>s!==null);if(t!==null&&o.includes(t))return;let r=i.map(s=>h(s.base)).join(", ");throw new d("input.invalid",`Refusing to send to ${h(e)} \u2014 this build only signs for: ${r}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let a=x(n);if(!(t!==null&&t===a))throw new d("input.invalid",`Refusing to send to ${h(e)} \u2014 this build only signs for ${h(n)}. Re-login against this build's environment, or use a build for that one.`)}var In=require("@noble/hashes/sha3");var Me=["USDT","USDC"];var Et=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var w=require("@oclif/core"),R=class e extends f.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:f.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:f.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:b()==="public"}),"api-base":f.Flags.string({description:G,helpGroup:"GLOBAL",hidden:b()==="public"}),"insecure-storage":f.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{te(this.jsonEnabled()),Re(),E({type:"session-start",command:this.id??"",argv:wn(this.argv)});let n=this.constructor;if(b()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new d("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new d("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!n.isLocalOnly&&D()!==void 0)throw new d("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(n.requiresEscapeHatch&&!ve())throw this.argv.length>0&&await this.parse(),new d("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let t=Ue(this.jsonEnabled()),i=this.argv.length===0&&!t&&$n(n)?this.config.findCommand(this.id??""):void 0;if(i){v();let o=await(0,f.loadHelpClass)(this.config),r=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,r).showCommandHelp(i,this.config.topics);return}let a=await this.runCommand();return E({type:"command-end",ok:!0}),v(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||ke(a),{data:a})}catch(n){let t=Se(n);E({type:"error",code:t.code,message:c(t.message)}),E({type:"command-end",ok:!1,exitCode:t.exitCode}),v(),this.emitError(t),process.exitCode=t.exitCode;return}finally{te(!1)}}resolveSessionApiBaseChain(n){let t=Fe(),i=n.profile??void 0,a=n["api-base"]??void 0,o=i!==void 0||ae()!==void 0,r=Ve(t,i,ae()),s=$e(t,r),u=a??D(),m=u??s?.api_base??O,A=xe({resolvedApiBase:m,fromExplicitOverride:u!==void 0,profileApiBase:s?.api_base,profileApiBaseSource:s?.api_base_source});return A&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,T({event:"legacy_staging_profile",api_base:m,profile:r},A)),{apiBase:m,explicitApiBase:u,profileApiBase:s?.api_base,profile:r,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||se(t),t}resolveContext(n){if(b()==="public"){if(n.token!==void 0)throw new d("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(n["api-base"]!==void 0)throw new d("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&D()!==void 0)throw new d("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let t=n.token??void 0,i=!!n["insecure-storage"],{apiBase:a,explicitApiBase:o,profile:r,profileApiBase:s,profileExplicit:u}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(se(a),Ge(a)),{apiBase:a,profile:r,token:t??Be(),insecureStorage:i||Pe(),apiBaseSource:o!==void 0?"explicit":s!==void 0?"profile":"default",profileExplicit:u}}emitError(n){process.stderr.write(`${Fn(n)}
15
+ `)}},$=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Rn=new Set(Array.from($).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function wn(e){let n=[];for(let t=0;t<e.length;t+=1){let i=e[t];if(i.startsWith("-")){let a=i.indexOf("=");if(a!==-1){let o=i.slice(0,a);if($.has(o)){n.push(`${o}=<redacted>`);continue}}}if($.has(i)){n.push(i),t+1<e.length&&($.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2&&i[1]!=="="){let a=i.slice(0,2);if(Rn.has(a)){n.push(`${a}<redacted>`);continue}}n.push(i)}return n}var Un=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Bn(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Un.test(n)}var Pn=/_(removed|cleared|count|total)$/i;function vn(e,n){return typeof n=="number"&&Pn.test(e)}var xn=new Set(Me);function Dn(e,n){return e==="token_symbol"&&typeof n=="string"&&xn.has(n)}var F=100;function le(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,F),i=t.map(a=>le(a,n+1));return e.length>t.length&&i.push(`<${e.length-t.length} more items truncated>`),i}if(e!==null&&typeof e=="object"){let t=Object.create(null),i=Object.entries(e);for(let[a,o]of i.slice(0,F))t[a]=Bn(a)&&!vn(a,o)&&!Dn(a,o)?"<redacted>":le(o,n+1);if(i.length>F){let a="<truncated>";for(;a in t;)a=`<${a}>`;t[a]=`${i.length-F} more keys`}return t}return typeof e=="string"?c(e):e}function Fn(e){let n=Ee()?void 0:2,t=le(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:c(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function $n(e){if(e.requiresInput===!0)return!0;let n=a=>typeof a=="object"&&a!==null&&a.required===!0,t=e.flags??{},i=e.args??{};return Object.values(t).some(a=>n(a))||Object.values(i).some(a=>n(a))}var Je=[{name:"create_claim_link",kind:"mutation",description:"Create a single App claim link. Returns the pending link, funding address, exact deposit total, and bearer claim URL. The link becomes available after the sender's deposit is confirmed. No claim-back.",args:[{name:"input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateClaimLinkInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"CreateClaimLinkResult",ofType:null}},deprecated:null},{name:"create_contact",kind:"mutation",description:"create a new contact",args:[{name:"create_input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateContactInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"create_payment",kind:"mutation",description:"create a new payment",args:[{name:"payment",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreatePaymentInput",ofType:null}},defaultValue:null},{name:"wallet_ids",description:null,type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"create_store",kind:"mutation",description:"create store",args:[{name:"input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateStoreInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"StoreCreateResult",ofType:null}},deprecated:null},{name:"update_payment",kind:"mutation",description:"update an existing payment status by its ID",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"payment",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"UpdatePaymentInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"activities",kind:"query",description:"Get current user's activity list with multi-dimensional filters (type, status, contact, wallet, time range, amount range)",args:[{name:"filter_input",description:null,type:{kind:"INPUT_OBJECT",name:"ActivityFilterInput",ofType:null},defaultValue:"null"},{name:"skip",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"limit",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"20"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ActivityItemPaginatedResponse",ofType:null}},deprecated:null},{name:"auto_payout_session_status",kind:"query",description:"Return the current merchant auto-payout status, expiry, total/used/remaining USD cap, per-transaction limit, and authorized chain/token pairs. Merchants without an active setup receive provisioned=false with null money/expiry fields and no pairs.",args:[],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"AutoPayoutSessionStatus",ofType:null}},deprecated:null},{name:"business",kind:"query",description:"get one business by it's id",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Business",ofType:null}},deprecated:null},{name:"business_transaction_records",kind:"query",description:"get transaction records for business",args:[{name:"direction",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"transaction_type",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"status",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"TransactionPaginatedResponse",ofType:null}},deprecated:null},{name:"business_wallets",kind:"query",description:"List the CALLER'S OWN non-custodial wallets (id, chain, address, coin balances). Takes no business id \u2014 the owner is derived from the authenticated identity, so there is no caller-supplied id to mismatch and no way to read another merchant's wallets. Returns [] when the account has no wallet yet.",args:[],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"WalletEmbedded",ofType:null}}}},deprecated:null},{name:"claim_link",kind:"query",description:"Get one of the caller's own claim links by id (sender surface). A non-owned or unknown id returns CLAIM_LINK_NOT_AVAILABLE \u2014 no existence leak.",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},deprecated:null},{name:"claim_link_fee_preview",kind:"query",description:"Preview the Amount / Network fee / Service fee / Total breakdown without creating a link. Asset and precision validation matches create, but create-time amount and rate limits are enforced only when the link is created, so a successful preview does not guarantee create will succeed. per_transfer_gas is the withdrawal gas estimate in token units.",args:[{name:"amount",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"token_symbol",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"per_transfer_gas",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},deprecated:null},{name:"contact",kind:"query",description:"get one contact by it's id",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"contact_by_email",kind:"query",description:"get one contact by it's email",args:[{name:"email",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"contacts",kind:"query",description:"get multi contacts by owner business id",args:[{name:"owner_business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ContactPaginatedResponse",ofType:null}},deprecated:null},{name:"my_claim_links",kind:"query",description:"List the caller's claim links, newest first. Optional status and link_source filters narrow the results; query_input controls pagination, ordering, and the created_at time range.",args:[{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"},{name:"status",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"link_source",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkPaginatedResponse",ofType:null}},deprecated:null},{name:"my_transactions",kind:"query",description:"get one user's successful transactions by query",args:[{name:"query_input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"TransactionPaginatedResponse",ofType:null}},deprecated:null},{name:"payment",kind:"query",description:"get one payment by its ID",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"payments",kind:"query",description:"All payments by business ID as sender or recipient",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"recipient_payments",kind:"query",description:"Get multiple payments by business ID as recipient",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"sender_payments",kind:"query",description:"Get multiple payments by business ID as sender",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"transaction",kind:"query",description:"get one transaction by id_str",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Transaction",ofType:null}},deprecated:null}];var de={source:"public-cli-contract",synced_at:"2026-08-03T03:01:54.000Z"};var V=class e extends R{static requiresEscapeHatch=!0;static isLocalOnly=!0;static description="List every operation exposed by the schema (queries and mutations). Disabled by default (exit 10); set ALLSCALE_ALLOW_RAW=1 to enable.";static examples=["$ allscale operations","$ allscale operations --kind mutation","$ allscale operations --grep invoice"];static flags={kind:w.Flags.string({char:"k",description:"Filter by operation kind",options:["query","mutation"]}),grep:w.Flags.string({char:"g",description:"Filter by substring match against name + description (case-insensitive)"}),...R.baseFlags};async runCommand(){let{flags:n}=await this.parse(e),t=n.kind,i=n.grep?.toLowerCase(),a=Je.filter(r=>!(t&&r.kind!==t||i&&!`${r.name} ${r.description??""}`.toLowerCase().includes(i))),o={query:0,mutation:0};for(let r of a)o[r.kind]=(o[r.kind]??0)+1;return{total:a.length,by_kind:o,schema_source:de.source,schema_synced_at:de.synced_at,operations:a.map(r=>({name:r.name,kind:r.kind,description:r.description,arg_names:r.args.map(s=>s.name),return_type:ue(r.returnType)}))}}};function ue(e){return e.kind==="NON_NULL"&&e.ofType?`${ue(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${ue(e.ofType)}]`:e.name??"Unknown"}
16
+ //# sourceMappingURL=operations.js.map
@@ -0,0 +1,23 @@
1
+ "use strict";var Un=Object.create;var oe=Object.defineProperty;var $n=Object.getOwnPropertyDescriptor;var Fn=Object.getOwnPropertyNames;var Mn=Object.getPrototypeOf,Gn=Object.prototype.hasOwnProperty;var Kn=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},wt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fn(t))!Gn.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(r=$n(t,i))||r.enumerable});return e};var w=(e,t,n)=>(n=e!=null?Un(Mn(e)):{},wt(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),Yn=e=>wt(oe({},"__esModule",{value:!0}),e);var ki={};Kn(ki,{default:()=>ve});module.exports=Yn(ki);var Pe=require("process");var I=require("@oclif/core");var St="public",Et="https://app.allscale.io";var bt=["https://app.allscale.io"];var xe="Override the API base URL (public builds accept only https://app.allscale.io)";var Be="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function At(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function kt(e){return At(e)!==null}function De(e){let t=At(e);return t!==null&&bt.includes(t.origin)}function W(){return"".trim()||void 0}function J(){return"public"}function R(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function $e(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Ue()}function Ue(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Lt="allscale device-login";function Ot(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}var Hn={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},jn=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Ge(e){return(typeof e=="string"?e:String(e??"")).replace(jn,"")}var qn=64;function Fe(e,t=new Map,n=0){if(typeof e=="string")return Ge(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=qn)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Fe(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:Fe(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super(Ge(n)),this.code=t,this.details=r&&Fe(r),this.name="AllscaleError"}get exitCode(){return Hn[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function It(e){if(e instanceof l)return e;if(e instanceof Error){if(zn(e)){let t=Xn(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var Wn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Jn=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function zn(e){if(Vn(e))return!0;let t=e.name??"";return Wn.has(t)?t==="CLIError"?Me(e,"parse")||Tt(e.message):!0:Tt(e.message)}function Vn(e){if(!Me(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Me(e,"parse")}function Tt(e){return e?Ge(e).split(`
2
+ `).some(t=>Jn.some(n=>n.test(t.trim()))):!1}function Me(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Xn(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ct(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var f=w(require("fs")),ae=w(require("path")),Dt=w(require("crypto"));var Zn="...<truncated>",Qn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,er=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,We=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ke=String.raw`(?:proxy[_-]?)?authorization`,tr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ke}"|'${Ke}'|${Ke})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${We}`,"gi"),nr=/\b(https?:\/\/)[^\s/?#]+@/gi,Ye=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,rr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ye}"|'${Ye}'|${Ye})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${We}`,"gi"),He=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${We}`,"g");function Rt(e){return e.replace(nr,"$1<redacted>@").replace(Qn,"<redacted-jwt>").replace(tr,"$1$2$3<redacted>").replace(rr,"$1$2<redacted>").replace(ir,"$1$2<redacted>").replace(er,"Bearer <redacted>")}function Pt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function vt(e,t,n=Zn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let m=Buffer.byteLength(d,"utf8");if(u+m>t)break;c+=d,u+=m}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function S(e,t=16384){return vt(Pt(Rt(e)),t)}var je=100,or=8,sr=8*1024;function se(){return{remaining:sr}}function qe(e,t){let n=Math.min(16384,t.remaining),r=vt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function $(e,t,n=0,r={}){if(n>or)return qe("<truncated>",t);if(typeof e=="string"){let i=Rt(e);return qe(r.escapeControls?Pt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,je),o=i.map(s=>$(s,t,n+1,r));return e.length>i.length&&o.push(qe(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,je))i[s]=$(c,t,n+1,r);return o.length>je&&(i.output_truncated=!0),i}return e}var Je=require("process");var ze=!1;function Ve(e){ze=e}function xt(){return ze}var Nt="1";function M(e,t){if(ze){let n={...e};delete n.version;let r=se(),i={event:n.event,...n},o=$(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Nt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Nt,event:o.event,output_truncated:!0})),Je.stderr.write(`${s}
4
+ `)}else Je.stderr.write(t)}var Bt="2",G=null,b=null,K=!1;function ar(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Dt.randomBytes(4).toString("hex");return ae.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Xe=64*1024*1024,lr=null;function Ut(){if(K)return;let e=ar();if(!e)return;G=null;let t=null;try{if((lr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ae.dirname(e);if(f.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=f.statSync(n),u=c.mode&511;if(!c.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let r=f.constants.O_NOFOLLOW??0;t=f.openSync(e,f.constants.O_APPEND|f.constants.O_CREAT|f.constants.O_WRONLY|(f.constants.O_NONBLOCK??0)|r,384);let i=f.fstatSync(t),o=f.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let s=i.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);f.fchmodSync(t,384)}catch(n){if(t!==null)try{f.closeSync(t)}catch{}M({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${S(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}G=e,b=t,K=!0}var cr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function ur(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return cr.some(n=>n.test(t))}function $t(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=dr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)ur(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function dr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function pr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:$t(e.url)}:e}function fr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=$(i,se()),s=JSON.stringify({version:Bt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Bt,timestamp:t,type:r,output_truncated:!0})),s}function Y(e){if(!K||!G||b===null)return;let t=pr(e),n=fr(t);try{if(f.fstatSync(b).size+Buffer.byteLength(n,"utf8")+1>Xe){K=!1;try{f.closeSync(b)}catch{}b=null,M({event:"sidecar_disabled",reason:"size_limit",...G===null?{}:{path:S(G)},max_bytes:Xe},`${S(`[allscale] sidecar exceeded ${Xe} bytes; disabling it for the rest of this run. Rotate or remove ${G}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}f.appendFileSync(b,`${n}
7
+ `)}catch(r){if(K=!1,b!==null){try{f.closeSync(b)}catch{}b=null}try{M({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var Ft=$t;function Mt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function le(){if(K=!1,b!==null){try{f.closeSync(b)}catch{}b=null}}function Gt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Mt()||!t}var V=W()??Et,j={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function ce(e){return kt(e)?new URL(e).origin:null}function q(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Kt(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Ze(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ue(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Yt(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Ht(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function jt(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function qt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(W()===void 0&&V!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${V} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
11
+ the old default rather than a deliberate choice.
12
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
+ To move to production, run: ${Lt} --api-base ${V}
14
+ `}var O=w(require("fs")),Wt=w(require("os")),Qe=w(require("path")),de=w(require("@iarna/toml"));var mr=".allscale",_r="config.toml";function pe(){return Qe.join(Wt.homedir(),mr)}function fe(){return Qe.join(pe(),_r)}function X(){let e=fe();if(!O.existsSync(e))return{};let t=O.readFileSync(e,"utf-8");try{return de.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Jt(e){let t=pe();O.existsSync(t)||O.mkdirSync(t,{recursive:!0,mode:448});let n=de.stringify(e);O.writeFileSync(fe(),n,{mode:384})}function zt(e,t){return e.profile?.[t]}function Vt(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function Xt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function ge(e){if(!De(e))throw new l("input.invalid",`Refusing to send credentials to API base ${q(e)}. `+Be)}function et(e){let t=W();if(t===void 0||R(e))return;let n=ce(e),r=z();if(r.length>0){let o=r.map(c=>ce(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>q(c.base)).join(", ");throw new l("input.invalid",`Refusing to send to ${q(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=ce(t);if(!(n!==null&&n===i))throw new l("input.invalid",`Refusing to send to ${q(e)} \u2014 this build only signs for ${q(t)}. Re-login against this build's environment, or use a build for that one.`)}var yr=require("@noble/hashes/sha3");var Zt=["USDT","USDC"];var po=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var k=require("@oclif/core"),Z=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:J()==="public"}),"api-base":I.Flags.string({description:xe,helpGroup:"GLOBAL",hidden:J()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ve(this.jsonEnabled()),Ut(),Y({type:"session-start",command:this.id??"",argv:Sr(this.argv)});let t=this.constructor;if(J()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ue()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!jt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=Gt(this.jsonEnabled()),r=this.argv.length===0&&!n&&Ir(t)?this.config.findCommand(this.id??""):void 0;if(r){le();let o=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return Y({type:"command-end",ok:!0}),le(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ct(i),{data:i})}catch(t){let n=It(t);Y({type:"error",code:n.code,message:S(n.message)}),Y({type:"command-end",ok:!1,exitCode:n.exitCode}),le(),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ve(!1)}}resolveSessionApiBaseChain(t){let n=X(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Ze()!==void 0,s=Xt(n,r,Ze()),c=zt(n,s),u=i??ue(),d=u??c?.api_base??V,m=qt({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return m&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,M({event:"legacy_staging_profile",api_base:d,profile:s},m)),{apiBase:d,explicitApiBase:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||ge(n),n}resolveContext(t){if(J()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ue()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(ge(i),et(i)),{apiBase:i,profile:s,token:n??Kt(),insecureStorage:r||Yt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Or(t)}
15
+ `)}},me=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),wr=new Set(Array.from(me).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Sr(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(me.has(o)){t.push(`${o}=<redacted>`);continue}}}if(me.has(r)){t.push(r),n+1<e.length&&(me.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(wr.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Er=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function br(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Er.test(t)}var Ar=/_(removed|cleared|count|total)$/i;function kr(e,t){return typeof t=="number"&&Ar.test(e)}var Lr=new Set(Zt);function Tr(e,t){return e==="token_symbol"&&typeof t=="string"&&Lr.has(t)}var he=100;function tt(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,he),r=n.map(i=>tt(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,he))n[i]=br(i)&&!kr(i,o)&&!Tr(i,o)?"<redacted>":tt(o,t+1);if(r.length>he){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-he} more keys`}return n}return typeof e=="string"?S(e):e}function Or(e){let t=xt()?void 0:2,n=tt(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Ir(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function Qt(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),s=t.get(i)??new Set;s.add(o),t.set(i,s)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var en=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","store:all","wallet:read_only"]);var gn=w(require("path"));var it=require("crypto"),a=w(require("fs")),h=w(require("path"));var _e=1024*1024,Cr=5e3,Rr=20,Pr=3e4,nt=4096,vr=new Int32Array(new SharedArrayBuffer(4)),Q=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ye(e){return e instanceof Q}var E=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Nr=null;function v(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function we(){return(Nr??process.platform)!=="win32"}function cn(){if(!we())throw v()}function un(e){try{return a.default.lstatSync(e),!1}catch(t){if(!g(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(h.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(g(t,"ENOENT"))return!0;throw t}}function g(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ee(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function te(e,t){return e.dev===t.dev&&e.ino===t.ino}function xr(e){Atomics.wait(vr,0,0,e)}function dn(e){try{return process.kill(e,0),!0}catch(t){return!g(t,"ESRCH")}}function Br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tn(e,t){let n=h.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&g(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!te(o,s))throw new Error("credential-store parent changed while it was being inspected");ee(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&h.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function C(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&g(o,"ENOENT")?new E:o}if(!te(n,i))throw r.retryOnPathChange?new E:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new Q;if(ee(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Dr(e,t){if(t.size>_e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(_e+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>_e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function nn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(g(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(g(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=C(e,t,n);return Dr(t,r)}finally{t!==null&&a.default.closeSync(t)}}function rn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(g(i,"ENOENT")&&un(e))return;throw i}let n=a.default.fstatSync(t),r=C(e,t,n);N(e,r)}finally{t!==null&&a.default.closeSync(t)}fn(h.dirname(e))}function Ur(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(g(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new Q;ee(t,"credential-store replacement target")}function $r(e,t){for(let n=0;n<8;n+=1){let r=(0,it.randomBytes)(12).toString("hex"),i=h.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(g(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function pn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function fn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Fr(e,t){let n=Buffer.from(t,"utf8");if(n.length>_e)throw new Error("credential-store file exceeds the maximum supported size");let r=h.dirname(e),i=h.basename(e),o=null,s=null,c=!1;try{let u=$r(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((C(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");pn(o,n),a.default.fsyncSync(o),C(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ur(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}fn(r)}function Mr(e){return h.join(h.dirname(e),`.${h.basename(e)}.lock`)}function Gr(e){return h.join(h.dirname(e),`.${h.basename(e)}.lock-recovery`)}function Kr(e,t){if(t.size>nt)return null;let n=Buffer.alloc(nt+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>nt)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function N(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!te(n,t))throw new Error("credential-store lock changed while it was being inspected");ee(n,"credential-store lock"),a.default.unlinkSync(e)}function on(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(g(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new E}catch(d){if(g(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Kr(n,i);return{state:(o?.target===t&&o?!dn(o.pid):Date.now()-i.mtimeMs>=Pr)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Yr(e,t){for(let n=0;n<8;n+=1){let r=(0,it.randomBytes)(12).toString("hex"),i=h.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=C(i,s,c,{allowMultipleLinks:!0});return pn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(g(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Hr(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw g(r,"ENOENT")?new E:r}try{let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!te(i,t))throw new E;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function sn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(g(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new E}catch(r){if(g(r,"ENOENT"))return!1;throw r}throw n}return C(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function jr(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(g(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=C(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{N(e,n)}catch{}throw a.default.closeSync(t),r}}function P(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");xr(Rr)}function an(e){let t=h.dirname(e),n=h.basename(e),r=Mr(e),i=Gr(e),o=Yr(t,n),s=Date.now()+Cr,c=!1,u=!1,d=null,m;try{for(;d===null;)try{if(sn(i)){P(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Hr(r,o.stats),c=!0}catch(p){if(u&&!c){try{N(r,o.stats)}catch{}u=!1}if(p instanceof E){P(s,!1);continue}if(!g(p,"EEXIST"))throw p;let _;try{_=on(r,n)}catch(y){if(y instanceof E){P(s,!1);continue}throw y}if(_.state==="absent")continue;if(_.state==="stale"){let y;try{y=jr(i)}catch(A){if(A instanceof E){P(s,!1);continue}throw A}if(y!==null){try{let A;try{A=on(r,n)}catch(D){if(D instanceof E){P(s,!1);continue}throw D}A.state==="stale"&&N(r,A.stats)}finally{rt(y)}continue}}let T;try{T=sn(i)}catch(y){if(y instanceof E){P(s,!1);continue}throw y}P(s,T)}}catch(p){m=p}try{N(o.claimPath,o.stats)}catch(p){!g(p,"ENOENT")&&!c&&m===void 0&&(m=p)}if(m!==void 0)throw m;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function rt(e){try{N(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function qr(e,t){let n=Br(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function ln(e){let t=h.dirname(e),n=h.basename(e);for(let r of a.default.readdirSync(t)){let i=qr(r,n);if(i===null||dn(i))continue;let o=h.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(g(d,"ENOENT")||g(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!te(c,u))continue;try{ee(c,"credential-store orphan")}catch{continue}N(o,c)}catch(c){if(!g(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ne(e,t,n){if(!we()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw v();if(!tn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw v()}});let s=an(e);try{return ln(e),n({read:()=>nn(e),remove:()=>rn(e),write:()=>{throw v()}})}finally{rt(s)}}if(!t.createParent){let o=!1;try{o=un(e)}catch{throw v()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw v()}})}throw v()}if(!tn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=an(e);try{return ln(e),n({read:()=>nn(e),remove:()=>rn(e),write:o=>Fr(e,o)})}finally{rt(i)}}var ot="allscale-cli";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hn(e){return ct(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function B(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function st(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Se(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var x,at=!1;function Wr(){return Ht()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Jr(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function zr(){if(x!==void 0)return x;if(Wr())return at=!1,x=null,x;try{x=require("keytar"),at=!1}catch(e){at=!Jr(e),x=null}return x}function mn(){let e=we()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function lt(e){try{return await e()}catch{throw mn()}}var ut=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await lt(()=>this.keytar.getPassword(ot,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw B("OS keychain")}if(!hn(r))throw B("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await lt(()=>this.keytar.setPassword(ot,t,JSON.stringify(n)))}async delete(t){await this.read(t),await lt(()=>this.keytar.deletePassword(ot,t))}},Vr="credentials.json",dt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??gn.join(pe(),Vr)}read(t){let n;try{n=t.read()}catch(i){throw ye(i)?st():B("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw B("plaintext file")}if(!ct(r)||!ct(r.profiles))throw B("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ye(r)?st():Se()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!hn(r))throw B("plaintext file");return r}}async get(t){try{return ne(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:B("plaintext file")}}async set(t,n){try{ne(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof l?r:Se()}}async delete(t){try{ne(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Se()}}async clearProfile(t){try{return ne(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:ye(n)?st():Se()}}};function _n(e){if(e.insecureStorage)return cn(),new dt(e.insecureFilePath);let t=zr();if(t)return new ut(t);throw mn()}async function yn(e,t){await e.get(t)}async function wn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof l?r.message:S(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new l(r instanceof l?r.code:"storage.unavailable",`${i} ${o}`,r instanceof l?r.details:void 0)}}var Sn=w(require("crypto")),En=w(require("fs")),bn=w(require("path"));var Xr="key-id",Zr="x-allscale-cli-version",pt="cli-1",Qr="aScaLe_cli_obf_v1",ei="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function ti(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var ni=ti(ei,Qr),ri=`Bearer ${ni}`;function An(e,t){let n=$e(e);if(n!==null)return t.find(r=>$e(r.base)===n)}function ii(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=An(e,t);if(r)return r.key;if(R(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:R(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function oi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?An(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&R(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():pt}if(!R(t[0].base))return pt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():pt}function si(){return"0.1.0"}function ai(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ee(e,t){let n=ii(t);if(!n)throw ai();let r=oi(t),i=Math.floor(Date.now()/1e3).toString(),o=Sn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Zr]:si()};return r.length>0&&(s[Xr]=r),s}function be(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ie=256*1024,re=class extends l{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Ae=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function ft(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new re(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,m=d===void 0?void 0:new Promise((p,_)=>{u=setTimeout(()=>{_(new Ae(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:_,value:T}=m?await Promise.race([p,m]):await p;if(_)break;if(c+=T.byteLength,c>t)throw o.cancel().catch(()=>{}),new re(e.status,t,n.oversizeKind);s.push(Buffer.from(T))}}catch(p){throw p instanceof Ae&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}async function gt(e,t){let n;try{n=await ft(e,t)}catch(r){if(r instanceof re)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var cs=32*1024*1024,us=4*1024*1024;function li(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${Ft(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function ke(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var kn=2014;function ci(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===kn||n===String(kn)}var ui=1e4;async function Le(e,t=ui){if(e.status>=200&&e.status<300)return"";try{return await ft(e,ie,{timeoutMs:t})}catch{return""}}function Te(e,t){if(!(e>=200&&e<300)&&ci(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}var _t=require("process");var di={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Ln(e){if(typeof e=="string")return e;if(typeof e=="number")return di[e]??`user_type_${e}`}function ht(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Tn=3100,pi=2090,fi=2001,gi=2092,L="allscale.io";function Oe(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Ie(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}function hi(e,t){return new l("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:Tn})}function mt(e,t,n,r,i){let o=Oe(e),s=o.endsWith(`.${L}`)?`@${L} subdomains are not whitelisted \u2014 use a bare @${L} address, or contact support / wait for the backend allowlist fix.`:`Use an @${L} address, or contact support / wait for the backend allowlist fix.`,c=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${L} addresses can receive a login code here. Re-run with an @${L} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${L} is whitelisted.`;return new l(r,c,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function mi(e,t){return new l("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function On(e){if(e.length===0)throw new l("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new l("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function In(e){if(e)throw new l("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var _i=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:Tn,build:e=>hi(e.email,e.status)},{flows:["otp-send"],status:403,code:pi,when:e=>{let t=Oe(e.email);return t.length>0&&t!==L},build:e=>mt(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:gi,build:e=>new l("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:fi,build:e=>mi(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>new l("input.invalid","OTP rejected: the code may be incorrect, expired, already used, or locked after too many attempts. Request a new code and try again.",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7531,build:e=>new l("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new l("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Ce(e){if(e.backendCode!==void 0){for(let t of _i)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var yi="/api/v1/public/turnkey/cli/email-otps",wi="/api/v1/public/turnkey/email-otps",Rn=Symbol("cli-otp-route-missing");async function Pn(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=Ee(be(n),e);try{return await fetch(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(s){throw new l("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function vn(e){let t=await gt(e,ie);if(typeof t.data!="string"||t.data.length===0)throw new l("backend.internal","OTP send response did not include otp_id.",{body:JSON.stringify(t).slice(0,500)});return{otp_id:t.data}}async function Nn(e,t){let n=await Si(e,t);return n!==Rn?n:Ei(e,t)}async function Si(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Pn(e,yi,n);await ke(r);let i=await Le(r);Te(r.status,i);let o=Ie(i),s=Ce({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return Rn;if(r.status===429)throw new l("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new l("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new l("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return vn(r)}async function Ei(e,t){let n={email:t.email,check_user_existence:!0};t.name!==void 0&&(n.name=t.name),t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Pn(e,wi,n);await ke(r);let i=await Le(r);Te(r.status,i);let o=Ie(i),s=Ce({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new l("not_found","OTP send endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});let c=Oe(t.email),u=c.length>0&&c!==L;if(r.status===429)throw new l("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw r.status===500&&u?mt(t.email,r.status,o,"backend.internal",!1):new l("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new l("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return vn(r)}async function xn(e,t){let n=new URL("/api/v1/public/turnkey/sessions:email-otp",e).toString(),r={email:t.email,otp_id:t.otp_id,otp_code:t.otp_code,credential_mode:"agent_key",scopes:t.scopes};t.device_label!==void 0&&(r.device_label=t.device_label),t.referer_id!==void 0&&(r.referer_id=t.referer_id);let i=JSON.stringify(r),o=Ee(be(r),e),s;try{s=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(U){throw new l("transport.network",`Network error contacting ${n}: ${U.message}`)}await ke(s);let c=await Le(s);Te(s.status,c);let u=Ie(c),d=Ce({flow:"otp-verify",status:s.status,backendCode:u,email:t.email});if(d)throw d;if(s.status===401||s.status===403)throw new l("auth.permission_denied","OTP rejected: the code may be incorrect, expired, already used, or locked after too many attempts. Request a new code and try again.",{status:s.status});if(s.status===404)throw new l("not_found","OTP auth endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});if(s.status===429)throw new l("rate_limited","OTP verification throttled by the backend. Wait before retrying.",{status:429});if(s.status>=500)throw new l("backend.internal",`Backend returned ${s.status} during OTP auth.`,{status:s.status});if(s.status!==200){let U=u;throw new l("input.invalid",`OTP auth failed: HTTP ${s.status}`,{status:s.status,...U===void 0?{}:{backend_code:U}})}let p=(await gt(s,ie)).data??{},_=Ln(p.user_type)??"business",T=p.agent_key;if(typeof T!="string"||T.length===0)throw new l("backend.internal","Requested a scoped agent key, but the backend answered with a legacy cookie session \u2014 it may not support scoped OTP keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential; the OTP code was consumed, so request a new one before retrying.",{status:200,expected_credential:"agent_key"});let y=p.scopes,A=Array.isArray(y)&&y.every(U=>typeof U=="string")?y:[],D=p.agent_key_expires_at,Ne=p.business_id,yt=ht(p.user?.email)??ht(t.email);return{user:p.user??{},user_type:_,scopes:A,tokens:{access_token:"",refresh_token:"",agent_key:T,...typeof D=="number"&&D>0?{agent_key_expires_at:D}:{},...A.length>0?{scopes:A}:{},...typeof Ne=="string"&&Ne.length>0?{business_id:Ne}:{},...yt===void 0?{}:{user_email:yt},user_type:_,api_base:e}}}var Re="ALLSCALE_OTP";function Bn(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[Re];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function Dn(e,t){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(t){let r=process.env[Re];return typeof r=="string"&&r.trim().length>0&&_t.stderr.write(`warning: --otp-stdin is set, so ${Re} is ignored (stdin takes precedence).
17
+ `),Cn()}let n=process.env[Re];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return _t.stderr.write("OTP code: "),Cn()}var bi=1024;async function Cn(){let e="";try{for await(let t of process.stdin){e+=t;let n=e.indexOf(`
18
+ `);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=bi)throw new l("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(t){throw t instanceof l?t:new l("input.invalid",`Failed to read OTP from stdin: ${t instanceof Error?t.message:String(t)}`)}return e.trim()}var ve=class e extends Z{static description="Terminal-only Email OTP login for headless / scripted shells. Works with any account email (external domains included; the account must already exist). Sends the code (unless --otp-id is supplied), reads it in the terminal, and mints a scope-ENFORCED agent API key \u2014 the only credential this CLI issues. Scopes are set with --scopes (required; no full-permission default exists).";static examples=["$ allscale otp-login --email me@example.com --scopes invoice:read_only # interactive: prompts on stdin",`$ printf '%s' "$OTP" | allscale otp-login --email me@example.com --scopes invoice:all --otp-stdin`,"$ ALLSCALE_OTP=$(read-from-mailbox) allscale otp-login --email me@example.com --scopes claim_link:all","$ allscale otp-login --email me@example.com --scopes invoice:read_only --otp-id <id> --otp <code>"];static flags={email:k.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),scopes:k.Flags.string({helpGroup:"REQUIRED",description:"Scopes the minted agent key should carry, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs that reach a real operation today: "+Qt(en)+". Other pairs are accepted by the catalog but grant nothing, and this command does NOT warn when a requested scope is clipped \u2014 verify with `allscale scope` after minting. Required \u2014 the backend deliberately has no full-permission default. Requested scopes are clipped to your account's role; keys are ENFORCED server-side on every request.",multiple:!0,required:!0}),"otp-id":k.Flags.string({description:"Skip the send step and use this otp_id (e.g. from a previous `otp-send`)"}),otp:k.Flags.string({description:"OTP code from the email. Prefer ALLSCALE_OTP or --otp-stdin to keep it out of shell history.",exclusive:["otp-stdin"]}),"otp-stdin":k.Flags.boolean({description:"Read the OTP code as one line from stdin",default:!1,exclusive:["otp"]}),"no-existence-check":k.Flags.boolean({description:"(DEPRECATED \u2014 now errors) Registration via the CLI OTP flow was removed: the CLI-only login endpoint signs in existing accounts only. Create the account in the AllScale web app first, then log in without this flag.",default:!1,hidden:!0}),"device-label":k.Flags.string({description:"Human-readable device/agent label recorded on the minted key so it is identifiable in the key management list."}),...Z.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();On(n),In(!!t["no-existence-check"]);let r=this.resolveContext(t);if(!Bn(t.otp,!!t["otp-stdin"]))throw new l("input.invalid","An OTP code source is required. Pass --otp, set ALLSCALE_OTP, pipe via --otp-stdin, or run interactively.");let o=_n({insecureStorage:r.insecureStorage});await yn(o,r.profile);let s=t["otp-id"]?.trim();if(!s)try{s=(await Nn(r.apiBase,{email:n})).otp_id,Pe.stderr.write(`OTP sent to ${n}. otp_id=${s}. Check your inbox; the code is short-lived.
19
+ `)}catch(_){throw _ instanceof l&&_.code==="rate_limited"&&_.details?.status===429?new l(_.code,"OTP send was rate-limited. If a code was already sent for this email by `allscale otp-send` or an earlier `allscale otp-login`, re-run the same `allscale otp-login` command with `--otp-id <earlier-otp-id>` using the exact otp_id that command returned or printed, and the same OTP input; otherwise wait before requesting another code.",_.details):_}let c=await Dn(t.otp,!!t["otp-stdin"]);if(!c)throw new l("input.invalid","An OTP code is required. Pass --otp, set ALLSCALE_OTP, pipe via --otp-stdin, or run interactively.");let u=await xn(r.apiBase,{email:n,otp_id:s,otp_code:c,scopes:t.scopes,device_label:t["device-label"]});await wn(o,r.profile,u.tokens);let d=X(),m=Vt(d,r.profile,{api_base:r.apiBase,user_type:Ai(u.user_type),api_base_source:r.apiBaseSource});m.default||(m.default=r.profile),Jt(m),Pe.stderr.write(`Saved tokens to ${o.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${r.profile}). Profile metadata: ${fe()}
20
+ `);let p=typeof u.tokens.agent_key_expires_at=="number"?new Date(u.tokens.agent_key_expires_at*1e3).toISOString():void 0;return Pe.stderr.write(`Credential: scoped agent key. Scopes${u.scopes.length>0?` (${u.scopes.join(", ")})`:""} are ENFORCED server-side.
21
+ ${p?`The key expires at ${p}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`${Ot(r.profile)}\` when it expires or is revoked.
22
+ `),{profile:r.profile,api_base:r.apiBase,user_type:u.user_type,storage:o.kind,...u.tokens.business_id===void 0?{}:{business_id:u.tokens.business_id},...u.tokens.user_email===void 0?{}:{user_email:u.tokens.user_email},credential:"agent_key",scopes:u.scopes,...p?{agent_key_expires_at:p}:{}}}};function Ai(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}
23
+ //# sourceMappingURL=otp-login.js.map
@@ -0,0 +1,17 @@
1
+ "use strict";var bt=Object.create;var U=Object.defineProperty;var wt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var kt=(e,t)=>{for(var n in t)U(e,n,{get:t[n],enumerable:!0})},xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Lt(t))!Tt.call(e,i)&&i!==n&&U(e,i,{get:()=>t[i],enumerable:!(r=wt(t,i))||r.enumerable});return e};var g=(e,t,n)=>(n=e!=null?bt(It(e)):{},xe(t||!e||!e.__esModule?U(n,"default",{value:e,enumerable:!0}):n,e)),Ot=e=>xe(U({},"__esModule",{value:!0}),e);var Yn={};kt(Yn,{default:()=>z});module.exports=Ot(Yn);var St=require("process");var m=require("@oclif/core");var ve="public",Ne="https://app.allscale.io";var Be=["https://app.allscale.io"];var Z="Override the API base URL (public builds accept only https://app.allscale.io)";var X="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function De(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Ue(e){return De(e)!==null}function Q(e){let t=De(e);return t!==null&&Be.includes(t.origin)}function C(){return"".trim()||void 0}function R(){return"public"}function E(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function te(e){try{return new URL(e).origin}catch{return null}}function P(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return ee()}function ee(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var $e="allscale device-login";var Ct={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},Rt=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function ie(e){return(typeof e=="string"?e:String(e??"")).replace(Rt,"")}var Pt=64;function ne(e,t=new Map,n=0){if(typeof e=="string")return ie(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Pt)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ne(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ne(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(ie(n)),this.code=t,this.details=r&&ne(r),this.name="AllscaleError"}get exitCode(){return Ct[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Me(e){if(e instanceof a)return e;if(e instanceof Error){if(Nt(e)){let t=Dt(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var xt=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),vt=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Nt(e){if(Bt(e))return!0;let t=e.name??"";return xt.has(t)?t==="CLIError"?re(e,"parse")||Ge(e.message):!0:Ge(e.message)}function Bt(e){if(!re(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&re(e,"parse")}function Ge(e){return e?ie(e).split(`
2
+ `).some(t=>vt.some(n=>n.test(t.trim()))):!1}function re(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Dt(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Fe(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var u=g(require("fs")),G=g(require("path")),We=g(require("crypto"));var Ut="...<truncated>",$t=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Gt=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,le=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,oe=String.raw`(?:proxy[_-]?)?authorization`,Mt=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${oe}"|'${oe}'|${oe})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${le}`,"gi"),Ft=/\b(https?:\/\/)[^\s/?#]+@/gi,se=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Yt=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${se}"|'${se}'|${se})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${le}`,"gi"),ae=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Kt=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ae}"|'${ae}'|${ae})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${le}`,"g");function Ye(e){return e.replace(Ft,"$1<redacted>@").replace($t,"<redacted-jwt>").replace(Mt,"$1$2$3<redacted>").replace(Yt,"$1$2<redacted>").replace(Kt,"$1$2<redacted>").replace(Gt,"Bearer <redacted>")}function Ke(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function He(e,t,n=Ut){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let _=Buffer.byteLength(d,"utf8");if(l+_>t)break;c+=d,l+=_}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function f(e,t=16384){return He(Ke(Ye(e)),t)}var ce=100,Ht=8,jt=8*1024;function $(){return{remaining:jt}}function ue(e,t){let n=Math.min(16384,t.remaining),r=He(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function y(e,t,n=0,r={}){if(n>Ht)return ue("<truncated>",t);if(typeof e=="string"){let i=Ye(e);return ue(r.escapeControls?Ke(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,ce),o=i.map(s=>y(s,t,n+1,r));return e.length>i.length&&o.push(ue(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,ce))i[s]=y(c,t,n+1,r);return o.length>ce&&(i.output_truncated=!0),i}return e}var de=require("process");var pe=!1;function fe(e){pe=e}function qe(){return pe}var je="1";function b(e,t){if(pe){let n={...e};delete n.version;let r=$(),i={event:n.event,...n},o=y(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:je,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:je,event:o.event,output_truncated:!0})),de.stderr.write(`${s}
4
+ `)}else de.stderr.write(t)}var Je="2",w=null,p=null,L=!1;function qt(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=We.randomBytes(4).toString("hex");return G.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var ge=64*1024*1024,Jt=null;function ze(){if(L)return;let e=qt();if(!e)return;w=null;let t=null;try{if((Jt??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=G.dirname(e);if(u.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=u.statSync(n),l=c.mode&511;if(!c.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let r=u.constants.O_NOFOLLOW??0;t=u.openSync(e,u.constants.O_APPEND|u.constants.O_CREAT|u.constants.O_WRONLY|(u.constants.O_NONBLOCK??0)|r,384);let i=u.fstatSync(t),o=u.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let s=i.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);u.fchmodSync(t,384)}catch(n){if(t!==null)try{u.closeSync(t)}catch{}b({event:"sidecar_disabled",reason:"open_failed",detail:f(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${f(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}w=e,p=t,L=!0}var Wt=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function zt(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Wt.some(n=>n.test(t))}function Ve(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=Vt(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)zt(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Vt(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Zt(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ve(e.url)}:e}function Xt(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=y(i,$()),s=JSON.stringify({version:Je,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Je,timestamp:t,type:r,output_truncated:!0})),s}function I(e){if(!L||!w||p===null)return;let t=Zt(e),n=Xt(t);try{if(u.fstatSync(p).size+Buffer.byteLength(n,"utf8")+1>ge){L=!1;try{u.closeSync(p)}catch{}p=null,b({event:"sidecar_disabled",reason:"size_limit",...w===null?{}:{path:f(w)},max_bytes:ge},`${f(`[allscale] sidecar exceeded ${ge} bytes; disabling it for the rest of this run. Rotate or remove ${w}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}u.appendFileSync(p,`${n}
7
+ `)}catch(r){if(L=!1,p!==null){try{u.closeSync(p)}catch{}p=null}try{b({event:"sidecar_disabled",reason:"write_failed",detail:f(r.message)},`${f(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var Ze=Ve;function Xe(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function M(){if(L=!1,p!==null){try{u.closeSync(p)}catch{}p=null}}function Qe(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Xe()||!t}var x=C()??Ne,v={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function F(e){return Ue(e)?new URL(e).origin:null}function k(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function et(){let e=process.env[v.TOKEN]?.trim();return e&&e.length>0?e:void 0}function he(){let e=process.env[v.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Y(){let e=process.env[v.API_BASE]?.trim();return e&&e.length>0?e:void 0}function tt(){let e=process.env[v.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function nt(){let e=process.env[v.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(C()===void 0&&x!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${x} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
11
+ the old default rather than a deliberate choice.
12
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
+ To move to production, run: ${$e} --api-base ${x}
14
+ `}var O=g(require("fs")),it=g(require("os")),_e=g(require("path")),me=g(require("@iarna/toml"));var tn=".allscale",nn="config.toml";function rn(){return _e.join(it.homedir(),tn)}function on(){return _e.join(rn(),nn)}function Ae(){let e=on();if(!O.existsSync(e))return{};let t=O.readFileSync(e,"utf-8");try{return me.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function ot(e,t){return e.profile?.[t]}function st(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function K(e){if(!Q(e))throw new a("input.invalid",`Refusing to send credentials to API base ${k(e)}. `+X)}function Ee(e){let t=C();if(t===void 0||E(e))return;let n=F(e),r=P();if(r.length>0){let o=r.map(c=>F(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>k(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${k(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=F(t);if(!(n!==null&&n===i))throw new a("input.invalid",`Refusing to send to ${k(e)} \u2014 this build only signs for ${k(t)}. Re-login against this build's environment, or use a build for that one.`)}var sn=require("@noble/hashes/sha3");var at=["USDT","USDC"];var Cr=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var B=require("@oclif/core"),N=class e extends m.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:m.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:m.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:R()==="public"}),"api-base":m.Flags.string({description:Z,helpGroup:"GLOBAL",hidden:R()==="public"}),"insecure-storage":m.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{fe(this.jsonEnabled()),ze(),I({type:"session-start",command:this.id??"",argv:cn(this.argv)});let t=this.constructor;if(R()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Y()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!nt())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=Qe(this.jsonEnabled()),r=this.argv.length===0&&!n&&_n(t)?this.config.findCommand(this.id??""):void 0;if(r){M();let o=await(0,m.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return I({type:"command-end",ok:!0}),M(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Fe(i),{data:i})}catch(t){let n=Me(t);I({type:"error",code:n.code,message:f(n.message)}),I({type:"command-end",ok:!1,exitCode:n.exitCode}),M(),this.emitError(n),process.exitCode=n.exitCode;return}finally{fe(!1)}}resolveSessionApiBaseChain(t){let n=Ae(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||he()!==void 0,s=st(n,r,he()),c=ot(n,s),l=i??Y(),d=l??c?.api_base??x,_=rt({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return _&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,b({event:"legacy_staging_profile",api_base:d,profile:s},_)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||K(n),n}resolveContext(t){if(R()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Y()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(K(i),Ee(i)),{apiBase:i,profile:s,token:n??et(),insecureStorage:r||tt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${hn(t)}
15
+ `)}},j=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),an=new Set(Array.from(j).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function cn(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(j.has(o)){t.push(`${o}=<redacted>`);continue}}}if(j.has(r)){t.push(r),n+1<e.length&&(j.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(an.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var un=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function ln(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return un.test(t)}var dn=/_(removed|cleared|count|total)$/i;function pn(e,t){return typeof t=="number"&&dn.test(e)}var fn=new Set(at);function gn(e,t){return e==="token_symbol"&&typeof t=="string"&&fn.has(t)}var H=100;function ye(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,H),r=n.map(i=>ye(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,H))n[i]=ln(i)&&!pn(i,o)&&!gn(i,o)?"<redacted>":ye(o,t+1);if(r.length>H){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-H} more keys`}return n}return typeof e=="string"?f(e):e}function hn(e){let t=qe()?void 0:2,n=ye(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:f(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function _n(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var ct=g(require("crypto")),ut=g(require("fs")),lt=g(require("path"));var mn="key-id",An="x-allscale-cli-version",Se="cli-1",En="aScaLe_cli_obf_v1",yn="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Sn(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var bn=Sn(yn,En),wn=`Bearer ${bn}`;function dt(e,t){let n=te(e);if(n!==null)return t.find(r=>te(r.base)===n)}function Ln(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=P();if(t.length>0){let r=dt(e,t);if(r)return r.key;if(E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:E(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function In(e){{let r="cli-1".trim();if(r.length>0)return r}let t=P();if(t.length>0){let r=e!==void 0?dt(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Se}if(!E(t[0].base))return Se}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Se}function Tn(){return"0.1.0"}function kn(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function be(e,t){let n=Ln(t);if(!n)throw kn();let r=In(t),i=Math.floor(Date.now()/1e3).toString(),o=ct.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[An]:Tn()};return r.length>0&&(s[mn]=r),s}function we(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var J=256*1024,D=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},q=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Le(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new D(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,_=d===void 0?void 0:new Promise((A,V)=>{l=setTimeout(()=>{V(new q(e.status,d))},d),l.unref?.()});try{for(;;){let A=o.read(),{done:V,value:Pe}=_?await Promise.race([A,_]):await A;if(V)break;if(c+=Pe.byteLength,c>t)throw o.cancel().catch(()=>{}),new D(e.status,t,n.oversizeKind);s.push(Buffer.from(Pe))}}catch(A){throw A instanceof q&&o.cancel(A).catch(()=>{}),A}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}async function pt(e,t){let n;try{n=await Le(e,t)}catch(r){if(r instanceof D)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var mi=32*1024*1024,Ai=4*1024*1024;function On(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${Ze(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Ie(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}On(e.status,e.url)}}var ft=2014;function Cn(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===ft||n===String(ft)}var Rn=1e4;async function Te(e,t=Rn){if(e.status>=200&&e.status<300)return"";try{return await Le(e,J,{timeoutMs:t})}catch{return""}}function ke(e,t){if(!(e>=200&&e<300)&&Cn(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}var Un=require("process");var gt=3100,Pn=2090,xn=2001,vn=2092,h="allscale.io";function W(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Oe(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}function Nn(e,t){return new a("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:gt})}function Ce(e,t,n,r,i){let o=W(e),s=o.endsWith(`.${h}`)?`@${h} subdomains are not whitelisted \u2014 use a bare @${h} address, or contact support / wait for the backend allowlist fix.`:`Use an @${h} address, or contact support / wait for the backend allowlist fix.`,c=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${h} addresses can receive a login code here. Re-run with an @${h} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${h} is whitelisted.`;return new a(r,c,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function Bn(e,t){return new a("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function ht(e){if(e.length===0)throw new a("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new a("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function _t(e){if(e)throw new a("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var Dn=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:gt,build:e=>Nn(e.email,e.status)},{flows:["otp-send"],status:403,code:Pn,when:e=>{let t=W(e.email);return t.length>0&&t!==h},build:e=>Ce(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:vn,build:e=>new a("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:xn,build:e=>Bn(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>new a("input.invalid","OTP rejected: the code may be incorrect, expired, already used, or locked after too many attempts. Request a new code and try again.",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7531,build:e=>new a("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new a("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Re(e){if(e.backendCode!==void 0){for(let t of Dn)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var $n="/api/v1/public/turnkey/cli/email-otps",Gn="/api/v1/public/turnkey/email-otps",mt=Symbol("cli-otp-route-missing");async function At(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=be(we(n),e);try{return await fetch(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(s){throw new a("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function Et(e){let t=await pt(e,J);if(typeof t.data!="string"||t.data.length===0)throw new a("backend.internal","OTP send response did not include otp_id.",{body:JSON.stringify(t).slice(0,500)});return{otp_id:t.data}}async function yt(e,t){let n=await Mn(e,t);return n!==mt?n:Fn(e,t)}async function Mn(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await At(e,$n,n);await Ie(r);let i=await Te(r);ke(r.status,i);let o=Oe(i),s=Re({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return mt;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return Et(r)}async function Fn(e,t){let n={email:t.email,check_user_existence:!0};t.name!==void 0&&(n.name=t.name),t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await At(e,Gn,n);await Ie(r);let i=await Te(r);ke(r.status,i);let o=Oe(i),s=Re({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new a("not_found","OTP send endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});let c=W(t.email),l=c.length>0&&c!==h;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw r.status===500&&l?Ce(t.email,r.status,o,"backend.internal",!1):new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return Et(r)}var z=class e extends N{static description="Send an email OTP for login. Works with any account email (external domains included). Returns the otp_id; the user receives the code by email. Login only: the account must already exist.";static examples=["$ allscale otp-send --email me@example.com"];static flags={email:B.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),"no-existence-check":B.Flags.boolean({description:"(DEPRECATED \u2014 now errors) Registration via the CLI OTP flow was removed: the CLI-only login endpoint signs in existing accounts only. Create the account in the AllScale web app first, then log in without this flag.",default:!1,hidden:!0}),...N.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();ht(n),_t(!!t["no-existence-check"]);let r=this.resolveContext(t),i=await yt(r.apiBase,{email:n});return St.stderr.write(`OTP sent to ${n}. Check the inbox; the code is short-lived.
16
+ `),{email:n,otp_id:i.otp_id,api_base:r.apiBase}}};
17
+ //# sourceMappingURL=otp-send.js.map
@@ -0,0 +1,23 @@
1
+ "use strict";var Ft=Object.create;var H=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Kt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var Ht=(e,t)=>{for(var n in t)H(e,n,{get:t[n],enumerable:!0})},Fe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Gt(t))!Yt.call(e,i)&&i!==n&&H(e,i,{get:()=>t[i],enumerable:!(r=Mt(t,i))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Ft(Kt(e)):{},Fe(t||!e||!e.__esModule?H(n,"default",{value:e,enumerable:!0}):n,e)),qt=e=>Fe(H({},"__esModule",{value:!0}),e);var rr={};Ht(rr,{default:()=>re});module.exports=qt(rr);var A=require("@oclif/core");var Me="public",Ge="https://app.allscale.io",x="https://openapi.allscale.io";var Ke=["https://app.allscale.io"],Ye=["https://openapi.allscale.io"],B=[],He={"https://openapi.allscale.io":"production \u2014 real funds"},ie="Override the API base URL (public builds accept only https://app.allscale.io)",oe="Standalone partner API origin for store-HMAC payouts. Defaults to https://openapi.allscale.io. Also via ALLSCALE_PAYOUT_API_BASE.",se="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.",ae="Only https://openapi.allscale.io is allowed. Set --payout-api-base (or ALLSCALE_PAYOUT_API_BASE) to choose it explicitly; otherwise the public build uses its production partner API default.";function le(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function qe(e){return le(e)!==null}function ce(e){let t=le(e);return t!==null&&Ke.includes(t.origin)}function D(e){let t=le(e);return t!==null&&Ye.includes(t.origin)}function ue(e){return!1}function q(e){return x}function U(){return"".trim()||void 0}function $(){return"public"}function pe(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function fe(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return de()}function de(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:l,keyId:c}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof c=="string"?c.trim():"";i.push({base:a.trim(),key:l,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var je="allscale device-login";var jt={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},zt=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function me(e){return(typeof e=="string"?e:String(e??"")).replace(zt,"")}var Wt=64;function ge(e,t=new Map,n=0){if(typeof e=="string")return me(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Wt)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let l of e)a.push(ge(l,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,l]of Object.entries(e))Object.defineProperty(o,a,{value:ge(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(t,n,r){super(me(n)),this.code=t,this.details=r&&ge(r),this.name="AllscaleError"}get exitCode(){return jt[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function We(e){if(e instanceof s)return e;if(e instanceof Error){if(Xt(e)){let t=Qt(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new s("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var Jt=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Vt=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Xt(e){if(Zt(e))return!0;let t=e.name??"";return Jt.has(t)?t==="CLIError"?he(e,"parse")||ze(e.message):!0:ze(e.message)}function Zt(e){if(!he(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&he(e,"parse")}function ze(e){return e?me(e).split(`
2
+ `).some(t=>Vt.some(n=>n.test(t.trim()))):!1}function he(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Qt(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Je(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var u=h(require("fs")),z=h(require("path")),nt=h(require("crypto"));var en="...<truncated>",tn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,nn=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,we=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,_e=String.raw`(?:proxy[_-]?)?authorization`,rn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${_e}"|'${_e}'|${_e})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${we}`,"gi"),on=/\b(https?:\/\/)[^\s/?#]+@/gi,ye=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,sn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ye}"|'${ye}'|${ye})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${we}`,"gi"),Ee=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,an=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ee}"|'${Ee}'|${Ee})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${we}`,"g");function Ve(e){return e.replace(on,"$1<redacted>@").replace(tn,"<redacted-jwt>").replace(rn,"$1$2$3<redacted>").replace(sn,"$1$2<redacted>").replace(an,"$1$2<redacted>").replace(nn,"Bearer <redacted>")}function Xe(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function Ze(e,t,n=en){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",c=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(c+p>t)break;l+=d,c+=p}return l}let i=t-r,o="",a=0;for(let l of e){let c=Buffer.byteLength(l,"utf8");if(a+c>i)break;o+=l,a+=c}return`${o}${n}`}function _(e,t=16384){return Ze(Xe(Ve(e)),t)}var Se=100,ln=8,cn=8*1024;function j(){return{remaining:cn}}function Ae(e,t){let n=Math.min(16384,t.remaining),r=Ze(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function L(e,t,n=0,r={}){if(n>ln)return Ae("<truncated>",t);if(typeof e=="string"){let i=Ve(e);return Ae(r.escapeControls?Xe(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Se),o=i.map(a=>L(a,t,n+1,r));return e.length>i.length&&o.push(Ae(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,l]of o.slice(0,Se))i[a]=L(l,t,n+1,r);return o.length>Se&&(i.output_truncated=!0),i}return e}var be=require("process");var ke=!1;function Le(e){ke=e}function et(){return ke}var Qe="1";function w(e,t){if(ke){let n={...e};delete n.version;let r=j(),i={event:n.event,...n},o=L(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:Qe,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Qe,event:o.event,output_truncated:!0})),be.stderr.write(`${a}
4
+ `)}else be.stderr.write(t)}var tt="2",I=null,y=null,O=!1;function un(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=nt.randomBytes(4).toString("hex");return z.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Te=64*1024*1024,dn=null;function rt(){if(O)return;let e=un();if(!e)return;I=null;let t=null;try{if((dn??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=z.dirname(e);if(u.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=u.statSync(n),c=l.mode&511;if(!l.isDirectory()||(c&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${c.toString(8).padStart(3,"0")}`)}let r=u.constants.O_NOFOLLOW??0;t=u.openSync(e,u.constants.O_APPEND|u.constants.O_CREAT|u.constants.O_WRONLY|(u.constants.O_NONBLOCK??0)|r,384);let i=u.fstatSync(t),o=u.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let a=i.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);u.fchmodSync(t,384)}catch(n){if(t!==null)try{u.closeSync(t)}catch{}w({event:"sidecar_disabled",reason:"open_failed",detail:_(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${_(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}I=e,y=t,O=!0}var pn=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function fn(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return pn.some(n=>n.test(t))}function it(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=gn(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)fn(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function gn(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function hn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:it(e.url)}:e}function mn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=L(i,j()),a=JSON.stringify({version:tt,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:tt,timestamp:t,type:r,output_truncated:!0})),a}function C(e){if(!O||!I||y===null)return;let t=hn(e),n=mn(t);try{if(u.fstatSync(y).size+Buffer.byteLength(n,"utf8")+1>Te){O=!1;try{u.closeSync(y)}catch{}y=null,w({event:"sidecar_disabled",reason:"size_limit",...I===null?{}:{path:_(I)},max_bytes:Te},`${_(`[allscale] sidecar exceeded ${Te} bytes; disabling it for the rest of this run. Rotate or remove ${I}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}u.appendFileSync(y,`${n}
7
+ `)}catch(r){if(O=!1,y!==null){try{u.closeSync(y)}catch{}y=null}try{w({event:"sidecar_disabled",reason:"write_failed",detail:_(r.message)},`${_(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var ot=it;function st(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function W(){if(O=!1,y!==null){try{u.closeSync(y)}catch{}y=null}}function at(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||st()||!t}var F=U()??Ge,b={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function P(e){return qe(e)?new URL(e).origin:null}function S(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function lt(){let e=process.env[b.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Oe(){let e=process.env[b.PROFILE]?.trim();return e&&e.length>0?e:void 0}function J(){let e=process.env[b.API_BASE]?.trim();return e&&e.length>0?e:void 0}function ct(){let e=process.env[b.PAYOUT_API_BASE]?.trim();return e&&e.length>0?e:void 0}function ut(){let e=process.env[b.STORE_API_KEY]?.trim();return e&&e.length>0?e:void 0}function dt(){let e=process.env[b.STORE_API_SECRET]?.trim();return e&&e.length>0?e:void 0}function pt(){let e=process.env[b.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ft(){let e=process.env[b.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function gt(e){let t;try{t=new URL(e).origin}catch{}let n=t===void 0?void 0:He[t],r=n===void 0?"":` (${n})`;return`Notice: no --payout-api-base given; using ${e}${r}.
9
+ Set --payout-api-base (or ALLSCALE_PAYOUT_API_BASE) to choose the destination explicitly.
10
+ `}function ht(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(U()===void 0&&F!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
11
+ The CLI default is now ${F} (production), but a saved profile wins over the default,
12
+ so this session still uses staging. That pin was written before the default changed, so it may just be
13
+ the old default rather than a deliberate choice.
14
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
15
+ To move to production, run: ${je} --api-base ${F}
16
+ `}var v=h(require("fs")),mt=h(require("os")),Ce=h(require("path")),Re=h(require("@iarna/toml"));var _n=".allscale",yn="config.toml";function _t(){return Ce.join(mt.homedir(),_n)}function En(){return Ce.join(_t(),yn)}function Pe(){let e=En();if(!v.existsSync(e))return{};let t=v.readFileSync(e,"utf-8");try{return Re.parse(t)}catch(n){throw new s("internal",`Failed to parse ${e}: ${n.message}`)}}function yt(e,t){return e.profile?.[t]}function Et(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new s("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function M(e){if(!ce(e))throw new s("input.invalid",`Refusing to send credentials to API base ${S(e)}. `+se)}function G(e){if(!D(e))throw new s("input.invalid",`Refusing to send store credentials to payout API base ${S(e)}. `+ae)}function ve(e,t){let n=P(e),r=P(t);if(!(n&&r===n))throw new s("input.invalid",`Refusing API request to ${S(t)} because it is outside the configured API origin ${S(e)}.`)}function Ne(e){let t=U();if(t===void 0||pe(e))return;let n=P(e),r=fe();if(r.length>0){let o=r.map(l=>P(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let a=r.map(l=>S(l.base)).join(", ");throw new s("input.invalid",`Refusing to send to ${S(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=P(t);if(!(n!==null&&n===i))throw new s("input.invalid",`Refusing to send to ${S(e)} \u2014 this build only signs for ${S(t)}. Re-login against this build's environment, or use a build for that one.`)}var Sn=require("@noble/hashes/sha3");function St(e,t){switch(t){case 1:case 2:return e===6?18:6}}var An={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},At=["ethereum","bsc","base","polygon","arbitrum","optimism"],V=["USDT","USDC"];function wt(e){return An[e.toLowerCase()]??null}function bt(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var Dr=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var m=require("@oclif/core"),K=class e extends A.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:A.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:A.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:$()==="public"}),"api-base":A.Flags.string({description:ie,helpGroup:"GLOBAL",hidden:$()==="public"}),"insecure-storage":A.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Le(this.jsonEnabled()),rt(),C({type:"session-start",command:this.id??"",argv:bn(this.argv)});let t=this.constructor;if($()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&J()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!ft())throw this.argv.length>0&&await this.parse(),new s("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=at(this.jsonEnabled()),r=this.argv.length===0&&!n&&Pn(t)?this.config.findCommand(this.id??""):void 0;if(r){W();let o=await(0,A.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return C({type:"command-end",ok:!0}),W(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Je(i),{data:i})}catch(t){let n=We(t);C({type:"error",code:n.code,message:_(n.message)}),C({type:"command-end",ok:!1,exitCode:n.exitCode}),W(),this.emitError(n),process.exitCode=n.exitCode;return}finally{Le(!1)}}resolveSessionApiBaseChain(t){let n=Pe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Oe()!==void 0,a=Et(n,r,Oe()),l=yt(n,a),c=i??J(),d=c??l?.api_base??F,p=ht({resolvedApiBase:d,fromExplicitOverride:c!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,w({event:"legacy_staging_profile",api_base:d,profile:a},p)),{apiBase:d,explicitApiBase:c,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||M(n),n}resolveContext(t){if($()==="public"){if(t.token!==void 0)throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&J()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:a,profileApiBase:l,profileExplicit:c}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(M(i),Ne(i)),{apiBase:i,profile:a,token:n??lt(),insecureStorage:r||pt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:c}}emitError(t){process.stderr.write(`${Rn(t)}
17
+ `)}},Z=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),wn=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function bn(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(Z.has(o)){t.push(`${o}=<redacted>`);continue}}}if(Z.has(r)){t.push(r),n+1<e.length&&(Z.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(wn.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var kn=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Ln(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return kn.test(t)}var Tn=/_(removed|cleared|count|total)$/i;function In(e,t){return typeof t=="number"&&Tn.test(e)}var On=new Set(V);function Cn(e,t){return e==="token_symbol"&&typeof t=="string"&&On.has(t)}var X=100;function xe(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,X),r=n.map(i=>xe(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,X))n[i]=Ln(i)&&!In(i,o)&&!Cn(i,o)?"<redacted>":xe(o,t+1);if(r.length>X){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-X} more keys`}return n}return typeof e=="string"?_(e):e}function Rn(e){let t=et()?void 0:2,n=xe(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:_(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Pn(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var vn=h(require("crypto")),Nn=h(require("fs")),xn=h(require("path"));var Bn="aScaLe_cli_obf_v1",Dn="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Un(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var $n=Un(Dn,Bn),Fn=`Bearer ${$n}`;var Be=256*1024,Q=class extends s{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ee=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function De(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Q(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],l=0,c,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,g)=>{c=setTimeout(()=>{g(new ee(e.status,d))},d),c.unref?.()});try{for(;;){let f=o.read(),{done:g,value:k}=p?await Promise.race([f,p]):await f;if(g)break;if(l+=k.byteLength,l>t)throw o.cancel().catch(()=>{}),new Q(e.status,t,n.oversizeKind);a.push(Buffer.from(k))}}catch(f){throw f instanceof ee&&o.cancel(f).catch(()=>{}),f}finally{c!==void 0&&clearTimeout(c);try{o.releaseLock()}catch{}}return Buffer.concat(a,l).toString("utf8")}var Ti=32*1024*1024,Ii=4*1024*1024;function Mn(e,t){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${ot(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function kt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Mn(e.status,e.url)}}var N=require("crypto");function Gn(e){return(0,N.createHash)("sha256").update(e??"").digest("hex")}function Kn(e){let t=Gn(e.body),n=`${e.method.toUpperCase()}
18
+ ${e.path}
19
+ ${e.query}
20
+ ${e.ts}
21
+ ${e.nonce}
22
+ ${t}`;return Buffer.from(n,"utf-8")}function Yn(e,t){return`v1=${(0,N.createHmac)("sha256",Buffer.from(e,"utf-8")).update(t).digest("base64")}`}function Hn(){return(0,N.randomBytes)(16).toString("hex")}function qn(){return String(Math.floor(Date.now()/1e3))}var te={apiKey:"X-API-Key",timestamp:"X-Timestamp",nonce:"X-Nonce",signature:"X-Signature"};function Lt(e){let t=e.ts??qn(),n=e.nonce??Hn(),r=Kn({method:e.method,path:e.path,query:e.query??"",ts:t,nonce:n,body:e.body}),i=Yn(e.apiSecret,r);return{[te.apiKey]:e.apiKey,[te.timestamp]:t,[te.nonce]:n,[te.signature]:i}}var Tt="/v1/claim_link_auto_payouts",jn=12e4,E={OK:0,VALIDATION_ERROR:10001,AUTH_MISSING_HEADERS:20001,AUTH_BAD_SIGNATURE:20002,FORBIDDEN:30001,SCOPE_FORBIDDEN:30002,RATE_LIMIT_EXCEEDED:40001,CREATE_ERROR:50103,API_DISABLED:50104,DUPLICATE_REFERENCE:50105,REFERENCE_CONFLICT:50106};function zn(e){let t={amount:e.amount,stable_coin:e.stableCoin,chain:e.chain,reference_id:e.referenceId};return e.receiverEmail&&(t.receiver_email=e.receiverEmail),e.senderDisplayName&&(t.sender_display_name=e.senderDisplayName),e.senderMessage&&(t.sender_message=e.senderMessage),JSON.stringify(t)}function Wn(e,t){let n=t?.code,r=t?.error?.details?.reason??t?.error?.message??`HTTP ${e}`,i={httpStatus:e,code:n,reason:r};switch(n){case E.FORBIDDEN:return new s("auth.permission_denied",`This store key is not allowed to perform this operation (${r}). Check the key belongs to the right store and environment.`,i);case E.SCOPE_FORBIDDEN:return new s("auth.permission_denied","This store key is not authorized for auto-payout (missing claim_link:auto_payout scope). Complete Payout onboarding for this store, then retry.",i);case E.API_DISABLED:return new s("auth.permission_denied","Auto-payout is unavailable: it is disabled in this environment, or this is a sandbox key (live signing requires a production store key).",i);case E.DUPLICATE_REFERENCE:return new s("rate_limited",`A create for reference_id is already in flight; retry shortly (a settled duplicate returns the original link). reason: ${r}`,i);case E.REFERENCE_CONFLICT:return new s("input.invalid",`This reference_id was already used for a different payout request (${r}). Reuse it only with the original chain, token, and amount; otherwise choose a new reference_id.`,{...i,...Jn(t?.error?.details)});case E.VALIDATION_ERROR:return new s("input.invalid",`Auto-payout request rejected: ${r}`,i);case E.AUTH_MISSING_HEADERS:case E.AUTH_BAD_SIGNATURE:return new s("auth.permission_denied",`Store-key authentication failed (${r}). Check --api-key / ALLSCALE_STORE_API_SECRET and that the system clock is accurate.`,i);case E.RATE_LIMIT_EXCEEDED:return new s("rate_limited",`Rate limited: ${r}`,i);case E.CREATE_ERROR:return new s("backend.internal",`Auto-payout could not fund the claim link (${r}). Run \`allscale payout status\` to check the session is active and has enough remaining cap/balance before retrying.`,i);default:return new s("backend.internal",`Auto-payout failed: ${r}`,i)}}function Jn(e){if(!e)return{};let t={};typeof e.reference_id=="string"&&(t.reference_id=e.reference_id);for(let n of["existing","request"]){let r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;let i=r,o={};(typeof i.chain=="string"||typeof i.chain=="number")&&(o.chain=i.chain),typeof i.token_symbol=="string"&&(o.token_symbol=i.token_symbol),(typeof i.amount=="string"||typeof i.amount=="number")&&(o.amount=i.amount),t[n]=o}return t}function Vn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=r=>t[r]===null||typeof t[r]=="string";return typeof t.claim_link_id=="string"&&t.claim_link_id.length>0&&n("reference_id")&&(typeof t.amount=="string"||typeof t.amount=="number")&&typeof t.token_symbol=="string"&&typeof t.chain_id=="number"&&Number.isFinite(t.chain_id)&&typeof t.status=="string"&&n("token")&&n("claim_url")&&n("funding_tx_hash")&&(t.funded_amount===null||typeof t.funded_amount=="string"||typeof t.funded_amount=="number")&&typeof t.idempotent_hit=="boolean"}async function It(e){G(e.apiBase);let t=new URL(Tt,e.apiBase).toString();ve(e.apiBase,t);let n=zn(e.input),r={"Content-Type":"application/json",...Lt({apiKey:e.apiKey,apiSecret:e.apiSecret,method:"POST",path:Tt,body:n})},i=new AbortController,o=!1,a=setTimeout(()=>{o=!0,i.abort()},e.timeoutMs??jn),l=g=>{let k=g instanceof s&&typeof g.details?.status=="number"&&Number.isSafeInteger(g.details.status)?g.details.status:void 0,Y=g instanceof s&&typeof g.details?.max_body_bytes=="number"&&Number.isSafeInteger(g.details.max_body_bytes)?g.details.max_body_bytes:void 0;return new s(o?"transport.timeout":"transport.network",o?"Auto-payout timed out waiting for the funding receipt. The payment MAY have been broadcast \u2014 re-run with the SAME --reference-id to safely resolve it (idempotent).":"Auto-payout transport failed after dispatch. The payout request may still have been created; retry or reconcile with the SAME --reference-id.",{reference_id:e.input.referenceId,...k===void 0?{}:{status:k},...Y===void 0?{}:{max_body_bytes:Y}})},c,d;try{c=await fetch(t,{method:"POST",headers:r,body:n,signal:i.signal,redirect:"manual"}),await kt(c),d=await De(c,Be)}catch(g){throw l(g)}finally{clearTimeout(a)}let p=null;try{p=d?JSON.parse(d):null}catch{p=null}let f=p&&typeof p=="object"&&!Array.isArray(p)?p:null;if(c.ok&&f?.code===E.OK&&Vn(f.payload))return f.payload;throw c.ok&&(!f||typeof f.code!="number"||f.code===E.OK)?new s("backend.internal","Auto-payout returned an unreadable success response. The payout may still have been created; do not use a new reference id. Retry or reconcile with the SAME --reference-id.",{httpStatus:c.status,reference_id:e.input.referenceId}):Wn(c.status,f)}var Qn=h(require("path"));var Xn=require("crypto"),Zn=h(require("fs")),Ue=h(require("path"));var Ui=1024*1024;var $i=new Int32Array(new SharedArrayBuffer(4));var er=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,tr=/^0(?:\.0+)?$/,Ot=128;function Ct(e,t,n={}){if(t.length>Ot)throw new s("input.invalid",`${e} is too long; decimal values may contain at most ${Ot} characters.`);let r=t.trim();if(!er.test(r))throw new s("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&tr.test(r))throw new s("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Rt(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new s("input.invalid",`${e} supports at most ${n} effective decimal places for the selected token and chain; got '${t}'. The CLI will not round a funds amount.`);return t}function ne(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new s("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}function Pt(e){let t=ne("--receiver-email",e,254);if(t!==void 0){if(!t.includes("@"))throw new s("input.invalid","--receiver-email is not a valid email.");return t}}var $e=11,vt=[...At,...B],nr=B.length>0,Nt=nr?"EVM chain slug. sepolia is a testnet and is accepted only by beta or loopback payout APIs.":"EVM mainnet chain slug.";function xt(e){let t=e.toLowerCase();return t==="sepolia"&&B.includes(t)?$e:wt(t)}function Bt(e){return e===$e}function Dt(e,t){return e===$e?6:St(e,t)}var re=class e extends K{static description="Create and auto-fund a claim link from this store's enabled auto-payout wallet. Authenticates with the store API key/secret (NOT your login), so it needs a store that has completed Payout onboarding. Idempotent on --reference-id.";static examples=["$ ALLSCALE_STORE_API_SECRET=\u2026 allscale payout send --api-key ak_\u2026 --amount 10 --chain base --reference-id order-1042","$ allscale payout send --payout-api-base https://openapi.allscale.io --api-key ak_\u2026 --api-secret \u2026 --amount 25 --stable-coin USDC --chain polygon --reference-id inv-77 --receiver-email client@example.com"];static flags={amount:m.Flags.string({helpGroup:"REQUIRED",description:"Claimable amount in token units (decimal string, e.g. 10 or 25.50); at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:m.Flags.string({helpGroup:"REQUIRED",description:Nt,options:[...vt],required:!0}),"reference-id":m.Flags.string({helpGroup:"REQUIRED",description:"Your idempotency key (e.g. your order id). REQUIRED \u2014 a retry with the same value is safe (no double-fund).",required:!0}),"payout-api-base":m.Flags.string({description:oe}),"stable-coin":m.Flags.string({description:"Stablecoin to fund in.",options:[...V],default:"USDT"}),"receiver-email":m.Flags.string({description:"Optional email to send the claim invite to."}),"sender-display-name":m.Flags.string({description:"Optional display name shown to the receiver. Max 100 chars."}),message:m.Flags.string({description:"Optional message shown to the receiver. Max 200 chars."}),"api-key":m.Flags.string({description:"Store API key (public id). Falls back to ALLSCALE_STORE_API_KEY."}),"api-secret":m.Flags.string({description:"Store API secret. Prefer the ALLSCALE_STORE_API_SECRET env var (a flag value can leak via shell history / process list)."}),...K.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);if(t["payout-api-base"]!==void 0&&t["api-base"]!==void 0)throw new s("input.invalid","Use only one of --payout-api-base or the legacy --api-base for payout send.");let n=t["payout-api-base"]?.trim(),r=t["api-base"]?.trim(),i=r!==void 0&&D(r)?r:void 0;if(r!==void 0&&i===void 0){let $t=q(r);(!!1||$t===x)&&G(r)}let o=n??i??ct(),a=o??x;G(a);let l=xt(t.chain);if(l===null)throw new s("input.invalid",`Unsupported --chain '${t.chain}'.`);if(Bt(l)&&!ue(a))throw new s("input.invalid","--chain sepolia is testnet-only and can be used only with the beta or sandbox partner API, or an explicit loopback payout API. No request was sent.");o===void 0&&w({event:"payout_destination",payout_api_base:a},gt(a));let c=(t["api-key"]??ut())?.trim(),d=(t["api-secret"]??dt())?.trim();if(!c)throw new s("input.invalid","Missing store API key. Pass --api-key or set ALLSCALE_STORE_API_KEY.");if(!d)throw new s("input.invalid","Missing store API secret. Set ALLSCALE_STORE_API_SECRET (preferred) or pass --api-secret.");let p=Ct("--amount",t.amount),f=t["reference-id"].trim();if(!f)throw new s("input.invalid","--reference-id must be a non-empty idempotency key (it deduplicates retries).");let g=bt(t["stable-coin"]);if(g===null)throw new s("input.invalid",`Unsupported --stable-coin '${t["stable-coin"]}'.`);Rt("--amount",p,Dt(l,g));let k=Pt(t["receiver-email"]),Y=ne("--sender-display-name",t["sender-display-name"],100),Ut=ne("--message",t.message,200);return It({apiBase:a,apiKey:c,apiSecret:d,input:{amount:p,stableCoin:g,chain:l,referenceId:f,receiverEmail:k,senderDisplayName:Y,senderMessage:Ut}})}};
23
+ //# sourceMappingURL=send.js.map