@allscale/cli 1.0.4 → 1.0.5

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.
@@ -1,29 +1,29 @@
1
- "use strict";var zr=Object.create;var Fe=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var no=(e,n)=>{for(var t in n)Fe(e,t,{get:n[t],enumerable:!0})},bt=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Qr(n))!eo.call(e,r)&&r!==t&&Fe(e,r,{get:()=>n[r],enumerable:!(i=Xr(n,r))||i.enumerable});return e};var N=(e,n,t)=>(t=e!=null?zr(Zr(e)):{},bt(n||!e||!e.__esModule?Fe(t,"default",{value:e,enumerable:!0}):t,e)),to=e=>bt(Fe({},"__esModule",{value:!0}),e);var _l={};no(_l,{default:()=>yn});module.exports=to(_l);var wt=require("process"),Yr=require("@oclif/core");var j=require("@oclif/core");var Tt="public",Lt="https://app.allscale.io";var Et=["https://app.allscale.io"];var _n="Override the API base URL (public builds accept only https://app.allscale.io)";var Se="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Nt(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 Ct(e){return Nt(e)!==null}function de(e){let n=Nt(e);return n!==null&&Et.includes(n.origin)}function kn(e){return de(e)}function we(){return"".trim()||void 0}function ue(){return"public"}function W(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function wn(e){try{return new URL(e).origin}catch{return null}}function Ae(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return Sn()}function Sn(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let i=JSON.parse(e);if(!Array.isArray(i))return[];let r=[];for(let o of i){if(typeof o!="object"||o===null)continue;let{base:a,key:c,keyId:l}=o;if(typeof a!="string"||a.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";r.push({base:a.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return r}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 Tn="device-login",io=/^[A-Za-z0-9._-]{1,64}$/;function Ln(e){return io.test(e)?e:"<profile>"}function be(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ln(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Me(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Rt(e){let n=Ln(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${n}\` (recommended), or use \`${be(e)}\` for headless automation.`}function It(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Tn} --profile ${Ln(e)}\`.`}var ro={"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_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"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_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var oo=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 En(e){return(typeof e=="string"?e:String(e??"")).replace(oo,"")}var ao=64;function An(e,n=new Map,t=0){if(typeof e=="string")return En(e);if(e===null||typeof e!="object")return e;let i=n.get(e);if(i!==void 0)return i;if(t>=ao)return e;if(Array.isArray(e)){let a=[];n.set(e,a);for(let c of e)a.push(An(c,n,t+1));return a}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let o={};n.set(e,o);for(let[a,c]of Object.entries(e))Object.defineProperty(o,a,{value:An(c,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(n,t,i){super(En(t)),this.code=n,this.details=i&&An(i),this.name="AllscaleError"}get exitCode(){return ro[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function vt(e){if(e instanceof s)return e;if(e instanceof Error){if(co(e)){let n=po(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new s("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var so=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),lo=[/^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 co(e){if(uo(e))return!0;let n=e.name??"";return so.has(n)?n==="CLIError"?bn(e,"parse")||Ot(e.message):!0:Ot(e.message)}function uo(e){if(!bn(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&bn(e,"parse")}function Ot(e){return e?En(e).split(`
2
- `).some(n=>lo.some(t=>t.test(n.trim()))):!1}function bn(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function po(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function xt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var w=N(require("fs")),He=N(require("path")),Mt=N(require("crypto"));var fo="...<truncated>",mo=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,yo=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,In=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Nn=String.raw`(?:proxy[_-]?)?authorization`,ho=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Nn}"|'${Nn}'|${Nn})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${In}`,"gi"),go=/\b(https?:\/\/)[^\s/?#]+@/gi,_o=String.raw`(?:[A-Za-z0-9]+[_-])*`,ko=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Bt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Pt=Bt(_o),So=Bt(ko),wo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Pt}"|'${Pt}'|${So})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${In}`,"gi"),Cn=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)`,Ao=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Cn}"|'${Cn}'|${Cn})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${In}`,"g");function Ge(e){return e.replace(go,"$1<redacted>@").replace(mo,"<redacted-jwt>").replace(ho,"$1$2$3<redacted>").replace(wo,"$1$2<redacted>").replace(Ao,"$1$2<redacted>").replace(yo,"Bearer <redacted>")}var bo=/(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 qe(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return bo.test(n)}function Ut(e){let n="";for(let t of e){let i=t.codePointAt(0),r=i<=8||i>=11&&i<=12||i>=14&&i<=31||i>=127&&i<=159;n+=r?`\\u${i.toString(16).padStart(4,"0")}`:t}return n}function je(e,n,t=fo){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let c="",l=0;for(let d of t){let p=Buffer.byteLength(d,"utf8");if(l+p>n)break;c+=d,l+=p}return c}let r=n-i,o="",a=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(a+l>r)break;o+=c,a+=l}return`${o}${t}`}function v(e,n=16384){return je(Ut(Ge(e)),n)}var On=100,To=8,Lo=8*1024;function Ke(){return{remaining:Lo}}function Rn(e,n){let t=Math.min(16384,n.remaining),i=je(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function pe(e,n,t=0,i={}){if(t>To)return Rn("<truncated>",n);if(typeof e=="string"){let r=Ge(e);return Rn(i.escapeControls?Ut(r):r,n)}if(Array.isArray(e)){let r=e.slice(0,On),o=r.map(a=>pe(a,n,t+1,i));return e.length>r.length&&o.push(Rn(`<${e.length-r.length} more items truncated>`,n)),o}if(e!==null&&typeof e=="object"){let r=Object.create(null),o=Object.entries(e);for(let[a,c]of o.slice(0,On))r[a]=pe(c,n,t+1,i);return o.length>On&&(r.output_truncated=!0),r}return e}var vn=require("process");var xn=!1;function Pn(e){xn=e}function $t(){return xn}var Dt="1";function me(e,n){if(xn){let t={...e};delete t.version;let i=Ke(),r={event:t.event,...t},o=pe(r,i,0,{escapeControls:!0}),a=JSON.stringify({version:Dt,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Dt,event:o.event,output_truncated:!0})),vn.stderr.write(`${a}
4
- `)}else vn.stderr.write(n)}var Ft="2",ye=null,U=null,he=!1,Te=!1;function Eo(){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=Mt.randomBytes(4).toString("hex");return He.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var Bn=64*1024*1024,No=null;function Un(e={}){if(e.quiet&&(Te=!0),he)return;let n=Eo();if(!n)return;ye=null;let t=null;try{if((No??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let i=He.dirname(n);if(w.mkdirSync(i,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=w.statSync(i),d=l.mode&511;if(!l.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let r=w.constants.O_NOFOLLOW??0;t=w.openSync(n,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|r,384);let o=w.fstatSync(t),a=w.lstatSync(n);if(!o.isFile()||a.isSymbolicLink()||a.dev!==o.dev||a.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);w.fchmodSync(t,384)}catch(i){if(t!==null)try{w.closeSync(t)}catch{}Te||me({event:"sidecar_disabled",reason:"open_failed",detail:v(`sidecar path '${n}' could not be opened safely (${i.message})`)},`${v(`[allscale] sidecar path '${n}' could not be opened safely (${i.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}ye=n,U=t,he=!0}var Co=[/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 Oo(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Co.some(t=>t.test(n))}function Gt(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=Ro(n.pathname);let r=t;n.pathname!==i&&(r=!0);for(let[o]of n.searchParams)Oo(o)&&(n.searchParams.set(o,"<redacted>"),r=!0);return r?n.toString():e}catch{return e}}function Ro(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Io(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Gt(e.url)}:e}function vo(e){let n=new Date().toISOString(),t=e,{type:i,...r}=t,o=pe(r,Ke()),a=JSON.stringify({version:Ft,timestamp:n,type:i,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Ft,timestamp:n,type:i,output_truncated:!0})),a}function h(e){if(!he||!ye||U===null)return;let n=Io(e),t=vo(n);try{if(w.fstatSync(U).size+Buffer.byteLength(t,"utf8")+1>Bn){he=!1;try{w.closeSync(U)}catch{}U=null,Te||me({event:"sidecar_disabled",reason:"size_limit",...ye===null?{}:{path:v(ye)},max_bytes:Bn},`${v(`[allscale] sidecar exceeded ${Bn} bytes; disabling it for the rest of this run. Rotate or remove ${ye}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
1
+ "use strict";var zr=Object.create;var Fe=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var no=(e,n)=>{for(var t in n)Fe(e,t,{get:n[t],enumerable:!0})},Lt=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Qr(n))!eo.call(e,r)&&r!==t&&Fe(e,r,{get:()=>n[r],enumerable:!(i=Xr(n,r))||i.enumerable});return e};var N=(e,n,t)=>(t=e!=null?zr(Zr(e)):{},Lt(n||!e||!e.__esModule?Fe(t,"default",{value:e,enumerable:!0}):t,e)),to=e=>Lt(Fe({},"__esModule",{value:!0}),e);var _l={};no(_l,{default:()=>hn});module.exports=to(_l);var bt=require("process"),Yr=require("@oclif/core");var j=require("@oclif/core");var Et="public",Nt="https://app.allscale.io";var Ct=["https://app.allscale.io"];var kn="Override the API base URL (public builds accept only https://app.allscale.io)";var Se="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Ot(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 Rt(e){return Ot(e)!==null}function de(e){let n=Ot(e);return n!==null&&Ct.includes(n.origin)}function Sn(e){return de(e)}function we(){return"".trim()||void 0}function ue(){return"public"}function W(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function An(e){try{return new URL(e).origin}catch{return null}}function Ae(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return wn()}function wn(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let i=JSON.parse(e);if(!Array.isArray(i))return[];let r=[];for(let o of i){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 u=typeof c=="string"?c.trim():"";r.push({base:a.trim(),key:l,keyId:u.length>0?u:"cli-1"})}return r}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 Ln="device-login",io=/^[A-Za-z0-9._-]{1,64}$/;function En(e){return io.test(e)?e:"<profile>"}function be(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":En(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Me(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function vt(e){let n=En(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${n}\` (recommended), or use \`${be(e)}\` for headless automation.`}function xt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Ln} --profile ${En(e)}\`.`}var ro={"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_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"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_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var oo=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 Nn(e){return(typeof e=="string"?e:String(e??"")).replace(oo,"")}var ao=64;function bn(e,n=new Map,t=0){if(typeof e=="string")return Nn(e);if(e===null||typeof e!="object")return e;let i=n.get(e);if(i!==void 0)return i;if(t>=ao)return e;if(Array.isArray(e)){let a=[];n.set(e,a);for(let l of e)a.push(bn(l,n,t+1));return a}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let o={};n.set(e,o);for(let[a,l]of Object.entries(e))Object.defineProperty(o,a,{value:bn(l,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(n,t,i){super(Nn(t)),this.code=n,this.details=i&&bn(i),this.name="AllscaleError"}get exitCode(){return ro[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Pt(e){if(e instanceof s)return e;if(e instanceof Error){if(co(e)){let n=po(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new s("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var so=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),lo=[/^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 co(e){if(uo(e))return!0;let n=e.name??"";return so.has(n)?n==="CLIError"?Tn(e,"parse")||It(e.message):!0:It(e.message)}function uo(e){if(!Tn(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&Tn(e,"parse")}function It(e){return e?Nn(e).split(`
2
+ `).some(n=>lo.some(t=>t.test(n.trim()))):!1}function Tn(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function po(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function Bt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var w=N(require("fs")),He=N(require("path")),qt=N(require("crypto"));var fo="...<truncated>",mo=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,yo=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,vn=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Cn=String.raw`(?:proxy[_-]?)?authorization`,ho=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Cn}"|'${Cn}'|${Cn})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${vn}`,"gi"),go=/\b(https?:\/\/)[^\s/?#]+@/gi,_o=String.raw`(?:[A-Za-z0-9]+[_-])*`,ko=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Dt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Ut=Dt(_o),So=Dt(ko),wo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ut}"|'${Ut}'|${So})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${vn}`,"gi"),On=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)`,Ao=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${On}"|'${On}'|${On})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${vn}`,"g");function Ge(e){return e.replace(go,"$1<redacted>@").replace(mo,"<redacted-jwt>").replace(ho,"$1$2$3<redacted>").replace(wo,"$1$2<redacted>").replace(Ao,"$1$2<redacted>").replace(yo,"Bearer <redacted>")}var bo=/(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 qe(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return bo.test(n)}function $t(e){let n="";for(let t of e){let i=t.codePointAt(0),r=i<=8||i>=11&&i<=12||i>=14&&i<=31||i>=127&&i<=159;n+=r?`\\u${i.toString(16).padStart(4,"0")}`:t}return n}function je(e,n,t=fo){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let l="",c=0;for(let u of t){let p=Buffer.byteLength(u,"utf8");if(c+p>n)break;l+=u,c+=p}return l}let r=n-i,o="",a=0;for(let l of e){let c=Buffer.byteLength(l,"utf8");if(a+c>r)break;o+=l,a+=c}return`${o}${t}`}function v(e,n=16384){return je($t(Ge(e)),n)}var Rn=100,To=8,Lo=8*1024;function Ke(){return{remaining:Lo}}function In(e,n){let t=Math.min(16384,n.remaining),i=je(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function pe(e,n,t=0,i={}){if(t>To)return In("<truncated>",n);if(typeof e=="string"){let r=Ge(e);return In(i.escapeControls?$t(r):r,n)}if(Array.isArray(e)){let r=e.slice(0,Rn),o=r.map(a=>pe(a,n,t+1,i));return e.length>r.length&&o.push(In(`<${e.length-r.length} more items truncated>`,n)),o}if(e!==null&&typeof e=="object"){let r=Object.create(null),o=Object.entries(e);for(let[a,l]of o.slice(0,Rn))r[a]=pe(l,n,t+1,i);return o.length>Rn&&(r.output_truncated=!0),r}return e}var xn=require("process");var Pn=!1;function Bn(e){Pn=e}function Mt(){return Pn}var Ft="1";function me(e,n){if(Pn){let t={...e};delete t.version;let i=Ke(),r={event:t.event,...t},o=pe(r,i,0,{escapeControls:!0}),a=JSON.stringify({version:Ft,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Ft,event:o.event,output_truncated:!0})),xn.stderr.write(`${a}
4
+ `)}else xn.stderr.write(n)}var Gt="2",ye=null,U=null,he=!1,Te=!1;function Eo(){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=qt.randomBytes(4).toString("hex");return He.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var Un=64*1024*1024,No=null;function Dn(e={}){if(e.quiet&&(Te=!0),he)return;let n=Eo();if(!n)return;ye=null;let t=null;try{if((No??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let i=He.dirname(n);if(w.mkdirSync(i,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=w.statSync(i),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=w.constants.O_NOFOLLOW??0;t=w.openSync(n,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|r,384);let o=w.fstatSync(t),a=w.lstatSync(n);if(!o.isFile()||a.isSymbolicLink()||a.dev!==o.dev||a.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let l=o.mode&511;if((l&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${l.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);w.fchmodSync(t,384)}catch(i){if(t!==null)try{w.closeSync(t)}catch{}Te||me({event:"sidecar_disabled",reason:"open_failed",detail:v(`sidecar path '${n}' could not be opened safely (${i.message})`)},`${v(`[allscale] sidecar path '${n}' could not be opened safely (${i.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}ye=n,U=t,he=!0}var Co=[/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 Oo(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Co.some(t=>t.test(n))}function jt(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=Ro(n.pathname);let r=t;n.pathname!==i&&(r=!0);for(let[o]of n.searchParams)Oo(o)&&(n.searchParams.set(o,"<redacted>"),r=!0);return r?n.toString():e}catch{return e}}function Ro(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Io(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:jt(e.url)}:e}function vo(e){let n=new Date().toISOString(),t=e,{type:i,...r}=t,o=pe(r,Ke()),a=JSON.stringify({version:Gt,timestamp:n,type:i,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Gt,timestamp:n,type:i,output_truncated:!0})),a}function h(e){if(!he||!ye||U===null)return;let n=Io(e),t=vo(n);try{if(w.fstatSync(U).size+Buffer.byteLength(t,"utf8")+1>Un){he=!1;try{w.closeSync(U)}catch{}U=null,Te||me({event:"sidecar_disabled",reason:"size_limit",...ye===null?{}:{path:v(ye)},max_bytes:Un},`${v(`[allscale] sidecar exceeded ${Un} bytes; disabling it for the rest of this run. Rotate or remove ${ye}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
6
  `);return}w.appendFileSync(U,`${t}
7
7
  `)}catch(i){if(he=!1,U!==null){try{w.closeSync(U)}catch{}U=null}try{Te||me({event:"sidecar_disabled",reason:"write_failed",detail:v(i.message)},`${v(`[allscale] sidecar write failed (${i.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var J=Gt;function qt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Le(){if(Te=!1,he=!1,U!==null){try{w.closeSync(U)}catch{}U=null}}function jt(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||qt()||!n}var Ee=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"]),xo=new Set(Array.from(Ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Po=Array.from(Ee).filter(e=>e.startsWith("--")).sort((e,n)=>n.length-e.length),Bo=new Set(["--otp-stdin","--password-stdin"]);function Dn(e){let n=[];for(let t=0;t<e.length;t+=1){let i=e[t];if(i.startsWith("-")){let o=i.indexOf("=");if(o!==-1){let a=i.slice(0,o);if(Ee.has(a)){n.push(`${a}=<redacted>`);continue}}}if(Ee.has(i)){n.push(i),t+1<e.length&&(Ee.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2&&i[1]!=="="){let o=i.slice(0,2);if(xo.has(o)){n.push(`${o}<redacted>`);continue}}let r=Bo.has(i)?void 0:Po.find(o=>i.length>o.length&&i.startsWith(o));if(r){n.push(`${r}<redacted>`);continue}n.push(i)}return n}function Kt(e){h({type:"error",code:e.code,message:v(e.message)}),h({type:"command-end",ok:!1,exitCode:e.exitCode}),Le()}var Ne=we()??Lt,_e={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 z(e){return Ct(e)?new URL(e).origin:null}function x(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Ht(){let e=process.env[_e.TOKEN]?.trim();return e&&e.length>0?e:void 0}function $n(){let e=process.env[_e.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Ce(){let e=process.env[_e.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Jt(){let e=process.env[_e.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[_e.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Vt(){let e=process.env[_e.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Wt(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:r}=e;if(we()===void 0&&Ne!==""&&"".length!==0&&!t&&r!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
8
+ `)}catch{}}}var J=jt;function Kt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Le(){if(Te=!1,he=!1,U!==null){try{w.closeSync(U)}catch{}U=null}}function Ht(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Kt()||!n}var Ee=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"]),xo=new Set(Array.from(Ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Po=Array.from(Ee).filter(e=>e.startsWith("--")).sort((e,n)=>n.length-e.length),Bo=new Set(["--otp-stdin","--password-stdin"]);function $n(e){let n=[];for(let t=0;t<e.length;t+=1){let i=e[t];if(i.startsWith("-")){let o=i.indexOf("=");if(o!==-1){let a=i.slice(0,o);if(Ee.has(a)){n.push(`${a}=<redacted>`);continue}}}if(Ee.has(i)){n.push(i),t+1<e.length&&(Ee.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2&&i[1]!=="="){let o=i.slice(0,2);if(xo.has(o)){n.push(`${o}<redacted>`);continue}}let r=Bo.has(i)?void 0:Po.find(o=>i.length>o.length&&i.startsWith(o));if(r){n.push(`${r}<redacted>`);continue}n.push(i)}return n}function Jt(e){h({type:"error",code:e.code,message:v(e.message)}),h({type:"command-end",ok:!1,exitCode:e.exitCode}),Le()}var Ne=we()??Nt,_e={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 z(e){return Rt(e)?new URL(e).origin:null}function x(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Yt(){let e=process.env[_e.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Fn(){let e=process.env[_e.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Ce(){let e=process.env[_e.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Vt(){let e=process.env[_e.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Wt(){let e=process.env[_e.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function zt(){let e=process.env[_e.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Xt(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:r}=e;if(we()===void 0&&Ne!==""&&"".length!==0&&!t&&r!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
9
  The CLI default is now ${Ne} (production), but a saved profile wins over the default,
10
10
  so this session still uses staging. That pin was written before the default changed, so it may just be
11
11
  the old default rather than a deliberate choice.
12
12
  To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
13
13
  To move to production, run: allscale device-login --api-base ${Ne}
14
- `}var X=N(require("fs")),zt=N(require("os")),Fn=N(require("path")),Mn=N(require("@iarna/toml"));var $o=".allscale",Fo="config.toml";function Oe(){return Fn.join(zt.homedir(),$o)}function Mo(){return Fn.join(Oe(),Fo)}function Je(){let e=Mo();if(!X.existsSync(e))return{};let n=X.readFileSync(e,"utf-8");try{return Mn.parse(n)}catch(t){throw new s("internal",`Failed to parse ${e}: ${t.message}`)}}function Xt(e){return Object.keys(e.profile??{}).sort()}function Qt(e,n){return e.profile?.[n]}function Zt(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new s("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function ke(e){if(!de(e))throw new s("input.invalid",`Refusing to send credentials to API base ${x(e)}. `+Se)}function Ye(e,n){ke(e);let t=z(e),i=typeof n=="string"?z(n):null;if(t&&i===t)return;let r=typeof n=="string"?x(n):"<missing origin binding>";throw new s("input.invalid",`Refusing to send stored credentials: API base ${x(e)} does not match their bound origin ${r}. Re-login against the intended API base before retrying.`)}function ei(e,n){let t=z(e),i=z(n);if(!(t&&i===t))throw new s("input.invalid",`Refusing API request to ${x(n)} because it is outside the configured API origin ${x(e)}.`)}function Ve(e){let n=qo(e);if(n)throw new s("input.invalid",n.message)}function Go(){let e=we();if(e===void 0)return;let n=Ae();return n.length>0?{endpoints:n.map(t=>t.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function qo(e){let n=Go();if(n===void 0||W(e))return;let{endpoints:t,fromPairs:i}=n,r=z(e),o=t.map(c=>z(c)).filter(c=>c!==null);if(r!==null&&o.includes(r))return;let a=t.map(c=>x(c)).join(", ");return{message:i?`Refusing to send to ${x(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.`:`Refusing to send to ${x(e)} \u2014 this build only signs for ${a}. Re-login against this build's environment, or use a build for that one.`}}var ni=require("@noble/hashes/sha3");var We=(a=>(a[a.ETHEREUM=1]="ETHEREUM",a[a.BASE=5]="BASE",a[a.BNB=6]="BNB",a[a.ARBITRUM=7]="ARBITRUM",a[a.POLYGON=8]="POLYGON",a[a.OPTIMISM=9]="OPTIMISM",a))(We||{});var jo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},ti=["ethereum","bsc","base","polygon","arbitrum","optimism"],ze=["USDT","USDC"];function ii(e){return jo[e.toLowerCase()]??null}function ri(e){let n=e.toUpperCase();return n==="USDT"?1:n==="USDC"?2:null}function oi(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let n=e.slice(2);if(n===n.toLowerCase()||n===n.toUpperCase())return!0;let t=n.toLowerCase(),i=Buffer.from((0,ni.keccak_256)(Buffer.from(t,"ascii"))).toString("hex");for(let r=0;r<n.length;r+=1){let o=n[r];if(!/[a-fA-F]/.test(o))continue;let a=Number.parseInt(i[r],16)>=8;if(a&&o!==o.toUpperCase()||!a&&o!==o.toLowerCase())return!1}return!0}var Ko=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function ai(e){return Ko.has(e.toLowerCase())}function Xe(e,n){let i={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return i?`${i}/${n}`:""}function M(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Q(e){return e===1?"USDT":"USDC"}var Ho="unknown_otp_id",Jo="invalid_code",Yo="expired_code";function Vo(e){return`'${e.replace(/'/g,"'\\''")}'`}function si(e){return`Run \`allscale otp-send --email ${Vo(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Wo=new Map([[Ho,(e,n)=>`${e}: this environment never issued the --otp-id you passed for '${n}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${si(n)}`],[Jo,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[Yo,(e,n,t)=>t?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${si(n)}`]]);var li=[...Wo.keys()];var Y=require("@oclif/core"),Re=class e extends j.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:j.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:j.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ue()==="public"}),"api-base":j.Flags.string({description:_n,helpGroup:"GLOBAL",hidden:ue()==="public"}),"insecure-storage":j.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{Pn(this.jsonEnabled()),Un(),h({type:"session-start",command:this.id??"",argv:Dn(this.argv)});let n=this.constructor;if(ue()==="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(!n.isLocalOnly&&Ce()!==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 t=jt(this.jsonEnabled()),i=this.argv.length===0&&!t&&ra(n)?this.config.findCommand(this.id??""):void 0;if(i){Le();let o=await(0,j.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(i,this.config.topics);return}if(n.requiresEscapeHatch&&!Vt())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. Access remains governed by the key's granted scopes, which the backend checks on each request.");let r=await this.runCommand();return h({type:"command-end",ok:!0}),Le(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||xt(r),{data:r})}catch(n){let t=vt(n);Kt({code:t.code,message:t.message,exitCode:t.exitCode}),this.emitError(t),process.exitCode=t.exitCode;return}finally{Pn(!1)}}resolveSessionApiBaseChain(n){let t=Je(),i=n.profile??void 0,r=n["api-base"]??void 0,o=i!==void 0||$n()!==void 0,a=Zt(t,i,$n()),c=Qt(t,a),l=ue()==="public"&&Ce()!==void 0,d=r??(l?void 0:Ce()),p=d??c?.api_base??Ne,f=Wt({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,me({event:"legacy_staging_profile",api_base:p,profile:a},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:c?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||ke(t),t}resolveContext(n){if(ue()==="public"){if(n.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(n["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&&Ce()!==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 t=n.token??void 0,i=!!n["insecure-storage"],{apiBase:r,explicitApiBase:o,envApiBaseIgnored:a,profile:c,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(ke(r),Ve(r)),{apiBase:r,profile:c,token:t??Ht(),insecureStorage:i||Jt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:a}}emitError(n){process.stderr.write(`${ia(n)}
15
- `)}};var zo=/_(removed|cleared|count|total)$/i;function Xo(e,n){return typeof n=="number"&&zo.test(e)}var Qo=new Set(ze);function Zo(e,n){return e==="token_symbol"&&typeof n=="string"&&Qo.has(n)}var ea=new Set(li);function na(e,n){return e==="otp_reason"&&typeof n=="string"&&ea.has(n)}var Qe=100;function Ze(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,Qe),i=t.map(r=>Ze(r,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[r,o]of i.slice(0,Qe))t[r]=qe(r)&&!Xo(r,o)&&!Zo(r,o)&&!na(r,o)?"<redacted>":Ze(o,n+1);if(i.length>Qe){let r="<truncated>";for(;r in t;)r=`<${r}>`;t[r]=`${i.length-Qe} more keys`}return t}if(typeof e=="string"){let t=ta(e);return t!==void 0?v(JSON.stringify(Ze(t,n+1))):v(e)}return e}function ta(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function ia(e){let n=$t()?void 0:2,t=Ze(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:v(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function ra(e){if(e.requiresInput===!0)return!0;let n=r=>typeof r=="object"&&r!==null&&r.required===!0,t=e.flags??{},i=e.args??{};return Object.values(t).some(r=>n(r))||Object.values(i).some(r=>n(r))}function oa(e,n={}){let t;try{t=Xt(Je())}catch{return}if(!(t.length===0||t.includes(e)))return new s("auth.unknown_profile",It(e)+(n.messageSuffix??""),{profile:e})}function en(e){if(e.profileExplicit){let n=oa(e.profile);if(n)return n}return new s("auth.no_token",Rt(e.profile))}var wi=N(require("path"));var jn=require("crypto"),u=N(require("fs")),b=N(require("path"));var nn=1024*1024,aa=5e3,sa=20,la=3e4,Gn=4096,ca=new Int32Array(new SharedArrayBuffer(4)),Ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function tn(e){return e instanceof Ie}var P=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},da=null;function ee(){return new s("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 rn(){return(da??process.platform)!=="win32"}function hi(){if(!rn())throw ee()}function gi(e){try{return u.default.lstatSync(e),!1}catch(n){if(!A(n,"ENOENT"))throw n}try{let n=u.default.lstatSync(b.dirname(e));return!n.isSymbolicLink()&&n.isDirectory()}catch(n){if(A(n,"ENOENT"))return!0;throw n}}function A(e,n){return typeof e=="object"&&e!==null&&e.code===n}function ve(e,n){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${n} is not owned by the current effective user`)}function xe(e,n){return e.dev===n.dev&&e.ino===n.ino}function ua(e){Atomics.wait(ca,0,0,e)}function _i(e){try{return process.kill(e,0),!0}catch(n){return!A(n,"ESRCH")}}function pa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ci(e,n){let t=b.dirname(e);n&&u.default.mkdirSync(t,{recursive:!0,mode:448});let i;try{i=u.default.lstatSync(t)}catch(o){if(!n&&A(o,"ENOENT"))return!1;throw o}if(i.isSymbolicLink()||!i.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let r=null;try{r=u.default.openSync(t,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0));let o=u.default.fstatSync(r),a=u.default.lstatSync(t);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!xe(o,a))throw new Error("credential-store parent changed while it was being inspected");ve(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&b.basename(t)===".allscale"&&(u.default.fchmodSync(r,448),c=u.default.fstatSync(r)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{r!==null&&u.default.closeSync(r)}return!0}function K(e,n,t,i={}){if(!t.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let r;try{r=u.default.lstatSync(e)}catch(o){throw i.retryOnPathChange&&A(o,"ENOENT")?new P:o}if(!xe(t,r))throw i.retryOnPathChange?new P:new Error("credential-store target changed while it was being opened or is not a regular file");if(r.isSymbolicLink()||!r.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!i.allowMultipleLinks&&(t.nlink!==1||r.nlink!==1))throw new Ie;if(ve(t,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(n,384);let o=u.default.fstatSync(n);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return t}function fa(e,n){if(n.size>nn)throw new Error("credential-store file exceeds the maximum supported size");let t=Buffer.alloc(nn+1),i=0;for(;i<t.length;){let r=u.default.readSync(e,t,i,t.length-i,null);if(r===0)break;i+=r}if(i>nn)throw new Error("credential-store file exceeds the maximum supported size");return t.subarray(0,i).toString("utf8")}function di(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(A(o,"ENOENT"))return null;throw o}throw r}let t=u.default.fstatSync(n),i=K(e,n,t);return fa(n,i)}finally{n!==null&&u.default.closeSync(n)}}function ui(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT")&&gi(e))return;throw r}let t=u.default.fstatSync(n),i=K(e,n,t);ne(e,i)}finally{n!==null&&u.default.closeSync(n)}Si(b.dirname(e))}function ma(e){let n;try{n=u.default.lstatSync(e)}catch(t){if(A(t,"ENOENT"))return;throw t}if(n.isSymbolicLink()||!n.isFile())throw new Error("credential-store replacement target must be a regular file");if(n.nlink!==1)throw new Ie;ve(n,"credential-store replacement target")}function ya(e,n){for(let t=0;t<8;t+=1){let i=(0,jn.randomBytes)(12).toString("hex"),r=b.join(e,`.${n}.${process.pid}.${i}.tmp`);try{return{fd:u.default.openSync(r,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:r}}catch(o){if(A(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function ki(e,n){let t=0;for(;t<n.length;){let i=u.default.writeSync(e,n,t,n.length-t,null);if(!Number.isSafeInteger(i)||i<=0)throw new Error("credential-store temp file write made no progress");t+=i}}function Si(e){if(process.platform==="win32")return;let n=null;try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(n)}catch{}finally{if(n!==null)try{u.default.closeSync(n)}catch{}}}function ha(e,n){let t=Buffer.from(n,"utf8");if(t.length>nn)throw new Error("credential-store file exceeds the maximum supported size");let i=b.dirname(e),r=b.basename(e),o=null,a=null,c=!1;try{let l=ya(i,r);o=l.fd,a=l.tempPath;let d=u.default.fstatSync(o);if((K(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");ki(o,t),u.default.fsyncSync(o),K(a,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),ma(e),u.default.renameSync(a,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&a!==null)try{u.default.unlinkSync(a)}catch{}}Si(i)}function ga(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function _a(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function ka(e,n){if(n.size>Gn)return null;let t=Buffer.alloc(Gn+1),i=0;for(;i<t.length;){let o=u.default.readSync(e,t,i,t.length-i,null);if(o===0)break;i+=o}if(i>Gn)return null;let r;try{r=JSON.parse(t.subarray(0,i).toString("utf8"))}catch{return null}return typeof r!="object"||r===null||!Number.isSafeInteger(r.pid)||(r.pid??0)<=0||typeof r.nonce!="string"||!/^[a-f0-9]{24}$/.test(r.nonce??"")||typeof r.target!="string"?null:r}function ne(e,n){let t=u.default.lstatSync(e);if(t.isSymbolicLink()||!t.isFile()||!xe(t,n))throw new Error("credential-store lock changed while it was being inspected");ve(t,"credential-store lock"),u.default.unlinkSync(e)}function pi(e,n){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(l){if(A(l,"ENOENT"))try{let d=u.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new P}catch(d){if(A(d,"ENOENT"))return{state:"absent"};throw d}throw l}let i=u.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ka(t,r);return{state:(o?.target===n&&o?!_i(o.pid):Date.now()-r.mtimeMs>=la)?"stale":"active",stats:r}}finally{t!==null&&u.default.closeSync(t)}}function Sa(e,n){for(let t=0;t<8;t+=1){let i=(0,jn.randomBytes)(12).toString("hex"),r=b.join(e,`.${n}.${process.pid}.${i}.lock-claim`),o={pid:process.pid,nonce:i,target:n},a=null;try{a=u.default.openSync(r,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384);let c=u.default.fstatSync(a),l=K(r,a,c,{allowMultipleLinks:!0});return ki(a,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(a),{claimPath:r,metadata:o,stats:l}}catch(c){if(A(c,"EEXIST"))continue;try{u.default.unlinkSync(r)}catch{}throw c}finally{a!==null&&u.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function wa(e,n){let t;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){throw A(i,"ENOENT")?new P:i}try{let i=u.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!xe(r,n))throw new P;return{fd:t,lockPath:e,stats:r}}catch(i){throw u.default.closeSync(t),i}}function fi(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(t){if(A(t,"ENOENT"))try{let i=u.default.lstatSync(e);throw i.isSymbolicLink()||!i.isFile()?new Error("credential-store recovery gate must be a real regular file"):new P}catch(i){if(A(i,"ENOENT"))return!1;throw i}throw t}return K(e,n,u.default.fstatSync(n),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{n!==null&&u.default.closeSync(n)}}function Aa(e){let n;try{n=u.default.openSync(e,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_RDWR|(u.default.constants.O_NOFOLLOW??0),384)}catch(i){if(A(i,"EEXIST"))return null;throw i}let t=null;try{t=u.default.fstatSync(n);let i=K(e,n,t,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:n,lockPath:e,stats:i}}catch(i){if(t!==null)try{ne(e,t)}catch{}throw u.default.closeSync(n),i}}function Z(e,n){if(Date.now()>=e)throw n?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");ua(sa)}function mi(e){let n=b.dirname(e),t=b.basename(e),i=ga(e),r=_a(e),o=Sa(n,t),a=Date.now()+aa,c=!1,l=!1,d=null,p;try{for(;d===null;)try{if(fi(r)){Z(a,!0);continue}u.default.linkSync(o.claimPath,i),l=!0,d=wa(i,o.stats),c=!0}catch(f){if(l&&!c){try{ne(i,o.stats)}catch{}l=!1}if(f instanceof P){Z(a,!1);continue}if(!A(f,"EEXIST"))throw f;let y;try{y=pi(i,t)}catch(g){if(g instanceof P){Z(a,!1);continue}throw g}if(y.state==="absent")continue;if(y.state==="stale"){let g;try{g=Aa(r)}catch(_){if(_ instanceof P){Z(a,!1);continue}throw _}if(g!==null){try{let _;try{_=pi(i,t)}catch(E){if(E instanceof P){Z(a,!1);continue}throw E}_.state==="stale"&&ne(i,_.stats)}finally{qn(g)}continue}}let m;try{m=fi(r)}catch(g){if(g instanceof P){Z(a,!1);continue}throw g}Z(a,m)}}catch(f){p=f}try{ne(o.claimPath,o.stats)}catch(f){!A(f,"ENOENT")&&!c&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function qn(e){try{ne(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function ba(e,n){let t=pa(n),i=new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!i)return null;let r=Number(i[1]);return Number.isSafeInteger(r)&&r>0?r:null}function yi(e){let n=b.dirname(e),t=b.basename(e);for(let i of u.default.readdirSync(n)){let r=ba(i,t);if(r===null||_i(r))continue;let o=b.join(n,i),a=null;try{try{a=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(A(d,"ENOENT")||A(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(a),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!xe(c,l))continue;try{ve(c,"credential-store orphan")}catch{continue}ne(o,c)}catch(c){if(!A(c,"ENOENT"))throw c}finally{a!==null&&u.default.closeSync(a)}}}function Pe(e,n,t){if(!rn()){if(n.allowUnsupportedPlatformCleanup){if(n.createParent)throw ee();if(!ci(e,!1))return t({read:()=>null,remove:()=>{},write:()=>{throw ee()}});let a=mi(e);try{return yi(e),t({read:()=>di(e),remove:()=>ui(e),write:()=>{throw ee()}})}finally{qn(a)}}if(!n.createParent){let o=!1;try{o=gi(e)}catch{throw ee()}if(o)return t({read:()=>null,remove:()=>{},write:()=>{throw ee()}})}throw ee()}if(!ci(e,n.createParent))return t({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let r=mi(e);try{return yi(e),t({read:()=>di(e),remove:()=>ui(e),write:o=>ha(e,o)})}finally{qn(r)}}var Kn="allscale-cli";function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ai(e){return Vn(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function ie(e){return new s("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 Hn(){return new s("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 on(){return new s("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var te,Jn=!1;function Ta(){return Yt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function La(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let n=e.message;return typeof n=="string"&&n.split(`
16
- `,1)[0]==="Cannot find module 'keytar'"}function Ea(){if(te!==void 0)return te;if(Ta())return Jn=!1,te=null,te;try{te=require("keytar"),Jn=!1}catch(e){Jn=!La(e),te=null}return te}var Na="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function bi(){let e=rn()?"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 s("storage.unavailable",`${Na} `+e+" Never silently downgrade in production.")}async function Yn(e){try{return await e()}catch{throw bi()}}var Wn=class{constructor(n){this.keytar=n}keytar;kind="keychain";async read(n){let t=await Yn(()=>this.keytar.getPassword(Kn,n));if(t===null)return null;let i;try{i=JSON.parse(t)}catch{throw ie("OS keychain")}if(!Ai(i))throw ie("OS keychain");return i}async get(n){return this.read(n)}async set(n,t){await this.read(n),await Yn(()=>this.keytar.setPassword(Kn,n,JSON.stringify(t)))}async delete(n){await this.read(n),await Yn(()=>this.keytar.deletePassword(Kn,n))}},Ca="credentials.json",zn=class{kind="insecure-file";filePath;constructor(n){this.filePath=n??wi.join(Oe(),Ca)}read(n){let t;try{t=n.read()}catch(r){throw tn(r)?Hn():ie("plaintext file")}if(t===null)return{profiles:{}};let i;try{i=JSON.parse(t)}catch{throw ie("plaintext file")}if(!Vn(i)||!Vn(i.profiles))throw ie("plaintext file");return i}write(n,t){try{n.write(JSON.stringify(t,null,2))}catch(i){throw tn(i)?Hn():on()}}profileTokens(n,t){let i=n.profiles[t];if(i!==void 0){if(!Ai(i))throw ie("plaintext file");return i}}async get(n){try{return Pe(this.filePath,{createParent:!1},t=>this.profileTokens(this.read(t),n)??null)}catch(t){throw t instanceof s?t:ie("plaintext file")}}async set(n,t){try{Pe(this.filePath,{createParent:!0},i=>{let r=this.read(i);this.profileTokens(r,n),r.profiles[n]=t,this.write(i,r)})}catch(i){throw i instanceof s?i:on()}}async delete(n){try{Pe(this.filePath,{createParent:!1},t=>{let i=this.read(t);this.profileTokens(i,n)!==void 0&&(delete i.profiles[n],this.write(t,i))})}catch(t){throw t instanceof s?t:on()}}async clearProfile(n){try{return Pe(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},t=>{let i=this.read(t);return this.profileTokens(i,n)===void 0?!1:(delete i.profiles[n],Object.keys(i.profiles).length===0?t.remove():this.write(t,i),!0)})}catch(t){throw t instanceof s?t:tn(t)?Hn():on()}}};function an(e){if(e.insecureStorage)return hi(),new zn(e.insecureFilePath);let n=Ea();if(n)return new Wn(n);throw bi()}var Xn=class{kind="insecure-file";async get(n){return null}async set(n,t){throw new s("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(n){}};function sn(){return new Xn}async function Ti(e){if(e.token)return{kind:"override",accessToken:e.token};let t=await an({insecureStorage:e.insecureStorage}).get(e.profile),i=t?.api_base;return t?.agent_key?{kind:"agent",storedApiBase:i,businessId:Qn(t.business_id),userEmail:Qn(t.user_email),scopes:Oa(t.scopes)}:t?.access_token?{kind:"human",storedApiBase:i,accessToken:t.access_token,userEmail:Qn(t.user_email)}:{kind:"none"}}function Qn(e){return typeof e=="string"&&e.length>0?e:void 0}function Oa(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string"&&t.length>0);return n.length>0?n:void 0}function Ei(e){let n=e.split(".");if(n.length!==3)throw new s("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let t;try{let i=Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");t=JSON.parse(i)}catch{throw Li()}if(typeof t!="object"||t===null||Array.isArray(t))throw Li();return t}function Li(){return new s("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}async function Ra(e){let n=i=>{let r=Ei(i);return typeof r.user_id=="string"&&r.user_id.length>0?r.user_id:void 0},t=await Ti(e);switch(t.kind){case"override":case"human":return n(t.accessToken);case"agent":return t.businessId;case"none":throw en({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ia(t)}}function Ia(e){throw new s("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}var va=/^[0-9a-f]{24}$/i;async function Ni(e,n){if(typeof n!="string"||n.length===0)return;if(!va.test(n))throw new s("input.invalid",`--business-id '${n}' is not a valid business id (expected 24 hexadecimal characters). Omit the flag to use the business you are signed in as.`);let t=await Ra(e);if(t===void 0){process.stderr.write(`Note: could not verify that --business-id '${n}' is your own business \u2014 this session stores no business id (an agent-key login predating the backend returning it). The command acts as the business you are signed in as regardless. Re-run \`allscale device-login\` to store it and enable this check.
17
- `);return}if(t.toLowerCase()!==n.toLowerCase())throw new s("auth.permission_denied",`--business-id '${n}' is not the business you are signed in as. This command always acts as the authenticated business, so a different business id cannot be used. Omit the flag, or sign in as that business.`)}var ln="allscale_access_token",Zn="allscale_refresh_token";function Ci(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(t=>{let i=t.indexOf(";"),r=i===-1?t:t.slice(0,i),o=r.indexOf("=");return o===-1?null:{name:r.slice(0,o).trim(),value:r.slice(o+1).trim()}}).filter(t=>t!==null)}function et(e){return e.map(n=>`${n.name}=${n.value}`).join("; ")}function nt(e,n){return e.find(t=>t.name===n)?.value??null}var Oi=N(require("crypto")),Ri=N(require("fs")),Ii=N(require("path"));var xa="key-id",Pa="x-allscale-cli-version",tt="cli-1",Ba="aScaLe_cli_obf_v1",Ua="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Da(e,n){let t=Buffer.from(e,"base64"),i=Buffer.from(n,"utf8"),r=Buffer.alloc(t.length);for(let o=0;o<t.length;o++)r[o]=t[o]^i[o%i.length];return r.toString("utf8")}var $a=Da(Ua,Ba),vi=`Bearer ${$a}`;function xi(e,n){let t=wn(e);if(t!==null)return n.find(i=>wn(i.base)===t)}function Fa(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let n=Ae();if(n.length>0){let i=xi(e,n);if(i)return i.key;if(W(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?r:W(n[0].base)?n[0].key:void 0}return}let t=process.env.ALLSCALE_SIGNING_KEY;return t&&t.trim().length>0?t:void 0}function Ma(e){{let i="cli-1".trim();if(i.length>0)return i}let n=Ae();if(n.length>0){let i=e!==void 0?xi(e,n):void 0;if(i)return i.keyId;if(e!==void 0&&W(e)){let r=process.env.ALLSCALE_SIGNING_KEY;if(r&&r.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():tt}if(!W(n[0].base))return tt}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():tt}function Ga(){return"1.0.4"}function qa(){return new s("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 it(e,n){let t=Fa(n);if(!t)throw qa();let i=Ma(n),r=Math.floor(Date.now()/1e3).toString(),o=Oi.createHash("sha256").update(`${t}${r}${e}`).digest("hex"),a={timestamp:r,"secret-key":o,[Pa]:Ga()};return i.length>0&&(a[xa]=i),a}function Pi(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ja=500,Ka=8,Bi=100;function rt(e,n=0){if(n>Ka)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,Bi),i=t.map(r=>rt(r,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);for(let[i,r]of Object.entries(e).slice(0,Bi))t[i]=qe(i)?"<redacted>":rt(r,n+1);return t}return e}function Ha(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function Ui(e,n=ja){let t=Ha(e),i=t===void 0?Ge(e):JSON.stringify(rt(t));return je(i,n)}var ot=256*1024,cn=class extends s{constructor(n,t,i="backend-envelope"){let r=i==="successful-query",o=i==="successful-mutation";super(r?"transport.response_too_large":"backend.internal",r?`The API returned an HTTP-success response larger than the CLI's ${t}-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 ${t}-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 ${t}-byte safety limit and was not parsed.`,{status:n,max_body_bytes:t,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},dn=class extends Error{status;timeoutMs;constructor(n,t){super(`API response body read exceeded its ${t}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=n,this.timeoutMs=t}};async function at(e,n,t={}){if(!Number.isSafeInteger(n)||n<=0)throw new RangeError("maxBytes must be a positive safe integer");if(t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let i=e.headers.get("content-length"),r=i!==null&&/^\d+$/.test(i.trim())?Number(i):void 0;if(r!==void 0&&r>n)throw e.body?.cancel().catch(()=>{}),new cn(e.status,n,t.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],c=0,l,d=t.timeoutMs,p=d===void 0?void 0:new Promise((f,y)=>{l=setTimeout(()=>{y(new dn(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:y,value:m}=p?await Promise.race([f,p]):await f;if(y)break;if(c+=m.byteLength,c>n)throw o.cancel().catch(()=>{}),new cn(e.status,n,t.oversizeKind);a.push(Buffer.from(m))}}catch(f){throw f instanceof dn&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(a,c).toString("utf8")}var Ja="X-AllScale-Api-Key",Ya=3e4,Va=32*1024*1024,Wa=4*1024*1024;function za(e,n){let t=new AbortController,i=!1,r=()=>{t.abort(e?.reason)};e?.aborted?r():e?.addEventListener("abort",r,{once:!0});let o=setTimeout(()=>{i=!0,t.abort()},n);return{signal:t.signal,timedOut:()=>i,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",r)}}}function Xa(e,n){return n?n.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((t,i)=>{let r=()=>{i(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};n.addEventListener("abort",r,{once:!0}),e.then(t,i).finally(()=>{n.removeEventListener("abort",r)})}):e}function Qa(e,n){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${J(n||"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 Gi(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Qa(e.status,e.url)}}var Di="--dns-result-order=ipv4first";async function un(e,n){if(e.status!==403)return;let t=e.headers.get("content-type")?.toLowerCase()??"",i=e.headers.get("cf-ray")??"",r=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=t.includes("text/html"),a=n?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),l=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||c)&&(r||n!==void 0&&l)))return;if(n===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(i)?i:void 0;throw new s("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Di} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Di}`})}var re=class{constructor(n){this.opts=n}opts;refreshInFlight=null;async requestWithMetadata(n){return this.requestInternal(n,{withMetadata:!0})}async request(n){return this.requestInternal(n,{withMetadata:!1})}async requestInternal(n,t){let i=n.timeoutMs??this.opts.requestTimeoutMs??Ya;if(!Number.isFinite(i)||i<1)throw new s("input.invalid","HTTP request timeout must be a positive number of milliseconds.");ke(this.opts.apiBase),Ve(this.opts.apiBase);let r=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=za(n.signal,i);try{return await this.requestWithinDeadline({...n,signal:o.signal},t,r)}catch(a){throw o.timedOut()?new s("transport.timeout",`Request to ${J(new URL(n.path,this.opts.apiBase).toString())} timed out after ${i}ms.`,{timeout_ms:i}):n.signal?.aborted&&!(a instanceof s)?new s("transport.network",`Request to ${J(new URL(n.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(n,t,i){let r=new URL(n.path,this.opts.apiBase).toString();ei(this.opts.apiBase,r);let o=i?.agent_key,a=n.auth??"auto",c=qi(n.path),l=a==="required"?!0:a==="none"?!1:ns(n.path);if((c||a==="required")&&!n._isRefresh&&!this.opts.override&&!i?.access_token&&!o)throw en({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Pi(n.body),p=!!o||!!i?.access_token;l&&p&&!this.opts.override&&Ye(this.opts.apiBase,i?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:i,extra:n.headers}),y=Date.now();h({type:"request",method:n.method??"GET",url:r,...n._isRefresh?{refresh:!0}:{}});let m;try{m=await fetch(r,{method:n.method??"GET",headers:f,body:n.body!==void 0?d:void 0,signal:n.signal,redirect:"manual"})}catch(_){throw new s("transport.network",`Network error contacting ${J(r)}: ${_ instanceof Error?_.message:String(_)}`)}if(h({type:"response",status:m.status,durationMs:Date.now()-y}),l&&!!i?.access_token&&!o&&m.status===401&&!n._isRefresh&&!this.opts.override){let _=await Xa(this.refreshSingleFlight(),n.signal),E=this.buildHeaders({attachAuth:l&&!!_.access_token,bodyForSig:d,tokens:_,extra:n.headers}),I=Date.now();h({type:"request",method:n.method??"GET",url:r});let S;try{S=await fetch(r,{method:n.method??"GET",headers:E,body:n.body!==void 0?d:void 0,signal:n.signal,redirect:"manual"})}catch(B){throw new s("transport.network",`Network error contacting ${J(r)} on refresh-retry: ${B instanceof Error?B.message:String(B)}`)}return h({type:"response",status:S.status,durationMs:Date.now()-I}),$i(S,{withMetadata:t.withMetadata,authBearing:l,responseKind:Fi(n)})}return $i(m,{withMetadata:t.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:Fi(n)})}buildHeaders(n){let i={Accept:"application/json","Content-Type":"application/json",...it(n.bodyForSig,this.opts.apiBase),...n.extra};if(n.attachAuth){i.Authorization=vi;let r=n.tokens;if(r?.agent_key)return i[Ja]=r.agent_key,i;let o=r?.access_token;o&&(i.Cookie=et([{name:ln,value:o}]))}return i}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(n){let t;try{t=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!t?.access_token||!t?.refresh_token||t.refresh_token===n.refresh_token)return null;if(Ye(this.opts.apiBase,t.api_base),t.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return t}async doRefresh(){let n=await this.opts.tokenStore.get(this.opts.profile);if(!n?.access_token||!n?.refresh_token)throw new s("auth.token_expired",`No refresh token available; log in again \u2014 ${Me()}.`);if(Ye(this.opts.apiBase,n.api_base),n.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let t=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),i=et([{name:ln,value:n.access_token},{name:Zn,value:n.refresh_token}]),r=it("",this.opts.apiBase);h({type:"request",method:"POST",url:t,refresh:!0});let o=new AbortController,a=!1,c=setTimeout(()=>{a=!0,o.abort()},1e4),l;try{l=await fetch(t,{method:"POST",headers:{Accept:"application/json",Cookie:i,...r},signal:o.signal,redirect:"manual"})}catch(m){throw h({type:"refresh",ok:!1}),new s("transport.network",a&&m instanceof Error&&m.name==="AbortError"?`Token refresh against ${J(t)} timed out after 10s with no response.`:`Network error during token refresh against ${J(t)}: ${m instanceof Error?m.message:String(m)}`)}finally{clearTimeout(c)}h({type:"response",status:l.status,durationMs:0});try{await Gi(l)}catch(m){throw h({type:"refresh",ok:!1}),m}if(l.status!==200){let m=null;try{await un(l);let g=await as(l);await un(l,g),Ki(l.status,g),l.status===401&&(m=await this.adoptConcurrentlyRotatedTokens(n))}catch(g){throw h({type:"refresh",ok:!1}),g}if(m)return h({type:"refresh",ok:!0,adopted:!0}),m;throw h({type:"refresh",ok:!1}),new s("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Me()}.`,{status:l.status})}let d=Ci(l.headers),p=nt(d,ln),f=nt(d,Zn);if(!p||!f)throw h({type:"refresh",ok:!1}),new s("auth.token_expired","Refresh response did not include new access/refresh cookies.");let y={...n,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,y),h({type:"refresh",ok:!0}),y}},Za=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function qi(e){let n=e.split(/[?#]/,1)[0];return Za.some(t=>n===t||n.startsWith(`${t}/`))}var es=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function st(e){let n=e.split(/[?#]/,1)[0];return es.some(t=>t.test(n))}function ns(e){return qi(e)||st(e)}async function $i(e,n={}){await Gi(e);let t=e.status>=200&&e.status<300;t||await un(e);let i=n.responseKind??"mutation",o=await at(e,t?i==="query"?Va:Wa:ot,{oversizeKind:t?i==="query"?"successful-query":"successful-mutation":"backend-envelope"});t||await un(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(n.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:a}}return a}let c=ss(a)??`HTTP ${e.status}`;if(Ki(e.status,a),rs(e.status,a,n),e.status===401){if(n.agentKeyAuth)throw new s("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let l=n.authBearing?"auth.token_expired":"input.invalid";throw new s(l,c,{status:401,body:a})}throw e.status===403?new s("auth.permission_denied",c,{status:403,body:a}):e.status===404?new s("not_found",c,{status:404,body:a}):e.status===429?new s("rate_limited",c,{status:429,body:a}):e.status>=500?new s("backend.internal",c,{status:e.status,body:a}):new s("input.invalid",c,{status:e.status,body:a})}function Fi(e){if(e.responseKind)return e.responseKind;let n=(e.method??"GET").toUpperCase();return n==="GET"||n==="HEAD"?"query":"mutation"}var ts=2014,Mi=2004;function ji(e,n){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let i=t.code;return i===n||i===String(n)}function is(e){return ji(e,ts)}function rs(e,n,t){if(!(e>=200&&e<300)&&t.authBearing&&!(e===401&&t.agentKeyAuth)&&ji(n,Mi))throw new s("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Me()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Mi})}var os=1e4;async function as(e,n=os){if(e.status>=200&&e.status<300)return"";try{return await at(e,ot,{timeoutMs:n})}catch{return""}}function Ki(e,n){if(!(e>=200&&e<300)&&is(n))throw new s("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 n=="string"?Ui(n):n})}function ss(e){if(!e||typeof e!="object")return;let n=e;if(typeof n.message=="string")return n.message;if(typeof n.detail=="string")return n.detail;if(Array.isArray(n.detail))return JSON.stringify(n.detail)}var ls=/^\/(api\/)?(v1\/)?public\//;function H(e,n={}){let t=typeof n.pathHint=="string"?n.pathHint:"",i=t&&ls.test(t),r=t&&st(t),o=i&&!r&&!n.forceAuth;if(e.token)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new re({apiBase:e.apiBase,tokenStore:an({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(r)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var Hi=[{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_contact_by_email",kind:"query",description:"Look up the contact card of the business whose login email is given. Used to fill the invoice header's From: block with the same name/email/phone the web editor shows.",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:"BusinessContact",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:"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}],Ji=[{name:"ActivityFilterInput",kind:"INPUT",description:null,inputFields:[{name:"transaction_types",description:"Filter by transaction types (OR): 1=PAYMENT, 2=REWARD, 3=WITHDRAWAL, 8=CHECKOUT_INTENT_EPHEMERAL, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 11=CHECKOUT_INTENT_EPHEMERAL_REFUND, 13=CHECKOUT_INTENT_EPHEMERAL_NET_INCOME, 14=CLAIM_LINK",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"transaction_statuses",description:"Filter by transaction statuses (OR): 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"payment_statuses",description:"Filter by payment statuses (OR): -4=OVERDUE, -1=FAILED, 0=DRAFT, 1=SENT, 2=ACKNOWLEDGED, 3=PROCESSING, 10=PAID",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"withdraw_statuses",description:"Filter by withdraw statuses (OR): -4=CANCELED, -1=FAILED, 1=CREATED, 20=CONFIRMED",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"directions",description:"Filter by transaction direction (OR): 1=INFLOW, -1=OUTFLOW",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"contact_keyword",description:"Fuzzy search by contact name/email or store name. OR relationship with wallet_address.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"wallet_address",description:"Fuzzy search by counterparty wallet address (tx_from/tx_to). OR relationship with contact_keyword.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"start_time",description:"Filter transactions after this time, ISO8601 format (e.g. 2024-01-01T00:00:00.000Z)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"end_time",description:"Filter transactions before this time, ISO8601 format",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"min_amount",description:"Filter transactions with amount >= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"max_amount",description:"Filter transactions with amount <= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"is_claim_link",description:"When true, return only claim-link activity: a receiver's claim (an ON_CHAIN_TX tagged with claim_link_id) OR a sender's CLAIM_LINK row (single claim_link_id / batch claim_link_batch_id). Matched by claim-link linkage presence, NOT transaction_types \u2014 a receiver's claim shares transaction_type=ON_CHAIN_TX(10) with a plain deposit, so it cannot be selected by type alone (bug 6935616).",type:{kind:"SCALAR",name:"Boolean",ofType:null},defaultValue:"null"}]},{name:"ActivityItem",kind:"OBJECT",description:null,fields:[{name:"transaction_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Transaction record ID"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Transaction amount in cryptocurrency"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Transaction amount in fiat cents"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"When the transaction occurred on-chain"},{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Record creation time in UTC"},{name:"transaction_status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Status: 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked payment ID for PAYMENT type transactions"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Type: 1=PAYMENT, 2=REWARD, 3=SEND, 4=SERVICE_FEE, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 14=CLAIM_LINK"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Direction: 1=INFLOW (received), -1=OUTFLOW (sent)"},{name:"wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Counterparty wallet address (sender if INFLOW, recipient if OUTFLOW)"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"On-chain transaction hash"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Blockchain network type"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Block number of the on-chain transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"User-provided memo or notes"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Cryptocurrency type (e.g. USDT)"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Fiat currency type (e.g. USD, CNY)"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee = network_fee + service_fee"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"On-chain gas/network fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"AllScale platform service fee"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Counterparty's business ID if they are an AllScale user"},{name:"claim_link_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked claim link ID for CLAIM_LINK type transactions"}]},{name:"ActivityItemPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ActivityItem",ofType:null}}}},description:null}]},{name:"AuthorizedPolicyPair",kind:"OBJECT",description:null,fields:[{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain identified by its BlockChainType value (for example BASE = 5) \u2014 not the EIP-155 chain id."},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Stablecoin symbol: USDT or USDC"}]},{name:"AutoPayoutSessionStatus",kind:"OBJECT",description:null,fields:[{name:"provisioned",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether auto-payout setup has been completed for this merchant."},{name:"active",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"True iff provisioned AND the session has not expired (the runtime auto-pay gate)"},{name:"session_expires_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"Session expiry (drives the countdown); null when not provisioned"},{name:"total_cap_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified session total cap in USD (decimal string); null when not provisioned"},{name:"used_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Cumulative USD spent (reserved + committed) this session (decimal string); populated only for an ACTIVE session, else null"},{name:"remaining_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"max(0, total_cap - used) in USD (decimal string); populated only for an ACTIVE session, else null"},{name:"per_transaction_limit",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified single-transaction limit (token-unit decimal string, stablecoin $ 1:1) recorded when auto-payout is enabled; null when not provisioned or when recorded entries have different limits. Retained after a session expires, so it still reports what was recorded."},{name:"authorized_pairs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"AuthorizedPolicyPair",ofType:null}}}},description:"The (chain, stable-coin) pairs the merchant authorized when enabling auto-payout; empty when auto-payout was never provisioned. Retained after a session expires, so it still reports what was authorized."},{name:"sponsor_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Lowercased sponsor address used to validate authorized payouts. Populated whether or not auto-payout is provisioned, so it is readable while enabling; null when unavailable."}]},{name:"Business",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"user name"},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"email of the user"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"description of the user"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the business"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address field for business"},{name:"country",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"country code of business"},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"contact name of business"},{name:"contact_avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact avatar url of business"},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact phone of business"},{name:"avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"avatar url of business"},{name:"default_currency",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"default currency for business"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the business"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax id of the business"},{name:"about",type:{kind:"SCALAR",name:"String",ofType:null},description:"about of the business, can be changed by business"},{name:"business_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"business type"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of accepted stablecoins for invoices (StableCoinFlag)"},{name:"employee_count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"total active employees in the business"}]},{name:"BusinessContact",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Display name of the business's user account."},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Login email of the business's user account."},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Contact person the business presents on its invoices. Preferred over `name` when both are set."},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"Contact phone the business presents on its invoices. Null when the business has not set one."}]},{name:"ClaimLink",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim link id"},{name:"business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"sender business that owns the link"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"ClaimLinkStatus lifecycle state"},{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount, decimal string in token units"},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"stablecoin symbol, e.g. USDT / USDC"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"BlockChainType the link is locked to"},{name:"sender_display_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name shown to the receiver (person or Store name)"},{name:"sender_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional message shown on the claim page"},{name:"receiver_email",type:{kind:"SCALAR",name:"String",ofType:null},description:"receiver email, if the sender supplied one"},{name:"reference_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"Optional merchant-supplied reference identifier."},{name:"expected_deposit_total",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the expected POOL balance (principal). The sender's gross outlay is the fee breakdown's total"},{name:"service_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"AllScale service fee fixed when the claim link is created; null when not applicable."},{name:"network_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"Network fee fixed when the claim link is created; null when not applicable."},{name:"funded_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the deposit actually received at the pool wallet"},{name:"funded_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the confirming sender deposit"},{name:"expiry_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC; the resolved claim-window deadline (funded_at + the chosen window, default 14d); None until link_sent"},{name:"claimed_via",type:{kind:"SCALAR",name:"String",ofType:null},description:"how it was claimed: masked receiver email or 0x address"},{name:"claim_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the successful claim"},{name:"refund_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the expiry refund back to the sender"},{name:"refunded_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC when the expiry refund proved on-chain"},{name:"cancel_requested_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC timestamp set when the sender requests cancellation while a claim is in progress. The request stays pending until the in-flight payout resolves: it is cleared if that payout completes (the cancellation is moot and the link is claimed), and retained if the payout did not go through and the link is cancelled and refunded. Null therefore means either no mid-claim cancellation was requested, or one that was resolved by a completed payout."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL returned by create and single-link detail operations. The sender distributes this URL themselves; it is never emailed to the receiver. Null when unavailable, and always null on list operations \u2014 selecting it there returns the field as null rather than omitting it."}]},{name:"ClaimLinkFeeBreakdown",kind:"OBJECT",description:null,fields:[{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount the receiver gets, decimal string"},{name:"network_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"gas reserve = gas_shares \xD7 per_transfer_gas, decimal string"},{name:"service_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"AllScale service fee for the chain, decimal string"},{name:"total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"amount + network_fee + service_fee \u2014 what the sender pays"},{name:"per_transfer_gas",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"one transfer's gas in token units (echoed for audit)"},{name:"gas_shares",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Number of per_transfer_gas shares reserved; currently 2 for a single claim link."}]},{name:"ClaimLinkPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}}}},description:null}]},{name:"CoinBalanceEmbedded",kind:"OBJECT",description:null,fields:[{name:"coin_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Stablecoin held, as the numeric StableCoin value (1 = USDT, 2 = USDC). `wallet list` decorates each balance with the derived `coin_name`."},{name:"balance",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Decimal",ofType:null}},description:"Balance of the coin"}]},{name:"Contact",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"id of the contact"},{name:"owner_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"owner id of the contact"},{name:"contact_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"contact id if contact is allscale business"},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name of the contact"},{name:"binding_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"the way of binding an allscale business id to the contact, by email matching(1) or scan qrcode(2), etc."},{name:"email",type:{kind:"SCALAR",name:"String",ofType:null},description:"email of the contact"},{name:"evm_wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"evm wallet address of the contact"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax number of the contact"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address of the contact"},{name:"phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"phone number of the contact"},{name:"last_payment_created_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last payment date of the contact"},{name:"last_paid_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last successful pay date"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"Free-form description of the contact."},{name:"is_favourite",type:{kind:"SCALAR",name:"Boolean",ofType:null},description:"is favourite or not"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the contact"}]},{name:"ContactPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}}}},description:null}]},{name:"CreateClaimLinkInput",kind:"INPUT",description:null,inputFields:[{name:"amount",description:"claim amount, decimal string in token units (e.g. '10.5')",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"token_symbol",description:"stablecoin symbol: 'USDT' or 'USDC'",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"BlockChainType value the link is locked to (EVM only)",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"per_transfer_gas",description:"one ERC-20 transfer's gas in TOKEN units (decimal string); from the App's withdraw estimate",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"receiver_email",description:"optional receiver email \u2014 a SENDER-SIDE LABEL ONLY, recording who the link is meant for. AllScale does NOT email the receiver (no invite, no expiry reminder, no resend); the sender must distribute `claim_url` themselves.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_display_name",description:"name shown to the receiver (person or Store name)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_message",description:"optional message shown on the claim page (<= 200 chars)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"idempotency_key",description:"optional client retry-safety token; a retried create with the same key returns the existing link instead of a duplicate",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_window_seconds",description:"Optional positive claim-window duration in seconds. Defaults to 14 days. The window starts when funding is confirmed; after it expires, unclaimed funds are returned to the sender.",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreateClaimLinkResult",kind:"OBJECT",description:null,fields:[{name:"claim_link",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},description:"the newly created link (pending_deposit)"},{name:"claim_token",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Bearer claim token returned only when the claim link is created and never available again. Capture and store it securely immediately; it preserves claim authority when claim_url is unavailable."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL; null when no claim-page URL is configured."},{name:"pool_wallet_address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"ERC-4337 address the sender funds"},{name:"expected_deposit_total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the expected POOL balance (principal), decimal string; the sender's gross outlay is the fee breakdown's total"},{name:"fees",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},description:"the frozen fee breakdown"}]},{name:"CreateContactInput",kind:"INPUT",description:null,inputFields:[{name:"owner_business_id",description:"owner id of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"name",description:"name of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"email",description:"email of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"evm_wallet_address",description:"evm wallet address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"address",description:"address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"phone",description:"phone number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_number",description:"tax number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"description",description:"Free-form description of the contact.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"binding_type",description:"binding type of the contact",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"sender_contact_id",description:"contact id of the payer/sender",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"payment_type",description:"payment type of the payment",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"accepted_stable_coins",description:"optional per-invoice bitflag (StableCoinFlag) overriding the recipient business's accepted_stable_coins setting",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"payment_extra_info",description:"payment extra info of the payment, JSON object string",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"currency",description:"currency of the payment, only if the payment_type is CURRENCY",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_cents",description:"amount of the payment in cents",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_coins",description:"amount of the payment in coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"html_template",description:"HTML template for the invoice",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_id",description:"optional taxpayer identification for the invoice",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"datetime the payment is due",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"},{name:"wallets",description:"list of wallets address",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"PlainWalletEmbeddedInput",ofType:null}}}},defaultValue:null}]},{name:"CreateStoreInput",kind:"INPUT",description:null,inputFields:[{name:"name",description:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"logo_url",description:"logo url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:null},{name:"business_id",description:"pay account business id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"type",description:"type of the store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"default_timeout_seconds",description:"default timeout seconds for checkout intents",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"3600"},{name:"swidge_enabled",description:"whether Swidge cross-chain checkout is enabled for this store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"claim_link_claim_notify_enabled",description:"Whether AllScale sends merchant claim-notification emails for this store; defaults to false.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"false"},{name:"description",description:"description",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"scopes",description:"permission scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:'["*"]'},{name:"ip_allowlist",description:"allowed IPs/CIDRs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:"[]"},{name:"is_sandbox",description:"Whether to create the store in sandbox mode.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"rate_limit_per_minute",description:"Optional request-per-minute limit; defaults to 300, and 0 uses the platform default.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"300"},{name:"replay_window_seconds",description:"override replay window seconds",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"transaction_webhook",description:"transaction webhook url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_link_webhook_url",description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"redirect_url",description:"Redirect URL used after payment completes.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"fee_rate",description:"fee rate",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"accepted_stable_coins",description:"bitflag of accepted stablecoins for checkout (StableCoinFlag); null inherits from business",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"Payment",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the payment"},{name:"recipient_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"business id of the payee/recipient"},{name:"sender_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the payer/sender"},{name:"sender_contact_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"contact id of the payer/sender"},{name:"payment_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"payment type of the payment"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of stablecoins accepted for this payment (StableCoinFlag). None on payments created before the multi-coin rollout."},{name:"payment_extra_info",type:{kind:"SCALAR",name:"String",ofType:null},description:"payment extra info of the payment, JSON object string"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the payment, only if the payment_type is CURRENCY"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the payment"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount of the payment in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount of the payment in coins"},{name:"invoice_url",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice url of the payment"},{name:"invoice_visible_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice visible id of the pdf"},{name:"tax_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional taxpayer identification for the invoice"},{name:"error_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"error message of the payment if status is failed"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the payment"},{name:"due_datetime",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"datetime the payment is due"},{name:"display_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"display amount of the payment"},{name:"encrypted_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Opaque payment identifier used in public payment links."}]},{name:"PaymentPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}}}},description:null}]},{name:"PlainWalletEmbeddedInput",kind:"INPUT",description:null,inputFields:[{name:"id_str",description:"Unique identifier for the wallet",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"Blockchain type of the address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"address",description:"Blockchain address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}]},{name:"QueryInput",kind:"INPUT",description:null,inputFields:[{name:"limit",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"skip",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"order_by",description:null,type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}},defaultValue:"null"},{name:"raw_filter_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:'"{}"'},{name:"created_at_lte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"created_at_gte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"}]},{name:"Store",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Unique store identifier."},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name"},{name:"type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the store"},{name:"scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},description:"permission scopes"},{name:"is_sandbox",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether this store uses sandbox mode."},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the store"},{name:"transaction_webhook",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction webhook url"},{name:"claim_link_webhook_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook."},{name:"redirect_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Redirect URL used after payment completes."}]},{name:"StoreCreateResult",kind:"OBJECT",description:null,fields:[{name:"store",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Store",ofType:null}},description:"store"},{name:"api_secret",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Store API secret returned only when the store is created and never available again. Capture and store it securely immediately."}]},{name:"Transaction",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the transaction record"},{name:"owner_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"owner user type of the record"},{name:"owner_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id that owns this transaction record"},{name:"owner_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id that owns this transaction record"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the transaction"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"direction of the transaction"},{name:"reference_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"reference type of the related record"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"payment id when reference_type is PAYMENT"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the counterparty"},{name:"counterparty_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id of the counterparty"},{name:"counterparty_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name of the counterparty"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"payment type if this is a payment transaction"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the transaction"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount in coins"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the transaction"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"actual transaction time"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"hash of the transaction"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block chain of the transaction"},{name:"tx_from",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction sender address"},{name:"tx_to",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction receiver address"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block number of the transaction"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee (network_fee + service_fee)"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Network/gas fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Allscale service fee (0.03%)"}]},{name:"TransactionPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Transaction",ofType:null}}}},description:null}]},{name:"UpdatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_business_id",description:"sender business id of the payer",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"new payment deadline for an OVERDUE invoice. Only an overdue invoice may be extended, and only FORWARD. Extending past now also revives the invoice (back to SENT/ACKNOWLEDGED) so buyers can pay again.",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"}]},{name:"WalletEmbedded",kind:"OBJECT",description:null,fields:[{name:"id_str",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet id"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain the wallet lives on, as the numeric BlockChainType value (NOT a name). `wallet list` decorates each wallet with the derived `chain_name` and `eip155_chain_id`."},{name:"address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet address"},{name:"coin_balances",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"OBJECT",name:"CoinBalanceEmbedded",ofType:null}}},description:"wallet balance"}]}];var pn=new Set(["SCALAR","ENUM"]),cs=new Set(["password","password_hash","totp_secret","credential","credentials","private_key","encryption_key"]),ds=[/(^|_)password(_|$)/i,/(^|_)secret(_|$)/i,/(^|_)token(_|$)/i,/(^|_)api[_-]?key(_|$)/i,/(^|_)signing[_-]?key(_|$)/i,/(^|_)private[_-]?key(_|$)/i,/(^|_)credential(_|$)/i],us=new Set(["CreateClaimLinkResult.claim_token","StoreCreateResult.api_secret"]),ps=new Map([["StoreCreateResult.store",["id","name"]],["CreateClaimLinkResult.claim_link",["id","token_symbol","status"]]]),fs=new Set(["token_symbol"]),ms=new Set;function lt(e,n){return ms.has(`${e}.${n}`)}function ct(e){return fs.has(e.toLowerCase())?!1:cs.has(e)?!0:ds.some(n=>n.test(e))}function ys(e,n){return us.has(`${e}.${n}`)}function dt(e){return e.kind==="NON_NULL"&&e.ofType?`${dt(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${dt(e.ofType)}]`:e.name??"Unknown"}function Be(e){let n=e;for(;n&&n.ofType;)n=n.ofType;return!n||!n.name?null:{kind:n.kind,name:n.name}}function hs(e,n){let t=n.find(a=>a.name===e);if(!t||t.kind==="SCALAR"||t.kind==="ENUM")return"";if(t.kind==="UNION")return"__typename";let i=t.fields??[];if(i.length===0)return"";let r=[],o=!1;for(let a of i){let c=Be(a.type);if(!c)continue;if(pn.has(c.kind)){if(ct(a.name)&&!ys(e,a.name)||lt(e,a.name))continue;r.push(a.name);continue}let l=ps.get(`${e}.${a.name}`);if(l){let d=n.find(m=>m.name===c.name),p=new Set((d?.fields??[]).filter(m=>{let g=Be(m.type);return g!==null&&pn.has(g.kind)&&!ct(m.name)}).map(m=>m.name)),f=l.filter(m=>!p.has(m));if(f.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${f.join(", ")}] that are not selectable scalars on ${c.name}; fix the entry or the public registry.`);let y=l.filter(m=>lt(c.name,m));if(y.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${y.join(", ")}] that DEFAULT_SELECTION_EXCLUSIONS keeps out of default selections on ${c.name}; drop the field from the nested entry, or remove the exclusion if it is no longer true.`);r.push(`${a.name} { ${l.join(" ")} }`);continue}if(!o&&a.name==="items"&&a.type.kind==="NON_NULL"&&a.type.ofType?.kind==="LIST"){let d=gs(a.type)?.name;if(d){let p=_s(d,n);p&&r.push(`items { ${p} }`),o=!0}}}return r.length>0?r.join(" "):"__typename"}function gs(e){return Be(e)}function _s(e,n){let t=n.find(o=>o.name===e);if(!t||t.kind==="UNION")return"__typename";let i=t.fields??[],r=[];for(let o of i){let a=Be(o.type);if(a&&pn.has(a.kind)){if(ct(o.name)||lt(e,o.name))continue;r.push(o.name)}}return r.length>0?r.join(" "):"__typename"}function Yi(e,n,t){let i=ks(e.name),r=e.args.map(p=>{let f=dt(p.type);return p.defaultValue!==null&&p.defaultValue!==void 0?`$${p.name}: ${f} = ${p.defaultValue}`:`$${p.name}: ${f}`}).join(", "),o=e.args.map(p=>`${p.name}: $${p.name}`).join(", "),a=r.length>0?`${e.kind} ${i}(${r})`:`${e.kind} ${i}`,c=o.length>0?`${e.name}(${o})`:e.name,l=Be(e.returnType),d;if(l&&pn.has(l.kind))d=c;else{let p=t&&t.trim().length>0?t.trim():l&&hs(l.name,n)||"__typename";d=`${c} { ${p} }`}return`${a} { ${d} }`}function Vi(e,n){let i=e.args.filter(r=>r.type.kind==="NON_NULL"&&r.defaultValue===null).map(r=>r.name).filter(r=>!(r in n));return i.length===0?{ok:!0}:{ok:!1,missing:i}}function Wi(e,n,t){return e.find(i=>i.kind===n&&i.name===t)??null}function zi(e){if(!e||typeof e!="object")return!1;let n=e.errors;return Array.isArray(n)&&n.length>0}function Xi(e,n=3){let t=e.errors;return!Array.isArray(t)||t.length===0?"":t.slice(0,n).map(i=>typeof i=="object"&&i!==null&&typeof i.message=="string"?i.message:JSON.stringify(i)).join("; ")}function ks(e){return e.replace(/[^_0-9A-Za-z]/g,"_")}var Ss=new Set;var ws=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),ut=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),pt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function fn(e){let n=e.lastIndexOf(":");return n===-1?e:e.slice(0,n)}function Qi(e,n){if(e===n)return!0;let t=":read_only";return n.endsWith(t)&&e===`${n.slice(0,-t.length)}:all`}var As=new Set(["cli_op:all"]),bs=new Set([...As].map(fn));var fd=new Set([...[...ws,...ut,...Ss].map(fn),...pt,...bs]);var Ts={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Ls={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},Es=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Ns=/is not available to API keys/i,Zi=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function er(e){if(typeof e!="string")return;let n=Es.exec(e);if(!n)return;let t=n[1].trim(),i=n[2].trim(),r=Ns.test(t),o=!r&&Zi.test(t)?t:void 0,a;if(i.toLowerCase()==="none")a=[];else{let c=i.split(",").map(l=>l.trim()).filter(l=>Zi.test(l));a=c.length>0?c:void 0}if(!(o===void 0&&!r))return{required:o,granted:a,notAvailableToKeys:r}}function nr(e){let n=Ls[e];if(n!==void 0)return{ungrantableReason:n};let t=Ts[e];if(t!==void 0)return{scope:t}}function tr(e){if(pt.has(fn(e)))return{kind:"ungrantable"};for(let n of ut)if(Qi(n,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}var Cs=8100,Os=new Set([Cs]),Rs=new Set([...Os,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function rr(e,n){let t=or(e),i={graphql_error_count:Is(e.errors),...t===void 0?{}:{backend_code:t}};if(t===2102)throw vs(e,n,i);if(t===429)throw new s("rate_limited",`GraphQL ${n.kind} '${n.operationName}' was rate limited. Retry after a backoff.`,i);if(t===1002)throw new s("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${n.kind} '${n.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,i);if(t!==void 0&&Rs.has(t))throw new s("not_found",`GraphQL ${n.kind} '${n.operationName}' could not find the requested resource.`,i);if(zi(e))throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' returned errors: ${Xi(e)}`,i);if(t!==void 0)throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' failed with backend code ${t}.`,i)}function or(e){let n=ir(e.code);if(n!==void 0)return n;if(Array.isArray(e.errors))for(let t of e.errors){if(!t||typeof t!="object")continue;let i=t.extensions;if(!i||typeof i!="object")continue;let r=ir(i.code);if(r!==void 0)return r}}function ir(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let n=Number(e);if(Number.isSafeInteger(n)&&n>0)return n}}function Is(e){return Array.isArray(e)?e.length:e==null?0:1}function vs(e,n,t){let i=`GraphQL ${n.kind} '${n.operationName}'`,r={...t,operation:n.operationName},o=er(xs(e,or(e))),a=nr(n.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??a?.scope,d=o?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||a?.ungrantableReason!==void 0){let f=a?.ungrantableReason!==void 0?`: ${a.ungrantableReason}`:"";return new s("auth.permission_denied",`${i} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...r,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=tr(l),y=f.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${be()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${be()}\` with \`--scopes ${l}\`.`;return new s("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${i}.${p} ${y}`,{...r,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new s("auth.permission_denied",`The current agent key does not have the scope required by ${i}.${p} Re-run \`allscale device-login\` (or \`${be()}\`) and grant the required scope.`,r)}function xs(e,n){let t=e.errors;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let i=r=>{if(r===null||typeof r!="object")return;let o=r.message;return typeof o=="string"?o:void 0};if(n!==void 0)for(let r of t){if(r===null||typeof r!="object")continue;let o=r.extensions;if(!o||typeof o!="object")continue;let a=o.code;if(a===n||typeof a=="string"&&Number(a)===n){let l=i(r);if(l!==void 0)return l}}for(let r of t){let o=i(r);if(o!==void 0)return o}return""}async function ft(e,n,t,i,r={}){let o=Wi(Hi,n,t);if(!o)throw new s("input.invalid",`No ${n} named '${t}' in the schema. Run \`allscale operations --kind ${n}\` to list options.`);let a=Vi(o,i);if(!a.ok)throw new s("input.invalid",`Missing required variables for ${t}: ${a.missing.join(", ")}`,{required:a.missing});let c=Yi(o,Ji,r.selection);return Ps(e,{...r,kind:n,operationName:o.name,document:c,variables:i})}async function Ps(e,n){n.showDoc&&process.stderr.write(`${n.document}
18
- `);let t=H(e),i=n.path??"/api/secure/graphql",r=await t.request({method:"POST",path:i,responseKind:n.kind,body:{query:n.document,...Object.keys(n.variables).length>0?{variables:n.variables}:{},operationName:n.operationName}});rr(r,{kind:n.kind,operationName:n.operationName});let o=r.data?.[n.operationName];return o===void 0?null:o}var _r=require("crypto"),L=require("process");var oe=/^0x[0-9a-fA-F]{64}$/,Bs=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function ar(e){return typeof e=="string"&&Bs.includes(e)}var $={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},Us=new Set(Object.values($));async function sr(e,n,t){let{body:i,headers:r}=await Fs(e,"/api/secure/wallet/cli_op_init",{op:n,payload:t},"cli_op_init");return{...i,server_now_ms:Ds(r)}}function Ds(e){let n=e.date??e.Date??Object.entries(e).find(([i])=>i.toLowerCase()==="date")?.[1];if(n===void 0)return null;let t=Date.parse(n);return Number.isFinite(t)?t:null}async function mt(e,n){return $s(e,"/api/secure/wallet/cli_op_result",{result_token:n},"cli_op_result")}async function $s(e,n,t,i){let r;try{r=await e.request({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=lr(o,i);if(a!==null)throw a}throw o}return cr(r,i)}async function Fs(e,n,t,i){let r;try{r=await e.requestWithMetadata({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=lr(o,i);if(a!==null)throw a}throw o}return{body:cr(r.body,i),headers:r.headers??{}}}function lr(e,n){let t=e.details?.body;if(!t||typeof t!="object")return null;let i=t,r=typeof i.code=="number"?i.code:void 0;if(r===void 0||r===0||!Us.has(r))return null;let o=typeof i.errors=="string"?i.errors:typeof i.message=="string"?i.message:e.message;return dr(r,o,n)}function cr(e,n){if(e.code!==void 0&&e.code!==0)throw dr(e.code,e.message,n);if(e.data===void 0)throw new s("backend.internal",`Broker ${n} returned no data envelope`,{envelope:e});return e.data}function dr(e,n,t){let i=n??`Broker ${t} returned code ${e}`;switch(e){case $.CLI_OP_NOT_FOUND:return new s("not_found",i,{broker_code:e});case $.CLI_OP_EXPIRED:return new s("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:i});case $.CLI_OP_UNAUTHORIZED:return new s("auth.permission_denied",i,{broker_code:e});case $.CLI_OP_UNKNOWN_TYPE:return new s("input.invalid",i,{broker_code:e});case $.CLI_OP_INVALID_PAYLOAD:case $.CLI_OP_SELF_TRANSFER:case $.CLI_OP_INSUFFICIENT_BALANCE:case $.CLI_OP_WALLET_STATE_CONFLICT:return new s("input.invalid",i,{broker_code:e});case $.CLI_OP_PREFLIGHT_UNAVAILABLE:return new s("backend.internal",i,{broker_code:e});case $.CLI_OP_TOKEN_CONSUMED:return new s("input.invalid",i,{broker_code:e});default:return new s("backend.internal",i,{broker_code:e})}}var fr=require("child_process");function ur(e){let n=e?.trim();return n?n!=="0"&&n.toLowerCase()!=="false":!1}var Ms=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Gs(e,n,t,i){if(ur(e.CI)||Ms.some(a=>ur(e[a])))return"ci";let o=n!=="darwin"&&n!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":t===!0||i===!0?null:"no-tty"}function qs(e){let n=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",t=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+n+t:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+n+t:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+n+t}async function mr(e,n={}){if(!kn(e))throw new s("input.invalid",`Refusing to launch browser for untrusted origin: ${x(e)}`);let t=n._env??process.env,i=n._platform??process.platform,r=t.BROWSER?.trim();if(r&&r.toLowerCase()==="none")throw new s("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let o=r?null:Gs(t,i,n._stdinIsTTY??process.stdin.isTTY,n._stderrIsTTY??process.stderr.isTTY);if(o)throw new s("wallet.requires_browser_auth",qs(o));if(i==="linux"&&!t.DISPLAY&&!r)throw new s("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(n._execOverride){await n._execOverride(e);return}let a=js(i,r);await Ks(a.command,[...a.args,e])}function js(e,n){return n&&n.length>0?{command:n,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Ks(e,n){return new Promise((t,i)=>{let r;try{r=(0,fr.spawn)(e,n,{detached:!0,stdio:"ignore"})}catch(a){i(pr(e,a));return}let o=!1;r.once("error",a=>{o||(o=!0,i(pr(e,a)))}),setImmediate(()=>{o||(o=!0,r.unref(),t())})})}function pr(e,n){return new s("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${n.message}. Re-run on a host with a graphical environment.`)}var yr=N(require("http"));var Hs=9e4,Js=16*1024;function hr(e){let n=e.timeoutMs??Hs;return new Promise((t,i)=>{let r=!1,o=!1,a=null,c,l,d=new Promise((f,y)=>{c=f,l=y}),p=yr.createServer((f,y)=>{Ys(f,y,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>r,tryConsume:()=>r?!1:(r=!0,!0),onSuccess:m=>{a&&clearTimeout(a),c(m),p.close()}})});p.on("error",f=>{let y=new s("transport.network",`Loopback listener error: ${f.message}`);o?l(y):i(y),a&&clearTimeout(a)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),i(new s("transport.network","Failed to read loopback listener port"));return}let y=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,m=y!=null?Math.max(1,Math.min(n,y)):n,g=y!=null&&y<=n;a=setTimeout(()=>{l(new s("wallet.bridge_timeout",`Bridge timed out after ${m}ms waiting for browser callback.`,{bridge_deadline:g?"op_ttl":"duration"})),p.close()},m),a.unref?.(),o=!0,t({port:f.port,awaitResult:d,close:()=>{a&&clearTimeout(a),p.close()}})})})}function Ys(e,n,t){let i=e.headers.origin??"";if(e.method==="OPTIONS"){if(i===t.expectedOrigin){let c={"Access-Control-Allow-Origin":t.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),n.writeHead(204,c)}else n.writeHead(403);n.end();return}if(e.method!=="POST"||e.url!=="/result"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"not_found"}));return}if(t.isConsumed()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}if(i!==t.expectedOrigin){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"origin_mismatch"}));return}let r=0,o=[],a=!1;e.on("data",c=>{if(!a){if(r+=c.length,r>Js){a=!0,n.writeHead(413,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(a)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_body"}));return}let d=l,p=typeof d.state=="string"?d.state:"",f=typeof d.result_token=="string"?d.result_token:void 0,y=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!Vs(p,t.state)){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&y===void 0){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"missing_result"}));return}if(!t.tryConsume()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}n.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":t.expectedOrigin}),n.end(JSON.stringify({ok:!0})),t.onSuccess({result_token:f,result_data:y})}),e.on("error",()=>{a||(a=!0)})}function Vs(e,n){if(e.length!==n.length)return!1;let t=0;for(let i=0;i<e.length;i+=1)t|=e.charCodeAt(i)^n.charCodeAt(i);return t===0}function yt(e){try{return JSON.parse(e),!0}catch{return!1}}function gr(){let e=process.stdin,n="",t=!1,i=()=>{},r=250,o=null,a=()=>{o&&(clearTimeout(o),o=null)},c=()=>{a(),o=setTimeout(()=>{t||(l(),i(n.trim()))},r),o.unref?.()},l=()=>{t=!0,a(),e.off("data",d),e.off("end",p),e.off("error",f),e.pause()},d=m=>{if(t)return;a(),n+=m.toString();let g=n.trim(),_=n.length-n.trimStart().length,E=n.indexOf(`
19
- `,_),I=E===-1?"":n.slice(_,E).trim();if(g.startsWith("{")){if(yt(g)){l(),i(g);return}if(E===-1){c();return}if(!yt(I)&&!I.endsWith("}")){let S=n.slice(E+1),B=S.split(`
20
- `).find(O=>O.trim()!=="")??"";if(I==="{"&&(!/\S/.test(S)||/^\s*"[^"]*"\s*:/.test(S)||/^\s*"[^"]*$/.test(B))){c();return}}l(),i(yt(I)?I:n.slice(_).trim());return}if(E!==-1){l(),i(I);return}else!g&&n.includes(`
21
- `)&&(l(),i(""))},p=()=>{if(t)return;let m=n.trim();if(!m){l();return}l(),i(m)},f=()=>{t||l()},y=new Promise(m=>{i=m});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",f),{promise:y,cancel:()=>{t||l()}}}function Ws(e){let n;return{promise:new Promise(i=>{if(e.aborted){i({source:"aborted"});return}n=()=>i({source:"aborted"}),e.addEventListener("abort",n,{once:!0})}),cleanup:()=>{n!==void 0&&e.removeEventListener("abort",n)}}}async function kr(e){let n=H(e.ctx),t=e.browserBase??e.ctx.apiBase,i=nl(t),r=e._openBrowser??mr,o=e._startListener??hr,a=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,_r.randomBytes)(32).toString("hex"),d=Date.now(),p=await sr(n,e.op,e.payload);h({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let y=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,m=2147483647,_=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,E=9e5,I=6e4,S=y!=null&&Number.isFinite(y)&&y>0?y:null,B=Math.max(0,Math.round((S??0)/1e3)),C=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,O=C!=null&&C<=m?C:null,F,ae,se=!1,D=!1,R=!1;if(S!=null){let T=Math.min(S,m),q=S>m;O!=null&&O<T?(F=O,ae="caller"):(F=T,ae=q?"timer_ceiling":"op_ttl",se=!q&&C!=null&&C>T)}else{let T=p.expires_at*1e3-d,q=Number.isFinite(T)?Math.min(Math.max(T,I),E):E,le=O??_;le>q?(F=q,ae="op_ttl_unverified",D=C!=null&&C>q):(F=le,ae=O!=null?"caller":"unknown_ttl"),R=C!=null&&O==null}let G=ae==="op_ttl",Ue=S!=null?`~${B}s`:"unknown";L.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${Ue}, waiting up to ${Math.round(F/1e3)}s for confirmation).
14
+ `}var X=N(require("fs")),Qt=N(require("os")),Mn=N(require("path")),Gn=N(require("@iarna/toml"));var $o=".allscale",Fo="config.toml";function Oe(){return Mn.join(Qt.homedir(),$o)}function Mo(){return Mn.join(Oe(),Fo)}function Je(){let e=Mo();if(!X.existsSync(e))return{};let n=X.readFileSync(e,"utf-8");try{return Gn.parse(n)}catch(t){throw new s("internal",`Failed to parse ${e}: ${t.message}`)}}function Zt(e){return Object.keys(e.profile??{}).sort()}function ei(e,n){return e.profile?.[n]}function ni(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new s("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function ke(e){if(!de(e))throw new s("input.invalid",`Refusing to send credentials to API base ${x(e)}. `+Se)}function Ye(e,n){ke(e);let t=z(e),i=typeof n=="string"?z(n):null;if(t&&i===t)return;let r=typeof n=="string"?x(n):"<missing origin binding>";throw new s("input.invalid",`Refusing to send stored credentials: API base ${x(e)} does not match their bound origin ${r}. Re-login against the intended API base before retrying.`)}function ti(e,n){let t=z(e),i=z(n);if(!(t&&i===t))throw new s("input.invalid",`Refusing API request to ${x(n)} because it is outside the configured API origin ${x(e)}.`)}function Ve(e){let n=qo(e);if(n)throw new s("input.invalid",n.message)}function Go(){let e=we();if(e===void 0)return;let n=Ae();return n.length>0?{endpoints:n.map(t=>t.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function qo(e){let n=Go();if(n===void 0||W(e))return;let{endpoints:t,fromPairs:i}=n,r=z(e),o=t.map(l=>z(l)).filter(l=>l!==null);if(r!==null&&o.includes(r))return;let a=t.map(l=>x(l)).join(", ");return{message:i?`Refusing to send to ${x(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.`:`Refusing to send to ${x(e)} \u2014 this build only signs for ${a}. Re-login against this build's environment, or use a build for that one.`}}var ii=require("@noble/hashes/sha3");var We=(a=>(a[a.ETHEREUM=1]="ETHEREUM",a[a.BASE=5]="BASE",a[a.BNB=6]="BNB",a[a.ARBITRUM=7]="ARBITRUM",a[a.POLYGON=8]="POLYGON",a[a.OPTIMISM=9]="OPTIMISM",a))(We||{});var jo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},ri=["ethereum","bsc","base","polygon","arbitrum","optimism"],ze=["USDT","USDC"];function oi(e){return jo[e.toLowerCase()]??null}function ai(e){let n=e.toUpperCase();return n==="USDT"?1:n==="USDC"?2:null}function si(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let n=e.slice(2);if(n===n.toLowerCase()||n===n.toUpperCase())return!0;let t=n.toLowerCase(),i=Buffer.from((0,ii.keccak_256)(Buffer.from(t,"ascii"))).toString("hex");for(let r=0;r<n.length;r+=1){let o=n[r];if(!/[a-fA-F]/.test(o))continue;let a=Number.parseInt(i[r],16)>=8;if(a&&o!==o.toUpperCase()||!a&&o!==o.toLowerCase())return!1}return!0}var Ko=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function li(e){return Ko.has(e.toLowerCase())}function Xe(e,n){let i={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return i?`${i}/${n}`:""}function M(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Q(e){return e===1?"USDT":"USDC"}var Ho="unknown_otp_id",Jo="invalid_code",Yo="expired_code";function Vo(e){return`'${e.replace(/'/g,"'\\''")}'`}function ci(e){return`Run \`allscale otp-send --email ${Vo(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Wo=new Map([[Ho,(e,n)=>`${e}: this environment never issued the --otp-id you passed for '${n}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${ci(n)}`],[Jo,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[Yo,(e,n,t)=>t?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${ci(n)}`]]);var di=[...Wo.keys()];var Y=require("@oclif/core"),Re=class e extends j.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:j.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:j.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ue()==="public"}),"api-base":j.Flags.string({description:kn,helpGroup:"GLOBAL",hidden:ue()==="public"}),"insecure-storage":j.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{Bn(this.jsonEnabled()),Dn(),h({type:"session-start",command:this.id??"",argv:$n(this.argv)});let n=this.constructor;if(ue()==="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(!n.isLocalOnly&&Ce()!==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 t=Ht(this.jsonEnabled()),i=this.argv.length===0&&!t&&ra(n)?this.config.findCommand(this.id??""):void 0;if(i){Le();let o=await(0,j.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(i,this.config.topics);return}if(n.requiresEscapeHatch&&!zt())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. Access remains governed by the key's granted scopes, which the backend checks on each request.");let r=await this.runCommand();return h({type:"command-end",ok:!0}),Le(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||Bt(r),{data:r})}catch(n){let t=Pt(n);Jt({code:t.code,message:t.message,exitCode:t.exitCode}),this.emitError(t),process.exitCode=t.exitCode;return}finally{Bn(!1)}}resolveSessionApiBaseChain(n){let t=Je(),i=n.profile??void 0,r=n["api-base"]??void 0,o=i!==void 0||Fn()!==void 0,a=ni(t,i,Fn()),l=ei(t,a),c=ue()==="public"&&Ce()!==void 0,u=r??(c?void 0:Ce()),p=u??l?.api_base??Ne,f=Xt({resolvedApiBase:p,fromExplicitOverride:u!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,me({event:"legacy_staging_profile",api_base:p,profile:a},f)),{apiBase:p,explicitApiBase:u,envApiBaseIgnored:c,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||ke(t),t}resolveContext(n){if(ue()==="public"){if(n.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(n["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&&Ce()!==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 t=n.token??void 0,i=!!n["insecure-storage"],{apiBase:r,explicitApiBase:o,envApiBaseIgnored:a,profile:l,profileApiBase:c,profileExplicit:u}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(ke(r),Ve(r)),{apiBase:r,profile:l,token:t??Yt(),insecureStorage:i||Vt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u,envApiBaseIgnored:a}}emitError(n){process.stderr.write(`${ia(n)}
15
+ `)}};var zo=/_(removed|cleared|count|total)$/i;function Xo(e,n){return typeof n=="number"&&zo.test(e)}var Qo=new Set(ze);function Zo(e,n){return e==="token_symbol"&&typeof n=="string"&&Qo.has(n)}var ea=new Set(di);function na(e,n){return e==="otp_reason"&&typeof n=="string"&&ea.has(n)}var Qe=100;function Ze(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,Qe),i=t.map(r=>Ze(r,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[r,o]of i.slice(0,Qe))t[r]=qe(r)&&!Xo(r,o)&&!Zo(r,o)&&!na(r,o)?"<redacted>":Ze(o,n+1);if(i.length>Qe){let r="<truncated>";for(;r in t;)r=`<${r}>`;t[r]=`${i.length-Qe} more keys`}return t}if(typeof e=="string"){let t=ta(e);return t!==void 0?v(JSON.stringify(Ze(t,n+1))):v(e)}return e}function ta(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function ia(e){let n=Mt()?void 0:2,t=Ze(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:v(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function ra(e){if(e.requiresInput===!0)return!0;let n=r=>typeof r=="object"&&r!==null&&r.required===!0,t=e.flags??{},i=e.args??{};return Object.values(t).some(r=>n(r))||Object.values(i).some(r=>n(r))}function oa(e,n={}){let t;try{t=Zt(Je())}catch{return}if(!(t.length===0||t.includes(e)))return new s("auth.unknown_profile",xt(e)+(n.messageSuffix??""),{profile:e})}function en(e){if(e.profileExplicit){let n=oa(e.profile);if(n)return n}return new s("auth.no_token",vt(e.profile))}var bi=N(require("path"));var Kn=require("crypto"),d=N(require("fs")),b=N(require("path"));var nn=1024*1024,aa=5e3,sa=20,la=3e4,qn=4096,ca=new Int32Array(new SharedArrayBuffer(4)),Ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function tn(e){return e instanceof Ie}var P=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},da=null;function ee(){return new s("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 rn(){return(da??process.platform)!=="win32"}function _i(){if(!rn())throw ee()}function ki(e){try{return d.default.lstatSync(e),!1}catch(n){if(!A(n,"ENOENT"))throw n}try{let n=d.default.lstatSync(b.dirname(e));return!n.isSymbolicLink()&&n.isDirectory()}catch(n){if(A(n,"ENOENT"))return!0;throw n}}function A(e,n){return typeof e=="object"&&e!==null&&e.code===n}function ve(e,n){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${n} is not owned by the current effective user`)}function xe(e,n){return e.dev===n.dev&&e.ino===n.ino}function ua(e){Atomics.wait(ca,0,0,e)}function Si(e){try{return process.kill(e,0),!0}catch(n){return!A(n,"ESRCH")}}function pa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ui(e,n){let t=b.dirname(e);n&&d.default.mkdirSync(t,{recursive:!0,mode:448});let i;try{i=d.default.lstatSync(t)}catch(o){if(!n&&A(o,"ENOENT"))return!1;throw o}if(i.isSymbolicLink()||!i.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let r=null;try{r=d.default.openSync(t,d.default.constants.O_RDONLY|(d.default.constants.O_DIRECTORY??0)|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0));let o=d.default.fstatSync(r),a=d.default.lstatSync(t);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!xe(o,a))throw new Error("credential-store parent changed while it was being inspected");ve(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&b.basename(t)===".allscale"&&(d.default.fchmodSync(r,448),l=d.default.fstatSync(r)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{r!==null&&d.default.closeSync(r)}return!0}function K(e,n,t,i={}){if(!t.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let r;try{r=d.default.lstatSync(e)}catch(o){throw i.retryOnPathChange&&A(o,"ENOENT")?new P:o}if(!xe(t,r))throw i.retryOnPathChange?new P:new Error("credential-store target changed while it was being opened or is not a regular file");if(r.isSymbolicLink()||!r.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!i.allowMultipleLinks&&(t.nlink!==1||r.nlink!==1))throw new Ie;if(ve(t,"credential-store file"),process.platform!=="win32"){d.default.fchmodSync(n,384);let o=d.default.fstatSync(n);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return t}function fa(e,n){if(n.size>nn)throw new Error("credential-store file exceeds the maximum supported size");let t=Buffer.alloc(nn+1),i=0;for(;i<t.length;){let r=d.default.readSync(e,t,i,t.length-i,null);if(r===0)break;i+=r}if(i>nn)throw new Error("credential-store file exceeds the maximum supported size");return t.subarray(0,i).toString("utf8")}function pi(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT"))try{if(d.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(A(o,"ENOENT"))return null;throw o}throw r}let t=d.default.fstatSync(n),i=K(e,n,t);return fa(n,i)}finally{n!==null&&d.default.closeSync(n)}}function fi(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT")&&ki(e))return;throw r}let t=d.default.fstatSync(n),i=K(e,n,t);ne(e,i)}finally{n!==null&&d.default.closeSync(n)}Ai(b.dirname(e))}function ma(e){let n;try{n=d.default.lstatSync(e)}catch(t){if(A(t,"ENOENT"))return;throw t}if(n.isSymbolicLink()||!n.isFile())throw new Error("credential-store replacement target must be a regular file");if(n.nlink!==1)throw new Ie;ve(n,"credential-store replacement target")}function ya(e,n){for(let t=0;t<8;t+=1){let i=(0,Kn.randomBytes)(12).toString("hex"),r=b.join(e,`.${n}.${process.pid}.${i}.tmp`);try{return{fd:d.default.openSync(r,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_WRONLY|(d.default.constants.O_NOFOLLOW??0),384),tempPath:r}}catch(o){if(A(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function wi(e,n){let t=0;for(;t<n.length;){let i=d.default.writeSync(e,n,t,n.length-t,null);if(!Number.isSafeInteger(i)||i<=0)throw new Error("credential-store temp file write made no progress");t+=i}}function Ai(e){if(process.platform==="win32")return;let n=null;try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_DIRECTORY??0)|(d.default.constants.O_NOFOLLOW??0)),d.default.fsyncSync(n)}catch{}finally{if(n!==null)try{d.default.closeSync(n)}catch{}}}function ha(e,n){let t=Buffer.from(n,"utf8");if(t.length>nn)throw new Error("credential-store file exceeds the maximum supported size");let i=b.dirname(e),r=b.basename(e),o=null,a=null,l=!1;try{let c=ya(i,r);o=c.fd,a=c.tempPath;let u=d.default.fstatSync(o);if((K(a,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");wi(o,t),d.default.fsyncSync(o),K(a,o,d.default.fstatSync(o));let f=o;o=null,d.default.closeSync(f),ma(e),d.default.renameSync(a,e),l=!0}finally{if(o!==null)try{d.default.closeSync(o)}catch{}if(!l&&a!==null)try{d.default.unlinkSync(a)}catch{}}Ai(i)}function ga(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function _a(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function ka(e,n){if(n.size>qn)return null;let t=Buffer.alloc(qn+1),i=0;for(;i<t.length;){let o=d.default.readSync(e,t,i,t.length-i,null);if(o===0)break;i+=o}if(i>qn)return null;let r;try{r=JSON.parse(t.subarray(0,i).toString("utf8"))}catch{return null}return typeof r!="object"||r===null||!Number.isSafeInteger(r.pid)||(r.pid??0)<=0||typeof r.nonce!="string"||!/^[a-f0-9]{24}$/.test(r.nonce??"")||typeof r.target!="string"?null:r}function ne(e,n){let t=d.default.lstatSync(e);if(t.isSymbolicLink()||!t.isFile()||!xe(t,n))throw new Error("credential-store lock changed while it was being inspected");ve(t,"credential-store lock"),d.default.unlinkSync(e)}function mi(e,n){let t=null;try{try{t=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(c){if(A(c,"ENOENT"))try{let u=d.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new P}catch(u){if(A(u,"ENOENT"))return{state:"absent"};throw u}throw c}let i=d.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ka(t,r);return{state:(o?.target===n&&o?!Si(o.pid):Date.now()-r.mtimeMs>=la)?"stale":"active",stats:r}}finally{t!==null&&d.default.closeSync(t)}}function Sa(e,n){for(let t=0;t<8;t+=1){let i=(0,Kn.randomBytes)(12).toString("hex"),r=b.join(e,`.${n}.${process.pid}.${i}.lock-claim`),o={pid:process.pid,nonce:i,target:n},a=null;try{a=d.default.openSync(r,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_WRONLY|(d.default.constants.O_NOFOLLOW??0),384);let l=d.default.fstatSync(a),c=K(r,a,l,{allowMultipleLinks:!0});return wi(a,Buffer.from(JSON.stringify(o),"utf8")),d.default.fsyncSync(a),{claimPath:r,metadata:o,stats:c}}catch(l){if(A(l,"EEXIST"))continue;try{d.default.unlinkSync(r)}catch{}throw l}finally{a!==null&&d.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function wa(e,n){let t;try{t=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(i){throw A(i,"ENOENT")?new P:i}try{let i=d.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!xe(r,n))throw new P;return{fd:t,lockPath:e,stats:r}}catch(i){throw d.default.closeSync(t),i}}function yi(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(t){if(A(t,"ENOENT"))try{let i=d.default.lstatSync(e);throw i.isSymbolicLink()||!i.isFile()?new Error("credential-store recovery gate must be a real regular file"):new P}catch(i){if(A(i,"ENOENT"))return!1;throw i}throw t}return K(e,n,d.default.fstatSync(n),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{n!==null&&d.default.closeSync(n)}}function Aa(e){let n;try{n=d.default.openSync(e,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_RDWR|(d.default.constants.O_NOFOLLOW??0),384)}catch(i){if(A(i,"EEXIST"))return null;throw i}let t=null;try{t=d.default.fstatSync(n);let i=K(e,n,t,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:n,lockPath:e,stats:i}}catch(i){if(t!==null)try{ne(e,t)}catch{}throw d.default.closeSync(n),i}}function Z(e,n){if(Date.now()>=e)throw n?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");ua(sa)}function hi(e){let n=b.dirname(e),t=b.basename(e),i=ga(e),r=_a(e),o=Sa(n,t),a=Date.now()+aa,l=!1,c=!1,u=null,p;try{for(;u===null;)try{if(yi(r)){Z(a,!0);continue}d.default.linkSync(o.claimPath,i),c=!0,u=wa(i,o.stats),l=!0}catch(f){if(c&&!l){try{ne(i,o.stats)}catch{}c=!1}if(f instanceof P){Z(a,!1);continue}if(!A(f,"EEXIST"))throw f;let y;try{y=mi(i,t)}catch(g){if(g instanceof P){Z(a,!1);continue}throw g}if(y.state==="absent")continue;if(y.state==="stale"){let g;try{g=Aa(r)}catch(_){if(_ instanceof P){Z(a,!1);continue}throw _}if(g!==null){try{let _;try{_=mi(i,t)}catch(E){if(E instanceof P){Z(a,!1);continue}throw E}_.state==="stale"&&ne(i,_.stats)}finally{jn(g)}continue}}let m;try{m=yi(r)}catch(g){if(g instanceof P){Z(a,!1);continue}throw g}Z(a,m)}}catch(f){p=f}try{ne(o.claimPath,o.stats)}catch(f){!A(f,"ENOENT")&&!l&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function jn(e){try{ne(e.lockPath,e.stats)}finally{d.default.closeSync(e.fd)}}function ba(e,n){let t=pa(n),i=new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!i)return null;let r=Number(i[1]);return Number.isSafeInteger(r)&&r>0?r:null}function gi(e){let n=b.dirname(e),t=b.basename(e);for(let i of d.default.readdirSync(n)){let r=ba(i,t);if(r===null||Si(r))continue;let o=b.join(n,i),a=null;try{try{a=d.default.openSync(o,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(u){if(A(u,"ENOENT")||A(u,"ELOOP"))continue;throw u}let l=d.default.fstatSync(a),c=d.default.lstatSync(o);if(!l.isFile()||c.isSymbolicLink()||!c.isFile()||!xe(l,c))continue;try{ve(l,"credential-store orphan")}catch{continue}ne(o,l)}catch(l){if(!A(l,"ENOENT"))throw l}finally{a!==null&&d.default.closeSync(a)}}}function Pe(e,n,t){if(!rn()){if(n.allowUnsupportedPlatformCleanup){if(n.createParent)throw ee();if(!ui(e,!1))return t({read:()=>null,remove:()=>{},write:()=>{throw ee()}});let a=hi(e);try{return gi(e),t({read:()=>pi(e),remove:()=>fi(e),write:()=>{throw ee()}})}finally{jn(a)}}if(!n.createParent){let o=!1;try{o=ki(e)}catch{throw ee()}if(o)return t({read:()=>null,remove:()=>{},write:()=>{throw ee()}})}throw ee()}if(!ui(e,n.createParent))return t({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let r=hi(e);try{return gi(e),t({read:()=>pi(e),remove:()=>fi(e),write:o=>ha(e,o)})}finally{jn(r)}}var Hn="allscale-cli";function Wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ti(e){return Wn(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function ie(e){return new s("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 Jn(){return new s("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 on(){return new s("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var te,Yn=!1;function Ta(){return Wt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function La(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let n=e.message;return typeof n=="string"&&n.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function Ea(){if(te!==void 0)return te;if(Ta())return Yn=!1,te=null,te;try{te=require("keytar"),Yn=!1}catch(e){Yn=!La(e),te=null}return te}var Na="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Li(){let e=rn()?"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 s("storage.unavailable",`${Na} `+e+" Never silently downgrade in production.")}async function Vn(e){try{return await e()}catch{throw Li()}}var zn=class{constructor(n){this.keytar=n}keytar;kind="keychain";async read(n){let t=await Vn(()=>this.keytar.getPassword(Hn,n));if(t===null)return null;let i;try{i=JSON.parse(t)}catch{throw ie("OS keychain")}if(!Ti(i))throw ie("OS keychain");return i}async get(n){return this.read(n)}async set(n,t){await this.read(n),await Vn(()=>this.keytar.setPassword(Hn,n,JSON.stringify(t)))}async delete(n){await this.read(n),await Vn(()=>this.keytar.deletePassword(Hn,n))}},Ca="credentials.json",Xn=class{kind="insecure-file";filePath;constructor(n){this.filePath=n??bi.join(Oe(),Ca)}read(n){let t;try{t=n.read()}catch(r){throw tn(r)?Jn():ie("plaintext file")}if(t===null)return{profiles:{}};let i;try{i=JSON.parse(t)}catch{throw ie("plaintext file")}if(!Wn(i)||!Wn(i.profiles))throw ie("plaintext file");return i}write(n,t){try{n.write(JSON.stringify(t,null,2))}catch(i){throw tn(i)?Jn():on()}}profileTokens(n,t){let i=n.profiles[t];if(i!==void 0){if(!Ti(i))throw ie("plaintext file");return i}}async get(n){try{return Pe(this.filePath,{createParent:!1},t=>this.profileTokens(this.read(t),n)??null)}catch(t){throw t instanceof s?t:ie("plaintext file")}}async set(n,t){try{Pe(this.filePath,{createParent:!0},i=>{let r=this.read(i);this.profileTokens(r,n),r.profiles[n]=t,this.write(i,r)})}catch(i){throw i instanceof s?i:on()}}async delete(n){try{Pe(this.filePath,{createParent:!1},t=>{let i=this.read(t);this.profileTokens(i,n)!==void 0&&(delete i.profiles[n],this.write(t,i))})}catch(t){throw t instanceof s?t:on()}}async clearProfile(n){try{return Pe(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},t=>{let i=this.read(t);return this.profileTokens(i,n)===void 0?!1:(delete i.profiles[n],Object.keys(i.profiles).length===0?t.remove():this.write(t,i),!0)})}catch(t){throw t instanceof s?t:tn(t)?Jn():on()}}};function an(e){if(e.insecureStorage)return _i(),new Xn(e.insecureFilePath);let n=Ea();if(n)return new zn(n);throw Li()}var Qn=class{kind="insecure-file";async get(n){return null}async set(n,t){throw new s("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(n){}};function sn(){return new Qn}async function Ei(e){if(e.token)return{kind:"override",accessToken:e.token};let t=await an({insecureStorage:e.insecureStorage}).get(e.profile),i=t?.api_base;return t?.agent_key?{kind:"agent",storedApiBase:i,businessId:Zn(t.business_id),userEmail:Zn(t.user_email),scopes:Oa(t.scopes)}:t?.access_token?{kind:"human",storedApiBase:i,accessToken:t.access_token,userEmail:Zn(t.user_email)}:{kind:"none"}}function Zn(e){return typeof e=="string"&&e.length>0?e:void 0}function Oa(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string"&&t.length>0);return n.length>0?n:void 0}function Ci(e){let n=e.split(".");if(n.length!==3)throw new s("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let t;try{let i=Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");t=JSON.parse(i)}catch{throw Ni()}if(typeof t!="object"||t===null||Array.isArray(t))throw Ni();return t}function Ni(){return new s("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}async function Ra(e){let n=i=>{let r=Ci(i);return typeof r.user_id=="string"&&r.user_id.length>0?r.user_id:void 0},t=await Ei(e);switch(t.kind){case"override":case"human":return n(t.accessToken);case"agent":return t.businessId;case"none":throw en({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ia(t)}}function Ia(e){throw new s("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}var va=/^[0-9a-f]{24}$/i;async function Oi(e,n){if(typeof n!="string"||n.length===0)return;if(!va.test(n))throw new s("input.invalid",`--business-id '${n}' is not a valid business id (expected 24 hexadecimal characters). Omit the flag to use the business you are signed in as.`);let t=await Ra(e);if(t===void 0){process.stderr.write(`Note: could not verify that --business-id '${n}' is your own business \u2014 this session stores no business id (an agent-key login predating the backend returning it). The command acts as the business you are signed in as regardless. Re-run \`allscale device-login\` to store it and enable this check.
17
+ `);return}if(t.toLowerCase()!==n.toLowerCase())throw new s("auth.permission_denied",`--business-id '${n}' is not the business you are signed in as. This command always acts as the authenticated business, so a different business id cannot be used. Omit the flag, or sign in as that business.`)}var ln="allscale_access_token",et="allscale_refresh_token";function Ri(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(t=>{let i=t.indexOf(";"),r=i===-1?t:t.slice(0,i),o=r.indexOf("=");return o===-1?null:{name:r.slice(0,o).trim(),value:r.slice(o+1).trim()}}).filter(t=>t!==null)}function nt(e){return e.map(n=>`${n.name}=${n.value}`).join("; ")}function tt(e,n){return e.find(t=>t.name===n)?.value??null}var Ii=N(require("crypto")),vi=N(require("fs")),xi=N(require("path"));var xa="key-id",Pa="x-allscale-cli-version",it="cli-1",Ba="aScaLe_cli_obf_v1",Ua="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Da(e,n){let t=Buffer.from(e,"base64"),i=Buffer.from(n,"utf8"),r=Buffer.alloc(t.length);for(let o=0;o<t.length;o++)r[o]=t[o]^i[o%i.length];return r.toString("utf8")}var $a=Da(Ua,Ba),Pi=`Bearer ${$a}`;function Bi(e,n){let t=An(e);if(t!==null)return n.find(i=>An(i.base)===t)}function Fa(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let n=Ae();if(n.length>0){let i=Bi(e,n);if(i)return i.key;if(W(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?r:W(n[0].base)?n[0].key:void 0}return}let t=process.env.ALLSCALE_SIGNING_KEY;return t&&t.trim().length>0?t:void 0}function Ma(e){{let i="cli-1".trim();if(i.length>0)return i}let n=Ae();if(n.length>0){let i=e!==void 0?Bi(e,n):void 0;if(i)return i.keyId;if(e!==void 0&&W(e)){let r=process.env.ALLSCALE_SIGNING_KEY;if(r&&r.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():it}if(!W(n[0].base))return it}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():it}function Ga(){return"1.0.5"}function qa(){return new s("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 rt(e,n){let t=Fa(n);if(!t)throw qa();let i=Ma(n),r=Math.floor(Date.now()/1e3).toString(),o=Ii.createHash("sha256").update(`${t}${r}${e}`).digest("hex"),a={timestamp:r,"secret-key":o,[Pa]:Ga()};return i.length>0&&(a[xa]=i),a}function Ui(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ja=new Set;var Ka=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),ot=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),at=new Set(["payroll","admin:user","admin:org","admin:audit"]);function cn(e){let n=e.lastIndexOf(":");return n===-1?e:e.slice(0,n)}function Di(e,n){if(e===n)return!0;let t=":read_only";return n.endsWith(t)&&e===`${n.slice(0,-t.length)}:all`}var Ha=new Set(["cli_op:all"]),Ja=new Set([...Ha].map(cn));var Yc=new Set([...[...Ka,...ot,...ja].map(cn),...at,...Ja]);var Ya={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Va={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},Wa=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,za=/is not available to API keys/i,$i=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Fi(e){if(typeof e!="string")return;let n=Wa.exec(e);if(!n)return;let t=n[1].trim(),i=n[2].trim(),r=za.test(t),o=!r&&$i.test(t)?t:void 0,a;if(i.toLowerCase()==="none")a=[];else{let l=i.split(",").map(c=>c.trim()).filter(c=>$i.test(c));a=l.length>0?l:void 0}if(!(o===void 0&&!r))return{required:o,granted:a,notAvailableToKeys:r}}function Mi(e){let n=Va[e];if(n!==void 0)return{ungrantableReason:n};let t=Ya[e];if(t!==void 0)return{scope:t}}function Gi(e){if(at.has(cn(e)))return{kind:"ungrantable"};for(let n of ot)if(Di(n,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function dn(e,n,t,i){let r=Fi(e),o=r?.notAvailableToKeys===!0,a=r?.required??i?.scope,l=r?.granted,c=l===void 0?"":` This key holds ${l.length>0?l.join(", "):"no scopes"}.`;if(o||i?.ungrantableReason!==void 0){let u=i?.ungrantableReason!==void 0?`: ${i.ungrantableReason}`:"";return new s("auth.permission_denied",`${n} is not available to agent keys${u}. Re-authorizing will NOT help \u2014 no scope grants it.${c} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...t,missing_scopes:[],...l===void 0?{}:{granted_scopes:l},ungrantable:!0})}if(a!==void 0){let u=Gi(a),p=u.kind==="ungrantable"?`\`${a}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:u.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${be()}\` with \`--scopes ${a}\`.`:`The browser approval screen does not offer \`${a}\`, so \`device-login\` cannot grant it \u2014 use \`${be()}\` with \`--scopes ${a}\`.`;return new s("auth.permission_denied",`The current agent key lacks \`${a}\`, required by ${n}.${c} ${p}`,{...t,missing_scopes:[a],...l===void 0?{}:{granted_scopes:l},...u.kind==="ungrantable"?{ungrantable:!0}:{}})}return new s("auth.permission_denied",`The current agent key does not have the scope required by ${n}.${c} Re-run \`allscale device-login\` (or \`${be()}\`) and grant the required scope.`,t)}var Xa=500,Qa=8,qi=100;function st(e,n=0){if(n>Qa)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,qi),i=t.map(r=>st(r,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);for(let[i,r]of Object.entries(e).slice(0,qi))t[i]=qe(i)?"<redacted>":st(r,n+1);return t}return e}function Za(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function ji(e,n=Xa){let t=Za(e),i=t===void 0?Ge(e):JSON.stringify(st(t));return je(i,n)}var lt=256*1024,un=class extends s{constructor(n,t,i="backend-envelope"){let r=i==="successful-query",o=i==="successful-mutation";super(r?"transport.response_too_large":"backend.internal",r?`The API returned an HTTP-success response larger than the CLI's ${t}-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 ${t}-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 ${t}-byte safety limit and was not parsed.`,{status:n,max_body_bytes:t,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},pn=class extends Error{status;timeoutMs;constructor(n,t){super(`API response body read exceeded its ${t}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=n,this.timeoutMs=t}};async function ct(e,n,t={}){if(!Number.isSafeInteger(n)||n<=0)throw new RangeError("maxBytes must be a positive safe integer");if(t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let i=e.headers.get("content-length"),r=i!==null&&/^\d+$/.test(i.trim())?Number(i):void 0;if(r!==void 0&&r>n)throw e.body?.cancel().catch(()=>{}),new un(e.status,n,t.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],l=0,c,u=t.timeoutMs,p=u===void 0?void 0:new Promise((f,y)=>{c=setTimeout(()=>{y(new pn(e.status,u))},u),c.unref?.()});try{for(;;){let f=o.read(),{done:y,value:m}=p?await Promise.race([f,p]):await f;if(y)break;if(l+=m.byteLength,l>n)throw o.cancel().catch(()=>{}),new un(e.status,n,t.oversizeKind);a.push(Buffer.from(m))}}catch(f){throw f instanceof pn&&o.cancel(f).catch(()=>{}),f}finally{c!==void 0&&clearTimeout(c);try{o.releaseLock()}catch{}}return Buffer.concat(a,l).toString("utf8")}var es="X-AllScale-Api-Key",ns=3e4,ts=32*1024*1024,is=4*1024*1024;function rs(e,n){let t=new AbortController,i=!1,r=()=>{t.abort(e?.reason)};e?.aborted?r():e?.addEventListener("abort",r,{once:!0});let o=setTimeout(()=>{i=!0,t.abort()},n);return{signal:t.signal,timedOut:()=>i,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",r)}}}function os(e,n){return n?n.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((t,i)=>{let r=()=>{i(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};n.addEventListener("abort",r,{once:!0}),e.then(t,i).finally(()=>{n.removeEventListener("abort",r)})}):e}function as(e,n){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${J(n||"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 Vi(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}as(e.status,e.url)}}var Ki="--dns-result-order=ipv4first";async function fn(e,n){if(e.status!==403)return;let t=e.headers.get("content-type")?.toLowerCase()??"",i=e.headers.get("cf-ray")??"",r=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=t.includes("text/html"),a=n?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),c=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||l)&&(r||n!==void 0&&c)))return;if(n===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(i)?i:void 0;throw new s("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Ki} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Ki}`})}var re=class{constructor(n){this.opts=n}opts;refreshInFlight=null;async requestWithMetadata(n){return this.requestInternal(n,{withMetadata:!0})}async request(n){return this.requestInternal(n,{withMetadata:!1})}async requestInternal(n,t){let i=n.timeoutMs??this.opts.requestTimeoutMs??ns;if(!Number.isFinite(i)||i<1)throw new s("input.invalid","HTTP request timeout must be a positive number of milliseconds.");ke(this.opts.apiBase),Ve(this.opts.apiBase);let r=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=rs(n.signal,i);try{return await this.requestWithinDeadline({...n,signal:o.signal},t,r)}catch(a){throw o.timedOut()?new s("transport.timeout",`Request to ${J(new URL(n.path,this.opts.apiBase).toString())} timed out after ${i}ms.`,{timeout_ms:i}):n.signal?.aborted&&!(a instanceof s)?new s("transport.network",`Request to ${J(new URL(n.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(n,t,i){let r=new URL(n.path,this.opts.apiBase).toString();ti(this.opts.apiBase,r);let o=i?.agent_key,a=n.auth??"auto",l=Wi(n.path),c=a==="required"?!0:a==="none"?!1:cs(n.path);if((l||a==="required")&&!n._isRefresh&&!this.opts.override&&!i?.access_token&&!o)throw en({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let u=Ui(n.body),p=!!o||!!i?.access_token;c&&p&&!this.opts.override&&Ye(this.opts.apiBase,i?.api_base);let f=this.buildHeaders({attachAuth:c&&p,bodyForSig:u,tokens:i,extra:n.headers}),y=Date.now();h({type:"request",method:n.method??"GET",url:r,...n._isRefresh?{refresh:!0}:{}});let m;try{m=await fetch(r,{method:n.method??"GET",headers:f,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(_){throw new s("transport.network",`Network error contacting ${J(r)}: ${_ instanceof Error?_.message:String(_)}`)}if(h({type:"response",status:m.status,durationMs:Date.now()-y}),c&&!!i?.access_token&&!o&&m.status===401&&!n._isRefresh&&!this.opts.override){let _=await os(this.refreshSingleFlight(),n.signal),E=this.buildHeaders({attachAuth:c&&!!_.access_token,bodyForSig:u,tokens:_,extra:n.headers}),I=Date.now();h({type:"request",method:n.method??"GET",url:r});let S;try{S=await fetch(r,{method:n.method??"GET",headers:E,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(B){throw new s("transport.network",`Network error contacting ${J(r)} on refresh-retry: ${B instanceof Error?B.message:String(B)}`)}return h({type:"response",status:S.status,durationMs:Date.now()-I}),Hi(S,{withMetadata:t.withMetadata,authBearing:c,responseKind:Ji(n)})}return Hi(m,{withMetadata:t.withMetadata,authBearing:c&&p,agentKeyAuth:c&&!!o,responseKind:Ji(n)})}buildHeaders(n){let i={Accept:"application/json","Content-Type":"application/json",...rt(n.bodyForSig,this.opts.apiBase),...n.extra};if(n.attachAuth){i.Authorization=Pi;let r=n.tokens;if(r?.agent_key)return i[es]=r.agent_key,i;let o=r?.access_token;o&&(i.Cookie=nt([{name:ln,value:o}]))}return i}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(n){let t;try{t=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!t?.access_token||!t?.refresh_token||t.refresh_token===n.refresh_token)return null;if(Ye(this.opts.apiBase,t.api_base),t.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return t}async doRefresh(){let n=await this.opts.tokenStore.get(this.opts.profile);if(!n?.access_token||!n?.refresh_token)throw new s("auth.token_expired",`No refresh token available; log in again \u2014 ${Me()}.`);if(Ye(this.opts.apiBase,n.api_base),n.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let t=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),i=nt([{name:ln,value:n.access_token},{name:et,value:n.refresh_token}]),r=rt("",this.opts.apiBase);h({type:"request",method:"POST",url:t,refresh:!0});let o=new AbortController,a=!1,l=setTimeout(()=>{a=!0,o.abort()},1e4),c;try{c=await fetch(t,{method:"POST",headers:{Accept:"application/json",Cookie:i,...r},signal:o.signal,redirect:"manual"})}catch(m){throw h({type:"refresh",ok:!1}),new s("transport.network",a&&m instanceof Error&&m.name==="AbortError"?`Token refresh against ${J(t)} timed out after 10s with no response.`:`Network error during token refresh against ${J(t)}: ${m instanceof Error?m.message:String(m)}`)}finally{clearTimeout(l)}h({type:"response",status:c.status,durationMs:0});try{await Vi(c)}catch(m){throw h({type:"refresh",ok:!1}),m}if(c.status!==200){let m=null;try{await fn(c);let g=await ms(c);await fn(c,g),zi(c.status,g),c.status===401&&(m=await this.adoptConcurrentlyRotatedTokens(n))}catch(g){throw h({type:"refresh",ok:!1}),g}if(m)return h({type:"refresh",ok:!0,adopted:!0}),m;throw h({type:"refresh",ok:!1}),new s("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Me()}.`,{status:c.status})}let u=Ri(c.headers),p=tt(u,ln),f=tt(u,et);if(!p||!f)throw h({type:"refresh",ok:!1}),new s("auth.token_expired","Refresh response did not include new access/refresh cookies.");let y={...n,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,y),h({type:"refresh",ok:!0}),y}},ss=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Wi(e){let n=e.split(/[?#]/,1)[0];return ss.some(t=>n===t||n.startsWith(`${t}/`))}var ls=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function dt(e){let n=e.split(/[?#]/,1)[0];return ls.some(t=>t.test(n))}function cs(e){return Wi(e)||dt(e)}async function Hi(e,n={}){await Vi(e);let t=e.status>=200&&e.status<300;t||await fn(e);let i=n.responseKind??"mutation",o=await ct(e,t?i==="query"?ts:is:lt,{oversizeKind:t?i==="query"?"successful-query":"successful-mutation":"backend-envelope"});t||await fn(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(n.withMetadata){let c={};return e.headers.forEach((u,p)=>{c[p]=u}),{status:e.status,headers:c,body:a}}return a}let l=ys(a)??`HTTP ${e.status}`;if(zi(e.status,a),ps(e.status,a,n),ut(a,2102))throw dn(a.errors,"this API request",{status:e.status,backend_code:2102});if(e.status===401){if(n.agentKeyAuth)throw new s("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let c=n.authBearing?"auth.token_expired":"input.invalid";throw new s(c,l,{status:401,body:a})}throw e.status===403?new s("auth.permission_denied",l,{status:403,body:a}):e.status===404?new s("not_found",l,{status:404,body:a}):e.status===429?new s("rate_limited",l,{status:429,body:a}):e.status>=500?new s("backend.internal",l,{status:e.status,body:a}):new s("input.invalid",l,{status:e.status,body:a})}function Ji(e){if(e.responseKind)return e.responseKind;let n=(e.method??"GET").toUpperCase();return n==="GET"||n==="HEAD"?"query":"mutation"}var ds=2014,Yi=2004;function ut(e,n){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let i=t.code;return i===n||i===String(n)}function us(e){return ut(e,ds)}function ps(e,n,t){if(!(e>=200&&e<300)&&t.authBearing&&!(e===401&&t.agentKeyAuth)&&ut(n,Yi))throw new s("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Me()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Yi})}var fs=1e4;async function ms(e,n=fs){if(e.status>=200&&e.status<300)return"";try{return await ct(e,lt,{timeoutMs:n})}catch{return""}}function zi(e,n){if(!(e>=200&&e<300)&&us(n))throw new s("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 n=="string"?ji(n):n})}function ys(e){if(!e||typeof e!="object")return;let n=e;if(typeof n.message=="string")return n.message;if(typeof n.detail=="string")return n.detail;if(Array.isArray(n.detail))return JSON.stringify(n.detail)}var hs=/^\/(api\/)?(v1\/)?public\//;function H(e,n={}){let t=typeof n.pathHint=="string"?n.pathHint:"",i=t&&hs.test(t),r=t&&dt(t),o=i&&!r&&!n.forceAuth;if(e.token)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new re({apiBase:e.apiBase,tokenStore:an({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(r)return new re({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var Xi=[{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_contact_by_email",kind:"query",description:"Look up the contact card of the business whose login email is given. Used to fill the invoice header's From: block with the same name/email/phone the web editor shows.",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:"BusinessContact",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_funding_by_idempotency_key",kind:"query",description:"Recover the caller's original Claim Link funding contract by its stable idempotency key. Returns null when no recoverable funding contract is available. The response includes bearer claim authority and requires the claim_link:all agent-key scope.",args:[{name:"idempotency_key",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"OBJECT",name:"ClaimLinkFundingReconciliation",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}],Qi=[{name:"ActivityFilterInput",kind:"INPUT",description:null,inputFields:[{name:"transaction_types",description:"Filter by transaction types (OR): 1=PAYMENT, 2=REWARD, 3=WITHDRAWAL, 8=CHECKOUT_INTENT_EPHEMERAL, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 11=CHECKOUT_INTENT_EPHEMERAL_REFUND, 13=CHECKOUT_INTENT_EPHEMERAL_NET_INCOME, 14=CLAIM_LINK",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"transaction_statuses",description:"Filter by transaction statuses (OR): 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"payment_statuses",description:"Filter by payment statuses (OR): -4=OVERDUE, -1=FAILED, 0=DRAFT, 1=SENT, 2=ACKNOWLEDGED, 3=PROCESSING, 10=PAID",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"withdraw_statuses",description:"Filter by withdraw statuses (OR): -4=CANCELED, -1=FAILED, 1=CREATED, 20=CONFIRMED",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"directions",description:"Filter by transaction direction (OR): 1=INFLOW, -1=OUTFLOW",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"contact_keyword",description:"Fuzzy search by contact name/email or store name. OR relationship with wallet_address.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"wallet_address",description:"Fuzzy search by counterparty wallet address (tx_from/tx_to). OR relationship with contact_keyword.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"start_time",description:"Filter transactions after this time, ISO8601 format (e.g. 2024-01-01T00:00:00.000Z)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"end_time",description:"Filter transactions before this time, ISO8601 format",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"min_amount",description:"Filter transactions with amount >= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"max_amount",description:"Filter transactions with amount <= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"is_claim_link",description:"When true, return only claim-link activity: a receiver's claim (an ON_CHAIN_TX tagged with claim_link_id) OR a sender's CLAIM_LINK row (single claim_link_id / batch claim_link_batch_id). Matched by claim-link linkage presence, NOT transaction_types \u2014 a receiver's claim shares transaction_type=ON_CHAIN_TX(10) with a plain deposit, so it cannot be selected by type alone (bug 6935616).",type:{kind:"SCALAR",name:"Boolean",ofType:null},defaultValue:"null"}]},{name:"ActivityItem",kind:"OBJECT",description:null,fields:[{name:"transaction_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Transaction record ID"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Transaction amount in cryptocurrency"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Transaction amount in fiat cents"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"When the transaction occurred on-chain"},{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Record creation time in UTC"},{name:"transaction_status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Status: 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked payment ID for PAYMENT type transactions"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Type: 1=PAYMENT, 2=REWARD, 3=SEND, 4=SERVICE_FEE, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 14=CLAIM_LINK"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Direction: 1=INFLOW (received), -1=OUTFLOW (sent)"},{name:"wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Counterparty wallet address (sender if INFLOW, recipient if OUTFLOW)"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"On-chain transaction hash"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Blockchain network type"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Block number of the on-chain transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"User-provided memo or notes"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Cryptocurrency type (e.g. USDT)"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Fiat currency type (e.g. USD, CNY)"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee = network_fee + service_fee"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"On-chain gas/network fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"AllScale platform service fee"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Counterparty's business ID if they are an AllScale user"},{name:"claim_link_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked claim link ID for CLAIM_LINK type transactions"}]},{name:"ActivityItemPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ActivityItem",ofType:null}}}},description:null}]},{name:"AuthorizedPolicyPair",kind:"OBJECT",description:null,fields:[{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain identified by its BlockChainType value (for example BASE = 5) \u2014 not the EIP-155 chain id."},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Stablecoin symbol: USDT or USDC"}]},{name:"AutoPayoutSessionStatus",kind:"OBJECT",description:null,fields:[{name:"provisioned",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether auto-payout setup has been completed for this merchant."},{name:"active",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"True iff provisioned AND the session has not expired (the runtime auto-pay gate)"},{name:"session_expires_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"Session expiry (drives the countdown); null when not provisioned"},{name:"total_cap_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified session total cap in USD (decimal string); null when not provisioned"},{name:"used_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Cumulative USD spent (reserved + committed) this session (decimal string); populated only for an ACTIVE session, else null"},{name:"remaining_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"max(0, total_cap - used) in USD (decimal string); populated only for an ACTIVE session, else null"},{name:"per_transaction_limit",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified single-transaction limit (token-unit decimal string, stablecoin $ 1:1) recorded when auto-payout is enabled; null when not provisioned or when recorded entries have different limits. Retained after a session expires, so it still reports what was recorded."},{name:"authorized_pairs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"AuthorizedPolicyPair",ofType:null}}}},description:"The (chain, stable-coin) pairs the merchant authorized when enabling auto-payout; empty when auto-payout was never provisioned. Retained after a session expires, so it still reports what was authorized."},{name:"sponsor_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Lowercased sponsor address used to validate authorized payouts. Populated whether or not auto-payout is provisioned, so it is readable while enabling; null when unavailable."}]},{name:"Business",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"user name"},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"email of the user"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"description of the user"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the business"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address field for business"},{name:"country",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"country code of business"},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"contact name of business"},{name:"contact_avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact avatar url of business"},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact phone of business"},{name:"avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"avatar url of business"},{name:"default_currency",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"default currency for business"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the business"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax id of the business"},{name:"about",type:{kind:"SCALAR",name:"String",ofType:null},description:"about of the business, can be changed by business"},{name:"business_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"business type"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of accepted stablecoins for invoices (StableCoinFlag)"},{name:"employee_count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"total active employees in the business"}]},{name:"BusinessContact",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Display name of the business's user account."},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Login email of the business's user account."},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Contact person the business presents on its invoices. Preferred over `name` when both are set."},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"Contact phone the business presents on its invoices. Null when the business has not set one."}]},{name:"ClaimLink",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim link id"},{name:"business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"sender business that owns the link"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"ClaimLinkStatus lifecycle state"},{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount, decimal string in token units"},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"stablecoin symbol, e.g. USDT / USDC"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"BlockChainType the link is locked to"},{name:"sender_display_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name shown to the receiver (person or Store name)"},{name:"sender_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional message shown on the claim page"},{name:"receiver_email",type:{kind:"SCALAR",name:"String",ofType:null},description:"receiver email, if the sender supplied one"},{name:"reference_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"Optional merchant-supplied reference identifier."},{name:"expected_deposit_total",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the expected POOL balance (principal). The sender's gross outlay is the fee breakdown's total"},{name:"service_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"AllScale service fee fixed when the claim link is created; null when not applicable."},{name:"network_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"Network fee fixed when the claim link is created; null when not applicable."},{name:"funded_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the deposit actually received at the pool wallet"},{name:"funded_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the confirming sender deposit"},{name:"expiry_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC; the resolved claim-window deadline (funded_at + the chosen window, default 14d); None until link_sent"},{name:"claimed_via",type:{kind:"SCALAR",name:"String",ofType:null},description:"how it was claimed: masked receiver email or 0x address"},{name:"claim_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the successful claim"},{name:"refund_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the expiry refund back to the sender"},{name:"refunded_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC when the expiry refund proved on-chain"},{name:"cancel_requested_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC timestamp set when the sender requests cancellation while a claim is in progress. The request stays pending until the in-flight payout resolves: it is cleared if that payout completes (the cancellation is moot and the link is claimed), and retained if the payout did not go through and the link is cancelled and refunded. Null therefore means either no mid-claim cancellation was requested, or one that was resolved by a completed payout."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL returned by create and single-link detail operations. The sender distributes this URL themselves; it is never emailed to the receiver. Null when unavailable, and always null on list operations \u2014 selecting it there returns the field as null rather than omitting it."}]},{name:"ClaimLinkFeeBreakdown",kind:"OBJECT",description:null,fields:[{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount the receiver gets, decimal string"},{name:"network_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"gas reserve = gas_shares \xD7 per_transfer_gas, decimal string"},{name:"service_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"AllScale service fee for the chain, decimal string"},{name:"total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"amount + network_fee + service_fee \u2014 what the sender pays"},{name:"per_transfer_gas",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"one transfer's gas in token units (echoed for audit)"},{name:"gas_shares",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Number of per_transfer_gas shares reserved; currently 2 for a single claim link."}]},{name:"ClaimLinkFundingReconciliation",kind:"OBJECT",description:null,fields:[{name:"claim_link",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},description:"the caller-owned link and its current funding status"},{name:"claim_token",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the original raw bearer claim token; returned so recovery remains usable when no claim-page base URL is configured"},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"convenience bearer claim URL; null when no claim-page base is configured (use claim_token to build it)"},{name:"pool_wallet_address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the original ERC-4337 pool address"},{name:"expected_deposit_total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the frozen pool principal, as an exact decimal string"},{name:"fees",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},description:"the frozen fee breakdown from the original create"},{name:"claim_window_seconds",type:{kind:"SCALAR",name:"Int",ofType:null},description:"the frozen create-time claimable-window duration in seconds; null means the backward-compatible 14-day default"}]},{name:"ClaimLinkPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}}}},description:null}]},{name:"CoinBalanceEmbedded",kind:"OBJECT",description:null,fields:[{name:"coin_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Stablecoin held, as the numeric StableCoin value (1 = USDT, 2 = USDC). `wallet list` decorates each balance with the derived `coin_name`."},{name:"balance",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Decimal",ofType:null}},description:"Balance of the coin"}]},{name:"Contact",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"id of the contact"},{name:"owner_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"owner id of the contact"},{name:"contact_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"contact id if contact is allscale business"},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name of the contact"},{name:"binding_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"the way of binding an allscale business id to the contact, by email matching(1) or scan qrcode(2), etc."},{name:"email",type:{kind:"SCALAR",name:"String",ofType:null},description:"email of the contact"},{name:"evm_wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"evm wallet address of the contact"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax number of the contact"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address of the contact"},{name:"phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"phone number of the contact"},{name:"last_payment_created_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last payment date of the contact"},{name:"last_paid_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last successful pay date"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"Free-form description of the contact."},{name:"is_favourite",type:{kind:"SCALAR",name:"Boolean",ofType:null},description:"is favourite or not"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the contact"}]},{name:"ContactPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}}}},description:null}]},{name:"CreateClaimLinkInput",kind:"INPUT",description:null,inputFields:[{name:"amount",description:"claim amount, decimal string in token units (e.g. '10.5')",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"token_symbol",description:"stablecoin symbol: 'USDT' or 'USDC'",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"BlockChainType value the link is locked to (EVM only)",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"per_transfer_gas",description:"one ERC-20 transfer's gas in TOKEN units (decimal string); from the App's withdraw estimate",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"receiver_email",description:"optional receiver email \u2014 a SENDER-SIDE LABEL ONLY, recording who the link is meant for. AllScale does NOT email the receiver (no invite, no expiry reminder, no resend); the sender must distribute `claim_url` themselves.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_display_name",description:"name shown to the receiver (person or Store name)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_message",description:"optional message shown on the claim page (<= 200 chars)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"idempotency_key",description:"optional client retry-safety token; a retried create with the same key returns the existing link instead of a duplicate",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_window_seconds",description:"Optional positive claim-window duration in seconds. Defaults to 14 days. The window starts when funding is confirmed; after it expires, unclaimed funds are returned to the sender.",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreateClaimLinkResult",kind:"OBJECT",description:null,fields:[{name:"claim_link",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},description:"the newly created link (pending_deposit)"},{name:"claim_token",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Bearer claim token returned only when the claim link is created and never available again. Capture and store it securely immediately; it preserves claim authority when claim_url is unavailable."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL; null when no claim-page URL is configured."},{name:"pool_wallet_address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"ERC-4337 address the sender funds"},{name:"expected_deposit_total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the expected POOL balance (principal), decimal string; the sender's gross outlay is the fee breakdown's total"},{name:"fees",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},description:"the frozen fee breakdown"}]},{name:"CreateContactInput",kind:"INPUT",description:null,inputFields:[{name:"owner_business_id",description:"owner id of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"name",description:"name of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"email",description:"email of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"evm_wallet_address",description:"evm wallet address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"address",description:"address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"phone",description:"phone number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_number",description:"tax number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"description",description:"Free-form description of the contact.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"binding_type",description:"binding type of the contact",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"sender_contact_id",description:"contact id of the payer/sender",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"payment_type",description:"payment type of the payment",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"accepted_stable_coins",description:"optional per-invoice bitflag (StableCoinFlag) overriding the recipient business's accepted_stable_coins setting",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"payment_extra_info",description:"payment extra info of the payment, JSON object string",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"currency",description:"currency of the payment, only if the payment_type is CURRENCY",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_cents",description:"amount of the payment in cents",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_coins",description:"amount of the payment in coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"html_template",description:"HTML template for the invoice",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_id",description:"optional taxpayer identification for the invoice",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"datetime the payment is due",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"},{name:"wallets",description:"list of wallets address",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"PlainWalletEmbeddedInput",ofType:null}}}},defaultValue:null}]},{name:"CreateStoreInput",kind:"INPUT",description:null,inputFields:[{name:"name",description:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"logo_url",description:"logo url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:null},{name:"business_id",description:"pay account business id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"type",description:"type of the store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"default_timeout_seconds",description:"default timeout seconds for checkout intents",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"3600"},{name:"swidge_enabled",description:"whether Swidge cross-chain checkout is enabled for this store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"claim_link_claim_notify_enabled",description:"Whether AllScale sends merchant claim-notification emails for this store; defaults to false.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"false"},{name:"description",description:"description",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"scopes",description:"permission scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:'["*"]'},{name:"ip_allowlist",description:"allowed IPs/CIDRs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:"[]"},{name:"is_sandbox",description:"Whether to create the store in sandbox mode.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"rate_limit_per_minute",description:"Optional request-per-minute limit; defaults to 300, and 0 uses the platform default.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"300"},{name:"replay_window_seconds",description:"override replay window seconds",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"transaction_webhook",description:"transaction webhook url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_link_webhook_url",description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"redirect_url",description:"Redirect URL used after payment completes.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"fee_rate",description:"fee rate",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"accepted_stable_coins",description:"bitflag of accepted stablecoins for checkout (StableCoinFlag); null inherits from business",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"Payment",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the payment"},{name:"recipient_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"business id of the payee/recipient"},{name:"sender_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the payer/sender"},{name:"sender_contact_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"contact id of the payer/sender"},{name:"payment_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"payment type of the payment"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of stablecoins accepted for this payment (StableCoinFlag). None on payments created before the multi-coin rollout."},{name:"payment_extra_info",type:{kind:"SCALAR",name:"String",ofType:null},description:"payment extra info of the payment, JSON object string"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the payment, only if the payment_type is CURRENCY"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the payment"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount of the payment in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount of the payment in coins"},{name:"invoice_url",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice url of the payment"},{name:"invoice_visible_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice visible id of the pdf"},{name:"tax_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional taxpayer identification for the invoice"},{name:"error_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"error message of the payment if status is failed"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the payment"},{name:"due_datetime",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"datetime the payment is due"},{name:"display_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"display amount of the payment"},{name:"encrypted_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Opaque payment identifier used in public payment links."}]},{name:"PaymentPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}}}},description:null}]},{name:"PlainWalletEmbeddedInput",kind:"INPUT",description:null,inputFields:[{name:"id_str",description:"Unique identifier for the wallet",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"Blockchain type of the address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"address",description:"Blockchain address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}]},{name:"QueryInput",kind:"INPUT",description:null,inputFields:[{name:"limit",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"skip",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"order_by",description:null,type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}},defaultValue:"null"},{name:"raw_filter_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:'"{}"'},{name:"created_at_lte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"created_at_gte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"}]},{name:"Store",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Unique store identifier."},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name"},{name:"type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the store"},{name:"scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},description:"permission scopes"},{name:"is_sandbox",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether this store uses sandbox mode."},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the store"},{name:"transaction_webhook",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction webhook url"},{name:"claim_link_webhook_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook."},{name:"redirect_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Redirect URL used after payment completes."}]},{name:"StoreCreateResult",kind:"OBJECT",description:null,fields:[{name:"store",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Store",ofType:null}},description:"store"},{name:"api_secret",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Store API secret returned only when the store is created and never available again. Capture and store it securely immediately."}]},{name:"Transaction",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the transaction record"},{name:"owner_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"owner user type of the record"},{name:"owner_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id that owns this transaction record"},{name:"owner_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id that owns this transaction record"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the transaction"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"direction of the transaction"},{name:"reference_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"reference type of the related record"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"payment id when reference_type is PAYMENT"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the counterparty"},{name:"counterparty_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id of the counterparty"},{name:"counterparty_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name of the counterparty"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"payment type if this is a payment transaction"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the transaction"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount in coins"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the transaction"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"actual transaction time"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"hash of the transaction"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block chain of the transaction"},{name:"tx_from",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction sender address"},{name:"tx_to",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction receiver address"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block number of the transaction"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee (network_fee + service_fee)"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Network/gas fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Allscale service fee (0.03%)"}]},{name:"TransactionPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Transaction",ofType:null}}}},description:null}]},{name:"UpdatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_business_id",description:"sender business id of the payer",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"new payment deadline for an OVERDUE invoice. Only an overdue invoice may be extended, and only FORWARD. Extending past now also revives the invoice (back to SENT/ACKNOWLEDGED) so buyers can pay again.",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"}]},{name:"WalletEmbedded",kind:"OBJECT",description:null,fields:[{name:"id_str",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet id"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain the wallet lives on, as the numeric BlockChainType value (NOT a name). `wallet list` decorates each wallet with the derived `chain_name` and `eip155_chain_id`."},{name:"address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet address"},{name:"coin_balances",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"OBJECT",name:"CoinBalanceEmbedded",ofType:null}}},description:"wallet balance"}]}];var mn=new Set(["SCALAR","ENUM"]),gs=new Set(["password","password_hash","totp_secret","credential","credentials","private_key","encryption_key"]),_s=[/(^|_)password(_|$)/i,/(^|_)secret(_|$)/i,/(^|_)token(_|$)/i,/(^|_)api[_-]?key(_|$)/i,/(^|_)signing[_-]?key(_|$)/i,/(^|_)private[_-]?key(_|$)/i,/(^|_)credential(_|$)/i],ks=new Set(["CreateClaimLinkResult.claim_token","StoreCreateResult.api_secret"]),Ss=new Map([["StoreCreateResult.store",["id","name"]],["CreateClaimLinkResult.claim_link",["id","token_symbol","status"]]]),ws=new Set(["token_symbol"]),As=new Set;function pt(e,n){return As.has(`${e}.${n}`)}function ft(e){return ws.has(e.toLowerCase())?!1:gs.has(e)?!0:_s.some(n=>n.test(e))}function bs(e,n){return ks.has(`${e}.${n}`)}function mt(e){return e.kind==="NON_NULL"&&e.ofType?`${mt(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${mt(e.ofType)}]`:e.name??"Unknown"}function Be(e){let n=e;for(;n&&n.ofType;)n=n.ofType;return!n||!n.name?null:{kind:n.kind,name:n.name}}function Ts(e,n){let t=n.find(a=>a.name===e);if(!t||t.kind==="SCALAR"||t.kind==="ENUM")return"";if(t.kind==="UNION")return"__typename";let i=t.fields??[];if(i.length===0)return"";let r=[],o=!1;for(let a of i){let l=Be(a.type);if(!l)continue;if(mn.has(l.kind)){if(ft(a.name)&&!bs(e,a.name)||pt(e,a.name))continue;r.push(a.name);continue}let c=Ss.get(`${e}.${a.name}`);if(c){let u=n.find(m=>m.name===l.name),p=new Set((u?.fields??[]).filter(m=>{let g=Be(m.type);return g!==null&&mn.has(g.kind)&&!ft(m.name)}).map(m=>m.name)),f=c.filter(m=>!p.has(m));if(f.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${f.join(", ")}] that are not selectable scalars on ${l.name}; fix the entry or the public registry.`);let y=c.filter(m=>pt(l.name,m));if(y.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${y.join(", ")}] that DEFAULT_SELECTION_EXCLUSIONS keeps out of default selections on ${l.name}; drop the field from the nested entry, or remove the exclusion if it is no longer true.`);r.push(`${a.name} { ${c.join(" ")} }`);continue}if(!o&&a.name==="items"&&a.type.kind==="NON_NULL"&&a.type.ofType?.kind==="LIST"){let u=Ls(a.type)?.name;if(u){let p=Es(u,n);p&&r.push(`items { ${p} }`),o=!0}}}return r.length>0?r.join(" "):"__typename"}function Ls(e){return Be(e)}function Es(e,n){let t=n.find(o=>o.name===e);if(!t||t.kind==="UNION")return"__typename";let i=t.fields??[],r=[];for(let o of i){let a=Be(o.type);if(a&&mn.has(a.kind)){if(ft(o.name)||pt(e,o.name))continue;r.push(o.name)}}return r.length>0?r.join(" "):"__typename"}function Zi(e,n,t){let i=Ns(e.name),r=e.args.map(p=>{let f=mt(p.type);return p.defaultValue!==null&&p.defaultValue!==void 0?`$${p.name}: ${f} = ${p.defaultValue}`:`$${p.name}: ${f}`}).join(", "),o=e.args.map(p=>`${p.name}: $${p.name}`).join(", "),a=r.length>0?`${e.kind} ${i}(${r})`:`${e.kind} ${i}`,l=o.length>0?`${e.name}(${o})`:e.name,c=Be(e.returnType),u;if(c&&mn.has(c.kind))u=l;else{let p=t&&t.trim().length>0?t.trim():c&&Ts(c.name,n)||"__typename";u=`${l} { ${p} }`}return`${a} { ${u} }`}function er(e,n){let i=e.args.filter(r=>r.type.kind==="NON_NULL"&&r.defaultValue===null).map(r=>r.name).filter(r=>!(r in n));return i.length===0?{ok:!0}:{ok:!1,missing:i}}function nr(e,n,t){return e.find(i=>i.kind===n&&i.name===t)??null}function tr(e){if(!e||typeof e!="object")return!1;let n=e.errors;return Array.isArray(n)&&n.length>0}function ir(e,n=3){let t=e.errors;return!Array.isArray(t)||t.length===0?"":t.slice(0,n).map(i=>typeof i=="object"&&i!==null&&typeof i.message=="string"?i.message:JSON.stringify(i)).join("; ")}function Ns(e){return e.replace(/[^_0-9A-Za-z]/g,"_")}var Cs=8100,Os=new Set([Cs]),Rs=new Set([...Os,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function or(e,n){let t=Is(e),i={graphql_error_count:vs(e.errors),...t===void 0?{}:{backend_code:t}};if(t===2102)throw dn(xs(e,t),`GraphQL ${n.kind} '${n.operationName}'`,{...i,operation:n.operationName},Mi(n.operationName));if(t===429)throw new s("rate_limited",`GraphQL ${n.kind} '${n.operationName}' was rate limited. Retry after a backoff.`,i);if(t===1002)throw new s("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${n.kind} '${n.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,i);if(t!==void 0&&Rs.has(t))throw new s("not_found",`GraphQL ${n.kind} '${n.operationName}' could not find the requested resource.`,i);if(tr(e))throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' returned errors: ${ir(e)}`,i);if(t!==void 0)throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' failed with backend code ${t}.`,i)}function Is(e){let n=rr(e.code);if(n!==void 0)return n;if(Array.isArray(e.errors))for(let t of e.errors){if(!t||typeof t!="object")continue;let i=t.extensions;if(!i||typeof i!="object")continue;let r=rr(i.code);if(r!==void 0)return r}}function rr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let n=Number(e);if(Number.isSafeInteger(n)&&n>0)return n}}function vs(e){return Array.isArray(e)?e.length:e==null?0:1}function xs(e,n){let t=e.errors;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let i=r=>{if(r===null||typeof r!="object")return;let o=r.message;return typeof o=="string"?o:void 0};if(n!==void 0)for(let r of t){if(r===null||typeof r!="object")continue;let o=r.extensions;if(!o||typeof o!="object")continue;let a=o.code;if(a===n||typeof a=="string"&&Number(a)===n){let c=i(r);if(c!==void 0)return c}}for(let r of t){let o=i(r);if(o!==void 0)return o}return""}async function yt(e,n,t,i,r={}){let o=nr(Xi,n,t);if(!o)throw new s("input.invalid",`No ${n} named '${t}' in the schema. Run \`allscale operations --kind ${n}\` to list options.`);let a=er(o,i);if(!a.ok)throw new s("input.invalid",`Missing required variables for ${t}: ${a.missing.join(", ")}`,{required:a.missing});let l=Zi(o,Qi,r.selection);return Ps(e,{...r,kind:n,operationName:o.name,document:l,variables:i})}async function Ps(e,n){n.showDoc&&process.stderr.write(`${n.document}
18
+ `);let t=H(e),i=n.path??"/api/secure/graphql",r=await t.request({method:"POST",path:i,responseKind:n.kind,body:{query:n.document,...Object.keys(n.variables).length>0?{variables:n.variables}:{},operationName:n.operationName}});or(r,{kind:n.kind,operationName:n.operationName});let o=r.data?.[n.operationName];return o===void 0?null:o}var _r=require("crypto"),L=require("process");var oe=/^0x[0-9a-fA-F]{64}$/,Bs=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function ar(e){return typeof e=="string"&&Bs.includes(e)}var $={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},Us=new Set(Object.values($));async function sr(e,n,t){let{body:i,headers:r}=await Fs(e,"/api/secure/wallet/cli_op_init",{op:n,payload:t},"cli_op_init");return{...i,server_now_ms:Ds(r)}}function Ds(e){let n=e.date??e.Date??Object.entries(e).find(([i])=>i.toLowerCase()==="date")?.[1];if(n===void 0)return null;let t=Date.parse(n);return Number.isFinite(t)?t:null}async function ht(e,n){return $s(e,"/api/secure/wallet/cli_op_result",{result_token:n},"cli_op_result")}async function $s(e,n,t,i){let r;try{r=await e.request({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=lr(o,i);if(a!==null)throw a}throw o}return cr(r,i)}async function Fs(e,n,t,i){let r;try{r=await e.requestWithMetadata({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=lr(o,i);if(a!==null)throw a}throw o}return{body:cr(r.body,i),headers:r.headers??{}}}function lr(e,n){let t=e.details?.body;if(!t||typeof t!="object")return null;let i=t,r=typeof i.code=="number"?i.code:void 0;if(r===void 0||r===0||!Us.has(r))return null;let o=typeof i.errors=="string"?i.errors:typeof i.message=="string"?i.message:e.message;return dr(r,o,n)}function cr(e,n){if(e.code!==void 0&&e.code!==0)throw dr(e.code,e.message,n);if(e.data===void 0)throw new s("backend.internal",`Broker ${n} returned no data envelope`,{envelope:e});return e.data}function dr(e,n,t){let i=n??`Broker ${t} returned code ${e}`;switch(e){case $.CLI_OP_NOT_FOUND:return new s("not_found",i,{broker_code:e});case $.CLI_OP_EXPIRED:return new s("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:i});case $.CLI_OP_UNAUTHORIZED:return new s("auth.permission_denied",i,{broker_code:e});case $.CLI_OP_UNKNOWN_TYPE:return new s("input.invalid",i,{broker_code:e});case $.CLI_OP_INVALID_PAYLOAD:case $.CLI_OP_SELF_TRANSFER:case $.CLI_OP_INSUFFICIENT_BALANCE:case $.CLI_OP_WALLET_STATE_CONFLICT:return new s("input.invalid",i,{broker_code:e});case $.CLI_OP_PREFLIGHT_UNAVAILABLE:return new s("backend.internal",i,{broker_code:e});case $.CLI_OP_TOKEN_CONSUMED:return new s("input.invalid",i,{broker_code:e});default:return new s("backend.internal",i,{broker_code:e})}}var fr=require("child_process");function ur(e){let n=e?.trim();return n?n!=="0"&&n.toLowerCase()!=="false":!1}var Ms=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Gs(e,n,t,i){if(ur(e.CI)||Ms.some(a=>ur(e[a])))return"ci";let o=n!=="darwin"&&n!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":t===!0||i===!0?null:"no-tty"}function qs(e){let n=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",t=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+n+t:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+n+t:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+n+t}async function mr(e,n={}){if(!Sn(e))throw new s("input.invalid",`Refusing to launch browser for untrusted origin: ${x(e)}`);let t=n._env??process.env,i=n._platform??process.platform,r=t.BROWSER?.trim();if(r&&r.toLowerCase()==="none")throw new s("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let o=r?null:Gs(t,i,n._stdinIsTTY??process.stdin.isTTY,n._stderrIsTTY??process.stderr.isTTY);if(o)throw new s("wallet.requires_browser_auth",qs(o));if(i==="linux"&&!t.DISPLAY&&!r)throw new s("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(n._execOverride){await n._execOverride(e);return}let a=js(i,r);await Ks(a.command,[...a.args,e])}function js(e,n){return n&&n.length>0?{command:n,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Ks(e,n){return new Promise((t,i)=>{let r;try{r=(0,fr.spawn)(e,n,{detached:!0,stdio:"ignore"})}catch(a){i(pr(e,a));return}let o=!1;r.once("error",a=>{o||(o=!0,i(pr(e,a)))}),setImmediate(()=>{o||(o=!0,r.unref(),t())})})}function pr(e,n){return new s("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${n.message}. Re-run on a host with a graphical environment.`)}var yr=N(require("http"));var Hs=9e4,Js=16*1024;function hr(e){let n=e.timeoutMs??Hs;return new Promise((t,i)=>{let r=!1,o=!1,a=null,l,c,u=new Promise((f,y)=>{l=f,c=y}),p=yr.createServer((f,y)=>{Ys(f,y,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>r,tryConsume:()=>r?!1:(r=!0,!0),onSuccess:m=>{a&&clearTimeout(a),l(m),p.close()}})});p.on("error",f=>{let y=new s("transport.network",`Loopback listener error: ${f.message}`);o?c(y):i(y),a&&clearTimeout(a)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),i(new s("transport.network","Failed to read loopback listener port"));return}let y=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,m=y!=null?Math.max(1,Math.min(n,y)):n,g=y!=null&&y<=n;a=setTimeout(()=>{c(new s("wallet.bridge_timeout",`Bridge timed out after ${m}ms waiting for browser callback.`,{bridge_deadline:g?"op_ttl":"duration"})),p.close()},m),a.unref?.(),o=!0,t({port:f.port,awaitResult:u,close:()=>{a&&clearTimeout(a),p.close()}})})})}function Ys(e,n,t){let i=e.headers.origin??"";if(e.method==="OPTIONS"){if(i===t.expectedOrigin){let l={"Access-Control-Allow-Origin":t.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(l["Access-Control-Allow-Private-Network"]="true"),n.writeHead(204,l)}else n.writeHead(403);n.end();return}if(e.method!=="POST"||e.url!=="/result"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"not_found"}));return}if(t.isConsumed()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}if(i!==t.expectedOrigin){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"origin_mismatch"}));return}let r=0,o=[],a=!1;e.on("data",l=>{if(!a){if(r+=l.length,r>Js){a=!0,n.writeHead(413,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"payload_too_large"}));return}o.push(l)}}),e.on("end",()=>{if(a)return;let l=Buffer.concat(o).toString("utf-8"),c;try{c=JSON.parse(l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_json"}));return}if(!c||typeof c!="object"){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_body"}));return}let u=c,p=typeof u.state=="string"?u.state:"",f=typeof u.result_token=="string"?u.result_token:void 0,y=u.result_data!==void 0&&u.result_data!==null&&typeof u.result_data=="object"&&!Array.isArray(u.result_data)?u.result_data:void 0;if(!Vs(p,t.state)){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&y===void 0){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"missing_result"}));return}if(!t.tryConsume()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}n.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":t.expectedOrigin}),n.end(JSON.stringify({ok:!0})),t.onSuccess({result_token:f,result_data:y})}),e.on("error",()=>{a||(a=!0)})}function Vs(e,n){if(e.length!==n.length)return!1;let t=0;for(let i=0;i<e.length;i+=1)t|=e.charCodeAt(i)^n.charCodeAt(i);return t===0}function gt(e){try{return JSON.parse(e),!0}catch{return!1}}function gr(){let e=process.stdin,n="",t=!1,i=()=>{},r=250,o=null,a=()=>{o&&(clearTimeout(o),o=null)},l=()=>{a(),o=setTimeout(()=>{t||(c(),i(n.trim()))},r),o.unref?.()},c=()=>{t=!0,a(),e.off("data",u),e.off("end",p),e.off("error",f),e.pause()},u=m=>{if(t)return;a(),n+=m.toString();let g=n.trim(),_=n.length-n.trimStart().length,E=n.indexOf(`
19
+ `,_),I=E===-1?"":n.slice(_,E).trim();if(g.startsWith("{")){if(gt(g)){c(),i(g);return}if(E===-1){l();return}if(!gt(I)&&!I.endsWith("}")){let S=n.slice(E+1),B=S.split(`
20
+ `).find(O=>O.trim()!=="")??"";if(I==="{"&&(!/\S/.test(S)||/^\s*"[^"]*"\s*:/.test(S)||/^\s*"[^"]*$/.test(B))){l();return}}c(),i(gt(I)?I:n.slice(_).trim());return}if(E!==-1){c(),i(I);return}else!g&&n.includes(`
21
+ `)&&(c(),i(""))},p=()=>{if(t)return;let m=n.trim();if(!m){c();return}c(),i(m)},f=()=>{t||c()},y=new Promise(m=>{i=m});return e.resume(),e.on("data",u),e.on("end",p),e.on("error",f),{promise:y,cancel:()=>{t||c()}}}function Ws(e){let n;return{promise:new Promise(i=>{if(e.aborted){i({source:"aborted"});return}n=()=>i({source:"aborted"}),e.addEventListener("abort",n,{once:!0})}),cleanup:()=>{n!==void 0&&e.removeEventListener("abort",n)}}}async function kr(e){let n=H(e.ctx),t=e.browserBase??e.ctx.apiBase,i=nl(t),r=e._openBrowser??mr,o=e._startListener??hr,a=e.mode??"ack",l=e._readPaste!==void 0||process.stdin.isTTY===!0,c=(0,_r.randomBytes)(32).toString("hex"),u=Date.now(),p=await sr(n,e.op,e.payload);h({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let y=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,m=2147483647,_=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,E=9e5,I=6e4,S=y!=null&&Number.isFinite(y)&&y>0?y:null,B=Math.max(0,Math.round((S??0)/1e3)),C=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,O=C!=null&&C<=m?C:null,F,ae,se=!1,D=!1,R=!1;if(S!=null){let T=Math.min(S,m),q=S>m;O!=null&&O<T?(F=O,ae="caller"):(F=T,ae=q?"timer_ceiling":"op_ttl",se=!q&&C!=null&&C>T)}else{let T=p.expires_at*1e3-u,q=Number.isFinite(T)?Math.min(Math.max(T,I),E):E,le=O??_;le>q?(F=q,ae="op_ttl_unverified",D=C!=null&&C>q):(F=le,ae=O!=null?"caller":"unknown_ttl"),R=C!=null&&O==null}let G=ae==="op_ttl",Ue=S!=null?`~${B}s`:"unknown";L.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${Ue}, waiting up to ${Math.round(F/1e3)}s for confirmation).
22
22
  `),se&&L.stderr.write(`Note: the confirmation wait of ${C}ms is longer than the confirmation link's remaining life (${Math.round(F/1e3)}s, from the server's stated expiry and its own clock), so the wait was capped at that.
23
23
  `),D&&L.stderr.write(`Note: the confirmation wait of ${C}ms is longer than the confirmation link's remaining life (~${Math.round(F/1e3)}s), so the wait was capped at that. No server-relative TTL was available, so that figure is the link's stated expiry read against THIS machine's clock \u2014 approximate: short if your clock runs fast, long if it runs slow.
24
24
  `),R&&L.stderr.write(`Note: the requested confirmation wait of ${C}ms is outside the usable range (1ms-${m}ms), so it was ignored and the wait fell back to ~${Math.round(F/1e3)}s.
25
- `);let k=await o({state:l,...S!=null?{deadlineAtMs:d+S}:{},expectedOrigin:i,timeoutMs:F}),hn=k.awaitResult.then(T=>({source:"loopback",...T}),T=>({source:"listener_error",error:T})),Vr=Date.now(),At=setInterval(()=>{let T=Math.floor((Date.now()-Vr)/1e3);L.stderr.write(`Still waiting for confirmation\u2026 (${T}s elapsed)
26
- `)},15e3);At.unref?.();let De,gn=e.signal===void 0?void 0:Ws(e.signal);try{let T=Zs(t,{op_id:p.op_id,port:k.port,state:l});h({type:"bridge_browser_open",url:T});let q=a==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(L.stderr.write(c?e.autoOpen===!1?`
25
+ `);let k=await o({state:c,...S!=null?{deadlineAtMs:u+S}:{},expectedOrigin:i,timeoutMs:F}),gn=k.awaitResult.then(T=>({source:"loopback",...T}),T=>({source:"listener_error",error:T})),Vr=Date.now(),Tt=setInterval(()=>{let T=Math.floor((Date.now()-Vr)/1e3);L.stderr.write(`Still waiting for confirmation\u2026 (${T}s elapsed)
26
+ `)},15e3);Tt.unref?.();let De,_n=e.signal===void 0?void 0:Ws(e.signal);try{let T=Zs(t,{op_id:p.op_id,port:k.port,state:c});h({type:"bridge_browser_open",url:T});let q=a==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(L.stderr.write(l?e.autoOpen===!1?`
27
27
  Confirm this in your browser. Open the URL below on any device where
28
28
  you're signed in to AllScale (local auto-open is disabled):
29
29
 
@@ -46,24 +46,24 @@ back from another device:
46
46
  `),e.autoOpen===!1)L.stderr.write(`(browser auto-open skipped \u2014 use the link above)
47
47
  `);else try{await r(T),L.stderr.write(`(opened in your default browser)
48
48
  `)}catch{L.stderr.write(`(no local browser to open \u2014 use the link above)
49
- `)}c?L.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
49
+ `)}l?L.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
50
50
  reach this machine (e.g. you opened the link elsewhere over SSH), copy
51
51
  the ${q} the page shows, paste it here, and press Enter:
52
52
 
53
53
  `):L.stderr.write(`stdin is non-interactive; waiting for the browser callback.
54
54
 
55
- `),c&&(De=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:gr());let le=[hn];De!==void 0&&le.push(De.promise.then(Wr=>({source:"paste",line:Wr}))),gn!==void 0&&le.push(gn.promise);let ce=await Promise.race(le);if(ce.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(ce.source==="listener_error")throw zs(ce.error,G);if(ce.source==="loopback")return L.stderr.write(`Browser returned result; processing\u2026
55
+ `),l&&(De=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:gr());let le=[gn];De!==void 0&&le.push(De.promise.then(Wr=>({source:"paste",line:Wr}))),_n!==void 0&&le.push(_n.promise);let ce=await Promise.race(le);if(ce.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(ce.source==="listener_error")throw zs(ce.error,G);if(ce.source==="loopback")return L.stderr.write(`Browser returned result; processing\u2026
56
56
  `),await Xs(n,a,ce);let $e=ce.line.trim();if(!$e)throw new s("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(a==="ack"&&$e.startsWith("{"))throw new s("wallet.bridge_invalid_response","Pasted value looks like JSON, not a confirmation token. Copy the single-line token the /cli page shows, not the result JSON.");if(a==="ack"&&/\s/.test($e))throw new s("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return L.stderr.write(`Received pasted ${q}; processing\u2026
57
- `),await Qs(n,a,$e,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(At),gn?.cleanup(),De?.cancel(),k.close()}}function zs(e,n){let i=(e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:n;return e instanceof s&&e.code==="wallet.bridge_timeout"&&i?new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} That was the confirmation link's own lifetime, so it has expired or is about to; a longer --bridge-timeout cannot extend a link past its lifetime.`,e.details):e instanceof s&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new s("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function Xs(e,n,t){if(n==="ack"){if(!t.result_token)throw new s("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");h({type:"bridge_result_received",source:"loopback"});let i=await mt(e,t.result_token);return h({type:"bridge_verified",op_id:i.op_id,source:"loopback"}),L.stderr.write(`Verified by broker.
57
+ `),await Qs(n,a,$e,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(Tt),_n?.cleanup(),De?.cancel(),k.close()}}function zs(e,n){let i=(e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:n;return e instanceof s&&e.code==="wallet.bridge_timeout"&&i?new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} That was the confirmation link's own lifetime, so it has expired or is about to; a longer --bridge-timeout cannot extend a link past its lifetime.`,e.details):e instanceof s&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new s("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function Xs(e,n,t){if(n==="ack"){if(!t.result_token)throw new s("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");h({type:"bridge_result_received",source:"loopback"});let i=await ht(e,t.result_token);return h({type:"bridge_verified",op_id:i.op_id,source:"loopback"}),L.stderr.write(`Verified by broker.
58
58
  `),{ack:i,result_data:t.result_data}}if(!t.result_data)throw new s("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return h({type:"bridge_result_received",source:"loopback"}),h({type:"bridge_data_received",source:"loopback"}),L.stderr.write(`Result received from browser.
59
- `),{result_data:t.result_data}}async function Qs(e,n,t,i){if(n==="ack"){h({type:"bridge_result_received",source:"paste"});let o=await mt(e,t);return h({type:"bridge_verified",op_id:o.op_id,source:"paste"}),L.stderr.write(`Verified by broker.
59
+ `),{result_data:t.result_data}}async function Qs(e,n,t,i){if(n==="ack"){h({type:"bridge_result_received",source:"paste"});let o=await ht(e,t);return h({type:"bridge_verified",op_id:o.op_id,source:"paste"}),L.stderr.write(`Verified by broker.
60
60
  `),{ack:o}}let r;try{r=el(t,{acceptBareTxHashPaste:i})}catch(o){throw o instanceof s&&o.code==="input.invalid"?new s("wallet.bridge_invalid_response",o.message):o}return h({type:"bridge_result_received",source:"paste"}),h({type:"bridge_data_received",source:"paste"}),L.stderr.write(`Result accepted.
61
61
  `),{result_data:r}}function Zs(e,n){let t=new URL("/cli",Sr(e));return t.searchParams.set("op_id",n.op_id),t.searchParams.set("port",String(n.port)),t.searchParams.set("state",n.state),t.toString()}function el(e,n={}){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(n.acceptBareTxHashPaste!==!1&&oe.test(e))return{tx_hash:e};throw new s("input.invalid",n.acceptBareTxHashPaste===!1?"Paste the complete JSON result object from the /cli page. A bare transaction hash is not accepted for this operation because it cannot distinguish confirmed, reverted, or unknown status.":`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function nl(e){return Sr(e).origin}function Sr(e){if(!de(e))throw new s("input.invalid",`Refusing browser base ${x(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${Se}`);return new URL(e)}var wr=["outcome","transaction_hash","error_code"],tl=["transaction_hash","error_code"];function Ar(e){if(e.outcome==="confirmed")return tl.some(i=>Object.prototype.hasOwnProperty.call(e,i))||typeof e.tx_hash!="string"||!oe.test(e.tx_hash)?null:{outcome:"confirmed",transactionHash:e.tx_hash};if(Object.keys(e).length!==wr.length||!wr.every(i=>Object.prototype.hasOwnProperty.call(e,i)))return null;let t=e.transaction_hash;return typeof t!="string"||!oe.test(t)?null:e.outcome==="failed"&&e.error_code==="transaction_reverted"?{outcome:"failed",transactionHash:t,errorCode:"transaction_reverted"}:e.outcome==="ambiguous"&&(e.error_code==="receipt_confirmation_timeout"||e.error_code==="receipt_confirmation_unavailable")?{outcome:"ambiguous",transactionHash:t,errorCode:e.error_code}:null}var V=N(require("fs")),br=N(require("path")),Tr=require("crypto");var il="device_id";function Lr(){let e=null,n=null;try{e=Oe(),n=br.join(e,il)}catch{}try{if(n){let i=V.readFileSync(n,"utf-8");if(i.length>70)throw new Error("oversized device_id");let r=i.split(`
62
62
  `)[0].trim();if(r&&/^cli_[0-9a-f]{32}$/.test(r))return r}}catch{}let t=`cli_${(0,Tr.randomBytes)(16).toString("hex")}`;try{if(!e||!n)throw new Error("persistence unavailable");V.mkdirSync(e,{recursive:!0,mode:448}),V.writeFileSync(n,`${t}
63
- `,{mode:384});try{V.chmodSync(n,384)}catch{}}catch{}return t}function Nr(e){return H(e,{pathHint:"/api/v1/public/businesses/payments"})}var Er=3e4;function rl(e){if(typeof e=="string"&&e.length>0)return e;if(Array.isArray(e)){let n=e.filter(t=>t!=null&&t!==!1&&t!==0).map(t=>typeof t=="string"?t:JSON.stringify(t)).filter(t=>typeof t=="string"&&t.length>0&&t!=="null"&&t!=="{}"&&t!=="[]");return n.length>0?n.join("; "):void 0}if(e!==null&&typeof e=="object"){let n=JSON.stringify(e);if(n!=="{}")return n}}function ol(e,n){if(e==null)return;let t=typeof e.code=="number"?e.code:0,i=rl(e.errors),r=(()=>{let p=e.error;if(p==null||p===!1||p===0||p==="")return;if(typeof p=="string")return p;if(typeof p!="object")return"backend flagged an unspecified error";let f=JSON.stringify(p);return f&&f!=="{}"&&f!=="[]"&&f!=="null"?f:void 0})(),o=i??r??(typeof e.message=="string"&&e.message.length>0?e.message:void 0),a=i??r,c=typeof e.code!="number"&&e.code!=="0"&&!!e.code,d=(e.code==null||e.code===""||e.code==="0"||e.code===0||e.code===!1)&&!!a;if(t!==0||c||d){let p=o??`${n} returned code ${String(e.code??t)}`;throw new s("backend.internal",p,{broker_code:e.code})}return e.data}async function ht(e,n,t,i,r){let o=r??H(e,{pathHint:n}),a=new AbortController,c=!1,l=setTimeout(()=>{c=!0,a.abort()},Er);try{let d=await o.request({method:"POST",path:n,body:t,signal:a.signal});return ol(d,i)}catch(d){throw c&&d instanceof s&&d.code==="transport.network"?new s("backend.internal",`${i} timed out after ${Er/1e3}s with no response from the backend.`):d}finally{clearTimeout(l)}}function Cr(e){let n=e.sender_email?.trim();return{sender_fingerprint:e.sender_fingerprint,...n?{sender_email:n}:{}}}async function Or(e,n,t,i){let r=await ht(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents`,Cr(t),"ensurePayIntent",i);if(!r)throw new s("backend.internal","ensurePayIntent: server returned success but no payment data.");if(!r.pay_intent)throw new s("input.invalid","This invoice has no crypto pay-intent \u2014 it may already be paid/processing, overdue, or a fiat-currency invoice that can't be paid from the CLI.",{status:r.status});let o=typeof r.pay_intent.id=="string"?r.pay_intent.id.trim():"";if(!o)throw new s("backend.internal","ensurePayIntent: server returned a pay_intent with no usable id \u2014 unexpected server response.");return{...r.pay_intent,id:o}}async function Rr(e,n,t){await ht(e,"/api/v1/public/businesses/transactions",{payment_id:n.payment_id,tx_hash:n.tx_hash,tx_block_chain:n.tx_block_chain,dest_stable_coin:n.dest_stable_coin,tx_from:n.tx_from,sender_fingerprint:n.sender_fingerprint,is_allscale_pay:!0},"reportTransaction",t)}async function Ir(e,n,t,i,r){await ht(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents/${encodeURIComponent(t)}:confirm`,Cr(i),"confirmPayIntent",r)}function al(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${Tn}\` to refresh the session, then retry.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function sl(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_op_expired",`${e.message.replace(/\.?$/,".")} No signed payment came back before the link expired. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run the command to get a fresh confirmation link; raising --bridge-timeout will not help, as the link cannot outlive the broker's op TTL.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function ll(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the transfer status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function vr(e,n){return!(e instanceof s)||!ar(e.code)?null:e.code==="wallet.bridge_timeout"?al(e,n):e.code==="wallet.bridge_op_expired"?sl(e,n):ll(e,n)}function xr(e,n){let t=e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:null;return{...t?{broker_code:t.broker_code}:{},...n}}function gt(e,n,t,i){let r=t instanceof Error?t.message:String(t),o=e==="record"?`Your payment was sent on-chain (tx ${n}) but the CLI could not record the transaction with AllScale: ${r}. The transfer is final \u2014 give this transaction hash to support so they can reconcile the invoice; do NOT pay again.`:`Your payment was sent on-chain (tx ${n}) AND recorded, but confirming it failed: ${r}. The transfer is final and the transaction is on file \u2014 the invoice's status flip may be delayed; give this hash to support if it doesn't clear, but do NOT pay again.`;return new s("backend.internal",o,i)}var Pr="/api/v1/secure/web3/gas-estimates";function Br(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return n}return null}function cl(e,n){if(!e)return null;let t=Br(e.estimatedFeeUsdt),i=e.platformFeeUsdt,r=i==null?0:Br(i)??NaN,o=Number(n);if(t==null||!Number.isFinite(r)||!Number.isFinite(o))return null;let a=Math.round((o+t+r)*1e8)/1e8;return{networkFee:t,serviceFee:r,totalDeduction:a}}function Ur(e){return e.toFixed(6).replace(/\.?0+$/,"")||"0"}function dl(e,n,t){let i=Q(n),r=t.networkFee+t.serviceFee;return`Invoice amount: ${e} ${i}
63
+ `,{mode:384});try{V.chmodSync(n,384)}catch{}}catch{}return t}function Nr(e){return H(e,{pathHint:"/api/v1/public/businesses/payments"})}var Er=3e4;function rl(e){if(typeof e=="string"&&e.length>0)return e;if(Array.isArray(e)){let n=e.filter(t=>t!=null&&t!==!1&&t!==0).map(t=>typeof t=="string"?t:JSON.stringify(t)).filter(t=>typeof t=="string"&&t.length>0&&t!=="null"&&t!=="{}"&&t!=="[]");return n.length>0?n.join("; "):void 0}if(e!==null&&typeof e=="object"){let n=JSON.stringify(e);if(n!=="{}")return n}}function ol(e,n){if(e==null)return;let t=typeof e.code=="number"?e.code:0,i=rl(e.errors),r=(()=>{let p=e.error;if(p==null||p===!1||p===0||p==="")return;if(typeof p=="string")return p;if(typeof p!="object")return"backend flagged an unspecified error";let f=JSON.stringify(p);return f&&f!=="{}"&&f!=="[]"&&f!=="null"?f:void 0})(),o=i??r??(typeof e.message=="string"&&e.message.length>0?e.message:void 0),a=i??r,l=typeof e.code!="number"&&e.code!=="0"&&!!e.code,u=(e.code==null||e.code===""||e.code==="0"||e.code===0||e.code===!1)&&!!a;if(t!==0||l||u){let p=o??`${n} returned code ${String(e.code??t)}`;throw new s("backend.internal",p,{broker_code:e.code})}return e.data}async function _t(e,n,t,i,r){let o=r??H(e,{pathHint:n}),a=new AbortController,l=!1,c=setTimeout(()=>{l=!0,a.abort()},Er);try{let u=await o.request({method:"POST",path:n,body:t,signal:a.signal});return ol(u,i)}catch(u){throw l&&u instanceof s&&u.code==="transport.network"?new s("backend.internal",`${i} timed out after ${Er/1e3}s with no response from the backend.`):u}finally{clearTimeout(c)}}function Cr(e){let n=e.sender_email?.trim();return{sender_fingerprint:e.sender_fingerprint,...n?{sender_email:n}:{}}}async function Or(e,n,t,i){let r=await _t(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents`,Cr(t),"ensurePayIntent",i);if(!r)throw new s("backend.internal","ensurePayIntent: server returned success but no payment data.");if(!r.pay_intent)throw new s("input.invalid","This invoice has no crypto pay-intent \u2014 it may already be paid/processing, overdue, or a fiat-currency invoice that can't be paid from the CLI.",{status:r.status});let o=typeof r.pay_intent.id=="string"?r.pay_intent.id.trim():"";if(!o)throw new s("backend.internal","ensurePayIntent: server returned a pay_intent with no usable id \u2014 unexpected server response.");return{...r.pay_intent,id:o}}async function Rr(e,n,t){await _t(e,"/api/v1/public/businesses/transactions",{payment_id:n.payment_id,tx_hash:n.tx_hash,tx_block_chain:n.tx_block_chain,dest_stable_coin:n.dest_stable_coin,tx_from:n.tx_from,sender_fingerprint:n.sender_fingerprint,is_allscale_pay:!0},"reportTransaction",t)}async function Ir(e,n,t,i,r){await _t(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents/${encodeURIComponent(t)}:confirm`,Cr(i),"confirmPayIntent",r)}function al(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${Ln}\` to refresh the session, then retry.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function sl(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_op_expired",`${e.message.replace(/\.?$/,".")} No signed payment came back before the link expired. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run the command to get a fresh confirmation link; raising --bridge-timeout will not help, as the link cannot outlive the broker's op TTL.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function ll(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the transfer status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function vr(e,n){return!(e instanceof s)||!ar(e.code)?null:e.code==="wallet.bridge_timeout"?al(e,n):e.code==="wallet.bridge_op_expired"?sl(e,n):ll(e,n)}function xr(e,n){let t=e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:null;return{...t?{broker_code:t.broker_code}:{},...n}}function kt(e,n,t,i){let r=t instanceof Error?t.message:String(t),o=e==="record"?`Your payment was sent on-chain (tx ${n}) but the CLI could not record the transaction with AllScale: ${r}. The transfer is final \u2014 give this transaction hash to support so they can reconcile the invoice; do NOT pay again.`:`Your payment was sent on-chain (tx ${n}) AND recorded, but confirming it failed: ${r}. The transfer is final and the transaction is on file \u2014 the invoice's status flip may be delayed; give this hash to support if it doesn't clear, but do NOT pay again.`;return new s("backend.internal",o,i)}var Pr="/api/v1/secure/web3/gas-estimates";function Br(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return n}return null}function cl(e,n){if(!e)return null;let t=Br(e.estimatedFeeUsdt),i=e.platformFeeUsdt,r=i==null?0:Br(i)??NaN,o=Number(n);if(t==null||!Number.isFinite(r)||!Number.isFinite(o))return null;let a=Math.round((o+t+r)*1e8)/1e8;return{networkFee:t,serviceFee:r,totalDeduction:a}}function Ur(e){return e.toFixed(6).replace(/\.?0+$/,"")||"0"}function dl(e,n,t){let i=Q(n),r=t.networkFee+t.serviceFee;return`Invoice amount: ${e} ${i}
64
64
  Estimated fees (gas + service): ${Ur(r)} ${i}
65
65
  Estimated total deduction from your wallet: ${Ur(t.totalDeduction)} ${i}
66
66
  `}var Dr=`Fee estimate unavailable \u2014 gas + AllScale service fees will still be charged on top of the invoice amount (as a separate SERVICE_FEE transaction under the same tx hash).
67
- `;async function $r(e,n,t){try{let r=await H(e,{pathHint:Pr}).request({method:"POST",path:Pr,responseKind:"query",body:{from_address:n.fromAddress,to_address:n.toAddress,chain:n.chain,amount:n.amount}}),o=cl(r?.data?.medium,n.amount);if(!o){t(Dr);return}t(dl(n.amount,n.stableCoin,o))}catch{t(Dr)}}function ul(e){if(e==null)return null;let n=typeof e=="string"?Number(e):e;return Number.isFinite(n)?n===0?null:n===1?1:n===2?2:"unsupported":"unsupported"}function Gr(e){let{paymentType:n,requestedCoin:t,requestedSlug:i,paymentId:r}=e,o=typeof n=="string"&&n.trim()==="";if(n!=null&&!o&&Number(n)===0)throw new s("input.invalid",`Invoice '${r}' is a fiat currency invoice (payment_type 0) and cannot be paid with crypto from the CLI.`);let a=ul(n);if(a==="unsupported")throw new s("input.invalid",`Invoice '${r}' must be paid in a stablecoin the CLI can't send (payment_type ${n}; only USDT and USDC are supported) \u2014 pay it from the web app.`);if(a!==null&&t!==null&&t!==a)throw new s("input.invalid",`This invoice must be paid in ${Q(a)}, but --stable-coin ${i} was requested. Re-run without --stable-coin to use the invoice's coin.`);if(a===null&&t===null)throw new s("input.invalid","This invoice pins no stablecoin (no payment_type). Pass --stable-coin USDT or --stable-coin USDC to choose which token to send.");return{stableCoin:a??t,autoSelected:a!==null&&t===null}}function pl(e){return ai(e)}function kt(e,n){let t=e.filter(r=>r.chain===n);if(t.length!==1)return null;let i=t[0].address;return!i||!oi(i)||pl(i)?null:i}function qr(e,n){let t=[...new Set(n.map(i=>i.chain))];if(t.length===0)throw new s("input.invalid","This invoice exposes no receiving wallet to pay to.");if(e){let i=ii(e);if(i===null)throw new s("input.invalid",`--chain '${e}' is not supported.`);if(!t.includes(i))throw new s("input.invalid",`The invoice has no receiving wallet on ${M(i)}. Available: ${t.map(r=>M(r)).join(", ")}.`);return i}if(t.length===1)return t[0];throw new s("input.invalid",`This invoice can be paid on multiple chains (${t.map(i=>M(i)).join(", ")}). Pass --chain to choose one.`)}var _t=128,mn=String(Number.MAX_SAFE_INTEGER),fl=/^(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function ml(e){if(e.length===0)return{kind:"invalid"};if(e.length>_t)return{kind:"normalization_limit"};let n=fl.exec(e);if(!n)return{kind:"invalid"};let t=n[1],i=n[2]??"",r=t+i,o=r.search(/[1-9]/);if(o===-1)return{kind:"invalid"};let a=BigInt(n[3]??"0"),c=r.slice(o),l=BigInt(t.length)+a-BigInt(o),d=BigInt(c.length);if((l<=0n?2n-l+d:l>=d?l:d+1n)>BigInt(_t))return{kind:"normalization_limit"};if(l<=0n)return{kind:"ok",amount:`0.${"0".repeat(Number(-l))}${c}`};if(l>=d)return{kind:"ok",amount:`${c}${"0".repeat(Number(l-d))}`};let f=Number(l);return{kind:"ok",amount:`${c.slice(0,f)}.${c.slice(f)}`}}function yl(e){let[n,t=""]=e.split(".");return n.length!==mn.length?n.length>mn.length:n!==mn?n>mn:/[1-9]/.test(t)}function St(e){let n=e==null?"":typeof e=="number"?String(e):e,t=ml(n);if(t.kind==="normalization_limit")throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} cannot safely normalize within the ${_t}-character amount limit.`);if(t.kind==="invalid")throw new s("input.invalid",`The invoice has no positive payable amount (got ${JSON.stringify(e)}).`);if(yl(t.amount))throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} is too large to represent exactly.`);return t.amount}function jr(e){try{return St(e)}catch(n){throw new s("backend.internal",`The pay-intent returned a non-positive or unverifiable settle amount (got ${JSON.stringify(e)}). Refusing to pay.`,{intent_amount:e,reason:n instanceof Error?n.message:String(n)})}}var Fr=6,hl=1000000n,gl=10098n;function Mr(e){if(e.length===0||e.length>128||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let[n,t=""]=e.split(".");return t.length>Fr?null:BigInt(n)*hl+BigInt(t.padEnd(Fr,"0"))}function Kr(e,n){let t=Mr(e),i=Mr(n),r=t===null||i===null?null:i-t;if(t===null||t<=0n||i===null||i<=0n||r===null||r<0n||r>gl)throw new s("backend.internal",`Pay-intent amount (${n}) is outside the backend's expected settlement range for invoice amount (${e}). Refusing to open the bridge.`,{intent_amount:n,invoice_amount:e})}var Hr=require("crypto");function Jr(e,n){return`cli-invoice-pay-${(0,Hr.createHash)("sha256").update("allscale-cli:invoice-pay:v1\0","utf8").update(e,"utf8").update("\0","utf8").update(n,"utf8").digest("hex")}`}var yn=class e extends Re{static description="Pay an invoice where you are the payer, from your AllScale wallet. Use `allscale invoice sent` to list the invoices you owe (add --status SENT --status ACKNOWLEDGED --status FAILED for the ones you can start paying). An OVERDUE invoice cannot start a new payment: if an earlier attempt of yours may still be in flight, reconcile that first \u2014 otherwise ask the issuer to extend its due date, which revives it. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (the transfer is confirmed in the browser), then reports and confirms the payment. Needs TWO scopes: `invoice:all` to create, report and confirm the pay intent, and `wallet:all` to register the withdrawal \u2014 the same broker op `wallet send` uses (backend gates the op, not the verb); it also covers the payer-address lookup, since `:all` implies `:read_only`. Neither login flow adds these scopes for you. A bare `device-login` starts every category OFF: request BOTH --scopes invoice:all --scopes wallet:all to preselect them, or turn on both Allow-changes switches on the approval screen. On `otp-login`, pass the same two --scopes values because it requests only explicitly supplied scopes, has no implicit scope defaults, and the final grants are clipped to your account's role.";static examples=["$ allscale invoice pay 65ab1234567890abcdef0123","$ allscale invoice pay 65ab1234567890abcdef0123 --chain bsc --stable-coin USDT"];static args={id:Yr.Args.string({description:"Invoice id to pay, as listed by `invoice sent`.",required:!0})};static flags={"business-id":Y.Flags.string({char:"b",description:"Your own business id. Optional and redundant \u2014 payment always comes from the wallet of the business you are signed in as. Supplying a different business id is rejected rather than silently paying from your own wallet; omit the flag unless a script needs to assert which business it is acting as."}),chain:Y.Flags.string({description:"Chain to pay on. Optional when the invoice lists a single receiving wallet; required when it lists several.",options:[...ti]}),"stable-coin":Y.Flags.string({description:"Stablecoin to pay with. Defaults to the invoice's own currency (from its payment_type); only needed to disambiguate an invoice that doesn't pin one. A value that conflicts with the invoice is rejected.",options:[...ze]}),"browser-base":Y.Flags.string({description:"Override the base URL of the /cli confirmation link (defaults to the session API base)."}),"bridge-timeout":Y.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life (~5 min). The browser only returns after the on-chain receipt confirms (it may poll for up to ~2 min after signing), so a shortened deadline must budget for the signing ceremony PLUS that receipt wait. Capped by the broker op TTL: a larger value is clamped, because the confirmation link cannot outlive its broker op. If no usable server-relative TTL is available, a withdraw waits up to 240s and may be shortened by the best-effort bound from the stated expiry.",min:1e3}),...Re.baseFlags};async runCommand(){let{args:n,flags:t}=await this.parse(e),i=this.resolveContext(t);await Ni(i,t["business-id"]);let r=n.id.trim();if(!r)throw new s("input.invalid","Invoice id cannot be blank.");let o=t["stable-coin"],a=o?ri(o):null;if(o&&a===null)throw new s("input.invalid",`--stable-coin '${o}' is not supported (USDT or USDC).`);let c=await ft(i,"query","payment",{id_str:r},{selection:"id encrypted_id amount_coins payment_type wallets { chain address }"}),l=(c?.wallets??[]).filter(k=>!!k&&typeof k.chain=="number"&&k.chain in We&&typeof k.address=="string"&&k.address.length>0);if(l.length===0)throw new s("input.invalid",c==null?`Invoice '${r}' was not found. Check the id and try again.`:"This invoice exposes no receiving wallet the CLI can pay to \u2014 it may be a fiat invoice, a non-EVM invoice, or not yet payable.");let{stableCoin:d,autoSelected:p}=Gr({paymentType:c?.payment_type,requestedCoin:a,requestedSlug:o,paymentId:r});p&&wt.stderr.write(`Paying in ${Q(d)} (the invoice's currency).
68
- `);let f=qr(t.chain,l);if(l.filter(k=>k.chain===f).length>1)throw new s("input.invalid",`This invoice has multiple receiving addresses on ${M(f)} \u2014 it's ambiguous which to pay. Contact support to resolve the duplicate wallet entries.`);let y=kt(l,f);if(!y)throw new s("input.invalid",`The invoice has no valid receiving address on ${M(f)}.`);let m=St(c?.amount_coins),g=typeof c?.encrypted_id=="string"?c.encrypted_id.trim():"";if(!g)throw new s("backend.internal","The invoice response did not include its public payment identifier; refusing to call the public payment endpoint with the internal id.");let _=await this.resolvePayerAddress(i,f);if(_.toLowerCase()===y.toLowerCase())throw new s("input.invalid","The invoice destination is your own wallet address; refusing a self-transfer.");let E=Lr(),I=Nr(i),S=await Or(i,g,{sender_fingerprint:E},I),B=S.amount_coins!=null?jr(S.amount_coins):m;S.amount_coins!=null&&Kr(m,B);let C=typeof c?.id=="string"?c.id.trim():"";if(!C)throw new s("backend.internal","The invoice response did not include its canonical payment id; refusing to derive an idempotency key from the command-line argument.");let O=Jr(C,S.id);await $r(i,{chain:f,fromAddress:_,toAddress:y,amount:B,stableCoin:d},k=>wt.stderr.write(k));let se=await kr({ctx:i,op:"withdraw_token",mode:"data",payload:{chain:f,to_address:y,amount:B,stable_coin:d,idempotency_key:O},timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1}).catch(k=>{throw vr(k,{payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:O})??k}),D=se.result_data??{},R=Ar(D);if(R&&R.outcome!=="confirmed"){let k={outcome:R.outcome,error_code:R.errorCode,transaction_hash:R.transactionHash,chain:f,explorer_url:Xe(f,R.transactionHash)||void 0,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:se.idempotency_key??O};if(R.outcome==="failed")throw new s("wallet.transaction_reverted",`The transaction was broadcast (tx ${R.transactionHash}) but reverted on-chain, so the transfer did not complete and the invoice was not paid. Inspect the transaction and correct the cause before submitting another payment; do not retry this command automatically.`,k);let hn=R.errorCode==="receipt_confirmation_timeout"?"receipt confirmation timed out":"the receipt confirmation provider was unavailable";throw new s("wallet.transaction_status_unknown",`The transaction was broadcast (tx ${R.transactionHash}), but its on-chain status is unknown because ${hn}. Do not retry this payment blindly; inspect the transaction hash and the invoice status before deciding whether another submission is needed.`,k)}if(!R)throw new s("wallet.bridge_invalid_response","Browser returned an unconfirmed or invalid withdrawal result. A transaction hash alone does not prove receipt confirmation. Check your wallet/the invoice status BEFORE retrying: if a transfer shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice.",{raw_tx_hash:typeof D.transaction_hash=="string"&&oe.test(D.transaction_hash)?D.transaction_hash:typeof D.tx_hash=="string"?D.tx_hash.slice(0,66):typeof D.transaction_hash=="string"?D.transaction_hash.slice(0,66):null,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:se.idempotency_key??O});let G=R.transactionHash,Ue=k=>xr(k,{tx_hash:G,tx_from:_,payment_id:r,pay_intent_id:S.id,idempotency_key:O,explorer_url:Xe(f,G)||null});try{await Rr(i,{payment_id:r,tx_hash:G,tx_block_chain:f,dest_stable_coin:d,tx_from:_,sender_fingerprint:E},I)}catch(k){throw gt("record",G,k,Ue(k))}try{await Ir(i,r,S.id,{sender_fingerprint:E},I)}catch(k){throw gt("confirm",G,k,Ue(k))}return{payment_id:r,pay_intent_id:S.id,tx_hash:G,chain:f,chain_name:M(f),amount:B,stable_coin:d,stable_coin_name:Q(d),explorer_url:Xe(f,G)||null,idempotency_key:O,status_optimistic:!0,status:"processing"}}async resolvePayerAddress(n,t){let r=(await ft(n,"query","business_wallets",{},{selection:"chain address"})??[]).filter(a=>!!a&&typeof a.chain=="number"&&a.chain in We&&typeof a.address=="string"&&a.address.length>0);if(r.filter(a=>a.chain===t).length>1)throw new s("input.invalid",`Your AllScale wallet has multiple addresses on ${M(t)} \u2014 can't auto-select which to pay from. Contact support.`);let o=kt(r,t);if(!o)throw new s("input.invalid",`Your AllScale wallet has no valid address on ${M(t)} to pay from.`);return o}};
67
+ `;async function $r(e,n,t){try{let r=await H(e,{pathHint:Pr}).request({method:"POST",path:Pr,responseKind:"query",body:{from_address:n.fromAddress,to_address:n.toAddress,chain:n.chain,amount:n.amount}}),o=cl(r?.data?.medium,n.amount);if(!o){t(Dr);return}t(dl(n.amount,n.stableCoin,o))}catch{t(Dr)}}function ul(e){if(e==null)return null;let n=typeof e=="string"?Number(e):e;return Number.isFinite(n)?n===0?null:n===1?1:n===2?2:"unsupported":"unsupported"}function Gr(e){let{paymentType:n,requestedCoin:t,requestedSlug:i,paymentId:r}=e,o=typeof n=="string"&&n.trim()==="";if(n!=null&&!o&&Number(n)===0)throw new s("input.invalid",`Invoice '${r}' is a fiat currency invoice (payment_type 0) and cannot be paid with crypto from the CLI.`);let a=ul(n);if(a==="unsupported")throw new s("input.invalid",`Invoice '${r}' must be paid in a stablecoin the CLI can't send (payment_type ${n}; only USDT and USDC are supported) \u2014 pay it from the web app.`);if(a!==null&&t!==null&&t!==a)throw new s("input.invalid",`This invoice must be paid in ${Q(a)}, but --stable-coin ${i} was requested. Re-run without --stable-coin to use the invoice's coin.`);if(a===null&&t===null)throw new s("input.invalid","This invoice pins no stablecoin (no payment_type). Pass --stable-coin USDT or --stable-coin USDC to choose which token to send.");return{stableCoin:a??t,autoSelected:a!==null&&t===null}}function pl(e){return li(e)}function wt(e,n){let t=e.filter(r=>r.chain===n);if(t.length!==1)return null;let i=t[0].address;return!i||!si(i)||pl(i)?null:i}function qr(e,n){let t=[...new Set(n.map(i=>i.chain))];if(t.length===0)throw new s("input.invalid","This invoice exposes no receiving wallet to pay to.");if(e){let i=oi(e);if(i===null)throw new s("input.invalid",`--chain '${e}' is not supported.`);if(!t.includes(i))throw new s("input.invalid",`The invoice has no receiving wallet on ${M(i)}. Available: ${t.map(r=>M(r)).join(", ")}.`);return i}if(t.length===1)return t[0];throw new s("input.invalid",`This invoice can be paid on multiple chains (${t.map(i=>M(i)).join(", ")}). Pass --chain to choose one.`)}var St=128,yn=String(Number.MAX_SAFE_INTEGER),fl=/^(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function ml(e){if(e.length===0)return{kind:"invalid"};if(e.length>St)return{kind:"normalization_limit"};let n=fl.exec(e);if(!n)return{kind:"invalid"};let t=n[1],i=n[2]??"",r=t+i,o=r.search(/[1-9]/);if(o===-1)return{kind:"invalid"};let a=BigInt(n[3]??"0"),l=r.slice(o),c=BigInt(t.length)+a-BigInt(o),u=BigInt(l.length);if((c<=0n?2n-c+u:c>=u?c:u+1n)>BigInt(St))return{kind:"normalization_limit"};if(c<=0n)return{kind:"ok",amount:`0.${"0".repeat(Number(-c))}${l}`};if(c>=u)return{kind:"ok",amount:`${l}${"0".repeat(Number(c-u))}`};let f=Number(c);return{kind:"ok",amount:`${l.slice(0,f)}.${l.slice(f)}`}}function yl(e){let[n,t=""]=e.split(".");return n.length!==yn.length?n.length>yn.length:n!==yn?n>yn:/[1-9]/.test(t)}function At(e){let n=e==null?"":typeof e=="number"?String(e):e,t=ml(n);if(t.kind==="normalization_limit")throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} cannot safely normalize within the ${St}-character amount limit.`);if(t.kind==="invalid")throw new s("input.invalid",`The invoice has no positive payable amount (got ${JSON.stringify(e)}).`);if(yl(t.amount))throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} is too large to represent exactly.`);return t.amount}function jr(e){try{return At(e)}catch(n){throw new s("backend.internal",`The pay-intent returned a non-positive or unverifiable settle amount (got ${JSON.stringify(e)}). Refusing to pay.`,{intent_amount:e,reason:n instanceof Error?n.message:String(n)})}}var Fr=6,hl=1000000n,gl=10098n;function Mr(e){if(e.length===0||e.length>128||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let[n,t=""]=e.split(".");return t.length>Fr?null:BigInt(n)*hl+BigInt(t.padEnd(Fr,"0"))}function Kr(e,n){let t=Mr(e),i=Mr(n),r=t===null||i===null?null:i-t;if(t===null||t<=0n||i===null||i<=0n||r===null||r<0n||r>gl)throw new s("backend.internal",`Pay-intent amount (${n}) is outside the backend's expected settlement range for invoice amount (${e}). Refusing to open the bridge.`,{intent_amount:n,invoice_amount:e})}var Hr=require("crypto");function Jr(e,n){return`cli-invoice-pay-${(0,Hr.createHash)("sha256").update("allscale-cli:invoice-pay:v1\0","utf8").update(e,"utf8").update("\0","utf8").update(n,"utf8").digest("hex")}`}var hn=class e extends Re{static description="Pay an invoice where you are the payer, from your AllScale wallet. Use `allscale invoice sent` to list the invoices you owe (add --status SENT --status ACKNOWLEDGED --status FAILED for the ones you can start paying). An OVERDUE invoice cannot start a new payment: if an earlier attempt of yours may still be in flight, reconcile that first \u2014 otherwise ask the issuer to extend its due date, which revives it. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (the transfer is confirmed in the browser), then reports and confirms the payment. Needs TWO scopes: `invoice:all` to create, report and confirm the pay intent, and `wallet:all` to register the withdrawal \u2014 the same broker op `wallet send` uses (backend gates the op, not the verb); it also covers the payer-address lookup, since `:all` implies `:read_only`. Neither login flow adds these scopes for you. A bare `device-login` starts every category OFF: request BOTH --scopes invoice:all --scopes wallet:all to preselect them, or turn on both Allow-changes switches on the approval screen. On `otp-login`, pass the same two --scopes values because it requests only explicitly supplied scopes, has no implicit scope defaults, and the final grants are clipped to your account's role.";static examples=["$ allscale invoice pay 65ab1234567890abcdef0123","$ allscale invoice pay 65ab1234567890abcdef0123 --chain bsc --stable-coin USDT"];static args={id:Yr.Args.string({description:"Invoice id to pay, as listed by `invoice sent`.",required:!0})};static flags={"business-id":Y.Flags.string({char:"b",description:"Your own business id. Optional and redundant \u2014 payment always comes from the wallet of the business you are signed in as. Supplying a different business id is rejected rather than silently paying from your own wallet; omit the flag unless a script needs to assert which business it is acting as."}),chain:Y.Flags.string({description:"Chain to pay on. Optional when the invoice lists a single receiving wallet; required when it lists several.",options:[...ri]}),"stable-coin":Y.Flags.string({description:"Stablecoin to pay with. Defaults to the invoice's own currency (from its payment_type); only needed to disambiguate an invoice that doesn't pin one. A value that conflicts with the invoice is rejected.",options:[...ze]}),"browser-base":Y.Flags.string({description:"Override the base URL of the /cli confirmation link (defaults to the session API base)."}),"bridge-timeout":Y.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life (~5 min). The browser only returns after the on-chain receipt confirms (it may poll for up to ~2 min after signing), so a shortened deadline must budget for the signing ceremony PLUS that receipt wait. Capped by the broker op TTL: a larger value is clamped, because the confirmation link cannot outlive its broker op. If no usable server-relative TTL is available, a withdraw waits up to 240s and may be shortened by the best-effort bound from the stated expiry.",min:1e3}),...Re.baseFlags};async runCommand(){let{args:n,flags:t}=await this.parse(e),i=this.resolveContext(t);await Oi(i,t["business-id"]);let r=n.id.trim();if(!r)throw new s("input.invalid","Invoice id cannot be blank.");let o=t["stable-coin"],a=o?ai(o):null;if(o&&a===null)throw new s("input.invalid",`--stable-coin '${o}' is not supported (USDT or USDC).`);let l=await yt(i,"query","payment",{id_str:r},{selection:"id encrypted_id amount_coins payment_type wallets { chain address }"}),c=(l?.wallets??[]).filter(k=>!!k&&typeof k.chain=="number"&&k.chain in We&&typeof k.address=="string"&&k.address.length>0);if(c.length===0)throw new s("input.invalid",l==null?`Invoice '${r}' was not found. Check the id and try again.`:"This invoice exposes no receiving wallet the CLI can pay to \u2014 it may be a fiat invoice, a non-EVM invoice, or not yet payable.");let{stableCoin:u,autoSelected:p}=Gr({paymentType:l?.payment_type,requestedCoin:a,requestedSlug:o,paymentId:r});p&&bt.stderr.write(`Paying in ${Q(u)} (the invoice's currency).
68
+ `);let f=qr(t.chain,c);if(c.filter(k=>k.chain===f).length>1)throw new s("input.invalid",`This invoice has multiple receiving addresses on ${M(f)} \u2014 it's ambiguous which to pay. Contact support to resolve the duplicate wallet entries.`);let y=wt(c,f);if(!y)throw new s("input.invalid",`The invoice has no valid receiving address on ${M(f)}.`);let m=At(l?.amount_coins),g=typeof l?.encrypted_id=="string"?l.encrypted_id.trim():"";if(!g)throw new s("backend.internal","The invoice response did not include its public payment identifier; refusing to call the public payment endpoint with the internal id.");let _=await this.resolvePayerAddress(i,f);if(_.toLowerCase()===y.toLowerCase())throw new s("input.invalid","The invoice destination is your own wallet address; refusing a self-transfer.");let E=Lr(),I=Nr(i),S=await Or(i,g,{sender_fingerprint:E},I),B=S.amount_coins!=null?jr(S.amount_coins):m;S.amount_coins!=null&&Kr(m,B);let C=typeof l?.id=="string"?l.id.trim():"";if(!C)throw new s("backend.internal","The invoice response did not include its canonical payment id; refusing to derive an idempotency key from the command-line argument.");let O=Jr(C,S.id);await $r(i,{chain:f,fromAddress:_,toAddress:y,amount:B,stableCoin:u},k=>bt.stderr.write(k));let se=await kr({ctx:i,op:"withdraw_token",mode:"data",payload:{chain:f,to_address:y,amount:B,stable_coin:u,idempotency_key:O},timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1}).catch(k=>{throw vr(k,{payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:O})??k}),D=se.result_data??{},R=Ar(D);if(R&&R.outcome!=="confirmed"){let k={outcome:R.outcome,error_code:R.errorCode,transaction_hash:R.transactionHash,chain:f,explorer_url:Xe(f,R.transactionHash)||void 0,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:se.idempotency_key??O};if(R.outcome==="failed")throw new s("wallet.transaction_reverted",`The transaction was broadcast (tx ${R.transactionHash}) but reverted on-chain, so the transfer did not complete and the invoice was not paid. Inspect the transaction and correct the cause before submitting another payment; do not retry this command automatically.`,k);let gn=R.errorCode==="receipt_confirmation_timeout"?"receipt confirmation timed out":"the receipt confirmation provider was unavailable";throw new s("wallet.transaction_status_unknown",`The transaction was broadcast (tx ${R.transactionHash}), but its on-chain status is unknown because ${gn}. Do not retry this payment blindly; inspect the transaction hash and the invoice status before deciding whether another submission is needed.`,k)}if(!R)throw new s("wallet.bridge_invalid_response","Browser returned an unconfirmed or invalid withdrawal result. A transaction hash alone does not prove receipt confirmation. Check your wallet/the invoice status BEFORE retrying: if a transfer shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice.",{raw_tx_hash:typeof D.transaction_hash=="string"&&oe.test(D.transaction_hash)?D.transaction_hash:typeof D.tx_hash=="string"?D.tx_hash.slice(0,66):typeof D.transaction_hash=="string"?D.transaction_hash.slice(0,66):null,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:se.idempotency_key??O});let G=R.transactionHash,Ue=k=>xr(k,{tx_hash:G,tx_from:_,payment_id:r,pay_intent_id:S.id,idempotency_key:O,explorer_url:Xe(f,G)||null});try{await Rr(i,{payment_id:r,tx_hash:G,tx_block_chain:f,dest_stable_coin:u,tx_from:_,sender_fingerprint:E},I)}catch(k){throw kt("record",G,k,Ue(k))}try{await Ir(i,r,S.id,{sender_fingerprint:E},I)}catch(k){throw kt("confirm",G,k,Ue(k))}return{payment_id:r,pay_intent_id:S.id,tx_hash:G,chain:f,chain_name:M(f),amount:B,stable_coin:u,stable_coin_name:Q(u),explorer_url:Xe(f,G)||null,idempotency_key:O,status_optimistic:!0,status:"processing"}}async resolvePayerAddress(n,t){let r=(await yt(n,"query","business_wallets",{},{selection:"chain address"})??[]).filter(a=>!!a&&typeof a.chain=="number"&&a.chain in We&&typeof a.address=="string"&&a.address.length>0);if(r.filter(a=>a.chain===t).length>1)throw new s("input.invalid",`Your AllScale wallet has multiple addresses on ${M(t)} \u2014 can't auto-select which to pay from. Contact support.`);let o=wt(r,t);if(!o)throw new s("input.invalid",`Your AllScale wallet has no valid address on ${M(t)} to pay from.`);return o}};
69
69
  //# sourceMappingURL=pay.js.map