@allscale/cli 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- "use strict";var Qn=Object.create;var ce=Object.defineProperty;var er=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var nr=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var or=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:!0})},It=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tr(t))!rr.call(e,o)&&o!==n&&ce(e,o,{get:()=>t[o],enumerable:!(r=er(t,o))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Qn(nr(e)):{},It(t||!e||!e.__esModule?ce(n,"default",{value:e,enumerable:!0}):n,e)),ir=e=>It(ce({},"__esModule",{value:!0}),e);var _i={};or(_i,{default:()=>Re});module.exports=ir(_i);var I=require("@oclif/core");var Ot="public",vt="https://app.allscale.io";var Ct=["https://app.allscale.io"];var Pe="Override the API base URL (public builds accept only https://app.allscale.io)";var Be="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Rt(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 Nt(e){return Rt(e)!==null}function $e(e){let t=Rt(e);return t!==null&&Ct.includes(t.origin)}function J(){return"".trim()||void 0}function v(){return"public"}function x(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Ue(e){try{return new URL(e).origin}catch{return null}}function V(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return De()}function De(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:c,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return o}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 sr="device-login",ar=/^[A-Za-z0-9._-]{1,64}$/;function Me(e){return ar.test(e)?e:"<profile>"}function Pt(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Me(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ue(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Bt(e){let t=Me(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Pt(e)}\` for headless automation.`}function $t(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${sr} --profile ${Me(e)}\`.`}var lr={"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 cr=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 Ke(e){return(typeof e=="string"?e:String(e??"")).replace(cr,"")}var ur=64;function Fe(e,t=new Map,n=0){if(typeof e=="string")return Ke(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ur)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Fe(c,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,c]of Object.entries(e))Object.defineProperty(i,s,{value:Fe(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var l=class extends Error{code;details;constructor(t,n,r){super(Ke(n)),this.code=t,this.details=r&&Fe(r),this.name="AllscaleError"}get exitCode(){return lr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Dt(e){if(e instanceof l)return e;if(e instanceof Error){if(pr(e)){let t=gr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var dr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),fr=[/^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 pr(e){if(hr(e))return!0;let t=e.name??"";return dr.has(t)?t==="CLIError"?Ge(e,"parse")||xt(e.message):!0:xt(e.message)}function hr(e){if(!Ge(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ge(e,"parse")}function xt(e){return e?Ke(e).split(`
2
- `).some(t=>fr.some(n=>n.test(t.trim()))):!1}function Ge(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function gr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ut(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var h=A(require("fs")),ge=A(require("path")),Yt=A(require("crypto"));var mr="...<truncated>",_r=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,yr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,We=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,je=String.raw`(?:proxy[_-]?)?authorization`,wr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${je}"|'${je}'|${je})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${We}`,"gi"),br=/\b(https?:\/\/)[^\s/?#]+@/gi,Er=String.raw`(?:[A-Za-z0-9]+[_-])*`,Sr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Gt=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)`,Ft=Gt(Er),Ar=Gt(Sr),kr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ft}"|'${Ft}'|${Ar})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${We}`,"gi"),qe=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)`,Lr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${qe}"|'${qe}'|${qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${We}`,"g");function de(e){return e.replace(br,"$1<redacted>@").replace(_r,"<redacted-jwt>").replace(wr,"$1$2$3<redacted>").replace(kr,"$1$2<redacted>").replace(Lr,"$1$2<redacted>").replace(yr,"Bearer <redacted>")}var Tr=/(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 fe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Tr.test(t)}function Mt(e){let t="";for(let n of e){let r=n.codePointAt(0),o=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=o?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function pe(e,t,n=mr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let o=t-r,i="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>o)break;i+=c,s+=u}return`${i}${n}`}function S(e,t=16384){return pe(Mt(de(e)),t)}var Ye=100,Ir=8,Or=8*1024;function he(){return{remaining:Or}}function He(e,t){let n=Math.min(16384,t.remaining),r=pe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>Ir)return He("<truncated>",t);if(typeof e=="string"){let o=de(e);return He(r.escapeControls?Mt(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,Ye),i=o.map(s=>K(s,t,n+1,r));return e.length>o.length&&i.push(He(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,c]of i.slice(0,Ye))o[s]=K(c,t,n+1,r);return i.length>Ye&&(o.output_truncated=!0),o}return e}var ze=require("process");var Je=!1;function Ve(e){Je=e}function jt(){return Je}var Kt="1";function q(e,t){if(Je){let n={...e};delete n.version;let r=he(),o={event:n.event,...n},i=K(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:Kt,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Kt,event:i.event,output_truncated:!0})),ze.stderr.write(`${s}
4
- `)}else ze.stderr.write(t)}var qt="2",Y=null,L=null,H=!1,X=!1;function vr(){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=Yt.randomBytes(4).toString("hex");return ge.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Xe=64*1024*1024,Cr=null;function Ze(e={}){if(e.quiet&&(X=!0),H)return;let t=vr();if(!t)return;Y=null;let n=null;try{if((Cr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=ge.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.statSync(r),d=u.mode&511;if(!u.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 o=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|o,384);let i=h.fstatSync(n),s=h.lstatSync(t);if(!i.isFile()||s.isSymbolicLink()||s.dev!==i.dev||s.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=i.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`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}X||q({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}Y=t,L=n,H=!0}var Rr=[/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 Nr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Rr.some(n=>n.test(t))}function Ht(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=xr(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Nr(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function xr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Pr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ht(e.url)}:e}function Br(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=K(o,he()),s=JSON.stringify({version:qt,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:qt,timestamp:t,type:r,output_truncated:!0})),s}function w(e){if(!H||!Y||L===null)return;let t=Pr(e),n=Br(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Xe){H=!1;try{h.closeSync(L)}catch{}L=null,X||q({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:S(Y)},max_bytes:Xe},`${S(`[allscale] sidecar exceeded ${Xe} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
1
+ "use strict";var or=Object.create;var ue=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var cr=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},Nt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sr(t))!lr.call(e,o)&&o!==n&&ue(e,o,{get:()=>t[o],enumerable:!(r=ir(t,o))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?or(ar(e)):{},Nt(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),ur=e=>Nt(ue({},"__esModule",{value:!0}),e);var ki={};cr(ki,{default:()=>xe});module.exports=ur(ki);var I=require("@oclif/core");var xt="public",Pt="https://app.allscale.io";var Bt=["https://app.allscale.io"];var $e="Override the API base URL (public builds accept only https://app.allscale.io)";var De="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function $t(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 Dt(e){return $t(e)!==null}function Ue(e){let t=$t(e);return t!==null&&Bt.includes(t.origin)}function J(){return"".trim()||void 0}function v(){return"public"}function x(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Me(e){try{return new URL(e).origin}catch{return null}}function V(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Fe()}function Fe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:c,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return o}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 dr="device-login",fr=/^[A-Za-z0-9._-]{1,64}$/;function je(e){return fr.test(e)?e:"<profile>"}function X(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":je(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function de(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Ft(e){let t=je(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${X(e)}\` for headless automation.`}function Mt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${dr} --profile ${je(e)}\`.`}var pr={"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 hr=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 qe(e){return(typeof e=="string"?e:String(e??"")).replace(hr,"")}var gr=64;function Ge(e,t=new Map,n=0){if(typeof e=="string")return qe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=gr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Ge(c,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,c]of Object.entries(e))Object.defineProperty(i,s,{value:Ge(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var l=class extends Error{code;details;constructor(t,n,r){super(qe(n)),this.code=t,this.details=r&&Ge(r),this.name="AllscaleError"}get exitCode(){return pr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Gt(e){if(e instanceof l)return e;if(e instanceof Error){if(yr(e)){let t=br(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var mr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),_r=[/^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 yr(e){if(wr(e))return!0;let t=e.name??"";return mr.has(t)?t==="CLIError"?Ke(e,"parse")||Ut(e.message):!0:Ut(e.message)}function wr(e){if(!Ke(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ke(e,"parse")}function Ut(e){return e?qe(e).split(`
2
+ `).some(t=>_r.some(n=>n.test(t.trim()))):!1}function Ke(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function br(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Kt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var h=A(require("fs")),me=A(require("path")),Jt=A(require("crypto"));var Er="...<truncated>",Sr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Ar=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Je=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ye=String.raw`(?:proxy[_-]?)?authorization`,kr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ye}"|'${Ye}'|${Ye})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Je}`,"gi"),Lr=/\b(https?:\/\/)[^\s/?#]+@/gi,Tr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Ir=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,qt=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)`,jt=qt(Tr),Or=qt(Ir),vr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${jt}"|'${jt}'|${Or})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Je}`,"gi"),He=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Cr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Je}`,"g");function fe(e){return e.replace(Lr,"$1<redacted>@").replace(Sr,"<redacted-jwt>").replace(kr,"$1$2$3<redacted>").replace(vr,"$1$2<redacted>").replace(Cr,"$1$2<redacted>").replace(Ar,"Bearer <redacted>")}var Rr=/(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 pe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Rr.test(t)}function Yt(e){let t="";for(let n of e){let r=n.codePointAt(0),o=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=o?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function he(e,t,n=Er){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let o=t-r,i="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>o)break;i+=c,s+=u}return`${i}${n}`}function S(e,t=16384){return he(Yt(fe(e)),t)}var We=100,Nr=8,xr=8*1024;function ge(){return{remaining:xr}}function ze(e,t){let n=Math.min(16384,t.remaining),r=he(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>Nr)return ze("<truncated>",t);if(typeof e=="string"){let o=fe(e);return ze(r.escapeControls?Yt(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,We),i=o.map(s=>K(s,t,n+1,r));return e.length>o.length&&i.push(ze(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,c]of i.slice(0,We))o[s]=K(c,t,n+1,r);return i.length>We&&(o.output_truncated=!0),o}return e}var Ve=require("process");var Xe=!1;function Ze(e){Xe=e}function Wt(){return Xe}var Ht="1";function q(e,t){if(Xe){let n={...e};delete n.version;let r=ge(),o={event:n.event,...n},i=K(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:Ht,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Ht,event:i.event,output_truncated:!0})),Ve.stderr.write(`${s}
4
+ `)}else Ve.stderr.write(t)}var zt="2",Y=null,L=null,H=!1,Z=!1;function Pr(){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=Jt.randomBytes(4).toString("hex");return me.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Qe=64*1024*1024,Br=null;function et(e={}){if(e.quiet&&(Z=!0),H)return;let t=Pr();if(!t)return;Y=null;let n=null;try{if((Br??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=me.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.statSync(r),d=u.mode&511;if(!u.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 o=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|o,384);let i=h.fstatSync(n),s=h.lstatSync(t);if(!i.isFile()||s.isSymbolicLink()||s.dev!==i.dev||s.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=i.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`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}Z||q({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}Y=t,L=n,H=!0}var $r=[/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 Dr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return $r.some(n=>n.test(t))}function Vt(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=Ur(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Dr(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function Ur(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Fr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Vt(e.url)}:e}function Mr(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=K(o,ge()),s=JSON.stringify({version:zt,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:zt,timestamp:t,type:r,output_truncated:!0})),s}function w(e){if(!H||!Y||L===null)return;let t=Fr(e),n=Mr(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Qe){H=!1;try{h.closeSync(L)}catch{}L=null,Z||q({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:S(Y)},max_bytes:Qe},`${S(`[allscale] sidecar exceeded ${Qe} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
6
  `);return}h.appendFileSync(L,`${n}
7
- `)}catch(r){if(H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{X||q({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var C=Ht;function Wt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Z(){if(X=!1,H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}}function zt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Wt()||!t}var Q=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"]),$r=new Set(Array.from(Q).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Dr=Array.from(Q).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Ur=new Set(["--otp-stdin","--password-stdin"]);function Qe(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let s=r.slice(0,i);if(Q.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Q.has(r)){t.push(r),n+1<e.length&&(Q.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if($r.has(i)){t.push(`${i}<redacted>`);continue}}let o=Ur.has(r)?void 0:Dr.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Jt(e){w({type:"error",code:e.code,message:S(e.message)}),w({type:"command-end",ok:!1,exitCode:e.exitCode}),Z()}var ee=J()??vt,z={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function P(e){return Nt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Vt(){let e=process.env[z.TOKEN]?.trim();return e&&e.length>0?e:void 0}function et(){let e=process.env[z.PROFILE]?.trim();return e&&e.length>0?e:void 0}function te(){let e=process.env[z.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Xt(){let e=process.env[z.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Zt(){let e=process.env[z.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Qt(){let e=process.env[z.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(J()===void 0&&ee!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
- The CLI default is now ${ee} (production), but a saved profile wins over the default,
7
+ `)}catch(r){if(H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{Z||q({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var C=Vt;function Xt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Q(){if(Z=!1,H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}}function Zt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Xt()||!t}var ee=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Gr=new Set(Array.from(ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Kr=Array.from(ee).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),jr=new Set(["--otp-stdin","--password-stdin"]);function tt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let s=r.slice(0,i);if(ee.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ee.has(r)){t.push(r),n+1<e.length&&(ee.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Gr.has(i)){t.push(`${i}<redacted>`);continue}}let o=jr.has(r)?void 0:Kr.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Qt(e){w({type:"error",code:e.code,message:S(e.message)}),w({type:"command-end",ok:!1,exitCode:e.exitCode}),Q()}var te=J()??Pt,z={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function P(e){return Dt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function en(){let e=process.env[z.TOKEN]?.trim();return e&&e.length>0?e:void 0}function nt(){let e=process.env[z.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ne(){let e=process.env[z.API_BASE]?.trim();return e&&e.length>0?e:void 0}function tn(){let e=process.env[z.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function nn(){let e=process.env[z.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rn(){let e=process.env[z.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function on(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(J()===void 0&&te!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${te} (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
- To move to production, run: allscale device-login --api-base ${ee}
14
- `}var B=A(require("fs")),tn=A(require("os")),tt=A(require("path")),nt=A(require("@iarna/toml"));var Mr=".allscale",Kr="config.toml";function rt(){return tt.join(tn.homedir(),Mr)}function jr(){return tt.join(rt(),Kr)}function me(){let e=jr();if(!B.existsSync(e))return{};let t=B.readFileSync(e,"utf-8");try{return nt.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function nn(e){return Object.keys(e.profile??{}).sort()}function rn(e,t){return e.profile?.[t]}function on(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function R(e){if(!$e(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Be)}function _e(e,t){R(e);let n=P(e),r=typeof t=="string"?P(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function sn(e,t){let n=P(e),r=P(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ye(e){let t=Yr(e);if(t)throw new l("input.invalid",t.message)}function qr(){let e=J();if(e===void 0)return;let t=V();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Yr(e){let t=qr();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,o=P(e),i=n.map(c=>P(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(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 ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Hr=require("@noble/hashes/sha3");var an=["USDT","USDC"];var os=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Wr="unknown_otp_id",zr="invalid_code",Jr="expired_code";function Vr(e){return`'${e.replace(/'/g,"'\\''")}'`}function ln(e){return`Run \`allscale otp-send --email ${Vr(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Xr=new Map([[Wr,(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. ${ln(t)}`],[zr,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.`],[Jr,(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. ${ln(t)}`]]);var cn=[...Xr.keys()];var re=require("@oclif/core"),ne=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:v()==="public"}),"api-base":I.Flags.string({description:Pe,helpGroup:"GLOBAL",hidden:v()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ve(this.jsonEnabled()),Ze(),w({type:"session-start",command:this.id??"",argv:Qe(this.argv)});let t=this.constructor;if(v()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&te()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&so(t)?this.config.findCommand(this.id??""):void 0;if(r){Z();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!Qt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let o=await this.runCommand();return w({type:"command-end",ok:!0}),Z(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ut(o),{data:o})}catch(t){let n=Dt(t);Jt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ve(!1)}}resolveSessionApiBaseChain(t){let n=me(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||et()!==void 0,s=on(n,r,et()),c=rn(n,s),u=v()==="public"&&te()!==void 0,d=o??(u?void 0:te()),f=d??c?.api_base??ee,p=en({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||R(n),n}resolveContext(t){if(v()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&te()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(R(o),ye(o)),{apiBase:o,profile:c,token:n??Vt(),insecureStorage:r||Xt(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${io(t)}
15
- `)}};var Zr=/_(removed|cleared|count|total)$/i;function Qr(e,t){return typeof t=="number"&&Zr.test(e)}var eo=new Set(an);function to(e,t){return e==="token_symbol"&&typeof t=="string"&&eo.has(t)}var no=new Set(cn);function ro(e,t){return e==="otp_reason"&&typeof t=="string"&&no.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(o=>be(o,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[o,i]of r.slice(0,we))n[o]=fe(o)&&!Qr(o,i)&&!to(o,i)&&!ro(o,i)?"<redacted>":be(i,t+1);if(r.length>we){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=oo(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function oo(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 io(e){let t=jt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function so(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}var Sn=A(require("path"));var st=require("crypto"),a=A(require("fs")),y=A(require("path"));var Ee=1024*1024,ao=5e3,lo=20,co=3e4,ot=4096,uo=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Se(e){return e instanceof oe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},fo=null;function D(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Ae(){return(fo??process.platform)!=="win32"}function _n(){if(!Ae())throw D()}function yn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ie(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function po(e){Atomics.wait(uo,0,0,e)}function wn(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function ho(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function un(e,t){let n=y.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&_(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(i,s))throw new Error("credential-store parent changed while it was being inspected");ie(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&y.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}return!0}function O(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 o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&_(i,"ENOENT")?new k:i}if(!se(n,o))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.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||o.nlink!==1))throw new oe;if(ie(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function go(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function dn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(_(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(_(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return go(t,r)}finally{t!==null&&a.default.closeSync(t)}}function fn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(_(o,"ENOENT")&&yn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);U(e,r)}finally{t!==null&&a.default.closeSync(t)}En(y.dirname(e))}function mo(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(_(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 oe;ie(t,"credential-store replacement target")}function _o(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),o=y.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(_(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function bn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function En(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function yo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),o=y.basename(e),i=null,s=null,c=!1;try{let u=_o(r,o);i=u.fd,s=u.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");bn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),mo(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}En(r)}function wo(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function bo(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function Eo(e,t){if(t.size>ot)return null;let n=Buffer.alloc(ot+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>ot)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function U(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),a.default.unlinkSync(e)}function pn(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(_(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(_(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Eo(n,o);return{state:(i?.target===t&&i?!wn(i.pid):Date.now()-o.mtimeMs>=co)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function So(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),o=y.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return bn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(_(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ao(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw _(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(o,t))throw new k;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function hn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(_(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function ko(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(_(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{U(e,n)}catch{}throw a.default.closeSync(t),r}}function $(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");po(lo)}function gn(e){let t=y.dirname(e),n=y.basename(e),r=wo(e),o=bo(e),i=So(t,n),s=Date.now()+ao,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(hn(o)){$(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Ao(r,i.stats),c=!0}catch(p){if(u&&!c){try{U(r,i.stats)}catch{}u=!1}if(p instanceof k){$(s,!1);continue}if(!_(p,"EEXIST"))throw p;let b;try{b=pn(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}if(b.state==="absent")continue;if(b.state==="stale"){let m;try{m=ko(o)}catch(E){if(E instanceof k){$(s,!1);continue}throw E}if(m!==null){try{let E;try{E=pn(r,n)}catch(N){if(N instanceof k){$(s,!1);continue}throw N}E.state==="stale"&&U(r,E.stats)}finally{it(m)}continue}}let g;try{g=hn(o)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}$(s,g)}}catch(p){f=p}try{U(i.claimPath,i.stats)}catch(p){!_(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function it(e){try{U(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Lo(e,t){let n=ho(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 o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function mn(e){let t=y.dirname(e),n=y.basename(e);for(let r of a.default.readdirSync(t)){let o=Lo(r,n);if(o===null||wn(o))continue;let i=y.join(t,r),s=null;try{try{s=a.default.openSync(i,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!se(c,u))continue;try{ie(c,"credential-store orphan")}catch{continue}U(i,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!Ae()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!un(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=gn(e);try{return mn(e),n({read:()=>dn(e),remove:()=>fn(e),write:()=>{throw D()}})}finally{it(s)}}if(!t.createParent){let i=!1;try{i=yn(e)}catch{throw D()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!un(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=gn(e);try{return mn(e),n({read:()=>dn(e),remove:()=>fn(e),write:i=>yo(e,i)})}finally{it(o)}}var at="allscale-cli";function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function An(e){return dt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function lt(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function ke(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var F,ct=!1;function To(){return Zt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Io(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 Oo(){if(F!==void 0)return F;if(To())return ct=!1,F=null,F;try{F=require("keytar"),ct=!1}catch(e){ct=!Io(e),F=null}return F}var vo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function kn(){let e=Ae()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable",`${vo} `+e+" Never silently downgrade in production.")}async function ut(e){try{return await e()}catch{throw kn()}}var ft=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ut(()=>this.keytar.getPassword(at,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!An(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ut(()=>this.keytar.setPassword(at,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ut(()=>this.keytar.deletePassword(at,t))}},Co="credentials.json",pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Sn.join(rt(),Co)}read(t){let n;try{n=t.read()}catch(o){throw Se(o)?lt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!dt(r)||!dt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Se(r)?lt():ke()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!An(r))throw G("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:G("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:ke()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:ke()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Se(n)?lt():ke()}}};function Ln(e){if(e.insecureStorage)return _n(),new pt(e.insecureFilePath);let t=Oo();if(t)return new ft(t);throw kn()}var ht=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Le(){return new ht}var Te="allscale_access_token",gt="allscale_refresh_token";function Tn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function _t(e,t){return e.find(n=>n.name===t)?.value??null}var In=A(require("crypto")),On=A(require("fs")),vn=A(require("path"));var Ro="key-id",No="x-allscale-cli-version",yt="cli-1",xo="aScaLe_cli_obf_v1",Po="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Bo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var $o=Bo(Po,xo),Cn=`Bearer ${$o}`;function Rn(e,t){let n=Ue(e);if(n!==null)return t.find(r=>Ue(r.base)===n)}function Do(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Rn(e,t);if(r)return r.key;if(x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:x(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 Uo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Rn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():yt}if(!x(t[0].base))return yt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():yt}function Fo(){return"1.0.3"}function Go(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function wt(e,t){let n=Do(t);if(!n)throw Go();let r=Uo(t),o=Math.floor(Date.now()/1e3).toString(),i=In.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[No]:Fo()};return r.length>0&&(s[Ro]=r),s}function Nn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Mo(e,t={}){let n;try{n=nn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",$t(e)+(t.messageSuffix??""),{profile:e})}function xn(e){if(e.profileExplicit){let t=Mo(e.profile);if(t)return t}return new l("auth.no_token",Bt(e.profile))}var Ko=500,jo=8,Pn=100;function bt(e,t=0){if(t>jo)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Pn),r=n.map(o=>bt(o,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,o]of Object.entries(e).slice(0,Pn))n[r]=fe(r)?"<redacted>":bt(o,t+1);return n}return e}function qo(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 Bn(e,t=Ko){let n=qo(e),r=n===void 0?de(e):JSON.stringify(bt(n));return pe(r,t)}var Et=256*1024,Ie=class extends l{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`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.`:i?`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,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Oe=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 St(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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ie(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,b)=>{u=setTimeout(()=>{b(new Oe(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:b,value:g}=f?await Promise.race([p,f]):await p;if(b)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ie(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Oe&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Yo="X-AllScale-Api-Key",Ho=3e4,Wo=32*1024*1024,zo=4*1024*1024;function Jo(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function Vo(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function Xo(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 Gn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Xo(e.status,e.url)}}var $n="--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")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/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(!((i||c)&&(o||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("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=${$n} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${$n}`})}var M=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??Ho;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),ye(this.opts.apiBase);let o=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),i=Jo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();sn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Mn(t.path),u=s==="required"?!0:s==="none"?!1:ei(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw xn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Nn(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();w({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new l("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-b}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await Vo(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),Zn=Date.now();w({type:"request",method:t.method??"GET",url:o});let Ne;try{Ne=await fetch(o,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(xe){throw new l("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${xe instanceof Error?xe.message:String(xe)}`)}return w({type:"response",status:Ne.status,durationMs:Date.now()-Zn}),Dn(Ne,{withMetadata:n.withMetadata,authBearing:u,responseKind:Un(t)})}return Dn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:Un(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...wt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Cn;let o=t.tokens;if(o?.agent_key)return r[Yo]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=mt([{name:Te,value:i}]))}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(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new l("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 l("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new l("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:Te,value:t.access_token},{name:gt,value:t.refresh_token}]),o=wt("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw w({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}w({type:"response",status:u.status,durationMs:0});try{await Gn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await ve(u);let m=await ii(u);await ve(u,m),jn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:u.status})}let d=Tn(u.headers),f=_t(d,Te),p=_t(d,gt);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,b),w({type:"refresh",ok:!0}),b}},Zo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Mn(e){let t=e.split(/[?#]/,1)[0];return Zo.some(n=>t===n||t.startsWith(`${n}/`))}var Qo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function At(e){let t=e.split(/[?#]/,1)[0];return Qo.some(n=>n.test(t))}function ei(e){return Mn(e)||At(e)}async function Dn(e,t={}){await Gn(e);let n=e.status>=200&&e.status<300;n||await ve(e);let r=t.responseKind??"mutation",i=await St(e,n?r==="query"?Wo:zo:Et,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await ve(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=si(s)??`HTTP ${e.status}`;if(jn(e.status,s),ri(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("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 u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function Un(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var ti=2014,Fn=2004;function Kn(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 ni(e){return Kn(e,ti)}function ri(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Kn(t,Fn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} 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:Fn})}var oi=1e4;async function ii(e,t=oi){if(e.status>=200&&e.status<300)return"";try{return await St(e,Et,{timeoutMs:t})}catch{return""}}function jn(e,t){if(!(e>=200&&e<300)&&ni(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?Bn(t):t})}function si(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 ai=/^\/(api\/)?(v1\/)?public\//;function kt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ai.test(n),o=n&&At(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Ln({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var li=new Set;var ci=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"]),qn=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"]),Yn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Lt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var ui=new Set(["cli_op:all"]),di=new Set([...ui].map(Lt));var ta=new Set([...[...ci,...qn,...li].map(Lt),...Yn,...di]);var le=8100,fi=new Set([le]),ga=new Set([...fi,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]);var Hn="/api/v1/public/claim-links";var pi=1e4,hi="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function gi(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function Wn(e){throw e instanceof l&&e.code==="not_found"&&gi(e.details)===le?new l("not_found",hi,{status:404,backend_code:le}):e}function zn(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Hn}/${n}:claim`:`${Hn}/${n}`}function Ce(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let o=t.trim();if(!o)throw new l("input.invalid","--claim-token is empty.");return Tt(o,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return Tt(mi(r),"--claim-url")}async function Jn(e,t,n=pi){let r=e["claim-url"]?.trim();if(!r)return Ce(e);let o;try{o=new URL(r)}catch{return Ce(e)}let i=/^\/s\/([^/]+)\/?$/.exec(o.pathname);if(!i||e["claim-token"]!==void 0)return Ce(e);R(t);let s=new URL(t).origin;if(o.origin!==s||o.username||o.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(i[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let b;try{b=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=b.headers.get("location");try{b.body?.cancel().catch(()=>{})}catch{}if(b.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:b.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let E=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!E)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(E[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return Tt(N,"--claim-url")}function Tt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function mi(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),o=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],i=o.endsWith(":claim")?o.slice(0,-6):o;try{return decodeURIComponent(i)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function Vn(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function Xn(e,t=""){let n=v()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Re=class e extends ne{static description="Read the public receiver-facing status snapshot for a Claim Link bearer token or URL.";static examples=["$ allscale claim-link status --claim-token claim-token-from-share-link","$ allscale claim-link status --claim-url https://app.allscale.io/claim/claim-token-from-share-link"];static usage=Xn("status");static requiresInput=!0;static flags={"claim-token":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),...ne.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Jn(t,n.apiBase),o=zn(r),s=await kt(n,{pathHint:o}).request({method:"GET",path:o,auth:"none"}).catch(Wn);return Vn(s)}};
13
+ To move to production, run: allscale device-login --api-base ${te}
14
+ `}var B=A(require("fs")),sn=A(require("os")),rt=A(require("path")),ot=A(require("@iarna/toml"));var Hr=".allscale",Wr="config.toml";function it(){return rt.join(sn.homedir(),Hr)}function zr(){return rt.join(it(),Wr)}function _e(){let e=zr();if(!B.existsSync(e))return{};let t=B.readFileSync(e,"utf-8");try{return ot.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function an(e){return Object.keys(e.profile??{}).sort()}function ln(e,t){return e.profile?.[t]}function cn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function R(e){if(!Ue(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function ye(e,t){R(e);let n=P(e),r=typeof t=="string"?P(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function un(e,t){let n=P(e),r=P(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function we(e){let t=Vr(e);if(t)throw new l("input.invalid",t.message)}function Jr(){let e=J();if(e===void 0)return;let t=V();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Vr(e){let t=Jr();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,o=P(e),i=n.map(c=>P(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(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 ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Xr=require("@noble/hashes/sha3");var dn=["USDT","USDC"];var ds=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Zr="unknown_otp_id",Qr="invalid_code",eo="expired_code";function to(e){return`'${e.replace(/'/g,"'\\''")}'`}function fn(e){return`Run \`allscale otp-send --email ${to(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var no=new Map([[Zr,(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. ${fn(t)}`],[Qr,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.`],[eo,(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. ${fn(t)}`]]);var pn=[...no.keys()];var oe=require("@oclif/core"),re=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:v()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:v()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ze(this.jsonEnabled()),et(),w({type:"session-start",command:this.id??"",argv:tt(this.argv)});let t=this.constructor;if(v()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ne()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=Zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&fo(t)?this.config.findCommand(this.id??""):void 0;if(r){Q();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!rn())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let o=await this.runCommand();return w({type:"command-end",ok:!0}),Q(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Kt(o),{data:o})}catch(t){let n=Gt(t);Qt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ze(!1)}}resolveSessionApiBaseChain(t){let n=_e(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||nt()!==void 0,s=cn(n,r,nt()),c=ln(n,s),u=v()==="public"&&ne()!==void 0,d=o??(u?void 0:ne()),f=d??c?.api_base??te,p=on({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||R(n),n}resolveContext(t){if(v()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ne()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(R(o),we(o)),{apiBase:o,profile:c,token:n??en(),insecureStorage:r||tn(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${uo(t)}
15
+ `)}};var ro=/_(removed|cleared|count|total)$/i;function oo(e,t){return typeof t=="number"&&ro.test(e)}var io=new Set(dn);function so(e,t){return e==="token_symbol"&&typeof t=="string"&&io.has(t)}var ao=new Set(pn);function lo(e,t){return e==="otp_reason"&&typeof t=="string"&&ao.has(t)}var be=100;function Ee(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,be),r=n.map(o=>Ee(o,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[o,i]of r.slice(0,be))n[o]=pe(o)&&!oo(o,i)&&!so(o,i)&&!lo(o,i)?"<redacted>":Ee(i,t+1);if(r.length>be){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-be} more keys`}return n}if(typeof e=="string"){let n=co(e);return n!==void 0?S(JSON.stringify(Ee(n,t+1))):S(e)}return e}function co(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 uo(e){let t=Wt()?void 0:2,n=Ee(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function fo(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}var Tn=A(require("path"));var lt=require("crypto"),a=A(require("fs")),y=A(require("path"));var Se=1024*1024,po=5e3,ho=20,go=3e4,st=4096,mo=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ae(e){return e instanceof ie}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},_o=null;function D(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function ke(){return(_o??process.platform)!=="win32"}function En(){if(!ke())throw D()}function Sn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function se(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function yo(e){Atomics.wait(mo,0,0,e)}function An(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function wo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hn(e,t){let n=y.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&_(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ae(i,s))throw new Error("credential-store parent changed while it was being inspected");se(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&y.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}return!0}function O(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 o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&_(i,"ENOENT")?new k:i}if(!ae(n,o))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.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||o.nlink!==1))throw new ie;if(se(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function bo(e,t){if(t.size>Se)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Se+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Se)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function gn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(_(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(_(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return bo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function mn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(_(o,"ENOENT")&&Sn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);U(e,r)}finally{t!==null&&a.default.closeSync(t)}Ln(y.dirname(e))}function Eo(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(_(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 ie;se(t,"credential-store replacement target")}function So(e,t){for(let n=0;n<8;n+=1){let r=(0,lt.randomBytes)(12).toString("hex"),o=y.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(_(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function kn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Ln(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Ao(e,t){let n=Buffer.from(t,"utf8");if(n.length>Se)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),o=y.basename(e),i=null,s=null,c=!1;try{let u=So(r,o);i=u.fd,s=u.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");kn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),Eo(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Ln(r)}function ko(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function Lo(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function To(e,t){if(t.size>st)return null;let n=Buffer.alloc(st+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>st)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function U(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ae(n,t))throw new Error("credential-store lock changed while it was being inspected");se(n,"credential-store lock"),a.default.unlinkSync(e)}function _n(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(_(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(_(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=To(n,o);return{state:(i?.target===t&&i?!An(i.pid):Date.now()-o.mtimeMs>=go)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function Io(e,t){for(let n=0;n<8;n+=1){let r=(0,lt.randomBytes)(12).toString("hex"),o=y.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return kn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(_(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Oo(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw _(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ae(o,t))throw new k;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function yn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(_(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function vo(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(_(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{U(e,n)}catch{}throw a.default.closeSync(t),r}}function $(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");yo(ho)}function wn(e){let t=y.dirname(e),n=y.basename(e),r=ko(e),o=Lo(e),i=Io(t,n),s=Date.now()+po,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(yn(o)){$(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Oo(r,i.stats),c=!0}catch(p){if(u&&!c){try{U(r,i.stats)}catch{}u=!1}if(p instanceof k){$(s,!1);continue}if(!_(p,"EEXIST"))throw p;let b;try{b=_n(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}if(b.state==="absent")continue;if(b.state==="stale"){let m;try{m=vo(o)}catch(E){if(E instanceof k){$(s,!1);continue}throw E}if(m!==null){try{let E;try{E=_n(r,n)}catch(N){if(N instanceof k){$(s,!1);continue}throw N}E.state==="stale"&&U(r,E.stats)}finally{at(m)}continue}}let g;try{g=yn(o)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}$(s,g)}}catch(p){f=p}try{U(i.claimPath,i.stats)}catch(p){!_(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function at(e){try{U(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Co(e,t){let n=wo(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 o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function bn(e){let t=y.dirname(e),n=y.basename(e);for(let r of a.default.readdirSync(t)){let o=Co(r,n);if(o===null||An(o))continue;let i=y.join(t,r),s=null;try{try{s=a.default.openSync(i,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!ae(c,u))continue;try{se(c,"credential-store orphan")}catch{continue}U(i,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function le(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!hn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=wn(e);try{return bn(e),n({read:()=>gn(e),remove:()=>mn(e),write:()=>{throw D()}})}finally{at(s)}}if(!t.createParent){let i=!1;try{i=Sn(e)}catch{throw D()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!hn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=wn(e);try{return bn(e),n({read:()=>gn(e),remove:()=>mn(e),write:i=>Ao(e,i)})}finally{at(o)}}var ct="allscale-cli";function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function In(e){return pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function M(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function ut(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Le(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var F,dt=!1;function Ro(){return nn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function No(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 xo(){if(F!==void 0)return F;if(Ro())return dt=!1,F=null,F;try{F=require("keytar"),dt=!1}catch(e){dt=!No(e),F=null}return F}var Po="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function On(){let e=ke()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable",`${Po} `+e+" Never silently downgrade in production.")}async function ft(e){try{return await e()}catch{throw On()}}var ht=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ft(()=>this.keytar.getPassword(ct,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw M("OS keychain")}if(!In(r))throw M("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ft(()=>this.keytar.setPassword(ct,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ft(()=>this.keytar.deletePassword(ct,t))}},Bo="credentials.json",gt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Tn.join(it(),Bo)}read(t){let n;try{n=t.read()}catch(o){throw Ae(o)?ut():M("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw M("plaintext file")}if(!pt(r)||!pt(r.profiles))throw M("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!In(r))throw M("plaintext file");return r}}async get(t){try{return le(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:M("plaintext file")}}async set(t,n){try{le(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:Le()}}async delete(t){try{le(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Le()}}async clearProfile(t){try{return le(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Ae(n)?ut():Le()}}};function vn(e){if(e.insecureStorage)return En(),new gt(e.insecureFilePath);let t=xo();if(t)return new ht(t);throw On()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Te(){return new mt}var Ie="allscale_access_token",_t="allscale_refresh_token";function Cn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function yt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function wt(e,t){return e.find(n=>n.name===t)?.value??null}var Rn=A(require("crypto")),Nn=A(require("fs")),xn=A(require("path"));var $o="key-id",Do="x-allscale-cli-version",bt="cli-1",Uo="aScaLe_cli_obf_v1",Fo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Mo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var Go=Mo(Fo,Uo),Pn=`Bearer ${Go}`;function Bn(e,t){let n=Me(e);if(n!==null)return t.find(r=>Me(r.base)===n)}function Ko(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Bn(e,t);if(r)return r.key;if(x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:x(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 jo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Bn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():bt}if(!x(t[0].base))return bt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():bt}function qo(){return"1.0.5"}function Yo(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Et(e,t){let n=Ko(t);if(!n)throw Yo();let r=jo(t),o=Math.floor(Date.now()/1e3).toString(),i=Rn.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Do]:qo()};return r.length>0&&(s[$o]=r),s}function $n(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Ho(e,t={}){let n;try{n=an(_e())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Mt(e)+(t.messageSuffix??""),{profile:e})}function Dn(e){if(e.profileExplicit){let t=Ho(e.profile);if(t)return t}return new l("auth.no_token",Ft(e.profile))}var Wo=new Set;var zo=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"]),St=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),At=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Oe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Un(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Jo=new Set(["cli_op:all"]),Vo=new Set([...Jo].map(Oe));var Hs=new Set([...[...zo,...St,...Wo].map(Oe),...At,...Vo]);var Xo=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Zo=/is not available to API keys/i,Fn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Mn(e){if(typeof e!="string")return;let t=Xo.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=Zo.test(n),i=!o&&Fn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(u=>u.trim()).filter(u=>Fn.test(u));s=c.length>0?c:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function Gn(e){if(At.has(Oe(e)))return{kind:"ungrantable"};for(let t of St)if(Un(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function kt(e,t,n,r){let o=Mn(e),i=o?.notAvailableToKeys===!0,s=o?.required??r?.scope,c=o?.granted,u=c===void 0?"":` This key holds ${c.length>0?c.join(", "):"no scopes"}.`;if(i||r?.ungrantableReason!==void 0){let d=r?.ungrantableReason!==void 0?`: ${r.ungrantableReason}`:"";return new l("auth.permission_denied",`${t} is not available to agent keys${d}. Re-authorizing will NOT help \u2014 no scope grants it.${u} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...n,missing_scopes:[],...c===void 0?{}:{granted_scopes:c},ungrantable:!0})}if(s!==void 0){let d=Gn(s),f=d.kind==="ungrantable"?`\`${s}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:d.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${X()}\` with \`--scopes ${s}\`.`:`The browser approval screen does not offer \`${s}\`, so \`device-login\` cannot grant it \u2014 use \`${X()}\` with \`--scopes ${s}\`.`;return new l("auth.permission_denied",`The current agent key lacks \`${s}\`, required by ${t}.${u} ${f}`,{...n,missing_scopes:[s],...c===void 0?{}:{granted_scopes:c},...d.kind==="ungrantable"?{ungrantable:!0}:{}})}return new l("auth.permission_denied",`The current agent key does not have the scope required by ${t}.${u} Re-run \`allscale device-login\` (or \`${X()}\`) and grant the required scope.`,n)}var Qo=500,ei=8,Kn=100;function Lt(e,t=0){if(t>ei)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Kn),r=n.map(o=>Lt(o,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,o]of Object.entries(e).slice(0,Kn))n[r]=pe(r)?"<redacted>":Lt(o,t+1);return n}return e}function ti(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 jn(e,t=Qo){let n=ti(e),r=n===void 0?fe(e):JSON.stringify(Lt(n));return he(r,t)}var Tt=256*1024,ve=class extends l{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`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.`:i?`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,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Ce=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 It(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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new ve(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,b)=>{u=setTimeout(()=>{b(new Ce(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:b,value:g}=f?await Promise.race([p,f]):await p;if(b)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new ve(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Ce&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ni="X-AllScale-Api-Key",ri=3e4,oi=32*1024*1024,ii=4*1024*1024;function si(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function ai(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function li(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 zn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var qn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/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(!((i||c)&&(o||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("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=${qn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${qn}`})}var G=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??ri;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),we(this.opts.apiBase);let o=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),i=si(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();un(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Jn(t.path),u=s==="required"?!0:s==="none"?!1:di(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw Dn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=$n(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&ye(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();w({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new l("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-b}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await ai(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),rr=Date.now();w({type:"request",method:t.method??"GET",url:o});let Pe;try{Pe=await fetch(o,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new l("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return w({type:"response",status:Pe.status,durationMs:Date.now()-rr}),Yn(Pe,{withMetadata:n.withMetadata,authBearing:u,responseKind:Hn(t)})}return Yn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:Hn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Et(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Pn;let o=t.tokens;if(o?.agent_key)return r[ni]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=yt([{name:Ie,value:i}]))}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(ye(this.opts.apiBase,n.api_base),n.agent_key)throw new l("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 l("auth.token_expired",`No refresh token available; log in again \u2014 ${de()}.`);if(ye(this.opts.apiBase,t.api_base),t.agent_key)throw new l("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=yt([{name:Ie,value:t.access_token},{name:_t,value:t.refresh_token}]),o=Et("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw w({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}w({type:"response",status:u.status,durationMs:0});try{await zn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await Re(u);let m=await mi(u);await Re(u,m),Vn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${de()}.`,{status:u.status})}let d=Cn(u.headers),f=wt(d,Ie),p=wt(d,_t);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,b),w({type:"refresh",ok:!0}),b}},ci=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Jn(e){let t=e.split(/[?#]/,1)[0];return ci.some(n=>t===n||t.startsWith(`${n}/`))}var ui=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Ot(e){let t=e.split(/[?#]/,1)[0];return ui.some(n=>n.test(t))}function di(e){return Jn(e)||Ot(e)}async function Yn(e,t={}){await zn(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",i=await It(e,n?r==="query"?oi:ii:Tt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=_i(s)??`HTTP ${e.status}`;if(Vn(e.status,s),hi(e.status,s,t),vt(s,2102))throw kt(s.errors,"this API request",{status:e.status,backend_code:2102});if(e.status===401){if(t.agentKeyAuth)throw new l("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 u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function Hn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fi=2014,Wn=2004;function vt(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 pi(e){return vt(e,fi)}function hi(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&vt(t,Wn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${de()} 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:Wn})}var gi=1e4;async function mi(e,t=gi){if(e.status>=200&&e.status<300)return"";try{return await It(e,Tt,{timeoutMs:t})}catch{return""}}function Vn(e,t){if(!(e>=200&&e<300)&&pi(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?jn(t):t})}function _i(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 yi=/^\/(api\/)?(v1\/)?public\//;function Ct(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&yi.test(n),o=n&&Ot(n),i=r&&!o&&!t.forceAuth;if(e.token)return new G({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new G({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new G({apiBase:e.apiBase,tokenStore:vn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new G({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var ce=8100,wi=new Set([ce]),ka=new Set([...wi,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]);var Xn="/api/v1/public/claim-links";var bi=1e4,Ei="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function Si(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function Zn(e){throw e instanceof l&&e.code==="not_found"&&Si(e.details)===ce?new l("not_found",Ei,{status:404,backend_code:ce}):e}function Qn(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Xn}/${n}:claim`:`${Xn}/${n}`}function Ne(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let o=t.trim();if(!o)throw new l("input.invalid","--claim-token is empty.");return Rt(o,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return Rt(Ai(r),"--claim-url")}async function er(e,t,n=bi){let r=e["claim-url"]?.trim();if(!r)return Ne(e);let o;try{o=new URL(r)}catch{return Ne(e)}let i=/^\/s\/([^/]+)\/?$/.exec(o.pathname);if(!i||e["claim-token"]!==void 0)return Ne(e);R(t);let s=new URL(t).origin;if(o.origin!==s||o.username||o.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(i[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let b;try{b=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=b.headers.get("location");try{b.body?.cancel().catch(()=>{})}catch{}if(b.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:b.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let E=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!E)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(E[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return Rt(N,"--claim-url")}function Rt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function Ai(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),o=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],i=o.endsWith(":claim")?o.slice(0,-6):o;try{return decodeURIComponent(i)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function tr(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function nr(e,t=""){let n=v()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var xe=class e extends re{static description="Read the public receiver-facing status snapshot for a Claim Link bearer token or URL.";static examples=["$ allscale claim-link status --claim-token claim-token-from-share-link","$ allscale claim-link status --claim-url https://app.allscale.io/claim/claim-token-from-share-link"];static usage=nr("status");static requiresInput=!0;static flags={"claim-token":oe.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":oe.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await er(t,n.apiBase),o=Qn(r),s=await Ct(n,{pathHint:o}).request({method:"GET",path:o,auth:"none"}).catch(Zn);return tr(s)}};
17
17
  //# sourceMappingURL=status.js.map