@allscale/cli 1.0.2 → 1.0.3

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,48 +1,48 @@
1
- "use strict";var bi=Object.create;var Re=Object.defineProperty;var ki=Object.getOwnPropertyDescriptor;var Si=Object.getOwnPropertyNames;var Ei=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var Li=(e,t)=>{for(var n in t)Re(e,n,{get:t[n],enumerable:!0})},an=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Si(t))!Ai.call(e,i)&&i!==n&&Re(e,i,{get:()=>t[i],enumerable:!(r=ki(t,i))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?bi(Ei(e)):{},an(t||!e||!e.__esModule?Re(n,"default",{value:e,enumerable:!0}):n,e)),Ti=e=>an(Re({},"__esModule",{value:!0}),e);var nl={};Li(nl,{default:()=>nt});module.exports=Ti(nl);var $=require("@oclif/core");var ln="public",cn="https://app.allscale.io";var un=["https://app.allscale.io"];var pe=[];var ot="Override the API base URL (public builds accept only https://app.allscale.io)";var fe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function dn(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function pn(e){return dn(e)!==null}function ee(e){let t=dn(e);return t!==null&&un.includes(t.origin)}function st(e){return ee(e)}function me(){return"".trim()||void 0}function te(){return"public"}function K(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function lt(e){try{return new URL(e).origin}catch{return null}}function ge(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return at()}function at(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Ii="device-login",Ci=/^[A-Za-z0-9._-]{1,64}$/;function dt(e){return Ci.test(e)?e:"<profile>"}function he(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":dt(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ve(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function mn(e){let t=dt(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${he(e)}\` for headless automation.`}function gn(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Ii} --profile ${dt(e)}\`.`}var Oi={"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},Ri=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 pt(e){return(typeof e=="string"?e:String(e??"")).replace(Ri,"")}var vi=64;function ct(e,t=new Map,n=0){if(typeof e=="string")return pt(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=vi)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ct(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ct(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(pt(n)),this.code=t,this.details=r&&ct(r),this.name="AllscaleError"}get exitCode(){return Oi[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function hn(e){if(e instanceof a)return e;if(e instanceof Error){if(Pi(e)){let t=Di(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var Ni=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),xi=[/^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 Pi(e){if(Bi(e))return!0;let t=e.name??"";return Ni.has(t)?t==="CLIError"?ut(e,"parse")||fn(e.message):!0:fn(e.message)}function Bi(e){if(!ut(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&ut(e,"parse")}function fn(e){return e?pt(e).split(`
2
- `).some(t=>xi.some(n=>n.test(t.trim()))):!1}function ut(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Di(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function _n(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var w=T(require("fs")),De=T(require("path")),An=T(require("crypto"));var $i="...<truncated>",Ui=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Fi=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,_t=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ft=String.raw`(?:proxy[_-]?)?authorization`,Mi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ft}"|'${ft}'|${ft})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${_t}`,"gi"),Gi=/\b(https?:\/\/)[^\s/?#]+@/gi,Ki=String.raw`(?:[A-Za-z0-9]+[_-])*`,Hi=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,yn=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)`,wn=yn(Ki),Yi=yn(Hi),ji=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${wn}"|'${wn}'|${Yi})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"gi"),mt=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)`,qi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mt}"|'${mt}'|${mt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"g");function Ne(e){return e.replace(Gi,"$1<redacted>@").replace(Ui,"<redacted-jwt>").replace(Mi,"$1$2$3<redacted>").replace(ji,"$1$2<redacted>").replace(qi,"$1$2<redacted>").replace(Fi,"Bearer <redacted>")}var Wi=/(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 xe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Wi.test(t)}function bn(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function Pe(e,t,n=$i){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;c+=d,l+=p}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function I(e,t=16384){return Pe(bn(Ne(e)),t)}var gt=100,Ji=8,zi=8*1024;function Be(){return{remaining:zi}}function ht(e,t){let n=Math.min(16384,t.remaining),r=Pe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function ne(e,t,n=0,r={}){if(n>Ji)return ht("<truncated>",t);if(typeof e=="string"){let i=Ne(e);return ht(r.escapeControls?bn(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,gt),o=i.map(s=>ne(s,t,n+1,r));return e.length>i.length&&o.push(ht(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,gt))i[s]=ne(c,t,n+1,r);return o.length>gt&&(i.output_truncated=!0),i}return e}var wt=require("process");var yt=!1;function bt(e){yt=e}function Sn(){return yt}var kn="1";function ie(e,t){if(yt){let n={...e};delete n.version;let r=Be(),i={event:n.event,...n},o=ne(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:kn,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:kn,event:o.event,output_truncated:!0})),wt.stderr.write(`${s}
4
- `)}else wt.stderr.write(t)}var En="2",oe=null,N=null,se=!1,_e=!1;function Xi(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=An.randomBytes(4).toString("hex");return De.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var kt=64*1024*1024,Vi=null;function St(e={}){if(e.quiet&&(_e=!0),se)return;let t=Xi();if(!t)return;oe=null;let n=null;try{if((Vi??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=De.dirname(t);if(w.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=w.statSync(r),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 i=w.constants.O_NOFOLLOW??0;n=w.openSync(t,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|i,384);let o=w.fstatSync(n),s=w.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.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(n,384)}catch(r){if(n!==null)try{w.closeSync(n)}catch{}_e||ie({event:"sidecar_disabled",reason:"open_failed",detail:I(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${I(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}oe=t,N=n,se=!0}var Zi=[/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 Qi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Zi.some(n=>n.test(t))}function Ln(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=eo(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Qi(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function eo(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function to(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ln(e.url)}:e}function no(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=ne(i,Be()),s=JSON.stringify({version:En,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:En,timestamp:t,type:r,output_truncated:!0})),s}function _(e){if(!se||!oe||N===null)return;let t=to(e),n=no(t);try{if(w.fstatSync(N).size+Buffer.byteLength(n,"utf8")+1>kt){se=!1;try{w.closeSync(N)}catch{}N=null,_e||ie({event:"sidecar_disabled",reason:"size_limit",...oe===null?{}:{path:I(oe)},max_bytes:kt},`${I(`[allscale] sidecar exceeded ${kt} bytes; disabling it for the rest of this run. Rotate or remove ${oe}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
1
+ "use strict";var ki=Object.create;var Re=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Si=Object.getOwnPropertyNames;var Ai=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Ti=(e,t)=>{for(var n in t)Re(e,n,{get:t[n],enumerable:!0})},ln=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Si(t))!Li.call(e,i)&&i!==n&&Re(e,i,{get:()=>t[i],enumerable:!(r=Ei(t,i))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?ki(Ai(e)):{},ln(t||!e||!e.__esModule?Re(n,"default",{value:e,enumerable:!0}):n,e)),Ci=e=>ln(Re({},"__esModule",{value:!0}),e);var il={};Ti(il,{default:()=>nt});module.exports=Ci(il);var $=require("@oclif/core");var cn="public",un="https://app.allscale.io";var dn=["https://app.allscale.io"];var pe=[];var ot="Override the API base URL (public builds accept only https://app.allscale.io)";var fe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function pn(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function fn(e){return pn(e)!==null}function ee(e){let t=pn(e);return t!==null&&dn.includes(t.origin)}function st(e){return ee(e)}function me(){return"".trim()||void 0}function te(){return"public"}function K(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function lt(e){try{return new URL(e).origin}catch{return null}}function he(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return at()}function at(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Ii="device-login",Oi=/^[A-Za-z0-9._-]{1,64}$/;function dt(e){return Oi.test(e)?e:"<profile>"}function ge(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":dt(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ve(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function hn(e){let t=dt(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${ge(e)}\` for headless automation.`}function gn(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Ii} --profile ${dt(e)}\`.`}var Ri={"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 vi=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 pt(e){return(typeof e=="string"?e:String(e??"")).replace(vi,"")}var Ni=64;function ct(e,t=new Map,n=0){if(typeof e=="string")return pt(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Ni)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ct(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ct(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(pt(n)),this.code=t,this.details=r&&ct(r),this.name="AllscaleError"}get exitCode(){return Ri[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function _n(e){if(e instanceof a)return e;if(e instanceof Error){if(Bi(e)){let t=$i(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var xi=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Pi=[/^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 Bi(e){if(Di(e))return!0;let t=e.name??"";return xi.has(t)?t==="CLIError"?ut(e,"parse")||mn(e.message):!0:mn(e.message)}function Di(e){if(!ut(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&ut(e,"parse")}function mn(e){return e?pt(e).split(`
2
+ `).some(t=>Pi.some(n=>n.test(t.trim()))):!1}function ut(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function $i(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function wn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var w=T(require("fs")),De=T(require("path")),Ln=T(require("crypto"));var Ui="...<truncated>",Fi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Mi=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,_t=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ft=String.raw`(?:proxy[_-]?)?authorization`,Gi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ft}"|'${ft}'|${ft})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${_t}`,"gi"),Ki=/\b(https?:\/\/)[^\s/?#]+@/gi,Hi=String.raw`(?:[A-Za-z0-9]+[_-])*`,ji=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,bn=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)`,yn=bn(Hi),Yi=bn(ji),qi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${yn}"|'${yn}'|${Yi})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"gi"),mt=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)`,Wi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mt}"|'${mt}'|${mt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"g");function Ne(e){return e.replace(Ki,"$1<redacted>@").replace(Fi,"<redacted-jwt>").replace(Gi,"$1$2$3<redacted>").replace(qi,"$1$2<redacted>").replace(Wi,"$1$2<redacted>").replace(Mi,"Bearer <redacted>")}var Ji=/(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 xe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Ji.test(t)}function kn(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function Pe(e,t,n=Ui){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;c+=d,l+=p}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function C(e,t=16384){return Pe(kn(Ne(e)),t)}var ht=100,zi=8,Xi=8*1024;function Be(){return{remaining:Xi}}function gt(e,t){let n=Math.min(16384,t.remaining),r=Pe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function ne(e,t,n=0,r={}){if(n>zi)return gt("<truncated>",t);if(typeof e=="string"){let i=Ne(e);return gt(r.escapeControls?kn(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,ht),o=i.map(s=>ne(s,t,n+1,r));return e.length>i.length&&o.push(gt(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,ht))i[s]=ne(c,t,n+1,r);return o.length>ht&&(i.output_truncated=!0),i}return e}var wt=require("process");var yt=!1;function bt(e){yt=e}function Sn(){return yt}var En="1";function ie(e,t){if(yt){let n={...e};delete n.version;let r=Be(),i={event:n.event,...n},o=ne(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:En,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:En,event:o.event,output_truncated:!0})),wt.stderr.write(`${s}
4
+ `)}else wt.stderr.write(t)}var An="2",oe=null,N=null,se=!1,_e=!1;function Vi(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Ln.randomBytes(4).toString("hex");return De.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var kt=64*1024*1024,Zi=null;function Et(e={}){if(e.quiet&&(_e=!0),se)return;let t=Vi();if(!t)return;oe=null;let n=null;try{if((Zi??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=De.dirname(t);if(w.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=w.statSync(r),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 i=w.constants.O_NOFOLLOW??0;n=w.openSync(t,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|i,384);let o=w.fstatSync(n),s=w.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.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(n,384)}catch(r){if(n!==null)try{w.closeSync(n)}catch{}_e||ie({event:"sidecar_disabled",reason:"open_failed",detail:C(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${C(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}oe=t,N=n,se=!0}var Qi=[/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 eo(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Qi.some(n=>n.test(t))}function Tn(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=to(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)eo(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function to(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function no(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Tn(e.url)}:e}function ro(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=ne(i,Be()),s=JSON.stringify({version:An,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:An,timestamp:t,type:r,output_truncated:!0})),s}function _(e){if(!se||!oe||N===null)return;let t=no(e),n=ro(t);try{if(w.fstatSync(N).size+Buffer.byteLength(n,"utf8")+1>kt){se=!1;try{w.closeSync(N)}catch{}N=null,_e||ie({event:"sidecar_disabled",reason:"size_limit",...oe===null?{}:{path:C(oe)},max_bytes:kt},`${C(`[allscale] sidecar exceeded ${kt} bytes; disabling it for the rest of this run. Rotate or remove ${oe}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
6
  `);return}w.appendFileSync(N,`${n}
7
- `)}catch(r){if(se=!1,N!==null){try{w.closeSync(N)}catch{}N=null}try{_e||ie({event:"sidecar_disabled",reason:"write_failed",detail:I(r.message)},`${I(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var M=Ln;function Tn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function we(){if(_e=!1,se=!1,N!==null){try{w.closeSync(N)}catch{}N=null}}function In(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Tn()||!t}var ye=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"]),ro=new Set(Array.from(ye).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),io=Array.from(ye).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),oo=new Set(["--otp-stdin","--password-stdin"]);function Et(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(ye.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ye.has(r)){t.push(r),n+1<e.length&&(ye.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(ro.has(o)){t.push(`${o}<redacted>`);continue}}let i=oo.has(r)?void 0:io.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function Cn(e){_({type:"error",code:e.code,message:I(e.message)}),_({type:"command-end",ok:!1,exitCode:e.exitCode}),we()}var be=me()??cn,le={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 H(e){return pn(e)?new URL(e).origin:null}function O(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function On(){let e=process.env[le.TOKEN]?.trim();return e&&e.length>0?e:void 0}function At(){let e=process.env[le.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ke(){let e=process.env[le.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Rn(){let e=process.env[le.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vn(){let e=process.env[le.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Nn(){let e=process.env[le.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function xn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(me()===void 0&&be!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
7
+ `)}catch(r){if(se=!1,N!==null){try{w.closeSync(N)}catch{}N=null}try{_e||ie({event:"sidecar_disabled",reason:"write_failed",detail:C(r.message)},`${C(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var M=Tn;function Cn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function we(){if(_e=!1,se=!1,N!==null){try{w.closeSync(N)}catch{}N=null}}function In(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Cn()||!t}var ye=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"]),io=new Set(Array.from(ye).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),oo=Array.from(ye).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),so=new Set(["--otp-stdin","--password-stdin"]);function St(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(ye.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ye.has(r)){t.push(r),n+1<e.length&&(ye.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(io.has(o)){t.push(`${o}<redacted>`);continue}}let i=so.has(r)?void 0:oo.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function On(e){_({type:"error",code:e.code,message:C(e.message)}),_({type:"command-end",ok:!1,exitCode:e.exitCode}),we()}var be=me()??un,le={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 H(e){return fn(e)?new URL(e).origin:null}function O(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Rn(){let e=process.env[le.TOKEN]?.trim();return e&&e.length>0?e:void 0}function At(){let e=process.env[le.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ke(){let e=process.env[le.API_BASE]?.trim();return e&&e.length>0?e:void 0}function vn(){let e=process.env[le.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Nn(){let e=process.env[le.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function xn(){let e=process.env[le.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Pn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(me()===void 0&&be!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
9
  The CLI default is now ${be} (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 ${be}
14
- `}var Y=T(require("fs")),Pn=T(require("os")),Lt=T(require("path")),Tt=T(require("@iarna/toml"));var lo=".allscale",co="config.toml";function It(){return Lt.join(Pn.homedir(),lo)}function uo(){return Lt.join(It(),co)}function $e(){let e=uo();if(!Y.existsSync(e))return{};let t=Y.readFileSync(e,"utf-8");try{return Tt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function Bn(e){return Object.keys(e.profile??{}).sort()}function Dn(e,t){return e.profile?.[t]}function $n(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function j(e){if(!ee(e))throw new a("input.invalid",`Refusing to send credentials to API base ${O(e)}. `+fe)}function Ue(e,t){j(e);let n=H(e),r=typeof t=="string"?H(t):null;if(n&&r===n)return;let i=typeof t=="string"?O(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${O(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Un(e,t){let n=H(e),r=H(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${O(t)} because it is outside the configured API origin ${O(e)}.`)}function Fe(e){let t=fo(e);if(t)throw new a("input.invalid",t.message)}function po(){let e=me();if(e===void 0)return;let t=ge();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function fo(e){let t=po();if(t===void 0||K(e))return;let{endpoints:n,fromPairs:r}=t,i=H(e),o=n.map(c=>H(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>O(c)).join(", ");return{message:r?`Refusing to send to ${O(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${O(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var mo=require("@noble/hashes/sha3");var go={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Fn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Me=["USDT","USDC"];function Mn(e){return go[e.toLowerCase()]??null}function Gn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var Gl=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Kn(e){return e===1?"USDT":"USDC"}var ho="unknown_otp_id",_o="invalid_code",wo="expired_code";function yo(e){return`'${e.replace(/'/g,"'\\''")}'`}function Hn(e){return`Run \`allscale otp-send --email ${yo(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var bo=new Map([[ho,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', 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. ${Hn(t)}`],[_o,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.`],[wo,(e,t,n)=>n?`${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. ${Hn(t)}`]]);var Yn=[...bo.keys()];var C=require("@oclif/core"),Se=class e extends $.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:$.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:$.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:te()==="public"}),"api-base":$.Flags.string({description:ot,helpGroup:"GLOBAL",hidden:te()==="public"}),"insecure-storage":$.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{bt(this.jsonEnabled()),St(),_({type:"session-start",command:this.id??"",argv:Et(this.argv)});let t=this.constructor;if(te()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=In(this.jsonEnabled()),r=this.argv.length===0&&!n&&Oo(t)?this.config.findCommand(this.id??""):void 0;if(r){we();let o=await(0,$.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!Nn())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return _({type:"command-end",ok:!0}),we(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||_n(i),{data:i})}catch(t){let n=hn(t);Cn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{bt(!1)}}resolveSessionApiBaseChain(t){let n=$e(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||At()!==void 0,s=$n(n,r,At()),c=Dn(n,s),l=te()==="public"&&ke()!==void 0,d=i??(l?void 0:ke()),p=d??c?.api_base??be,f=xn({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ie({event:"legacy_staging_profile",api_base:p,profile:s},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||j(n),n}resolveContext(t){if(te()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:c,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(j(i),Fe(i)),{apiBase:i,profile:c,token:n??On(),insecureStorage:r||Rn(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Co(t)}
15
- `)}};var ko=/_(removed|cleared|count|total)$/i;function So(e,t){return typeof t=="number"&&ko.test(e)}var Eo=new Set(Me);function Ao(e,t){return e==="token_symbol"&&typeof t=="string"&&Eo.has(t)}var Lo=new Set(Yn);function To(e,t){return e==="otp_reason"&&typeof t=="string"&&Lo.has(t)}var Ge=100;function Ke(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ge),r=n.map(i=>Ke(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Ge))n[i]=xe(i)&&!So(i,o)&&!Ao(i,o)&&!To(i,o)?"<redacted>":Ke(o,t+1);if(r.length>Ge){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ge} more keys`}return n}if(typeof e=="string"){let n=Io(e);return n!==void 0?I(JSON.stringify(Ke(n,t+1))):I(e)}return e}function Io(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Co(e){let t=Sn()?void 0:2,n=Ke(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:I(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Oo(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var ce=/^0x[0-9a-fA-F]{64}$/,Ro=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function jn(e){return typeof e=="string"&&Ro.includes(e)}var $r=require("crypto"),A=require("process");var ir=T(require("path"));var Rt=require("crypto"),u=T(require("fs")),S=T(require("path"));var He=1024*1024,vo=5e3,No=20,xo=3e4,Ct=4096,Po=new Int32Array(new SharedArrayBuffer(4)),Ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ye(e){return e instanceof Ee}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Bo=null;function W(){return new a("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 je(){return(Bo??process.platform)!=="win32"}function Qn(){if(!je())throw W()}function er(e){try{return u.default.lstatSync(e),!1}catch(t){if(!k(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(S.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(k(t,"ENOENT"))return!0;throw t}}function k(e,t){return typeof e=="object"&&e!==null&&e.code===t}function Ae(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function Le(e,t){return e.dev===t.dev&&e.ino===t.ino}function Do(e){Atomics.wait(Po,0,0,e)}function tr(e){try{return process.kill(e,0),!0}catch(t){return!k(t,"ESRCH")}}function $o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qn(e,t){let n=S.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&k(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=u.default.openSync(n,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(i),s=u.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Le(o,s))throw new Error("credential-store parent changed while it was being inspected");Ae(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&S.basename(n)===".allscale"&&(u.default.fchmodSync(i,448),c=u.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&u.default.closeSync(i)}return!0}function U(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=u.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&k(o,"ENOENT")?new R:o}if(!Le(n,i))throw r.retryOnPathChange?new R:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new Ee;if(Ae(n,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(t,384);let o=u.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Uo(e,t){if(t.size>He)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(He+1),r=0;for(;r<n.length;){let i=u.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>He)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Wn(e){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(i){if(k(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(k(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=U(e,t,n);return Uo(t,r)}finally{t!==null&&u.default.closeSync(t)}}function Jn(e){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(i){if(k(i,"ENOENT")&&er(e))return;throw i}let n=u.default.fstatSync(t),r=U(e,t,n);J(e,r)}finally{t!==null&&u.default.closeSync(t)}rr(S.dirname(e))}function Fo(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(k(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new Ee;Ae(t,"credential-store replacement target")}function Mo(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=S.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(k(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function nr(e,t){let n=0;for(;n<t.length;){let r=u.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function rr(e){if(process.platform==="win32")return;let t=null;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(t)}catch{}finally{if(t!==null)try{u.default.closeSync(t)}catch{}}}function Go(e,t){let n=Buffer.from(t,"utf8");if(n.length>He)throw new Error("credential-store file exceeds the maximum supported size");let r=S.dirname(e),i=S.basename(e),o=null,s=null,c=!1;try{let l=Mo(r,i);o=l.fd,s=l.tempPath;let d=u.default.fstatSync(o);if((U(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");nr(o,n),u.default.fsyncSync(o),U(s,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),Fo(e),u.default.renameSync(s,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&s!==null)try{u.default.unlinkSync(s)}catch{}}rr(r)}function Ko(e){return S.join(S.dirname(e),`.${S.basename(e)}.lock`)}function Ho(e){return S.join(S.dirname(e),`.${S.basename(e)}.lock-recovery`)}function Yo(e,t){if(t.size>Ct)return null;let n=Buffer.alloc(Ct+1),r=0;for(;r<n.length;){let o=u.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ct)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function J(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!Le(n,t))throw new Error("credential-store lock changed while it was being inspected");Ae(n,"credential-store lock"),u.default.unlinkSync(e)}function zn(e,t){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(l){if(k(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 R}catch(d){if(k(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Yo(n,i);return{state:(o?.target===t&&o?!tr(o.pid):Date.now()-i.mtimeMs>=xo)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function jo(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=S.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=u.default.openSync(i,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(s),l=U(i,s,c,{allowMultipleLinks:!0});return nr(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(c){if(k(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function qo(e,t){let n;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){throw k(r,"ENOENT")?new R:r}try{let r=u.default.fstatSync(n),i=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Le(i,t))throw new R;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function Xn(e){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(n){if(k(n,"ENOENT"))try{let r=u.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new R}catch(r){if(k(r,"ENOENT"))return!1;throw r}throw n}return U(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function Wo(e){let t;try{t=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(r){if(k(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=U(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{J(e,n)}catch{}throw u.default.closeSync(t),r}}function q(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");Do(No)}function Vn(e){let t=S.dirname(e),n=S.basename(e),r=Ko(e),i=Ho(e),o=jo(t,n),s=Date.now()+vo,c=!1,l=!1,d=null,p;try{for(;d===null;)try{if(Xn(i)){q(s,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=qo(r,o.stats),c=!0}catch(f){if(l&&!c){try{J(r,o.stats)}catch{}l=!1}if(f instanceof R){q(s,!1);continue}if(!k(f,"EEXIST"))throw f;let m;try{m=zn(r,n)}catch(y){if(y instanceof R){q(s,!1);continue}throw y}if(m.state==="absent")continue;if(m.state==="stale"){let y;try{y=Wo(i)}catch(h){if(h instanceof R){q(s,!1);continue}throw h}if(y!==null){try{let h;try{h=zn(r,n)}catch(b){if(b instanceof R){q(s,!1);continue}throw b}h.state==="stale"&&J(r,h.stats)}finally{Ot(y)}continue}}let g;try{g=Xn(i)}catch(y){if(y instanceof R){q(s,!1);continue}throw y}q(s,g)}}catch(f){p=f}try{J(o.claimPath,o.stats)}catch(f){!k(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 Ot(e){try{J(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function Jo(e,t){let n=$o(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Zn(e){let t=S.dirname(e),n=S.basename(e);for(let r of u.default.readdirSync(t)){let i=Jo(r,n);if(i===null||tr(i))continue;let o=S.join(t,r),s=null;try{try{s=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(k(d,"ENOENT")||k(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(s),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!Le(c,l))continue;try{Ae(c,"credential-store orphan")}catch{continue}J(o,c)}catch(c){if(!k(c,"ENOENT"))throw c}finally{s!==null&&u.default.closeSync(s)}}}function Te(e,t,n){if(!je()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw W();if(!qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw W()}});let s=Vn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:()=>{throw W()}})}finally{Ot(s)}}if(!t.createParent){let o=!1;try{o=er(e)}catch{throw W()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw W()}})}throw W()}if(!qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Vn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:o=>Go(e,o)})}finally{Ot(i)}}var vt="allscale-cli";function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function or(e){return Bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("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 Nt(){return new a("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 qe(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var z,xt=!1;function zo(){return vn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Xo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
- `,1)[0]==="Cannot find module 'keytar'"}function Vo(){if(z!==void 0)return z;if(zo())return xt=!1,z=null,z;try{z=require("keytar"),xt=!1}catch(e){xt=!Xo(e),z=null}return z}function sr(){let e=je()?"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 a("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Pt(e){try{return await e()}catch{throw sr()}}var Dt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Pt(()=>this.keytar.getPassword(vt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!or(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Pt(()=>this.keytar.setPassword(vt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Pt(()=>this.keytar.deletePassword(vt,t))}},Zo="credentials.json",$t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??ir.join(It(),Zo)}read(t){let n;try{n=t.read()}catch(i){throw Ye(i)?Nt():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Bt(r)||!Bt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ye(r)?Nt():qe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!or(r))throw X("plaintext file");return r}}async get(t){try{return Te(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{Te(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof a?r:qe()}}async delete(t){try{Te(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof a?n:qe()}}async clearProfile(t){try{return Te(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof a?n:Ye(n)?Nt():qe()}}};function ar(e){if(e.insecureStorage)return Qn(),new $t(e.insecureFilePath);let t=Vo();if(t)return new Dt(t);throw sr()}var Ut=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function We(){return new Ut}var Je="allscale_access_token",Ft="allscale_refresh_token";function lr(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function Mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Gt(e,t){return e.find(n=>n.name===t)?.value??null}var cr=T(require("crypto")),ur=T(require("fs")),dr=T(require("path"));var Qo="key-id",es="x-allscale-cli-version",Kt="cli-1",ts="aScaLe_cli_obf_v1",ns="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function rs(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var is=rs(ns,ts),pr=`Bearer ${is}`;function fr(e,t){let n=lt(e);if(n!==null)return t.find(r=>lt(r.base)===n)}function os(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=ge();if(t.length>0){let r=fr(e,t);if(r)return r.key;if(K(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:K(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function ss(e){{let r="cli-1".trim();if(r.length>0)return r}let t=ge();if(t.length>0){let r=e!==void 0?fr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&K(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Kt}if(!K(t[0].base))return Kt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Kt}function as(){return"1.0.2"}function ls(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ht(e,t){let n=os(t);if(!n)throw ls();let r=ss(t),i=Math.floor(Date.now()/1e3).toString(),o=cr.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[es]:as()};return r.length>0&&(s[Qo]=r),s}function mr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function cs(e,t={}){let n;try{n=Bn($e())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",gn(e)+(t.messageSuffix??""),{profile:e})}function gr(e){if(e.profileExplicit){let t=cs(e.profile);if(t)return t}return new a("auth.no_token",mn(e.profile))}var us=500,ds=8,hr=100;function Yt(e,t=0){if(t>ds)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,hr),r=n.map(i=>Yt(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,hr))n[r]=xe(r)?"<redacted>":Yt(i,t+1);return n}return e}function ps(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function _r(e,t=us){let n=ps(e),r=n===void 0?Ne(e):JSON.stringify(Yt(n));return Pe(r,t)}var jt=256*1024,ze=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Xe=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function qt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new ze(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,m)=>{l=setTimeout(()=>{m(new Xe(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:m,value:g}=p?await Promise.race([f,p]):await f;if(m)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new ze(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(f){throw f instanceof Xe&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var fs="X-AllScale-Api-Key",ms=3e4,gs=32*1024*1024,hs=4*1024*1024;function _s(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function ws(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function ys(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Sr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ys(e.status,e.url)}}var wr="--dns-result-order=ipv4first";async function Ve(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),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(s);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("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=${wr} 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=${wr}`})}var V=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??ms;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");j(this.opts.apiBase),Fe(this.opts.apiBase);let i=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=_s(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();Un(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Er(t.path),l=s==="required"?!0:s==="none"?!1:Ss(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw gr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=mr(t.body),p=!!o||!!r?.access_token;l&&p&&!this.opts.override&&Ue(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),m=Date.now();_({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(h){throw new a("transport.network",`Network error contacting ${M(i)}: ${h instanceof Error?h.message:String(h)}`)}if(_({type:"response",status:g.status,durationMs:Date.now()-m}),l&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let h=await ws(this.refreshSingleFlight(),t.signal),b=this.buildHeaders({attachAuth:l&&!!h.access_token,bodyForSig:d,tokens:h,extra:t.headers}),x=Date.now();_({type:"request",method:t.method??"GET",url:i});let L;try{L=await fetch(i,{method:t.method??"GET",headers:b,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(G){throw new a("transport.network",`Network error contacting ${M(i)} on refresh-retry: ${G instanceof Error?G.message:String(G)}`)}return _({type:"response",status:L.status,durationMs:Date.now()-x}),yr(L,{withMetadata:n.withMetadata,authBearing:l,responseKind:br(t)})}return yr(g,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:br(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ht(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=pr;let i=t.tokens;if(i?.agent_key)return r[fs]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=Mt([{name:Je,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(Ue(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new a("auth.token_expired",`No refresh token available; log in again \u2014 ${ve()}.`);if(Ue(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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 n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=Mt([{name:Je,value:t.access_token},{name:Ft,value:t.refresh_token}]),i=Ht("",this.opts.apiBase);_({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw _({type:"refresh",ok:!1}),new a("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}_({type:"response",status:l.status,durationMs:0});try{await Sr(l)}catch(g){throw _({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Ve(l);let y=await Is(l);await Ve(l,y),Lr(l.status,y),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw _({type:"refresh",ok:!1}),y}if(g)return _({type:"refresh",ok:!0,adopted:!0}),g;throw _({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ve()}.`,{status:l.status})}let d=lr(l.headers),p=Gt(d,Je),f=Gt(d,Ft);if(!p||!f)throw _({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,m),_({type:"refresh",ok:!0}),m}},bs=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Er(e){let t=e.split(/[?#]/,1)[0];return bs.some(n=>t===n||t.startsWith(`${n}/`))}var ks=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Wt(e){let t=e.split(/[?#]/,1)[0];return ks.some(n=>n.test(t))}function Ss(e){return Er(e)||Wt(e)}async function yr(e,t={}){await Sr(e);let n=e.status>=200&&e.status<300;n||await Ve(e);let r=t.responseKind??"mutation",o=await qt(e,n?r==="query"?gs:hs:jt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ve(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let c=Cs(s)??`HTTP ${e.status}`;if(Lr(e.status,s),Ls(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new a("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new a(l,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function br(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Es=2014,kr=2004;function Ar(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function As(e){return Ar(e,Es)}function Ls(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Ar(t,kr))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ve()} 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:kr})}var Ts=1e4;async function Is(e,t=Ts){if(e.status>=200&&e.status<300)return"";try{return await qt(e,jt,{timeoutMs:t})}catch{return""}}function Lr(e,t){if(!(e>=200&&e<300)&&As(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?_r(t):t})}function Cs(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var Os=/^\/(api\/)?(v1\/)?public\//;function Ze(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Os.test(n),i=n&&Wt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new V({apiBase:e.apiBase,tokenStore:ar({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var P={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},Rs=new Set(Object.values(P));async function Tr(e,t,n){let{body:r,headers:i}=await xs(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:vs(i)}}function vs(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function Jt(e,t){return Ns(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function Ns(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Ir(o,r);if(s!==null)throw s}throw o}return Cr(i,r)}async function xs(e,t,n,r){let i;try{i=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Ir(o,r);if(s!==null)throw s}throw o}return{body:Cr(i.body,r),headers:i.headers??{}}}function Ir(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,i=typeof r.code=="number"?r.code:void 0;if(i===void 0||i===0||!Rs.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return Or(i,o,t)}function Cr(e,t){if(e.code!==void 0&&e.code!==0)throw Or(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function Or(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case P.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case P.CLI_OP_EXPIRED:return new a("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:r});case P.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case P.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case P.CLI_OP_INVALID_PAYLOAD:case P.CLI_OP_SELF_TRANSFER:case P.CLI_OP_INSUFFICIENT_BALANCE:case P.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case P.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case P.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var Nr=require("child_process");function Rr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Ps=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Bs(e,t,n,r){if(Rr(e.CI)||Ps.some(s=>Rr(e[s])))return"ci";let o=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":n===!0||r===!0?null:"no-tty"}function Ds(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" 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."+t+n: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."+t+n:"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."+t+n}async function xr(e,t={}){if(!st(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${O(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new a("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=i?null:Bs(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new a("wallet.requires_browser_auth",Ds(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new a("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(t._execOverride){await t._execOverride(e);return}let s=$s(r,i);await Us(s.command,[...s.args,e])}function $s(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Us(e,t){return new Promise((n,r)=>{let i;try{i=(0,Nr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(vr(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(vr(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function vr(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Pr=T(require("http"));var Fs=9e4,Ms=16*1024;function Br(e){let t=e.timeoutMs??Fs;return new Promise((n,r)=>{let i=!1,o=!1,s=null,c,l,d=new Promise((f,m)=>{c=f,l=m}),p=Pr.createServer((f,m)=>{Gs(f,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:g=>{s&&clearTimeout(s),c(g),p.close()}})});p.on("error",f=>{let m=new a("transport.network",`Loopback listener error: ${f.message}`);o?l(m):r(m),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let m=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,g=m!=null?Math.max(1,Math.min(t,m)):t,y=m!=null&&m<=t;s=setTimeout(()=>{l(new a("wallet.bridge_timeout",`Bridge timed out after ${g}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},g),s.unref?.(),o=!0,n({port:f.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function Gs(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.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"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let i=0,o=[],s=!1;e.on("data",c=>{if(!s){if(i+=c.length,i>Ms){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.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,m=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(!Ks(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&m===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:f,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function Ks(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function zt(e){try{return JSON.parse(e),!0}catch{return!1}}function Dr(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},c=()=>{s(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",f),e.pause()},d=g=>{if(n)return;s(),t+=g.toString();let y=t.trim(),h=t.length-t.trimStart().length,b=t.indexOf(`
17
- `,h),x=b===-1?"":t.slice(h,b).trim();if(y.startsWith("{")){if(zt(y)){l(),r(y);return}if(b===-1){c();return}if(!zt(x)&&!x.endsWith("}")){let L=t.slice(b+1),G=L.split(`
18
- `).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(G))){c();return}}l(),r(zt(x)?x:t.slice(h).trim());return}if(b!==-1){l(),r(x);return}else!y&&t.includes(`
19
- `)&&(l(),r(""))},p=()=>{if(n)return;let g=t.trim();if(!g){l();return}l(),r(g)},f=()=>{n||l()},m=new Promise(g=>{r=g});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",f),{promise:m,cancel:()=>{n||l()}}}function Hs(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function Ur(e){let t=Ze(e.ctx),n=e.browserBase??e.ctx.apiBase,r=zs(n),i=e._openBrowser??xr,o=e._startListener??Br,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,$r.randomBytes)(32).toString("hex"),d=Date.now(),p=await Tr(t,e.op,e.payload);_({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let m=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,g=2147483647,h=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,b=9e5,x=6e4,L=m!=null&&Number.isFinite(m)&&m>0?m:null,G=Math.max(0,Math.round((L??0)/1e3)),v=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=v!=null&&v<=g?v:null,B,de,nn=!1,rn=!1,on=!1;if(L!=null){let E=Math.min(L,g),D=L>g;F!=null&&F<E?(B=F,de="caller"):(B=E,de=D?"timer_ceiling":"op_ttl",nn=!D&&v!=null&&v>E)}else{let E=p.expires_at*1e3-d,D=Number.isFinite(E)?Math.min(Math.max(E,x),b):b,Z=F??h;Z>D?(B=D,de="op_ttl_unverified",rn=v!=null&&v>D):(B=Z,de=F!=null?"caller":"unknown_ttl"),on=v!=null&&F==null}let gi=de==="op_ttl",hi=L!=null?`~${G}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${hi}, waiting up to ${Math.round(B/1e3)}s for confirmation).
20
- `),nn&&A.stderr.write(`Note: the confirmation wait of ${v}ms is longer than the confirmation link's remaining life (${Math.round(B/1e3)}s, from the server's stated expiry and its own clock), so the wait was capped at that.
21
- `),rn&&A.stderr.write(`Note: the confirmation wait of ${v}ms is longer than the confirmation link's remaining life (~${Math.round(B/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.
22
- `),on&&A.stderr.write(`Note: the requested confirmation wait of ${v}ms is outside the usable range (1ms-${g}ms), so it was ignored and the wait fell back to ~${Math.round(B/1e3)}s.
23
- `);let rt=await o({state:l,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),_i=rt.awaitResult.then(E=>({source:"loopback",...E}),E=>({source:"listener_error",error:E})),wi=Date.now(),sn=setInterval(()=>{let E=Math.floor((Date.now()-wi)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${E}s elapsed)
24
- `)},15e3);sn.unref?.();let Ce,it=e.signal===void 0?void 0:Hs(e.signal);try{let E=Ws(n,{op_id:p.op_id,port:rt.port,state:l});_({type:"bridge_browser_open",url:E});let D=s==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(A.stderr.write(c?e.autoOpen===!1?`
14
+ `}var j=T(require("fs")),Bn=T(require("os")),Lt=T(require("path")),Tt=T(require("@iarna/toml"));var co=".allscale",uo="config.toml";function Ct(){return Lt.join(Bn.homedir(),co)}function po(){return Lt.join(Ct(),uo)}function $e(){let e=po();if(!j.existsSync(e))return{};let t=j.readFileSync(e,"utf-8");try{return Tt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function Dn(e){return Object.keys(e.profile??{}).sort()}function $n(e,t){return e.profile?.[t]}function Un(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function Y(e){if(!ee(e))throw new a("input.invalid",`Refusing to send credentials to API base ${O(e)}. `+fe)}function Ue(e,t){Y(e);let n=H(e),r=typeof t=="string"?H(t):null;if(n&&r===n)return;let i=typeof t=="string"?O(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${O(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Fn(e,t){let n=H(e),r=H(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${O(t)} because it is outside the configured API origin ${O(e)}.`)}function Fe(e){let t=mo(e);if(t)throw new a("input.invalid",t.message)}function fo(){let e=me();if(e===void 0)return;let t=he();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function mo(e){let t=fo();if(t===void 0||K(e))return;let{endpoints:n,fromPairs:r}=t,i=H(e),o=n.map(c=>H(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>O(c)).join(", ");return{message:r?`Refusing to send to ${O(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${O(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var ho=require("@noble/hashes/sha3");var go={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Mn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Me=["USDT","USDC"];function Gn(e){return go[e.toLowerCase()]??null}function Kn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var Hl=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Hn(e){return e===1?"USDT":"USDC"}var _o="unknown_otp_id",wo="invalid_code",yo="expired_code";function bo(e){return`'${e.replace(/'/g,"'\\''")}'`}function jn(e){return`Run \`allscale otp-send --email ${bo(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var ko=new Map([[_o,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', 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. ${jn(t)}`],[wo,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,t,n)=>n?`${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. ${jn(t)}`]]);var Yn=[...ko.keys()];var I=require("@oclif/core"),Ee=class e extends $.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:$.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:$.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:te()==="public"}),"api-base":$.Flags.string({description:ot,helpGroup:"GLOBAL",hidden:te()==="public"}),"insecure-storage":$.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{bt(this.jsonEnabled()),Et(),_({type:"session-start",command:this.id??"",argv:St(this.argv)});let t=this.constructor;if(te()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=In(this.jsonEnabled()),r=this.argv.length===0&&!n&&Ro(t)?this.config.findCommand(this.id??""):void 0;if(r){we();let o=await(0,$.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!xn())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return _({type:"command-end",ok:!0}),we(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||wn(i),{data:i})}catch(t){let n=_n(t);On({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{bt(!1)}}resolveSessionApiBaseChain(t){let n=$e(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||At()!==void 0,s=Un(n,r,At()),c=$n(n,s),l=te()==="public"&&ke()!==void 0,d=i??(l?void 0:ke()),p=d??c?.api_base??be,f=Pn({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ie({event:"legacy_staging_profile",api_base:p,profile:s},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Y(n),n}resolveContext(t){if(te()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:c,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Y(i),Fe(i)),{apiBase:i,profile:c,token:n??Rn(),insecureStorage:r||vn(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Oo(t)}
15
+ `)}};var Eo=/_(removed|cleared|count|total)$/i;function So(e,t){return typeof t=="number"&&Eo.test(e)}var Ao=new Set(Me);function Lo(e,t){return e==="token_symbol"&&typeof t=="string"&&Ao.has(t)}var To=new Set(Yn);function Co(e,t){return e==="otp_reason"&&typeof t=="string"&&To.has(t)}var Ge=100;function Ke(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ge),r=n.map(i=>Ke(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Ge))n[i]=xe(i)&&!So(i,o)&&!Lo(i,o)&&!Co(i,o)?"<redacted>":Ke(o,t+1);if(r.length>Ge){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ge} more keys`}return n}if(typeof e=="string"){let n=Io(e);return n!==void 0?C(JSON.stringify(Ke(n,t+1))):C(e)}return e}function Io(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Oo(e){let t=Sn()?void 0:2,n=Ke(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:C(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Ro(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var ce=/^0x[0-9a-fA-F]{64}$/,vo=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function qn(e){return typeof e=="string"&&vo.includes(e)}var Ur=require("crypto"),A=require("process");var or=T(require("path"));var Rt=require("crypto"),u=T(require("fs")),E=T(require("path"));var He=1024*1024,No=5e3,xo=20,Po=3e4,It=4096,Bo=new Int32Array(new SharedArrayBuffer(4)),Se=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function je(e){return e instanceof Se}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Do=null;function W(){return new a("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 Ye(){return(Do??process.platform)!=="win32"}function er(){if(!Ye())throw W()}function tr(e){try{return u.default.lstatSync(e),!1}catch(t){if(!k(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(k(t,"ENOENT"))return!0;throw t}}function k(e,t){return typeof e=="object"&&e!==null&&e.code===t}function Ae(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function Le(e,t){return e.dev===t.dev&&e.ino===t.ino}function $o(e){Atomics.wait(Bo,0,0,e)}function nr(e){try{return process.kill(e,0),!0}catch(t){return!k(t,"ESRCH")}}function Uo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wn(e,t){let n=E.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&k(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=u.default.openSync(n,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(i),s=u.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Le(o,s))throw new Error("credential-store parent changed while it was being inspected");Ae(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&E.basename(n)===".allscale"&&(u.default.fchmodSync(i,448),c=u.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&u.default.closeSync(i)}return!0}function U(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=u.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&k(o,"ENOENT")?new R:o}if(!Le(n,i))throw r.retryOnPathChange?new R:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new Se;if(Ae(n,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(t,384);let o=u.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Fo(e,t){if(t.size>He)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(He+1),r=0;for(;r<n.length;){let i=u.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>He)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Jn(e){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(i){if(k(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(k(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=U(e,t,n);return Fo(t,r)}finally{t!==null&&u.default.closeSync(t)}}function zn(e){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(i){if(k(i,"ENOENT")&&tr(e))return;throw i}let n=u.default.fstatSync(t),r=U(e,t,n);J(e,r)}finally{t!==null&&u.default.closeSync(t)}ir(E.dirname(e))}function Mo(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(k(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new Se;Ae(t,"credential-store replacement target")}function Go(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(k(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function rr(e,t){let n=0;for(;n<t.length;){let r=u.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function ir(e){if(process.platform==="win32")return;let t=null;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(t)}catch{}finally{if(t!==null)try{u.default.closeSync(t)}catch{}}}function Ko(e,t){let n=Buffer.from(t,"utf8");if(n.length>He)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),i=E.basename(e),o=null,s=null,c=!1;try{let l=Go(r,i);o=l.fd,s=l.tempPath;let d=u.default.fstatSync(o);if((U(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");rr(o,n),u.default.fsyncSync(o),U(s,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),Mo(e),u.default.renameSync(s,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&s!==null)try{u.default.unlinkSync(s)}catch{}}ir(r)}function Ho(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function jo(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function Yo(e,t){if(t.size>It)return null;let n=Buffer.alloc(It+1),r=0;for(;r<n.length;){let o=u.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>It)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function J(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!Le(n,t))throw new Error("credential-store lock changed while it was being inspected");Ae(n,"credential-store lock"),u.default.unlinkSync(e)}function Xn(e,t){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(l){if(k(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 R}catch(d){if(k(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Yo(n,i);return{state:(o?.target===t&&o?!nr(o.pid):Date.now()-i.mtimeMs>=Po)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function qo(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=u.default.openSync(i,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(s),l=U(i,s,c,{allowMultipleLinks:!0});return rr(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(c){if(k(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Wo(e,t){let n;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){throw k(r,"ENOENT")?new R:r}try{let r=u.default.fstatSync(n),i=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Le(i,t))throw new R;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function Vn(e){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(n){if(k(n,"ENOENT"))try{let r=u.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new R}catch(r){if(k(r,"ENOENT"))return!1;throw r}throw n}return U(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function Jo(e){let t;try{t=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(r){if(k(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=U(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{J(e,n)}catch{}throw u.default.closeSync(t),r}}function q(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");$o(xo)}function Zn(e){let t=E.dirname(e),n=E.basename(e),r=Ho(e),i=jo(e),o=qo(t,n),s=Date.now()+No,c=!1,l=!1,d=null,p;try{for(;d===null;)try{if(Vn(i)){q(s,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=Wo(r,o.stats),c=!0}catch(f){if(l&&!c){try{J(r,o.stats)}catch{}l=!1}if(f instanceof R){q(s,!1);continue}if(!k(f,"EEXIST"))throw f;let m;try{m=Xn(r,n)}catch(y){if(y instanceof R){q(s,!1);continue}throw y}if(m.state==="absent")continue;if(m.state==="stale"){let y;try{y=Jo(i)}catch(g){if(g instanceof R){q(s,!1);continue}throw g}if(y!==null){try{let g;try{g=Xn(r,n)}catch(b){if(b instanceof R){q(s,!1);continue}throw b}g.state==="stale"&&J(r,g.stats)}finally{Ot(y)}continue}}let h;try{h=Vn(i)}catch(y){if(y instanceof R){q(s,!1);continue}throw y}q(s,h)}}catch(f){p=f}try{J(o.claimPath,o.stats)}catch(f){!k(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 Ot(e){try{J(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function zo(e,t){let n=Uo(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Qn(e){let t=E.dirname(e),n=E.basename(e);for(let r of u.default.readdirSync(t)){let i=zo(r,n);if(i===null||nr(i))continue;let o=E.join(t,r),s=null;try{try{s=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(k(d,"ENOENT")||k(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(s),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!Le(c,l))continue;try{Ae(c,"credential-store orphan")}catch{continue}J(o,c)}catch(c){if(!k(c,"ENOENT"))throw c}finally{s!==null&&u.default.closeSync(s)}}}function Te(e,t,n){if(!Ye()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw W();if(!Wn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw W()}});let s=Zn(e);try{return Qn(e),n({read:()=>Jn(e),remove:()=>zn(e),write:()=>{throw W()}})}finally{Ot(s)}}if(!t.createParent){let o=!1;try{o=tr(e)}catch{throw W()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw W()}})}throw W()}if(!Wn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Zn(e);try{return Qn(e),n({read:()=>Jn(e),remove:()=>zn(e),write:o=>Ko(e,o)})}finally{Ot(i)}}var vt="allscale-cli";function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sr(e){return Bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("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 Nt(){return new a("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 qe(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var z,xt=!1;function Xo(){return Nn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Vo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function Zo(){if(z!==void 0)return z;if(Xo())return xt=!1,z=null,z;try{z=require("keytar"),xt=!1}catch(e){xt=!Vo(e),z=null}return z}var Qo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function ar(){let e=Ye()?"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 a("storage.unavailable",`${Qo} `+e+" Never silently downgrade in production.")}async function Pt(e){try{return await e()}catch{throw ar()}}var Dt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Pt(()=>this.keytar.getPassword(vt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!sr(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Pt(()=>this.keytar.setPassword(vt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Pt(()=>this.keytar.deletePassword(vt,t))}},es="credentials.json",$t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??or.join(Ct(),es)}read(t){let n;try{n=t.read()}catch(i){throw je(i)?Nt():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Bt(r)||!Bt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw je(r)?Nt():qe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!sr(r))throw X("plaintext file");return r}}async get(t){try{return Te(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{Te(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof a?r:qe()}}async delete(t){try{Te(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof a?n:qe()}}async clearProfile(t){try{return Te(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof a?n:je(n)?Nt():qe()}}};function lr(e){if(e.insecureStorage)return er(),new $t(e.insecureFilePath);let t=Zo();if(t)return new Dt(t);throw ar()}var Ut=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function We(){return new Ut}var Je="allscale_access_token",Ft="allscale_refresh_token";function cr(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function Mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Gt(e,t){return e.find(n=>n.name===t)?.value??null}var ur=T(require("crypto")),dr=T(require("fs")),pr=T(require("path"));var ts="key-id",ns="x-allscale-cli-version",Kt="cli-1",rs="aScaLe_cli_obf_v1",is="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function os(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var ss=os(is,rs),fr=`Bearer ${ss}`;function mr(e,t){let n=lt(e);if(n!==null)return t.find(r=>lt(r.base)===n)}function as(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=mr(e,t);if(r)return r.key;if(K(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:K(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function ls(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?mr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&K(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Kt}if(!K(t[0].base))return Kt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Kt}function cs(){return"1.0.3"}function us(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ht(e,t){let n=as(t);if(!n)throw us();let r=ls(t),i=Math.floor(Date.now()/1e3).toString(),o=ur.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[ns]:cs()};return r.length>0&&(s[ts]=r),s}function hr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ds(e,t={}){let n;try{n=Dn($e())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",gn(e)+(t.messageSuffix??""),{profile:e})}function gr(e){if(e.profileExplicit){let t=ds(e.profile);if(t)return t}return new a("auth.no_token",hn(e.profile))}var ps=500,fs=8,_r=100;function jt(e,t=0){if(t>fs)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,_r),r=n.map(i=>jt(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,_r))n[r]=xe(r)?"<redacted>":jt(i,t+1);return n}return e}function ms(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function wr(e,t=ps){let n=ms(e),r=n===void 0?Ne(e):JSON.stringify(jt(n));return Pe(r,t)}var Yt=256*1024,ze=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Xe=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function qt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new ze(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,m)=>{l=setTimeout(()=>{m(new Xe(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:m,value:h}=p?await Promise.race([f,p]):await f;if(m)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new ze(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(f){throw f instanceof Xe&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var hs="X-AllScale-Api-Key",gs=3e4,_s=32*1024*1024,ws=4*1024*1024;function ys(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function bs(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function ks(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Sr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ks(e.status,e.url)}}var yr="--dns-result-order=ipv4first";async function Ve(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),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(s);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("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=${yr} 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=${yr}`})}var V=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??gs;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");Y(this.opts.apiBase),Fe(this.opts.apiBase);let i=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=ys(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();Fn(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Ar(t.path),l=s==="required"?!0:s==="none"?!1:As(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw gr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=hr(t.body),p=!!o||!!r?.access_token;l&&p&&!this.opts.override&&Ue(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),m=Date.now();_({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(g){throw new a("transport.network",`Network error contacting ${M(i)}: ${g instanceof Error?g.message:String(g)}`)}if(_({type:"response",status:h.status,durationMs:Date.now()-m}),l&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let g=await bs(this.refreshSingleFlight(),t.signal),b=this.buildHeaders({attachAuth:l&&!!g.access_token,bodyForSig:d,tokens:g,extra:t.headers}),x=Date.now();_({type:"request",method:t.method??"GET",url:i});let L;try{L=await fetch(i,{method:t.method??"GET",headers:b,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(G){throw new a("transport.network",`Network error contacting ${M(i)} on refresh-retry: ${G instanceof Error?G.message:String(G)}`)}return _({type:"response",status:L.status,durationMs:Date.now()-x}),br(L,{withMetadata:n.withMetadata,authBearing:l,responseKind:kr(t)})}return br(h,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:kr(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ht(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=fr;let i=t.tokens;if(i?.agent_key)return r[hs]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=Mt([{name:Je,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(Ue(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new a("auth.token_expired",`No refresh token available; log in again \u2014 ${ve()}.`);if(Ue(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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 n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=Mt([{name:Je,value:t.access_token},{name:Ft,value:t.refresh_token}]),i=Ht("",this.opts.apiBase);_({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw _({type:"refresh",ok:!1}),new a("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}_({type:"response",status:l.status,durationMs:0});try{await Sr(l)}catch(h){throw _({type:"refresh",ok:!1}),h}if(l.status!==200){let h=null;try{await Ve(l);let y=await Os(l);await Ve(l,y),Tr(l.status,y),l.status===401&&(h=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw _({type:"refresh",ok:!1}),y}if(h)return _({type:"refresh",ok:!0,adopted:!0}),h;throw _({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ve()}.`,{status:l.status})}let d=cr(l.headers),p=Gt(d,Je),f=Gt(d,Ft);if(!p||!f)throw _({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,m),_({type:"refresh",ok:!0}),m}},Es=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Ar(e){let t=e.split(/[?#]/,1)[0];return Es.some(n=>t===n||t.startsWith(`${n}/`))}var Ss=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Wt(e){let t=e.split(/[?#]/,1)[0];return Ss.some(n=>n.test(t))}function As(e){return Ar(e)||Wt(e)}async function br(e,t={}){await Sr(e);let n=e.status>=200&&e.status<300;n||await Ve(e);let r=t.responseKind??"mutation",o=await qt(e,n?r==="query"?_s:ws:Yt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ve(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let c=Rs(s)??`HTTP ${e.status}`;if(Tr(e.status,s),Cs(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new a("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new a(l,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function kr(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Ls=2014,Er=2004;function Lr(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function Ts(e){return Lr(e,Ls)}function Cs(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Lr(t,Er))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ve()} 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:Er})}var Is=1e4;async function Os(e,t=Is){if(e.status>=200&&e.status<300)return"";try{return await qt(e,Yt,{timeoutMs:t})}catch{return""}}function Tr(e,t){if(!(e>=200&&e<300)&&Ts(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?wr(t):t})}function Rs(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var vs=/^\/(api\/)?(v1\/)?public\//;function Ze(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&vs.test(n),i=n&&Wt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new V({apiBase:e.apiBase,tokenStore:lr({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var P={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},Ns=new Set(Object.values(P));async function Cr(e,t,n){let{body:r,headers:i}=await Bs(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:xs(i)}}function xs(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function Jt(e,t){return Ps(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function Ps(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Ir(o,r);if(s!==null)throw s}throw o}return Or(i,r)}async function Bs(e,t,n,r){let i;try{i=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Ir(o,r);if(s!==null)throw s}throw o}return{body:Or(i.body,r),headers:i.headers??{}}}function Ir(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,i=typeof r.code=="number"?r.code:void 0;if(i===void 0||i===0||!Ns.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return Rr(i,o,t)}function Or(e,t){if(e.code!==void 0&&e.code!==0)throw Rr(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function Rr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case P.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case P.CLI_OP_EXPIRED:return new a("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:r});case P.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case P.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case P.CLI_OP_INVALID_PAYLOAD:case P.CLI_OP_SELF_TRANSFER:case P.CLI_OP_INSUFFICIENT_BALANCE:case P.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case P.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case P.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var xr=require("child_process");function vr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Ds=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function $s(e,t,n,r){if(vr(e.CI)||Ds.some(s=>vr(e[s])))return"ci";let o=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":n===!0||r===!0?null:"no-tty"}function Us(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" 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."+t+n: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."+t+n:"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."+t+n}async function Pr(e,t={}){if(!st(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${O(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new a("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=i?null:$s(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new a("wallet.requires_browser_auth",Us(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new a("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(t._execOverride){await t._execOverride(e);return}let s=Fs(r,i);await Ms(s.command,[...s.args,e])}function Fs(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Ms(e,t){return new Promise((n,r)=>{let i;try{i=(0,xr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Nr(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(Nr(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function Nr(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Br=T(require("http"));var Gs=9e4,Ks=16*1024;function Dr(e){let t=e.timeoutMs??Gs;return new Promise((n,r)=>{let i=!1,o=!1,s=null,c,l,d=new Promise((f,m)=>{c=f,l=m}),p=Br.createServer((f,m)=>{Hs(f,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:h=>{s&&clearTimeout(s),c(h),p.close()}})});p.on("error",f=>{let m=new a("transport.network",`Loopback listener error: ${f.message}`);o?l(m):r(m),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let m=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,h=m!=null?Math.max(1,Math.min(t,m)):t,y=m!=null&&m<=t;s=setTimeout(()=>{l(new a("wallet.bridge_timeout",`Bridge timed out after ${h}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},h),s.unref?.(),o=!0,n({port:f.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function Hs(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.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"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let i=0,o=[],s=!1;e.on("data",c=>{if(!s){if(i+=c.length,i>Ks){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.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,m=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(!js(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&m===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:f,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function js(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function zt(e){try{return JSON.parse(e),!0}catch{return!1}}function $r(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},c=()=>{s(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",f),e.pause()},d=h=>{if(n)return;s(),t+=h.toString();let y=t.trim(),g=t.length-t.trimStart().length,b=t.indexOf(`
17
+ `,g),x=b===-1?"":t.slice(g,b).trim();if(y.startsWith("{")){if(zt(y)){l(),r(y);return}if(b===-1){c();return}if(!zt(x)&&!x.endsWith("}")){let L=t.slice(b+1),G=L.split(`
18
+ `).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(G))){c();return}}l(),r(zt(x)?x:t.slice(g).trim());return}if(b!==-1){l(),r(x);return}else!y&&t.includes(`
19
+ `)&&(l(),r(""))},p=()=>{if(n)return;let h=t.trim();if(!h){l();return}l(),r(h)},f=()=>{n||l()},m=new Promise(h=>{r=h});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",f),{promise:m,cancel:()=>{n||l()}}}function Ys(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function Fr(e){let t=Ze(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Vs(n),i=e._openBrowser??Pr,o=e._startListener??Dr,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,Ur.randomBytes)(32).toString("hex"),d=Date.now(),p=await Cr(t,e.op,e.payload);_({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let m=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,h=2147483647,g=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,b=9e5,x=6e4,L=m!=null&&Number.isFinite(m)&&m>0?m:null,G=Math.max(0,Math.round((L??0)/1e3)),v=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=v!=null&&v<=h?v:null,B,de,rn=!1,on=!1,sn=!1;if(L!=null){let S=Math.min(L,h),D=L>h;F!=null&&F<S?(B=F,de="caller"):(B=S,de=D?"timer_ceiling":"op_ttl",rn=!D&&v!=null&&v>S)}else{let S=p.expires_at*1e3-d,D=Number.isFinite(S)?Math.min(Math.max(S,x),b):b,Z=F??g;Z>D?(B=D,de="op_ttl_unverified",on=v!=null&&v>D):(B=Z,de=F!=null?"caller":"unknown_ttl"),sn=v!=null&&F==null}let gi=de==="op_ttl",_i=L!=null?`~${G}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${_i}, waiting up to ${Math.round(B/1e3)}s for confirmation).
20
+ `),rn&&A.stderr.write(`Note: the confirmation wait of ${v}ms is longer than the confirmation link's remaining life (${Math.round(B/1e3)}s, from the server's stated expiry and its own clock), so the wait was capped at that.
21
+ `),on&&A.stderr.write(`Note: the confirmation wait of ${v}ms is longer than the confirmation link's remaining life (~${Math.round(B/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.
22
+ `),sn&&A.stderr.write(`Note: the requested confirmation wait of ${v}ms is outside the usable range (1ms-${h}ms), so it was ignored and the wait fell back to ~${Math.round(B/1e3)}s.
23
+ `);let rt=await o({state:l,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),wi=rt.awaitResult.then(S=>({source:"loopback",...S}),S=>({source:"listener_error",error:S})),yi=Date.now(),an=setInterval(()=>{let S=Math.floor((Date.now()-yi)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${S}s elapsed)
24
+ `)},15e3);an.unref?.();let Ie,it=e.signal===void 0?void 0:Ys(e.signal);try{let S=zs(n,{op_id:p.op_id,port:rt.port,state:l});_({type:"bridge_browser_open",url:S});let D=s==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(A.stderr.write(c?e.autoOpen===!1?`
25
25
  Confirm this in your browser. Open the URL below on any device where
26
26
  you're signed in to AllScale (local auto-open is disabled):
27
27
 
28
- ${E}
28
+ ${S}
29
29
 
30
30
  `:`
31
31
  Confirm this in your browser. The URL is below \u2014 it auto-opens if a
32
32
  browser is available on this machine; otherwise open it on any device
33
33
  where you're signed in to AllScale:
34
34
 
35
- ${E}
35
+ ${S}
36
36
 
37
37
  `:`
38
38
  Confirm this in a browser on this machine. The callback must reach the
39
39
  local listener; non-interactive stdin cannot accept a result pasted
40
40
  back from another device:
41
41
 
42
- ${E}
42
+ ${S}
43
43
 
44
44
  `),e.autoOpen===!1)A.stderr.write(`(browser auto-open skipped \u2014 use the link above)
45
- `);else try{await i(E),A.stderr.write(`(opened in your default browser)
45
+ `);else try{await i(S),A.stderr.write(`(opened in your default browser)
46
46
  `)}catch{A.stderr.write(`(no local browser to open \u2014 use the link above)
47
47
  `)}c?A.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
48
48
  reach this machine (e.g. you opened the link elsewhere over SSH), copy
@@ -50,14 +50,14 @@ the ${D} the page shows, paste it here, and press Enter:
50
50
 
51
51
  `):A.stderr.write(`stdin is non-interactive; waiting for the browser callback.
52
52
 
53
- `),c&&(Ce=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:Dr());let Z=[_i];Ce!==void 0&&Z.push(Ce.promise.then(yi=>({source:"paste",line:yi}))),it!==void 0&&Z.push(it.promise);let Q=await Promise.race(Z);if(Q.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(Q.source==="listener_error")throw Ys(Q.error,gi);if(Q.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
54
- `),await js(t,s,Q);let Oe=Q.line.trim();if(!Oe)throw new a("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(s==="ack"&&Oe.startsWith("{"))throw new a("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(s==="ack"&&/\s/.test(Oe))throw new a("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 A.stderr.write(`Received pasted ${D}; processing\u2026
55
- `),await qs(t,s,Oe,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(sn),it?.cleanup(),Ce?.cancel(),rt.close()}}function Ys(e,t){let r=(e instanceof a&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:t;return e instanceof a&&e.code==="wallet.bridge_timeout"&&r?new a("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 a&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new a("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 js(e,t,n){if(t==="ack"){if(!n.result_token)throw new a("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");_({type:"bridge_result_received",source:"loopback"});let r=await Jt(e,n.result_token);return _({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),A.stderr.write(`Verified by broker.
53
+ `),c&&(Ie=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:$r());let Z=[wi];Ie!==void 0&&Z.push(Ie.promise.then(bi=>({source:"paste",line:bi}))),it!==void 0&&Z.push(it.promise);let Q=await Promise.race(Z);if(Q.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(Q.source==="listener_error")throw qs(Q.error,gi);if(Q.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
54
+ `),await Ws(t,s,Q);let Oe=Q.line.trim();if(!Oe)throw new a("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(s==="ack"&&Oe.startsWith("{"))throw new a("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(s==="ack"&&/\s/.test(Oe))throw new a("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 A.stderr.write(`Received pasted ${D}; processing\u2026
55
+ `),await Js(t,s,Oe,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(an),it?.cleanup(),Ie?.cancel(),rt.close()}}function qs(e,t){let r=(e instanceof a&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:t;return e instanceof a&&e.code==="wallet.bridge_timeout"&&r?new a("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 a&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new a("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 Ws(e,t,n){if(t==="ack"){if(!n.result_token)throw new a("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");_({type:"bridge_result_received",source:"loopback"});let r=await Jt(e,n.result_token);return _({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),A.stderr.write(`Verified by broker.
56
56
  `),{ack:r,result_data:n.result_data}}if(!n.result_data)throw new a("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return _({type:"bridge_result_received",source:"loopback"}),_({type:"bridge_data_received",source:"loopback"}),A.stderr.write(`Result received from browser.
57
- `),{result_data:n.result_data}}async function qs(e,t,n,r){if(t==="ack"){_({type:"bridge_result_received",source:"paste"});let o=await Jt(e,n);return _({type:"bridge_verified",op_id:o.op_id,source:"paste"}),A.stderr.write(`Verified by broker.
58
- `),{ack:o}}let i;try{i=Js(n,{acceptBareTxHashPaste:r})}catch(o){throw o instanceof a&&o.code==="input.invalid"?new a("wallet.bridge_invalid_response",o.message):o}return _({type:"bridge_result_received",source:"paste"}),_({type:"bridge_data_received",source:"paste"}),A.stderr.write(`Result accepted.
59
- `),{result_data:i}}function Ws(e,t){let n=new URL("/cli",Fr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}function Js(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&ce.test(e))return{tx_hash:e};throw new a("input.invalid",t.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 zs(e){return Fr(e).origin}function Fr(e){if(!ee(e))throw new a("input.invalid",`Refusing browser base ${O(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${fe}`);return new URL(e)}var Xs=new Set;var Vs=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"]),Xt=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"]),Vt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Qe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Mr(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Zs=new Set(["cli_op:all"]),Qs=new Set([...Zs].map(Qe));var ru=new Set([...[...Vs,...Xt,...Xs].map(Qe),...Vt,...Qs]);var ea={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"},ta={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"},na=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,ra=/is not available to API keys/i,Gr=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Kr(e){if(typeof e!="string")return;let t=na.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=ra.test(n),o=!i&&Gr.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(l=>l.trim()).filter(l=>Gr.test(l));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Hr(e){let t=ta[e];if(t!==void 0)return{ungrantableReason:t};let n=ea[e];if(n!==void 0)return{scope:n}}function Yr(e){if(Vt.has(Qe(e)))return{kind:"ungrantable"};for(let t of Xt)if(Mr(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function jr(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function qr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var ia=new Set([8100]),oa=new Set([...ia,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 Jr(e,t){let n=zr(e),r={graphql_error_count:sa(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw aa(e,t,r);if(n===429)throw new a("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new a("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&oa.has(n))throw new a("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(jr(e))throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${qr(e)}`,r);if(n!==void 0)throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function zr(e){let t=Wr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=Wr(r.code);if(i!==void 0)return i}}function Wr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function sa(e){return Array.isArray(e)?e.length:e==null?0:1}function aa(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Kr(la(e,zr(e))),s=Hr(t.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("auth.permission_denied",`${r} 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.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Yr(l),m=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 \`${he()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${he()}\` with \`--scopes ${l}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${m}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${he()}\`) and grant the required scope.`,i)}function la(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var ca="/api/secure/graphql";async function Xr(e,t){t.showDoc&&process.stderr.write(`${t.document}
60
- `);let r=await Ze(e).request({method:"POST",path:ca,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});Jr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var ua=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,da=/^0(?:\.0+)?$/,Zt=128;function Vr(e,t,n={}){if(t.length>Zt)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Zt} characters.`);let r=t.trim();if(!ua.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&da.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Zr(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function ue(e,t){let n=l=>{if(typeof l!="string"||l.length>Zt||!/^\d+(?:\.\d+)?$/.test(l))return null;let[d,p=""]=l.split(".");return{whole:d.replace(/^0+(?=\d)/,""),fraction:p.replace(/0+$/,"")}},r=n(e),i=n(t);if(!r||!i)return null;if(r.whole.length!==i.whole.length)return r.whole.length<i.whole.length?-1:1;if(r.whole!==i.whole)return r.whole<i.whole?-1:1;let o=Math.max(r.fraction.length,i.fraction.length),s=r.fraction.padEnd(o,"0"),c=i.fraction.padEnd(o,"0");return s===c?0:s<c?-1:1}function Ie(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new a("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}var pa=`query claim_link_funding_by_idempotency_key($idempotency_key: String!) {
57
+ `),{result_data:n.result_data}}async function Js(e,t,n,r){if(t==="ack"){_({type:"bridge_result_received",source:"paste"});let o=await Jt(e,n);return _({type:"bridge_verified",op_id:o.op_id,source:"paste"}),A.stderr.write(`Verified by broker.
58
+ `),{ack:o}}let i;try{i=Xs(n,{acceptBareTxHashPaste:r})}catch(o){throw o instanceof a&&o.code==="input.invalid"?new a("wallet.bridge_invalid_response",o.message):o}return _({type:"bridge_result_received",source:"paste"}),_({type:"bridge_data_received",source:"paste"}),A.stderr.write(`Result accepted.
59
+ `),{result_data:i}}function zs(e,t){let n=new URL("/cli",Mr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}function Xs(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&ce.test(e))return{tx_hash:e};throw new a("input.invalid",t.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 Vs(e){return Mr(e).origin}function Mr(e){if(!ee(e))throw new a("input.invalid",`Refusing browser base ${O(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${fe}`);return new URL(e)}var Zs=new Set;var Qs=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"]),Xt=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"]),Vt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Qe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Gr(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var ea=new Set(["cli_op:all"]),ta=new Set([...ea].map(Qe));var ou=new Set([...[...Qs,...Xt,...Zs].map(Qe),...Vt,...ta]);var na={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"},ra={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"},ia=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,oa=/is not available to API keys/i,Kr=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Hr(e){if(typeof e!="string")return;let t=ia.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=oa.test(n),o=!i&&Kr.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(l=>l.trim()).filter(l=>Kr.test(l));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function jr(e){let t=ra[e];if(t!==void 0)return{ungrantableReason:t};let n=na[e];if(n!==void 0)return{scope:n}}function Yr(e){if(Vt.has(Qe(e)))return{kind:"ungrantable"};for(let t of Xt)if(Gr(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function qr(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Wr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var Zt=8100,sa=new Set([Zt]),aa=new Set([...sa,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 zr(e,t){let n=Xr(e),r={graphql_error_count:la(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw ca(e,t,r);if(n===429)throw new a("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new a("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&aa.has(n))throw new a("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(qr(e))throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Wr(e)}`,r);if(n!==void 0)throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function Xr(e){let t=Jr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=Jr(r.code);if(i!==void 0)return i}}function Jr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function la(e){return Array.isArray(e)?e.length:e==null?0:1}function ca(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Hr(ua(e,Xr(e))),s=jr(t.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("auth.permission_denied",`${r} 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.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Yr(l),m=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 \`${ge()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${ge()}\` with \`--scopes ${l}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${m}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${ge()}\`) and grant the required scope.`,i)}function ua(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var da="/api/secure/graphql";async function Vr(e,t){t.showDoc&&process.stderr.write(`${t.document}
60
+ `);let r=await Ze(e).request({method:"POST",path:da,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});zr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var pa=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,fa=/^0(?:\.0+)?$/,Qt=128;function Zr(e,t,n={}){if(t.length>Qt)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Qt} characters.`);let r=t.trim();if(!pa.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&fa.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Qr(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function ue(e,t){let n=l=>{if(typeof l!="string"||l.length>Qt||!/^\d+(?:\.\d+)?$/.test(l))return null;let[d,p=""]=l.split(".");return{whole:d.replace(/^0+(?=\d)/,""),fraction:p.replace(/0+$/,"")}},r=n(e),i=n(t);if(!r||!i)return null;if(r.whole.length!==i.whole.length)return r.whole.length<i.whole.length?-1:1;if(r.whole!==i.whole)return r.whole<i.whole?-1:1;let o=Math.max(r.fraction.length,i.fraction.length),s=r.fraction.padEnd(o,"0"),c=i.fraction.padEnd(o,"0");return s===c?0:s<c?-1:1}function Ce(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new a("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}var ma=`query claim_link_funding_by_idempotency_key($idempotency_key: String!) {
61
61
  claim_link_funding_by_idempotency_key(idempotency_key: $idempotency_key) {
62
62
  claim_link {
63
63
  id
@@ -74,5 +74,5 @@ the ${D} the page shows, paste it here, and press Enter:
74
74
  claim_url
75
75
  claim_window_seconds
76
76
  }
77
- }`,Qr={1:"PENDING_DEPOSIT",2:"LINK_SENT",3:"CLAIMING",4:"CLAIMED",5:"EXPIRED",6:"CANCELLED"},fa=new Set(Object.values(Qr)),ma=new Set(["EXPIRED","CANCELLED"]),ga=new Set(["outcome","phase","claim_link_id","funding_tx_hash"]),ha=new Set(["completed","cancelled","ambiguous"]),_a=new Set(["pre_create","creating","created","signed","broadcast","settling","funded"]),wa=new Set(["creating","created","signed","broadcast","settling"]),ya=new Set(["created","signed","broadcast","settling","funded"]),ei=/^[A-Za-z0-9_-]{1,128}$/,ba=/^[A-Za-z0-9_-]{16,256}$/,ka=2048,Sa=16,Ea=/^\/(?:claim\/[A-Za-z0-9_-]{16,256}|s\/[A-Za-z0-9_-]{1,128})$/,Aa=2e3,La=500;function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ta(e,t){if(typeof e!="string"||!ei.test(e))throw new a("backend.internal",`${t} returned a malformed Claim Link id.`);return e}function Ia(e,t){if(typeof e!="string"||!ba.test(e))throw new a("backend.internal",`${t} returned a malformed claim token.`);return e}function Ca(e){if(typeof e=="number"&&Number.isInteger(e)){let t=Qr[e];if(t!==void 0)return t}if(typeof e=="string"){let t=e.trim().toUpperCase().replace(/-/g,"_");if(fa.has(t))return t}throw new a("backend.internal","Claim Link funding lookup returned an unknown lifecycle status.")}function Oa(e,t){if(e==null)return null;if(typeof e!="string"||!ce.test(e))throw new a("backend.internal",`${t} returned a malformed funding transaction hash.`);return e}function Ra(e,t){if(e==null)return null;if(typeof e!="string"||e.length===0||e.length>ka||e.trim()!==e)throw new a("backend.internal",`${t} returned a malformed Claim Link URL.`);return e}function va(e){if(typeof e!="string"||e.trim()!==e||ue(e,e)===null)throw new a("backend.internal","Claim Link funding lookup returned a malformed amount.");return e}function Na(e){if(typeof e!="string"||e.length===0||e.length>Sa||!/^[A-Za-z0-9]+$/.test(e))throw new a("backend.internal","Claim Link funding lookup returned a malformed token symbol.");return e}function xa(e){if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed chain.");return e}function Qt(e,t,n){if(e===null)return null;if(typeof e!="string"||e.length>n)throw new a("backend.internal",`Claim Link funding lookup returned a malformed ${t}.`);return e}function Pa(e){if(e===null)return null;if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed claim window.");return e}function Ba(e,t,n){let r;try{r=new URL(e)}catch{throw new a("backend.internal",`${n} returned a malformed Claim Link URL.`)}let i=new URL(t).origin;if(r.origin!==i||r.username.length>0||r.password.length>0||r.search.length>0||r.hash.length>0||!Ea.test(r.pathname))throw new a("backend.internal",`${n} returned a Claim Link URL outside the configured API origin or supported claim routes.`);return r.toString()}function Da(e){if(e==null)return null;if(!en(e)||!en(e.claim_link))throw new a("backend.internal","Claim Link funding lookup returned a malformed result.");return{claimLinkId:Ta(e.claim_link.id,"Claim Link funding lookup"),status:Ca(e.claim_link.status),amount:va(e.claim_link.amount),tokenSymbol:Na(e.claim_link.token_symbol),chain:xa(e.claim_link.chain),receiverEmail:Qt(e.claim_link.receiver_email,"receiver email",254),senderDisplayName:Qt(e.claim_link.sender_display_name,"sender display name",100),senderMessage:Qt(e.claim_link.sender_message,"sender message",200),claimWindowSeconds:Pa(e.claim_window_seconds),claimToken:Ia(e.claim_token,"Claim Link funding lookup"),claimUrl:Ra(e.claim_url,"Claim Link funding lookup"),fundingTxHash:Oa(e.claim_link.funded_tx_hash,"Claim Link funding lookup")}}function $a(e,t){let n=[];ue(e.amount,t.amount)!==0&&n.push("amount"),e.tokenSymbol.toUpperCase()!==Kn(t.stable_coin).toUpperCase()&&n.push("stable_coin"),e.chain!==t.chain&&n.push("chain");let r=i=>{let o=i?.trim()??"";return o.length===0?null:o};return r(e.receiverEmail)?.toLowerCase()!==r(t.receiver_email)?.toLowerCase()&&n.push("receiver_email"),r(e.senderDisplayName)!==r(t.sender_display_name)&&n.push("sender_display_name"),r(e.senderMessage)!==r(t.sender_message)&&n.push("sender_message"),e.claimWindowSeconds!==t.claim_window_seconds&&n.push("claim_window_seconds"),n}function et(e,t,n){let r=$a(e,t);if(r.length===0)return;let i={idempotency_key:t.idempotency_key,claim_link_id:e.claimLinkId,status:e.status,intent_conflict:!0,mismatched_fields:r,retry_with_same_idempotency_key:!1};throw n?new a("claim_link.funding_ambiguous","The authoritative Claim Link bound to this idempotency key does not match the requested intent after browser authorization may have started. Do not retry automatically, fund the returned link, or use a new key; inspect the existing operation manually.",{outcome_ambiguous:!0,...i}):new a("claim_link.intent_conflict","This idempotency key is already bound to different Claim Link terms. The browser was not opened and the existing link was not funded by this command. Re-run with the original terms or choose a new key only for an intentional new link.",i)}async function Ua(e,t){let n=await Xr(e,{kind:"query",operationName:"claim_link_funding_by_idempotency_key",document:pa,variables:{idempotency_key:t}});return Da(n)}function Fa(e){if(e==null)return null;if(typeof e!="string"||!ei.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Ma(e){if(e==null)return null;if(typeof e!="string"||!ce.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Ga(e){if(!en(e)||Object.keys(e).some(s=>!ga.has(s))||typeof e.outcome!="string"||!ha.has(e.outcome)||typeof e.phase!="string"||!_a.has(e.phase))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");let t=e.outcome,n=e.phase,r=Fa(e.claim_link_id),i=Ma(e.funding_tx_hash);if(!(t==="completed"&&n==="funded"&&r!==null||t==="cancelled"&&n==="pre_create"&&r===null&&i===null||t==="ambiguous"&&wa.has(n)&&(!ya.has(n)||r!==null)))throw new a("wallet.bridge_invalid_response","Browser returned an inconsistent Claim Link receipt.");return{outcome:t,phase:n,claimLinkId:r,fundingTxHash:i}}function tt(e,t,n){if(e.status==="PENDING_DEPOSIT")throw new Error("PENDING_DEPOSIT cannot be rendered as a success");if(ti(e))throw tn(n,e,null);let r;try{let i=e.claimUrl??new URL(`/claim/${encodeURIComponent(e.claimToken)}`,t).toString();r=Ba(i,t,"Claim Link funding lookup")}catch{throw new a("backend.internal","Claim Link funding is authoritative, but the lookup returned an untrusted or malformed claim URL. Do not create another link or use a new idempotency key; re-run only with exactly the same --idempotency-key after the service recovers.",{funding_authoritative:!0,idempotency_key:n,claim_link_id:e.claimLinkId,funding_tx_hash:e.fundingTxHash,status:e.status,retry_with_same_idempotency_key:!0})}return{claim_link_id:e.claimLinkId,claim_url:r,status:e.status,...e.fundingTxHash===null?{}:{funding_tx_hash:e.fundingTxHash}}}function ti(e){return ma.has(e.status)&&(e.fundingTxHash===null||!ce.test(e.fundingTxHash))}function Ka(e,t,n){let i=!(t!==null&&ti(t))&&(t===null||n?.claimLinkId===t.claimLinkId)?n:null;return{outcome_ambiguous:!0,idempotency_key:e,claim_link_id:t?.claimLinkId??i?.claimLinkId??null,funding_tx_hash:t===null?i?.fundingTxHash??null:t.fundingTxHash,phase:i?.phase??(t===null?"unknown":"created"),status:t?.status??null,retry_with_same_idempotency_key:!0}}function tn(e,t,n){return new a("claim_link.funding_ambiguous","Claim Link funding is not authoritatively proven complete. Funds may have been signed or broadcast, or a terminal state may lack a validated funding transaction hash. Re-run this command only with exactly the same --idempotency-key so it reconciles the existing operation; do not use a new key or create another link.",Ka(e,t,n))}function Ha(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener("abort",i),n(!0)},e);r.unref?.();let i=()=>{clearTimeout(r),n(!1)};t.addEventListener("abort",i,{once:!0})})}function Ya(e){return new Promise(t=>setTimeout(t,e))}async function ja(e,t,n){let r=Math.max(1,e._pollIntervalMs??Aa);for(;await Ha(r,n)&&!n.aborted;)try{let i=await t(e.ctx,e.intent.idempotency_key);if(i!==null&&i.status!=="PENDING_DEPOSIT")return i}catch{}return null}async function ni(e){let t=e._fetchFunding??Ua,n=e._runBridge??Ur,r=e.intent.idempotency_key,i=await t(e.ctx,r);if(i!==null&&et(i,e.intent,!1),i!==null&&i.status!=="PENDING_DEPOSIT")return tt(i,e.ctx.apiBase,r);let o,s=new AbortController,c=!1,l=new AbortController,d=n({ctx:e.ctx,op:"create_claim_link",mode:"data",payload:{...e.intent},timeoutMs:e.timeoutMs,browserBase:e.browserBase,autoOpen:e.autoOpen,signal:s.signal}).then(h=>(c=!0,{kind:"bridge",result:h}),h=>(c=!0,{kind:"bridge_error",error:h})),p=ja(e,t,l.signal).then(h=>({kind:"funding",record:h}));try{let h=await Promise.race([d,p]);if(h.kind==="funding"){if(h.record===null)throw new Error("Authoritative funding poll stopped unexpectedly.");et(h.record,e.intent,!0);let b=Math.max(0,e._bridgeCallbackGraceMs??La);return await Promise.race([d.then(()=>!0),Ya(b).then(()=>!1)])||s.abort(),tt(h.record,e.ctx.apiBase,r)}if(l.abort(),h.kind==="bridge_error")throw h.error;o=h.result}catch(h){if(l.abort(),!(h instanceof a)||!jn(h.code))throw h;let b=null;try{b=await t(e.ctx,r)}catch{}if(b!==null&&et(b,e.intent,!0),b!==null&&b.status!=="PENDING_DEPOSIT")return tt(b,e.ctx.apiBase,r);throw tn(r,b,null)}finally{l.abort(),c||s.abort()}let f=null;try{f=Ga(o.result_data)}catch{}let m=null,g=!1;try{m=await t(e.ctx,r),g=!0}catch{}if(m!==null&&et(m,e.intent,!0),m!==null&&m.status!=="PENDING_DEPOSIT")return tt(m,e.ctx.apiBase,r);throw f?.outcome==="cancelled"&&f.phase==="pre_create"&&g&&m===null?new a("claim_link.browser_cancelled","Claim Link creation was cancelled in the browser before a link was created.",{idempotency_key:r,claim_link_id:null,phase:"pre_create",status:null,retry_with_same_idempotency_key:!0}):tn(r,m,f)}var ri="0.1",ii="10000",qa=6,Wa=60n,Ja=30n*24n*60n*60n,oi=336*60*60,si="14d",za="between 1m and 30d (inclusive)",Xa=/^(\d+)\s*([dhm])$/i,Va=32,Za=/^[a-zA-Z0-9_'^&+%-]+(?:\.[a-zA-Z0-9_'^&+%-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/i;function ai(e){if(e.length>Va)throw new a("input.invalid","--expires is too long; expected a duration like 14d, 24h, or 90m.");let t=Xa.exec(e.trim());if(!t)throw new a("input.invalid",`--expires must be a duration like 14d, 24h, or 90m (units: d/h/m); got '${e}'.`);let n=BigInt(t[1]),r=t[2].toLowerCase(),o=n*(r==="d"?86400n:r==="h"?3600n:60n);if(o<Wa||o>Ja)throw new a("input.invalid",`--expires must be ${za}; got '${e}'.`);return{seconds:Number(o),label:`${n}${r}`}}function li(e){let t=Zr("--amount",Vr("--amount",e),qa),n=ue(t,ri),r=ue(t,ii);if(n===null||r===null)throw new a("input.invalid",`--amount is not a supported decimal value: '${e}'.`);if(n<0)throw new a("input.invalid",`--amount must be at least ${ri}; got '${t}'.`);if(r>0)throw new a("input.invalid",`--amount must not exceed ${ii}; got '${t}'.`);let[i,o]=t.split("."),s=o?.replace(/0+$/,"")??"";return s.length===0?i:`${i}.${s}`}function ci(e){let t=Ie("--receiver-email",e,254);if(t===void 0)return null;if(!Za.test(t))throw new a("input.invalid","--receiver-email is not a valid email address.");return t}var Qa=11,ui=[...Fn,...pe],el=pe.length>0,di=el?"EVM chain for the Claim Link. sepolia is a testnet (Ethereum Sepolia); the browser ceremony accepts it only on environments with testnets enabled.":"EVM chain for the Claim Link.";function pi(e){let t=e.toLowerCase();return t==="sepolia"&&pe.includes(t)?Qa:Mn(t)}var tl=require("crypto");var fi=128;function mi(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>fi)throw new a("input.invalid",`--idempotency-key must contain 1-${fi} characters after trimming.`);return t}var nt=class e extends Se{static description="Create and fund a fixed-intent Claim Link in one browser authorization ceremony, then confirm the authoritative lifecycle state. Requires claim_link:all for an agent-key session.";static examples=["$ allscale claim-link create --idempotency-key order-1042 --amount 10 --chain base","$ allscale claim-link create --idempotency-key order-1043 --amount 25.50 --stable-coin USDC --chain polygon --expires 7d --message 'Invoice 1043'","$ allscale claim-link create --idempotency-key order-1044 --amount 5 --chain base --receiver-email client@example.com --sender-display-name 'Acme' --no-browser"];static flags={amount:C.Flags.string({helpGroup:"REQUIRED",description:"Exact amount the receiver can claim, as a decimal string. Range 0.1-10000; at most 6 effective decimal places. The CLI never rounds it.",required:!0}),chain:C.Flags.string({helpGroup:"REQUIRED",description:di,options:[...ui],required:!0}),"idempotency-key":C.Flags.string({helpGroup:"REQUIRED",description:"Required stable key for this logical Claim Link create/fund operation (1-128 characters). Reuse it after an ambiguous result; use a new key only for an intentional second link.",required:!0}),"stable-coin":C.Flags.string({description:"Stablecoin for the Claim Link.",options:[...Me],default:"USDT"}),"receiver-email":C.Flags.string({description:"Optional sender-only receiver label. AllScale does not email the receiver; you still share the resulting link yourself."}),"sender-display-name":C.Flags.string({description:"Optional sender name shown to the receiver. Max 100 characters."}),message:C.Flags.string({description:"Optional purpose/message shown on the Claim Link page. Max 200 characters."}),expires:C.Flags.string({description:"Claim window as a duration using m/h/d (1m-30d). The window starts after funding confirms.",default:si}),"bridge-timeout":C.Flags.integer({description:"Shorten the browser confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life. It can only shorten the wait \u2014 a value above that is clamped to it, because the confirmation link cannot outlive its broker op. If the server's response carries no timestamp to measure that life against, the CLI says so on stderr and bounds the wait instead: with no --bridge-timeout this receipt-aware flow waits up to 240s and may be shortened by the best-effort bound from the stated expiry; an explicit value is honoured up to that same bound (clamped to 60s-15min), or 15min when the expiry itself is unreadable.",min:1e3}),"browser-base":C.Flags.string({description:"Override the trusted base URL of the printed /cli bridge link (defaults to the session API base)."}),"no-browser":C.Flags.boolean({description:"Do not auto-open a local browser. The command still prints the bridge URL and waits for its callback or a pasted receipt.",default:!1}),...Se.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=mi(t["idempotency-key"]);if(n===void 0)throw new a("input.invalid","--idempotency-key is required for Claim Link reconciliation.");let r=pi(t.chain);if(r===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let i=Gn(t["stable-coin"]);if(i===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);let o=ai(t.expires),s={idempotency_key:n,amount:li(t.amount),chain:r,stable_coin:i,receiver_email:ci(t["receiver-email"]),sender_display_name:Ie("--sender-display-name",t["sender-display-name"],100)??null,sender_message:Ie("--message",t.message,200)??null,claim_window_seconds:o.seconds===oi?null:o.seconds},c=this.resolveContext(t);return ni({ctx:c,intent:s,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],autoOpen:!t["no-browser"]})}};
77
+ }`,ei={1:"PENDING_DEPOSIT",2:"LINK_SENT",3:"CLAIMING",4:"CLAIMED",5:"EXPIRED",6:"CANCELLED"},ha=new Set(Object.values(ei)),ga=new Set(["EXPIRED","CANCELLED"]),_a=new Set(["outcome","phase","claim_link_id","funding_tx_hash"]),wa=new Set(["completed","cancelled","ambiguous"]),ya=new Set(["pre_create","creating","created","signed","broadcast","settling","funded"]),ba=new Set(["creating","created","signed","broadcast","settling"]),ka=new Set(["created","signed","broadcast","settling","funded"]),ti=/^[A-Za-z0-9_-]{1,128}$/,Ea=/^[A-Za-z0-9_-]{16,256}$/,Sa=2048,Aa=16,La=/^\/(?:claim\/[A-Za-z0-9_-]{16,256}|s\/[A-Za-z0-9_-]{1,128})$/,Ta=2e3,Ca=500;function tn(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ia(e,t){if(typeof e!="string"||!ti.test(e))throw new a("backend.internal",`${t} returned a malformed Claim Link id.`);return e}function Oa(e,t){if(typeof e!="string"||!Ea.test(e))throw new a("backend.internal",`${t} returned a malformed claim token.`);return e}function Ra(e){if(typeof e=="number"&&Number.isInteger(e)){let t=ei[e];if(t!==void 0)return t}if(typeof e=="string"){let t=e.trim().toUpperCase().replace(/-/g,"_");if(ha.has(t))return t}throw new a("backend.internal","Claim Link funding lookup returned an unknown lifecycle status.")}function va(e,t){if(e==null)return null;if(typeof e!="string"||!ce.test(e))throw new a("backend.internal",`${t} returned a malformed funding transaction hash.`);return e}function Na(e,t){if(e==null)return null;if(typeof e!="string"||e.length===0||e.length>Sa||e.trim()!==e)throw new a("backend.internal",`${t} returned a malformed Claim Link URL.`);return e}function xa(e){if(typeof e!="string"||e.trim()!==e||ue(e,e)===null)throw new a("backend.internal","Claim Link funding lookup returned a malformed amount.");return e}function Pa(e){if(typeof e!="string"||e.length===0||e.length>Aa||!/^[A-Za-z0-9]+$/.test(e))throw new a("backend.internal","Claim Link funding lookup returned a malformed token symbol.");return e}function Ba(e){if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed chain.");return e}function en(e,t,n){if(e===null)return null;if(typeof e!="string"||e.length>n)throw new a("backend.internal",`Claim Link funding lookup returned a malformed ${t}.`);return e}function Da(e){if(e===null)return null;if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed claim window.");return e}function $a(e,t,n){let r;try{r=new URL(e)}catch{throw new a("backend.internal",`${n} returned a malformed Claim Link URL.`)}let i=new URL(t).origin;if(r.origin!==i||r.username.length>0||r.password.length>0||r.search.length>0||r.hash.length>0||!La.test(r.pathname))throw new a("backend.internal",`${n} returned a Claim Link URL outside the configured API origin or supported claim routes.`);return r.toString()}function Ua(e){if(e==null)return null;if(!tn(e)||!tn(e.claim_link))throw new a("backend.internal","Claim Link funding lookup returned a malformed result.");return{claimLinkId:Ia(e.claim_link.id,"Claim Link funding lookup"),status:Ra(e.claim_link.status),amount:xa(e.claim_link.amount),tokenSymbol:Pa(e.claim_link.token_symbol),chain:Ba(e.claim_link.chain),receiverEmail:en(e.claim_link.receiver_email,"receiver email",254),senderDisplayName:en(e.claim_link.sender_display_name,"sender display name",100),senderMessage:en(e.claim_link.sender_message,"sender message",200),claimWindowSeconds:Da(e.claim_window_seconds),claimToken:Oa(e.claim_token,"Claim Link funding lookup"),claimUrl:Na(e.claim_url,"Claim Link funding lookup"),fundingTxHash:va(e.claim_link.funded_tx_hash,"Claim Link funding lookup")}}function Fa(e,t){let n=[];ue(e.amount,t.amount)!==0&&n.push("amount"),e.tokenSymbol.toUpperCase()!==Hn(t.stable_coin).toUpperCase()&&n.push("stable_coin"),e.chain!==t.chain&&n.push("chain");let r=i=>{let o=i?.trim()??"";return o.length===0?null:o};return r(e.receiverEmail)?.toLowerCase()!==r(t.receiver_email)?.toLowerCase()&&n.push("receiver_email"),r(e.senderDisplayName)!==r(t.sender_display_name)&&n.push("sender_display_name"),r(e.senderMessage)!==r(t.sender_message)&&n.push("sender_message"),e.claimWindowSeconds!==t.claim_window_seconds&&n.push("claim_window_seconds"),n}function et(e,t,n){let r=Fa(e,t);if(r.length===0)return;let i={idempotency_key:t.idempotency_key,claim_link_id:e.claimLinkId,status:e.status,intent_conflict:!0,mismatched_fields:r,retry_with_same_idempotency_key:!1};throw n?new a("claim_link.funding_ambiguous","The authoritative Claim Link bound to this idempotency key does not match the requested intent after browser authorization may have started. Do not retry automatically, fund the returned link, or use a new key; inspect the existing operation manually.",{outcome_ambiguous:!0,...i}):new a("claim_link.intent_conflict","This idempotency key is already bound to different Claim Link terms. The browser was not opened and the existing link was not funded by this command. Re-run with the original terms or choose a new key only for an intentional new link.",i)}async function Ma(e,t){let n=await Vr(e,{kind:"query",operationName:"claim_link_funding_by_idempotency_key",document:ma,variables:{idempotency_key:t}});return Ua(n)}function Ga(e){if(e==null)return null;if(typeof e!="string"||!ti.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Ka(e){if(e==null)return null;if(typeof e!="string"||!ce.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Ha(e){if(!tn(e)||Object.keys(e).some(s=>!_a.has(s))||typeof e.outcome!="string"||!wa.has(e.outcome)||typeof e.phase!="string"||!ya.has(e.phase))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");let t=e.outcome,n=e.phase,r=Ga(e.claim_link_id),i=Ka(e.funding_tx_hash);if(!(t==="completed"&&n==="funded"&&r!==null||t==="cancelled"&&n==="pre_create"&&r===null&&i===null||t==="ambiguous"&&ba.has(n)&&(!ka.has(n)||r!==null)))throw new a("wallet.bridge_invalid_response","Browser returned an inconsistent Claim Link receipt.");return{outcome:t,phase:n,claimLinkId:r,fundingTxHash:i}}function tt(e,t,n){if(e.status==="PENDING_DEPOSIT")throw new Error("PENDING_DEPOSIT cannot be rendered as a success");if(ni(e))throw nn(n,e,null);let r;try{let i=e.claimUrl??new URL(`/claim/${encodeURIComponent(e.claimToken)}`,t).toString();r=$a(i,t,"Claim Link funding lookup")}catch{throw new a("backend.internal","Claim Link funding is authoritative, but the lookup returned an untrusted or malformed claim URL. Do not create another link or use a new idempotency key; re-run only with exactly the same --idempotency-key after the service recovers.",{funding_authoritative:!0,idempotency_key:n,claim_link_id:e.claimLinkId,funding_tx_hash:e.fundingTxHash,status:e.status,retry_with_same_idempotency_key:!0})}return{claim_link_id:e.claimLinkId,claim_url:r,status:e.status,...e.fundingTxHash===null?{}:{funding_tx_hash:e.fundingTxHash}}}function ni(e){return ga.has(e.status)&&(e.fundingTxHash===null||!ce.test(e.fundingTxHash))}function ja(e,t,n){let i=!(t!==null&&ni(t))&&(t===null||n?.claimLinkId===t.claimLinkId)?n:null;return{outcome_ambiguous:!0,idempotency_key:e,claim_link_id:t?.claimLinkId??i?.claimLinkId??null,funding_tx_hash:t===null?i?.fundingTxHash??null:t.fundingTxHash,phase:i?.phase??(t===null?"unknown":"created"),status:t?.status??null,retry_with_same_idempotency_key:!0}}function nn(e,t,n){return new a("claim_link.funding_ambiguous","Claim Link funding is not authoritatively proven complete. Funds may have been signed or broadcast, or a terminal state may lack a validated funding transaction hash. Re-run this command only with exactly the same --idempotency-key so it reconciles the existing operation; do not use a new key or create another link.",ja(e,t,n))}function Ya(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener("abort",i),n(!0)},e);r.unref?.();let i=()=>{clearTimeout(r),n(!1)};t.addEventListener("abort",i,{once:!0})})}function qa(e){return new Promise(t=>setTimeout(t,e))}async function Wa(e,t,n){let r=Math.max(1,e._pollIntervalMs??Ta);for(;await Ya(r,n)&&!n.aborted;)try{let i=await t(e.ctx,e.intent.idempotency_key);if(i!==null&&i.status!=="PENDING_DEPOSIT")return i}catch{}return null}async function ri(e){let t=e._fetchFunding??Ma,n=e._runBridge??Fr,r=e.intent.idempotency_key,i=await t(e.ctx,r);if(i!==null&&et(i,e.intent,!1),i!==null&&i.status!=="PENDING_DEPOSIT")return tt(i,e.ctx.apiBase,r);let o,s=new AbortController,c=!1,l=new AbortController,d=n({ctx:e.ctx,op:"create_claim_link",mode:"data",payload:{...e.intent},timeoutMs:e.timeoutMs,browserBase:e.browserBase,autoOpen:e.autoOpen,signal:s.signal}).then(g=>(c=!0,{kind:"bridge",result:g}),g=>(c=!0,{kind:"bridge_error",error:g})),p=Wa(e,t,l.signal).then(g=>({kind:"funding",record:g}));try{let g=await Promise.race([d,p]);if(g.kind==="funding"){if(g.record===null)throw new Error("Authoritative funding poll stopped unexpectedly.");et(g.record,e.intent,!0);let b=Math.max(0,e._bridgeCallbackGraceMs??Ca);return await Promise.race([d.then(()=>!0),qa(b).then(()=>!1)])||s.abort(),tt(g.record,e.ctx.apiBase,r)}if(l.abort(),g.kind==="bridge_error")throw g.error;o=g.result}catch(g){if(l.abort(),!(g instanceof a)||!qn(g.code))throw g;let b=null;try{b=await t(e.ctx,r)}catch{}if(b!==null&&et(b,e.intent,!0),b!==null&&b.status!=="PENDING_DEPOSIT")return tt(b,e.ctx.apiBase,r);throw nn(r,b,null)}finally{l.abort(),c||s.abort()}let f=null;try{f=Ha(o.result_data)}catch{}let m=null,h=!1;try{m=await t(e.ctx,r),h=!0}catch{}if(m!==null&&et(m,e.intent,!0),m!==null&&m.status!=="PENDING_DEPOSIT")return tt(m,e.ctx.apiBase,r);throw f?.outcome==="cancelled"&&f.phase==="pre_create"&&h&&m===null?new a("claim_link.browser_cancelled","Claim Link creation was cancelled in the browser before a link was created.",{idempotency_key:r,claim_link_id:null,phase:"pre_create",status:null,retry_with_same_idempotency_key:!0}):nn(r,m,f)}var ii="0.1",oi="10000",Ja=6,za=60n,Xa=30n*24n*60n*60n,si=336*60*60,ai="14d",Va="between 1m and 30d (inclusive)",Za=/^(\d+)\s*([dhm])$/i,Qa=32,el=/^[a-zA-Z0-9_'^&+%-]+(?:\.[a-zA-Z0-9_'^&+%-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/i;function li(e){if(e.length>Qa)throw new a("input.invalid","--expires is too long; expected a duration like 14d, 24h, or 90m.");let t=Za.exec(e.trim());if(!t)throw new a("input.invalid",`--expires must be a duration like 14d, 24h, or 90m (units: d/h/m); got '${e}'.`);let n=BigInt(t[1]),r=t[2].toLowerCase(),o=n*(r==="d"?86400n:r==="h"?3600n:60n);if(o<za||o>Xa)throw new a("input.invalid",`--expires must be ${Va}; got '${e}'.`);return{seconds:Number(o),label:`${n}${r}`}}function ci(e){let t=Qr("--amount",Zr("--amount",e),Ja),n=ue(t,ii),r=ue(t,oi);if(n===null||r===null)throw new a("input.invalid",`--amount is not a supported decimal value: '${e}'.`);if(n<0)throw new a("input.invalid",`--amount must be at least ${ii}; got '${t}'.`);if(r>0)throw new a("input.invalid",`--amount must not exceed ${oi}; got '${t}'.`);let[i,o]=t.split("."),s=o?.replace(/0+$/,"")??"";return s.length===0?i:`${i}.${s}`}function ui(e){let t=Ce("--receiver-email",e,254);if(t===void 0)return null;if(!el.test(t))throw new a("input.invalid","--receiver-email is not a valid email address.");return t}var tl=11,di=[...Mn,...pe],nl=pe.length>0,pi=nl?"EVM chain for the Claim Link. sepolia is a testnet (Ethereum Sepolia); the browser ceremony accepts it only on environments with testnets enabled.":"EVM chain for the Claim Link.";function fi(e){let t=e.toLowerCase();return t==="sepolia"&&pe.includes(t)?tl:Gn(t)}var rl=require("crypto");var mi=128;function hi(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>mi)throw new a("input.invalid",`--idempotency-key must contain 1-${mi} characters after trimming.`);return t}var nt=class e extends Ee{static description="Create and fund a fixed-intent Claim Link in one browser authorization ceremony, then confirm the authoritative lifecycle state. Requires claim_link:all for an agent-key session.";static examples=["$ allscale claim-link create --idempotency-key order-1042 --amount 10 --chain base","$ allscale claim-link create --idempotency-key order-1043 --amount 25.50 --stable-coin USDC --chain polygon --expires 7d --message 'Invoice 1043'","$ allscale claim-link create --idempotency-key order-1044 --amount 5 --chain base --receiver-email client@example.com --sender-display-name 'Acme' --no-browser"];static flags={amount:I.Flags.string({helpGroup:"REQUIRED",description:"Exact amount the receiver can claim, as a decimal string. Range 0.1-10000; at most 6 effective decimal places. The CLI never rounds it.",required:!0}),chain:I.Flags.string({helpGroup:"REQUIRED",description:pi,options:[...di],required:!0}),"idempotency-key":I.Flags.string({helpGroup:"REQUIRED",description:"Required stable key for this logical Claim Link create/fund operation (1-128 characters). Reuse it after an ambiguous result; use a new key only for an intentional second link.",required:!0}),"stable-coin":I.Flags.string({description:"Stablecoin for the Claim Link.",options:[...Me],default:"USDT"}),"receiver-email":I.Flags.string({description:"Optional sender-only receiver label. AllScale does not email the receiver; you still share the resulting link yourself."}),"sender-display-name":I.Flags.string({description:"Optional sender name shown to the receiver. Max 100 characters."}),message:I.Flags.string({description:"Optional purpose/message shown on the Claim Link page. Max 200 characters."}),expires:I.Flags.string({description:"Claim window as a duration using m/h/d (1m-30d). The window starts after funding confirms.",default:ai}),"bridge-timeout":I.Flags.integer({description:"Shorten the browser confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life. It can only shorten the wait \u2014 a value above that is clamped to it, because the confirmation link cannot outlive its broker op. If the server's response carries no timestamp to measure that life against, the CLI says so on stderr and bounds the wait instead: with no --bridge-timeout this receipt-aware flow waits up to 240s and may be shortened by the best-effort bound from the stated expiry; an explicit value is honoured up to that same bound (clamped to 60s-15min), or 15min when the expiry itself is unreadable.",min:1e3}),"browser-base":I.Flags.string({description:"Override the trusted base URL of the printed /cli bridge link (defaults to the session API base)."}),"no-browser":I.Flags.boolean({description:"Do not auto-open a local browser. The command still prints the bridge URL and waits for its callback or a pasted receipt.",default:!1}),...Ee.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=hi(t["idempotency-key"]);if(n===void 0)throw new a("input.invalid","--idempotency-key is required for Claim Link reconciliation.");let r=fi(t.chain);if(r===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let i=Kn(t["stable-coin"]);if(i===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);let o=li(t.expires),s={idempotency_key:n,amount:ci(t.amount),chain:r,stable_coin:i,receiver_email:ui(t["receiver-email"]),sender_display_name:Ce("--sender-display-name",t["sender-display-name"],100)??null,sender_message:Ce("--message",t.message,200)??null,claim_window_seconds:o.seconds===si?null:o.seconds},c=this.resolveContext(t);return ri({ctx:c,intent:s,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],autoOpen:!t["no-browser"]})}};
78
78
  //# sourceMappingURL=create.js.map