@allscale/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +482 -0
  2. package/bin/dev.js +11 -0
  3. package/bin/run-oclif.js +69 -0
  4. package/bin/run.js +6 -0
  5. package/dist/commands/build-info.js +16 -0
  6. package/dist/commands/claim-link/claim.js +17 -0
  7. package/dist/commands/claim-link/create.js +75 -0
  8. package/dist/commands/claim-link/get.js +18 -0
  9. package/dist/commands/claim-link/list.js +18 -0
  10. package/dist/commands/claim-link/preview.js +18 -0
  11. package/dist/commands/claim-link/status.js +17 -0
  12. package/dist/commands/describe.js +16 -0
  13. package/dist/commands/device-login.js +40 -0
  14. package/dist/commands/invoice/get.js +18 -0
  15. package/dist/commands/invoice/list.js +19 -0
  16. package/dist/commands/invoice/pay.js +66 -0
  17. package/dist/commands/invoice/received.js +19 -0
  18. package/dist/commands/invoice/send.js +167 -0
  19. package/dist/commands/invoice/sent.js +18 -0
  20. package/dist/commands/invoice/update.js +18 -0
  21. package/dist/commands/logout.js +17 -0
  22. package/dist/commands/operations.js +16 -0
  23. package/dist/commands/otp-login.js +23 -0
  24. package/dist/commands/otp-send.js +17 -0
  25. package/dist/commands/payout/send.js +23 -0
  26. package/dist/commands/payout/status.js +18 -0
  27. package/dist/commands/scope.js +22 -0
  28. package/dist/commands/store/create.js +28 -0
  29. package/dist/commands/transaction/get.js +18 -0
  30. package/dist/commands/transaction/list.js +18 -0
  31. package/dist/commands/wallet/list.js +18 -0
  32. package/dist/commands/wallet/send.js +63 -0
  33. package/dist/commands/whoami.js +18 -0
  34. package/dist/hooks/version-suffix.js +2 -0
  35. package/dist/index.js +17 -0
  36. package/dist/lib/help.js +3 -0
  37. package/oclif.manifest.json +3329 -0
  38. package/package.json +135 -0
@@ -0,0 +1,63 @@
1
+ "use strict";var Zr=Object.create;var Te=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var ri=(e,t)=>{for(var n in t)Te(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ei(t))!ni.call(e,i)&&i!==n&&Te(e,i,{get:()=>t[i],enumerable:!(r=Qr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Zr(ti(e)):{},Qt(t||!e||!e.__esModule?Te(n,"default",{value:e,enumerable:!0}):n,e)),ii=e=>Qt(Te({},"__esModule",{value:!0}),e);var Es={};ri(Es,{default:()=>et});module.exports=ii(Es);var Vr=require("process");var B=require("@oclif/core");var en="public",nt="https://app.allscale.io";var Le=["https://app.allscale.io"];var rt="Override the API base URL (public builds accept only https://app.allscale.io)";var it="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";var le={"app.allscale.io":{authProxyConfigId:"918de955-34ae-4914-914d-5732611edbe7",apiBaseUrl:"https://api.turnkey.com",authProxyUrl:"https://authproxy.turnkey.com"}};function tn(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 nn(e){return tn(e)!==null}function X(e){let t=tn(e);return t!==null&&Le.includes(t.origin)}function ot(e){return X(e)}function ue(){return"".trim()||void 0}function de(){return"public"}function M(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function at(e){try{return new URL(e).origin}catch{return null}}function pe(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return st()}function st(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:c,keyId:l}=o;if(typeof a!="string"||a.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:a.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var rn="`allscale device-login` (or `allscale otp-login` for headless automation)",on="Headless signing needs a legacy JWT session, which this build cannot create \u2014 drop `--headless` to sign through the browser bridge.";var sn="drop `--headless` and use the browser-bridge flow with an agent-key session.",an="allscale device-login",ct=" Requires an existing legacy JWT session, which this build cannot create \u2014 use the browser-bridge flow instead.";var dt="device-login";function ln(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function pt(){return rn}function Oe(){return on}function un(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+sn:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${ln()}\` for headless automation`+"."}function dn(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${dt} --profile ${e}\`.`}var si={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},ai=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 ft(e){return(typeof e=="string"?e:String(e??"")).replace(ai,"")}var ci=64;function lt(e,t=new Map,n=0){if(typeof e=="string")return ft(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ci)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let c of e)a.push(lt(c,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,c]of Object.entries(e))Object.defineProperty(o,a,{value:lt(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(t,n,r){super(ft(n)),this.code=t,this.details=r&&lt(r),this.name="AllscaleError"}get exitCode(){return si[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function pn(e){if(e instanceof s)return e;if(e instanceof Error){if(di(e)){let t=fi(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new s("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var li=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),ui=[/^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 di(e){if(pi(e))return!0;let t=e.name??"";return li.has(t)?t==="CLIError"?ut(e,"parse")||cn(e.message):!0:cn(e.message)}function pi(e){if(!ut(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&ut(e,"parse")}function cn(e){return e?ft(e).split(`
2
+ `).some(t=>ui.some(n=>n.test(t.trim()))):!1}function ut(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function fi(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function fn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var b=A(require("fs")),ve=A(require("path")),bn=A(require("crypto"));var gi="...<truncated>",hi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,mi=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,wt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,gt=String.raw`(?:proxy[_-]?)?authorization`,yi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${gt}"|'${gt}'|${gt})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${wt}`,"gi"),_i=/\b(https?:\/\/)[^\s/?#]+@/gi,ht=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,wi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ht}"|'${ht}'|${ht})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${wt}`,"gi"),mt=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,bi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mt}"|'${mt}'|${mt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${wt}`,"g");function gn(e){return e.replace(_i,"$1<redacted>@").replace(hi,"<redacted-jwt>").replace(yi,"$1$2$3<redacted>").replace(wi,"$1$2<redacted>").replace(bi,"$1$2<redacted>").replace(mi,"Bearer <redacted>")}function hn(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function mn(e,t,n=gi){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;c+=d,l+=p}return c}let i=t-r,o="",a=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(a+l>i)break;o+=c,a+=l}return`${o}${n}`}function P(e,t=16384){return mn(hn(gn(e)),t)}var yt=100,ki=8,Si=8*1024;function Ie(){return{remaining:Si}}function _t(e,t){let n=Math.min(16384,t.remaining),r=mn(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function Z(e,t,n=0,r={}){if(n>ki)return _t("<truncated>",t);if(typeof e=="string"){let i=gn(e);return _t(r.escapeControls?hn(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,yt),o=i.map(a=>Z(a,t,n+1,r));return e.length>i.length&&o.push(_t(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,c]of o.slice(0,yt))i[a]=Z(c,t,n+1,r);return o.length>yt&&(i.output_truncated=!0),i}return e}var bt=require("process");var kt=!1;function St(e){kt=e}function _n(){return kt}var yn="1";function ee(e,t){if(kt){let n={...e};delete n.version;let r=Ie(),i={event:n.event,...n},o=Z(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:yn,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:yn,event:o.event,output_truncated:!0})),bt.stderr.write(`${a}
4
+ `)}else bt.stderr.write(t)}var wn="2",te=null,x=null,ne=!1;function Ei(){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=bn.randomBytes(4).toString("hex");return ve.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Et=64*1024*1024,Ai=null;function kn(){if(ne)return;let e=Ei();if(!e)return;te=null;let t=null;try{if((Ai??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ve.dirname(e);if(b.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=b.statSync(n),l=c.mode&511;if(!c.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let r=b.constants.O_NOFOLLOW??0;t=b.openSync(e,b.constants.O_APPEND|b.constants.O_CREAT|b.constants.O_WRONLY|(b.constants.O_NONBLOCK??0)|r,384);let i=b.fstatSync(t),o=b.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let a=i.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);b.fchmodSync(t,384)}catch(n){if(t!==null)try{b.closeSync(t)}catch{}ee({event:"sidecar_disabled",reason:"open_failed",detail:P(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${P(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}te=e,x=t,ne=!0}var Ti=[/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 Li(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Ti.some(n=>n.test(t))}function Sn(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=Oi(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Li(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Oi(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Ii(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Sn(e.url)}:e}function vi(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=Z(i,Ie()),a=JSON.stringify({version:wn,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:wn,timestamp:t,type:r,output_truncated:!0})),a}function w(e){if(!ne||!te||x===null)return;let t=Ii(e),n=vi(t);try{if(b.fstatSync(x).size+Buffer.byteLength(n,"utf8")+1>Et){ne=!1;try{b.closeSync(x)}catch{}x=null,ee({event:"sidecar_disabled",reason:"size_limit",...te===null?{}:{path:P(te)},max_bytes:Et},`${P(`[allscale] sidecar exceeded ${Et} bytes; disabling it for the rest of this run. Rotate or remove ${te}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}b.appendFileSync(x,`${n}
7
+ `)}catch(r){if(ne=!1,x!==null){try{b.closeSync(x)}catch{}x=null}try{ee({event:"sidecar_disabled",reason:"write_failed",detail:P(r.message)},`${P(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var D=Sn;function En(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Ce(){if(ne=!1,x!==null){try{b.closeSync(x)}catch{}x=null}}function An(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||En()||!t}var fe=ue()??nt,ie={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 U(e){return nn(e)?new URL(e).origin:null}function v(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Tn(){let e=process.env[ie.TOKEN]?.trim();return e&&e.length>0?e:void 0}function At(){let e=process.env[ie.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Re(){let e=process.env[ie.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Ln(){let e=process.env[ie.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function On(){let e=process.env[ie.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function In(){let e=process.env[ie.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vn(e){let t,n;try{t=new URL(e),n=new URL(nt)}catch{return}if(t.host===n.host)return;let r=le[t.host],i=le[n.host];if(!(r===void 0||i===void 0||r.authProxyConfigId!==i.authProxyConfigId))return`Notice: session ${t.origin} signs against the production Turnkey org (mainnet \u2014 real funds).
9
+ `}function Cn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(ue()===void 0&&fe!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
10
+ The CLI default is now ${fe} (production), but a saved profile wins over the default,
11
+ so this session still uses staging. That pin was written before the default changed, so it may just be
12
+ the old default rather than a deliberate choice.
13
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
14
+ To move to production, run: ${an} --api-base ${fe}
15
+ `}var oe=A(require("fs")),Rn=A(require("os")),Tt=A(require("path")),Lt=A(require("@iarna/toml"));var Pi=".allscale",xi="config.toml";function ge(){return Tt.join(Rn.homedir(),Pi)}function Ni(){return Tt.join(ge(),xi)}function Pe(){let e=Ni();if(!oe.existsSync(e))return{};let t=oe.readFileSync(e,"utf-8");try{return Lt.parse(t)}catch(n){throw new s("internal",`Failed to parse ${e}: ${n.message}`)}}function Pn(e){return Object.keys(e.profile??{}).sort()}function xn(e,t){return e.profile?.[t]}function Nn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new s("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function N(e){if(!X(e))throw new s("input.invalid",`Refusing to send credentials to API base ${v(e)}. `+it)}function he(e,t){N(e);let n=U(e),r=typeof t=="string"?U(t):null;if(n&&r===n)return;let i=typeof t=="string"?v(t):"<missing origin binding>";throw new s("input.invalid",`Refusing to send stored credentials: API base ${v(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Bn(e,t){let n=U(e),r=U(t);if(!(n&&r===n))throw new s("input.invalid",`Refusing API request to ${v(t)} because it is outside the configured API origin ${v(e)}.`)}function G(e){let t=ue();if(t===void 0||M(e))return;let n=U(e),r=pe();if(r.length>0){let o=r.map(c=>U(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let a=r.map(c=>v(c.base)).join(", ");throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=U(t);if(!(n!==null&&n===i))throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for ${v(t)}. Re-login against this build's environment, or use a build for that one.`)}var $n=require("@noble/hashes/sha3");function Dn(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Bi={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Un=["ethereum","bsc","base","polygon","arbitrum","optimism"],xe=["USDT","USDC"];function Fn(e){return Bi[e.toLowerCase()]??null}function Mn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function Gn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,$n.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let i=0;i<t.length;i+=1){let o=t[i];if(!/[a-fA-F]/.test(o))continue;let a=Number.parseInt(r[i],16)>=8;if(a&&o!==o.toUpperCase()||!a&&o!==o.toLowerCase())return!1}return!0}var $i=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Kn(e){return $i.has(e.toLowerCase())}function Hn(e,t){let r={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return r?`${r}/${t}`:""}function jn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Yn(e){return e===1?"USDT":"USDC"}var C=require("@oclif/core"),me=class e extends B.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:B.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:B.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:de()==="public"}),"api-base":B.Flags.string({description:rt,helpGroup:"GLOBAL",hidden:de()==="public"}),"insecure-storage":B.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{St(this.jsonEnabled()),kn(),w({type:"session-start",command:this.id??"",argv:Ui(this.argv)});let t=this.constructor;if(de()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Re()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!In())throw this.argv.length>0&&await this.parse(),new s("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=An(this.jsonEnabled()),r=this.argv.length===0&&!n&&qi(t)?this.config.findCommand(this.id??""):void 0;if(r){Ce();let o=await(0,B.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return w({type:"command-end",ok:!0}),Ce(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||fn(i),{data:i})}catch(t){let n=pn(t);w({type:"error",code:n.code,message:P(n.message)}),w({type:"command-end",ok:!1,exitCode:n.exitCode}),Ce(),this.emitError(n),process.exitCode=n.exitCode;return}finally{St(!1)}}resolveSessionApiBaseChain(t){let n=Pe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||At()!==void 0,a=Nn(n,r,At()),c=xn(n,a),l=i??Re(),d=l??c?.api_base??fe,p=Cn({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ee({event:"legacy_staging_profile",api_base:d,profile:a},p)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||N(n),n}resolveContext(t){if(de()==="public"){if(t.token!==void 0)throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Re()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:a,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(N(i),G(i)),{apiBase:i,profile:a,token:n??Tn(),insecureStorage:r||Ln(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${Yi(t)}
16
+ `)}},Be=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"]),Di=new Set(Array.from(Be).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Ui(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(Be.has(o)){t.push(`${o}=<redacted>`);continue}}}if(Be.has(r)){t.push(r),n+1<e.length&&(Be.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(Di.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Fi=/(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 Mi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fi.test(t)}var Gi=/_(removed|cleared|count|total)$/i;function Ki(e,t){return typeof t=="number"&&Gi.test(e)}var Hi=new Set(xe);function ji(e,t){return e==="token_symbol"&&typeof t=="string"&&Hi.has(t)}var Ne=100;function Ot(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ne),r=n.map(i=>Ot(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Ne))n[i]=Mi(i)&&!Ki(i,o)&&!ji(i,o)?"<redacted>":Ot(o,t+1);if(r.length>Ne){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ne} more keys`}return n}return typeof e=="string"?P(e):e}function Yi(e){let t=_n()?void 0:2,n=Ot(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:P(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function qi(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var Lr=require("crypto"),L=require("process");var ir=A(require("path"));var Ct=require("crypto"),u=A(require("fs")),E=A(require("path"));var $e=1024*1024,Ji=5e3,Wi=20,zi=3e4,It=4096,Vi=new Int32Array(new SharedArrayBuffer(4)),ye=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function De(e){return e instanceof ye}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Xi=null;function H(){return new s("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Ue(){return(Xi??process.platform)!=="win32"}function Qn(){if(!Ue())throw H()}function er(e){try{return u.default.lstatSync(e),!1}catch(t){if(!S(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(S(t,"ENOENT"))return!0;throw t}}function S(e,t){return typeof e=="object"&&e!==null&&e.code===t}function _e(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function we(e,t){return e.dev===t.dev&&e.ino===t.ino}function Zi(e){Atomics.wait(Vi,0,0,e)}function tr(e){try{return process.kill(e,0),!0}catch(t){return!S(t,"ESRCH")}}function Qi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qn(e,t){let n=E.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&S(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=u.default.openSync(n,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0));let o=u.default.fstatSync(i),a=u.default.lstatSync(n);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!we(o,a))throw new Error("credential-store parent changed while it was being inspected");_e(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&E.basename(n)===".allscale"&&(u.default.fchmodSync(i,448),c=u.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&u.default.closeSync(i)}return!0}function $(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=u.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&S(o,"ENOENT")?new R:o}if(!we(n,i))throw r.retryOnPathChange?new R:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new ye;if(_e(n,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(t,384);let o=u.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function eo(e,t){if(t.size>$e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc($e+1),r=0;for(;r<n.length;){let i=u.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>$e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Jn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(S(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(S(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=$(e,t,n);return eo(t,r)}finally{t!==null&&u.default.closeSync(t)}}function Wn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(S(i,"ENOENT")&&er(e))return;throw i}let n=u.default.fstatSync(t),r=$(e,t,n);j(e,r)}finally{t!==null&&u.default.closeSync(t)}rr(E.dirname(e))}function to(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(S(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 ye;_e(t,"credential-store replacement target")}function no(e,t){for(let n=0;n<8;n+=1){let r=(0,Ct.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(S(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function nr(e,t){let n=0;for(;n<t.length;){let r=u.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function rr(e){if(process.platform==="win32")return;let t=null;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(t)}catch{}finally{if(t!==null)try{u.default.closeSync(t)}catch{}}}function ro(e,t){let n=Buffer.from(t,"utf8");if(n.length>$e)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),i=E.basename(e),o=null,a=null,c=!1;try{let l=no(r,i);o=l.fd,a=l.tempPath;let d=u.default.fstatSync(o);if(($(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");nr(o,n),u.default.fsyncSync(o),$(a,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),to(e),u.default.renameSync(a,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&a!==null)try{u.default.unlinkSync(a)}catch{}}rr(r)}function io(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function oo(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function so(e,t){if(t.size>It)return null;let n=Buffer.alloc(It+1),r=0;for(;r<n.length;){let o=u.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>It)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function j(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!we(n,t))throw new Error("credential-store lock changed while it was being inspected");_e(n,"credential-store lock"),u.default.unlinkSync(e)}function zn(e,t){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(l){if(S(l,"ENOENT"))try{let d=u.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new R}catch(d){if(S(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=$(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=so(n,i);return{state:(o?.target===t&&o?!tr(o.pid):Date.now()-i.mtimeMs>=zi)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function ao(e,t){for(let n=0;n<8;n+=1){let r=(0,Ct.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},a=null;try{a=u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384);let c=u.default.fstatSync(a),l=$(i,a,c,{allowMultipleLinks:!0});return nr(a,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(a),{claimPath:i,metadata:o,stats:l}}catch(c){if(S(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{a!==null&&u.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function co(e,t){let n;try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){throw S(r,"ENOENT")?new R:r}try{let r=u.default.fstatSync(n),i=$(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!we(i,t))throw new R;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function Vn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(n){if(S(n,"ENOENT"))try{let r=u.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new R}catch(r){if(S(r,"ENOENT"))return!1;throw r}throw n}return $(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function lo(e){let t;try{t=u.default.openSync(e,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_RDWR|(u.default.constants.O_NOFOLLOW??0),384)}catch(r){if(S(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=$(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{j(e,n)}catch{}throw u.default.closeSync(t),r}}function K(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");Zi(Wi)}function Xn(e){let t=E.dirname(e),n=E.basename(e),r=io(e),i=oo(e),o=ao(t,n),a=Date.now()+Ji,c=!1,l=!1,d=null,p;try{for(;d===null;)try{if(Vn(i)){K(a,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=co(r,o.stats),c=!0}catch(f){if(l&&!c){try{j(r,o.stats)}catch{}l=!1}if(f instanceof R){K(a,!1);continue}if(!S(f,"EEXIST"))throw f;let g;try{g=zn(r,n)}catch(m){if(m instanceof R){K(a,!1);continue}throw m}if(g.state==="absent")continue;if(g.state==="stale"){let m;try{m=lo(i)}catch(k){if(k instanceof R){K(a,!1);continue}throw k}if(m!==null){try{let k;try{k=zn(r,n)}catch(T){if(T instanceof R){K(a,!1);continue}throw T}k.state==="stale"&&j(r,k.stats)}finally{vt(m)}continue}}let h;try{h=Vn(i)}catch(m){if(m instanceof R){K(a,!1);continue}throw m}K(a,h)}}catch(f){p=f}try{j(o.claimPath,o.stats)}catch(f){!S(f,"ENOENT")&&!c&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function vt(e){try{j(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function uo(e,t){let n=Qi(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Zn(e){let t=E.dirname(e),n=E.basename(e);for(let r of u.default.readdirSync(t)){let i=uo(r,n);if(i===null||tr(i))continue;let o=E.join(t,r),a=null;try{try{a=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(S(d,"ENOENT")||S(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(a),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!we(c,l))continue;try{_e(c,"credential-store orphan")}catch{continue}j(o,c)}catch(c){if(!S(c,"ENOENT"))throw c}finally{a!==null&&u.default.closeSync(a)}}}function be(e,t,n){if(!Ue()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw H();if(!qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw H()}});let a=Xn(e);try{return Zn(e),n({read:()=>Jn(e),remove:()=>Wn(e),write:()=>{throw H()}})}finally{vt(a)}}if(!t.createParent){let o=!1;try{o=er(e)}catch{throw H()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw H()}})}throw H()}if(!qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Xn(e);try{return Zn(e),n({read:()=>Jn(e),remove:()=>Wn(e),write:o=>ro(e,o)})}finally{vt(i)}}var Rt="allscale-cli";function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function or(e){return Bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function q(e){return new s("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function Pt(){return new s("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Fe(){return new s("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var Y,xt=!1;function po(){return On()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function fo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
17
+ `,1)[0]==="Cannot find module 'keytar'"}function go(){if(Y!==void 0)return Y;if(po())return xt=!1,Y=null,Y;try{Y=require("keytar"),xt=!1}catch(e){xt=!fo(e),Y=null}return Y}function sr(){let e=Ue()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new s("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Nt(e){try{return await e()}catch{throw sr()}}var $t=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Nt(()=>this.keytar.getPassword(Rt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw q("OS keychain")}if(!or(r))throw q("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Nt(()=>this.keytar.setPassword(Rt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Nt(()=>this.keytar.deletePassword(Rt,t))}},ho="credentials.json",Dt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??ir.join(ge(),ho)}read(t){let n;try{n=t.read()}catch(i){throw De(i)?Pt():q("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw q("plaintext file")}if(!Bt(r)||!Bt(r.profiles))throw q("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw De(r)?Pt():Fe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!or(r))throw q("plaintext file");return r}}async get(t){try{return be(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof s?n:q("plaintext file")}}async set(t,n){try{be(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof s?r:Fe()}}async delete(t){try{be(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 s?n:Fe()}}async clearProfile(t){try{return be(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 s?n:De(n)?Pt():Fe()}}};function Me(e){if(e.insecureStorage)return Qn(),new Dt(e.insecureFilePath);let t=go();if(t)return new $t(t);throw sr()}var Ut=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new s("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ge(){return new Ut}var J="allscale_access_token",Ft="allscale_refresh_token";function Ke(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function ke(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Mt(e,t){return e.find(n=>n.name===t)?.value??null}var ar=A(require("crypto")),cr=A(require("fs")),lr=A(require("path"));var mo="key-id",yo="x-allscale-cli-version",Gt="cli-1",_o="aScaLe_cli_obf_v1",wo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function bo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var ko=bo(wo,_o),He=`Bearer ${ko}`;function ur(e,t){let n=at(e);if(n!==null)return t.find(r=>at(r.base)===n)}function So(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=pe();if(t.length>0){let r=ur(e,t);if(r)return r.key;if(M(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:M(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 Eo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=pe();if(t.length>0){let r=e!==void 0?ur(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&M(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Gt}if(!M(t[0].base))return Gt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Gt}function Ao(){return"0.1.0"}function To(){return new s("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function se(e,t){let n=So(t);if(!n)throw To();let r=Eo(t),i=Math.floor(Date.now()/1e3).toString(),o=ar.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),a={timestamp:i,"secret-key":o,[yo]:Ao()};return r.length>0&&(a[mo]=r),a}function Se(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Lo(e,t={}){let n;try{n=Pn(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new s("auth.unknown_profile",dn(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function je(e){if(e.profileExplicit){let t=Lo(e.profile);if(t)return t}return new s("auth.no_token",un(e.profile,e.flow))}var Je=256*1024,Ye=class extends s{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},qe=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 Kt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Ye(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],c=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,g)=>{l=setTimeout(()=>{g(new qe(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:g,value:h}=p?await Promise.race([f,p]):await f;if(g)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new Ye(e.status,t,n.oversizeKind);a.push(Buffer.from(h))}}catch(f){throw f instanceof qe&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(a,c).toString("utf8")}var Oo="X-AllScale-Api-Key",Io=3e4,vo=32*1024*1024,Co=4*1024*1024;function Ro(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function Po(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function xo(e,t){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${D(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 Ht(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}xo(e.status,e.url)}}var dr="--dns-result-order=ipv4first";async function We(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),a=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),l=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new s("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${dr} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${dr}`})}var W=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??Io;if(!Number.isFinite(r)||r<1)throw new s("input.invalid","HTTP request timeout must be a positive number of milliseconds.");N(this.opts.apiBase),G(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=Ro(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(a){throw o.timedOut()?new s("transport.timeout",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(a instanceof s)?new s("transport.network",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();Bn(this.opts.apiBase,i);let o=r?.agent_key,a=t.auth??"auto",c=hr(t.path),l=a==="required"?!0:a==="none"?!1:$o(t.path);if((c||a==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw je({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Se(t.body),p=!!o||!!r?.access_token;l&&p&&!this.opts.override&&he(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();w({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(k){throw new s("transport.network",`Network error contacting ${D(i)}: ${k instanceof Error?k.message:String(k)}`)}if(w({type:"response",status:h.status,durationMs:Date.now()-g}),l&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let k=await Po(this.refreshSingleFlight(),t.signal),T=this.buildHeaders({attachAuth:l&&!!k.access_token,bodyForSig:d,tokens:k,extra:t.headers}),y=Date.now();w({type:"request",method:t.method??"GET",url:i});let _;try{_=await fetch(i,{method:t.method??"GET",headers:T,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(O){throw new s("transport.network",`Network error contacting ${D(i)} on refresh-retry: ${O instanceof Error?O.message:String(O)}`)}return w({type:"response",status:_.status,durationMs:Date.now()-y}),pr(_,{withMetadata:n.withMetadata,authBearing:l,responseKind:fr(t)})}return pr(h,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:fr(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...se(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=He;let i=t.tokens;if(i?.agent_key)return r[Oo]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=ke([{name:J,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new s("auth.token_expired",`No refresh token available; log in again \u2014 ${pt()}.`);if(he(this.opts.apiBase,t.api_base),t.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than 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=ke([{name:J,value:t.access_token},{name:Ft,value:t.refresh_token}]),i=se("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,a=!1,c=setTimeout(()=>{a=!0,o.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw w({type:"refresh",ok:!1}),new s("transport.network",a&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${D(n)} timed out after 10s with no response.`:`Network error during token refresh against ${D(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}w({type:"response",status:l.status,durationMs:0});try{await Ht(l)}catch(h){throw w({type:"refresh",ok:!1}),h}if(l.status!==200){w({type:"refresh",ok:!1}),await We(l);let h=await mr(l);throw await We(l,h),z(l.status,h),new s("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${pt()}.`,{status:l.status})}let d=Ke(l.headers),p=Mt(d,J),f=Mt(d,Ft);if(!p||!f)throw w({type:"refresh",ok:!1}),new s("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,g),w({type:"refresh",ok:!0}),g}},No=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function hr(e){let t=e.split(/[?#]/,1)[0];return No.some(n=>t===n||t.startsWith(`${n}/`))}var Bo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function jt(e){let t=e.split(/[?#]/,1)[0];return Bo.some(n=>n.test(t))}function $o(e){return hr(e)||jt(e)}async function pr(e,t={}){await Ht(e);let n=e.status>=200&&e.status<300;n||await We(e);let r=t.responseKind??"mutation",o=await Kt(e,n?r==="query"?vo:Co:Je,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await We(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:a}}return a}let c=Fo(a)??`HTTP ${e.status}`;if(z(e.status,a),e.status===401){if(t.agentKeyAuth)throw new s("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new s(l,c,{status:401,body:a})}throw e.status===403?new s("auth.permission_denied",c,{status:403,body:a}):e.status===404?new s("not_found",c,{status:404,body:a}):e.status===429?new s("rate_limited",c,{status:429,body:a}):e.status>=500?new s("backend.internal",c,{status:e.status,body:a}):new s("input.invalid",c,{status:e.status,body:a})}function fr(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var gr=2014;function Do(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===gr||n===String(gr)}var Uo=1e4;async function mr(e,t=Uo){if(e.status>=200&&e.status<300)return"";try{return await Kt(e,Je,{timeoutMs:t})}catch{return""}}function z(e,t){if(!(e>=200&&e<300)&&Do(t))throw new s("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}function Fo(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 Mo=/^\/(api\/)?(v1\/)?public\//;function Yt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Mo.test(n),i=n&&jt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new W({apiBase:e.apiBase,tokenStore:Me({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(i)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var ae={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_TOKEN_CONSUMED:7411},Go=new Set(Object.values(ae));async function yr(e,t,n){return _r(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init")}async function qt(e,t){return _r(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function _r(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof s){let a=Ko(o,r);if(a!==null)throw a}throw o}return Ho(i,r)}function Ko(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,i=typeof r.code=="number"?r.code:void 0;if(i===void 0||i===0||!Go.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return wr(i,o,t)}function Ho(e,t){if(e.code!==void 0&&e.code!==0)throw wr(e.code,e.message,t);if(e.data===void 0)throw new s("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function wr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case ae.CLI_OP_NOT_FOUND:return new s("not_found",r,{broker_code:e});case ae.CLI_OP_EXPIRED:return new s("wallet.bridge_timeout",r,{broker_code:e});case ae.CLI_OP_UNAUTHORIZED:return new s("auth.permission_denied",r,{broker_code:e});case ae.CLI_OP_UNKNOWN_TYPE:return new s("input.invalid",r,{broker_code:e});case ae.CLI_OP_TOKEN_CONSUMED:return new s("input.invalid",r,{broker_code:e});default:return new s("backend.internal",r,{broker_code:e})}}var kr=require("child_process");async function Sr(e,t={}){if(!ot(e))throw new s("input.invalid",`Refusing to launch browser for untrusted origin: ${v(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new s("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(r==="linux"&&!n.DISPLAY&&!i)throw new s("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let o=jo(r,i);await Yo(o.command,[...o.args,e])}function jo(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Yo(e,t){return new Promise((n,r)=>{let i;try{i=(0,kr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(a){r(br(e,a));return}let o=!1;i.once("error",a=>{o||(o=!0,r(br(e,a)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function br(e,t){return new s("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Er=A(require("http"));var qo=9e4,Jo=16*1024;function Ar(e){let t=e.timeoutMs??qo;return new Promise((n,r)=>{let i=!1,o=!1,a=null,c,l,d=new Promise((f,g)=>{c=f,l=g}),p=Er.createServer((f,g)=>{Wo(f,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:h=>{a&&clearTimeout(a),c(h),p.close()}})});p.on("error",f=>{let g=new s("transport.network",`Loopback listener error: ${f.message}`);o?l(g):r(g),a&&clearTimeout(a)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),r(new s("transport.network","Failed to read loopback listener port"));return}a=setTimeout(()=>{l(new s("wallet.bridge_timeout",`Bridge timed out after ${t}ms waiting for browser callback.`)),p.close()},t),a.unref?.(),o=!0,n({port:f.port,awaitResult:d,close:()=>{a&&clearTimeout(a),p.close()}})})})}function Wo(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let i=0,o=[],a=!1;e.on("data",c=>{if(!a){if(i+=c.length,i>Jo){a=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(a)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=l,p=typeof d.state=="string"?d.state:"",f=typeof d.result_token=="string"?d.result_token:void 0,g=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!zo(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&g===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:f,result_data:g})}),e.on("error",()=>{a||(a=!0)})}function zo(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Jt(e){try{return JSON.parse(e),!0}catch{return!1}}function Tr(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,a=()=>{o&&(clearTimeout(o),o=null)},c=()=>{a(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,a(),e.off("data",d),e.off("end",p),e.off("error",f),e.pause()},d=h=>{if(n)return;a(),t+=h.toString();let m=t.trim(),k=t.length-t.trimStart().length,T=t.indexOf(`
18
+ `,k),y=T===-1?"":t.slice(k,T).trim();if(m.startsWith("{")){if(Jt(m)){l(),r(m);return}if(T===-1){c();return}if(!Jt(y)&&!y.endsWith("}")){let _=t.slice(T+1),O=_.split(`
19
+ `).find(Ee=>Ee.trim()!=="")??"";if(y==="{"&&(!/\S/.test(_)||/^\s*"[^"]*"\s*:/.test(_)||/^\s*"[^"]*$/.test(O))){c();return}}l(),r(Jt(y)?y:t.slice(k).trim());return}if(T!==-1){l(),r(y);return}else!m&&t.includes(`
20
+ `)&&(l(),r(""))},p=()=>{if(n)return;let h=t.trim();if(!h){l();return}l(),r(h)},f=()=>{n||l()},g=new Promise(h=>{r=h});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",f),{promise:g,cancel:()=>{n||l()}}}function Vo(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function Or(e){let t=Yt(e.ctx),n=e.browserBase??e.ctx.apiBase,r=rs(n),i=e._openBrowser??Sr,o=e._startListener??Ar,a=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,Lr.randomBytes)(32).toString("hex"),d=await yr(t,e.op,e.payload);w({type:"bridge_init",op_id:d.op_id,expires_at:d.expires_at});let p=d.expires_at-Math.floor(Date.now()/1e3),f=Number.isFinite(p)?Math.max(0,p):0,g=Math.min(Math.max(6e4,f*1e3),2147483647),h=e.timeoutMs!=null&&e.timeoutMs>0&&e.timeoutMs<=2147483647?e.timeoutMs:g;L.stderr.write(`Bridge op registered (op_id=${d.op_id}, op TTL ~${f}s, waiting up to ${Math.round(h/1e3)}s for confirmation).
21
+ `);let m=await o({state:l,expectedOrigin:r,timeoutMs:h}),k=m.awaitResult.then(I=>({source:"loopback",...I}),I=>({source:"listener_error",error:I})),T=Date.now(),y=setInterval(()=>{let I=Math.floor((Date.now()-T)/1e3);L.stderr.write(`Still waiting for confirmation\u2026 (${I}s elapsed)
22
+ `)},15e3);y.unref?.();let _,O=e.signal===void 0?void 0:Vo(e.signal);try{let I=es(n,{op_id:d.op_id,port:m.port,state:l});w({type:"bridge_browser_open",url:I});let Ee=a==="ack"?"confirmation token":"result";if(L.stderr.write(c?e.autoOpen===!1?`
23
+ Confirm this in your browser. Open the URL below on any device where
24
+ you're signed in to AllScale (local auto-open is disabled):
25
+
26
+ ${I}
27
+
28
+ `:`
29
+ Confirm this in your browser. The URL is below \u2014 it auto-opens if a
30
+ browser is available on this machine; otherwise open it on any device
31
+ where you're signed in to AllScale:
32
+
33
+ ${I}
34
+
35
+ `:`
36
+ Confirm this in a browser on this machine. The callback must reach the
37
+ local listener; non-interactive stdin cannot accept a result pasted
38
+ back from another device:
39
+
40
+ ${I}
41
+
42
+ `),e.autoOpen===!1)L.stderr.write(`(browser auto-open skipped \u2014 use the link above)
43
+ `);else try{await i(I),L.stderr.write(`(opened in your default browser)
44
+ `)}catch{L.stderr.write(`(no local browser to open \u2014 use the link above)
45
+ `)}c?L.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
46
+ reach this machine (e.g. you opened the link elsewhere over SSH), copy
47
+ the ${Ee} the page shows, paste it here, and press Enter:
48
+
49
+ `):L.stderr.write(`stdin is non-interactive; waiting for the browser callback.
50
+
51
+ `),c&&(_=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:Tr());let tt=[k];_!==void 0&&tt.push(_.promise.then(Xr=>({source:"paste",line:Xr}))),O!==void 0&&tt.push(O.promise);let V=await Promise.race(tt);if(V.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(V.source==="listener_error")throw Xo(V.error);if(V.source==="loopback")return L.stderr.write(`Browser returned result; processing\u2026
52
+ `),await Zo(t,a,V);let Ae=V.line.trim();if(!Ae)throw new s("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(a==="ack"&&Ae.startsWith("{"))throw new s("wallet.bridge_invalid_response","Pasted value looks like JSON, not a confirmation token. Copy the single-line token the /cli page shows, not the result JSON.");if(a==="ack"&&/\s/.test(Ae))throw new s("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return L.stderr.write(`Received pasted ${Ee}; processing\u2026
53
+ `),await Qo(t,a,Ae)}finally{clearInterval(y),O?.cleanup(),_?.cancel(),m.close()}}function Xo(e){return e instanceof s&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_invalid_response")?e:new s("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function Zo(e,t,n){if(t==="ack"){if(!n.result_token)throw new s("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");w({type:"bridge_result_received",source:"loopback"});let r=await qt(e,n.result_token);return w({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),L.stderr.write(`Verified by broker.
54
+ `),{ack:r,result_data:n.result_data}}if(!n.result_data)throw new s("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return w({type:"bridge_result_received",source:"loopback"}),w({type:"bridge_data_received",source:"loopback"}),L.stderr.write(`Result received from browser.
55
+ `),{result_data:n.result_data}}async function Qo(e,t,n){if(t==="ack"){w({type:"bridge_result_received",source:"paste"});let i=await qt(e,n);return w({type:"bridge_verified",op_id:i.op_id,source:"paste"}),L.stderr.write(`Verified by broker.
56
+ `),{ack:i}}let r;try{r=ns(n)}catch(i){throw i instanceof s&&i.code==="input.invalid"?new s("wallet.bridge_invalid_response",i.message):i}return w({type:"bridge_result_received",source:"paste"}),w({type:"bridge_data_received",source:"paste"}),L.stderr.write(`Result accepted.
57
+ `),{result_data:r}}function es(e,t){let n=new URL("/cli",Ir(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}var ts=/^0x[0-9a-fA-F]{64}$/;function ns(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(ts.test(e))return{tx_hash:e};throw new s("input.invalid",`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function rs(e){return Ir(e).origin}function Ir(e){if(!X(e))throw new s("input.invalid",`Refusing browser base ${v(e)}: bridge state and operation identifiers may only be sent to an exact trusted AllScale origin (${Le.join(", ")}) or an explicit loopback development origin. It must not contain embedded URL userinfo.`);return new URL(e)}var ze=/^0x[0-9a-fA-F]{64}$/,is=["wallet.bridge_timeout","wallet.bridge_invalid_response","wallet.headless_sign_failed"];function vr(e){return typeof e=="string"&&is.includes(e)}var os=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,ss=/^0(?:\.0+)?$/,Cr=128;function Rr(e,t,n={}){if(t.length>Cr)throw new s("input.invalid",`${e} is too long; decimal values may contain at most ${Cr} characters.`);let r=t.trim();if(!os.test(r))throw new s("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&ss.test(r))throw new s("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Pr(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new s("input.invalid",`${e} supports at most ${n} effective decimal places for the selected token and chain; got '${t}'. The CLI will not round a funds amount.`);return t}var Wt=require("process");function xr(e){let t=e.split(".");if(t.length!==3)throw new s("auth.token_expired","Stored token is not a valid JWT.");try{let n=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(n)}catch(n){throw new s("auth.token_expired",`Failed to decode JWT payload: ${n.message}`)}}var ce="ALLSCALE_OTP";function Br(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[ce];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function $r(e,t){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(t){let r=process.env[ce];return typeof r=="string"&&r.trim().length>0&&Wt.stderr.write(`warning: --otp-stdin is set, so ${ce} is ignored (stdin takes precedence).
58
+ `),Nr()}let n=process.env[ce];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return Wt.stderr.write("OTP code: "),Nr()}var as=1024;async function Nr(){let e="";try{for await(let t of process.stdin){e+=t;let n=e.indexOf(`
59
+ `);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=as)throw new s("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(t){throw t instanceof s?t:new s("input.invalid",`Failed to read OTP from stdin: ${t instanceof Error?t.message:String(t)}`)}return e.trim()}var jr=require("crypto"),Yr=require("@turnkey/crypto"),Qe=require("@turnkey/api-key-stamper"),qr=require("@turnkey/http");var F=A(require("fs")),Dr=A(require("path")),Ur=require("crypto");var cs="device_id";function Fr(){let e=null,t=null;try{e=ge(),t=Dr.join(e,cs)}catch{}try{if(t){let r=F.readFileSync(t,"utf-8");if(r.length>70)throw new Error("oversized device_id");let i=r.split(`
60
+ `)[0].trim();if(i&&/^cli_[0-9a-f]{32}$/.test(i))return i}}catch{}let n=`cli_${(0,Ur.randomBytes)(16).toString("hex")}`;try{if(!e||!t)throw new Error("persistence unavailable");F.mkdirSync(e,{recursive:!0,mode:448}),F.writeFileSync(t,`${n}
61
+ `,{mode:384});try{F.chmodSync(t,384)}catch{}}catch{}return n}var ls=require("crypto");var Mr=128;function Ve(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Mr)throw new s("input.invalid",`--idempotency-key must contain 1-${Mr} characters after trimming.`);return t}var Gr=le;function us(e){let t="";try{t=new URL(e).host}catch{}let n=Gr[t];if(!n)throw new s("wallet.headless_config_missing",`Headless signing has no Turnkey config for '${t||"(unparseable URL)"}'. Supported hosts: ${Object.keys(Gr).join(", ")}. Upgrade the CLI or contact support.`);if(!n.apiBaseUrl.startsWith("https:")||!n.authProxyUrl.startsWith("https:"))throw new s("wallet.headless_config_missing",`Headless Turnkey config for '${t}' has a non-HTTPS URL \u2014 refusing to send credentials.`);return n}var ds=1,Jr=4,ps="CLIENT_SIGNATURE_SCHEME_API_P256",fs="900",Xt=3e4,gs=9e4,Kr=12e4,Xe=256*1024;async function Ze(e,t,n,r){if(!n.startsWith("/")||n.startsWith("//"))throw new s("backend.internal",`secureFetch: path must be root-relative with a single leading '/' (got '${n.split("?")[0]}')`);let i=new URL(n,e).toString(),o=n.split("?")[0],a=r.body===void 0?"":Se(r.body),c=se(a,e),l=[{name:J,value:r.accessToken},...(r.extraCookies??[]).map(g=>({name:g.name,value:g.value}))],d;try{d=await fetch(i,{method:t,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},Authorization:He,Cookie:ke(l),...c},body:r.body===void 0?void 0:a,redirect:"manual",signal:AbortSignal.timeout(r.timeoutMs??Xt)})}catch(g){throw new s("transport.network",`Network error contacting AllScale API (${o}): ${g instanceof Error?g.message:String(g)}`)}let p=await Wr(d,o),f=null;if(p)try{f=JSON.parse(p)}catch{f=null}return{status:d.status,json:f,setCookies:Ke(d.headers)}}async function Wr(e,t){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Xe)throw new s("backend.internal",`Response body from ${t} declares ${n} bytes (over the ${Xe} cap); refusing to read.`);if(!e.body)return"";let r=[],i=0;try{for await(let o of e.body){if(i+=o.byteLength,i>Xe)throw new s("backend.internal",`Response body from ${t} is too large (over the ${Xe}-byte cap); refusing to parse.`);r.push(Buffer.from(o))}}catch(o){if(o instanceof s)throw o}return Buffer.concat(r).toString("utf-8")}async function zt(e,t,n,r){if(!t.startsWith("/")||t.startsWith("//"))throw new s("backend.internal",`authProxyPost: path must be root-relative with a single leading '/' (got '${t.split("?")[0]}')`);let i;try{i=await fetch(new URL(t,e.authProxyUrl).toString(),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Proxy-Config-ID":e.authProxyConfigId},body:JSON.stringify(n),redirect:"manual",signal:AbortSignal.timeout(Xt)})}catch(c){throw new s("transport.network",`Network error contacting Turnkey auth proxy (${r}): ${c instanceof Error?c.message:String(c)}`)}let o=await Wr(i,`Turnkey ${r}`),a={};if(o)try{let c=JSON.parse(o);a=c&&typeof c=="object"&&!Array.isArray(c)?c:{}}catch{a={}}if(i.status<200||i.status>=300){let c=i.status===401&&r==="otp_verify"?"Invalid or expired OTP code \u2014 re-request the code and try again.":i.status===400&&r==="otp_verify"?"Malformed OTP code \u2014 check the code format and try again.":i.status===400&&r==="otp_init"?"Turnkey rejected the account email for OTP delivery \u2014 the account may not be set up for email OTP; contact support.":`Turnkey ${r} failed: HTTP ${i.status}`,l=i.status===429?"rate_limited":i.status>=500?"backend.internal":r==="otp_verify"&&(i.status===400||i.status===401)?"input.invalid":"backend.internal";throw new s(l,c,{status:i.status,where:r})}return a}function hs(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Vt(e){return e===401?"auth.token_expired":e===429?"rate_limited":"backend.internal"}function Hr(e){let t=new Map;for(let n of e)n.name!==J&&t.set(n.name,n);return[...t.values()]}async function ms(e){if(N(e.apiBase),G(e.apiBase),e.token)return e.token;let n=await Me({insecureStorage:e.insecureStorage}).get(e.profile);if((n?.access_token||n?.agent_key)&&he(e.apiBase,n.api_base),n?.agent_key)throw new s("auth.permission_denied","Headless signing requires the user token from a legacy JWT session; agent keys do not contain it. The CLI no longer issues cookie sessions \u2014 use the browser-bridge flow instead (omit --headless).");if(!n?.access_token)throw je({profile:e.profile,profileExplicit:e.profileExplicit,flow:"headless"});return n.access_token}async function ys(e,t){let n=xr(t).user_id,r=typeof n=="string"?n:"";if(!r)throw new s("auth.no_token","Access token has no user_id; re-login.");let o=await Ze(e.apiBase,"POST","/api/secure/graphql",{accessToken:t,body:{query:"query($id:String!){business(id_str:$id){email turnkey{auth_type turnkey_sub_org_id turnkey_session_user_id}}}",variables:{id:r}}});if(o.status!==200)throw z(o.status,o.json),new s(Vt(o.status),`Failed to load account turnkey info (HTTP ${o.status}).`,{http_status:o.status});if(o.json?.errors?.length){let c=o.json.errors.some(l=>/unauth|forbidden|expired|denied|not.?allowed/i.test(l?.message??""));throw new s(c?"auth.token_expired":"backend.internal",c?`Account info query was rejected (authorization) \u2014 the access token may be stale. ${Oe()}`:"Account info query returned GraphQL errors.",{http_status:o.status,graphql_error_count:o.json.errors.length})}if(!o.json?.data?.business)throw new s("backend.internal",`Account info query returned no business data \u2014 the account may not exist or the access token may be stale. ${Oe()}`,{http_status:o.status});let a=o.json.data.business.turnkey;return{businessId:r,email:o.json.data.business.email??"",authType:a?.auth_type??0,subOrgId:a?.turnkey_sub_org_id??"",sessionUserId:a?.turnkey_session_user_id??""}}function _s(e){return(e&ds)!==0&&(e&Jr)===0}async function zr(e,t){let{ctx:n}=e;N(n.apiBase),G(n.apiBase);let r=us(n.apiBase),i=vn(n.apiBase);if(i!==void 0&&process.stderr.write(i),(e.otp?.trim()||process.env[ce]?.trim())&&!e.otpId?.trim()&&!e.otpStdin)throw new s("input.invalid","--otp / ALLSCALE_OTP without --otp-id always fails for headless signing: the CLI emails a fresh OTP at run time that a pre-set value can't match. Use --otp-stdin (pipe the just-emailed code), add --otp-id, or unset ALLSCALE_OTP to use the interactive prompt.");let a=Ve(typeof e.payload.idempotency_key=="string"?e.payload.idempotency_key:void 0);if(!a)throw new s("input.invalid","Headless signing requires a caller-stable idempotency key.");let c=await ms(n),l=await ys(n,c);if(!_s(l.authType))throw new s("wallet.headless_not_supported",(l.authType&Jr)!==0?"This account has a passkey enabled, which can't sign headless. Omit --headless to use the browser flow.":"This account isn't eligible for headless signing (it needs Turnkey email-OTP enabled and no passkey). Omit --headless to use the browser flow.");if(!l.email)throw new s("backend.internal","Account has no email for OTP delivery.");if(!l.subOrgId||!l.sessionUserId)throw new s("wallet.headless_setup_required","Account has no Turnkey session user yet \u2014 sign in once on the web app to provision it, then retry --headless.");let d=Fr(),p=await Ze(n.apiBase,"GET",`/api/v1/secure/turnkey/sessions/current/status?device_id_str=${encodeURIComponent(d)}`,{accessToken:c});if(p.status!==200)throw z(p.status,p.json),new s(Vt(p.status),`Failed to get Turnkey session status (HTTP ${p.status}).`,{http_status:p.status});if(!p.json?.data?.public_key)throw new s("backend.internal","Turnkey session status returned no session public key \u2014 the backend may need to re-provision it; contact support.",{http_status:p.status});let f=p.json.data.public_key,g=Hr(p.setCookies);if(g.length===0)throw new s("backend.internal","get_session_status returned no session cookie (only the access-token cookie, or none at all); cannot continue headless.");let h=(0,jr.randomUUID)();await ws({env:r,runId:h,subOrgId:l.subOrgId,sessionUserId:l.sessionUserId,email:l.email,sessionPublicKey:f,otp:e.otp,otpStdin:!!e.otpStdin,otpId:e.otpId,resolveOtp:t});let m=await Ze(n.apiBase,"POST","/api/v1/secure/turnkey/sessions/current:activate",{accessToken:c,body:{device_id_str:d},extraCookies:g});if(m.status!==200)throw z(m.status,m.json),new s(Vt(m.status),`Failed to activate Turnkey session (HTTP ${m.status}).`,{http_status:m.status});if(typeof m.json?.data?.expires_at_ts!="number")throw new s("backend.internal","Turnkey session did not activate (empty, unreadable, or no-expiry response); not attempting to sign.",{http_status:m.status});let k=Hr(m.setCookies),T=k.length?k:g,y=a,_;try{_=await Ze(n.apiBase,"POST","/api/v1/secure/web3/transfers:gasless-evm-token",{accessToken:c,body:{chain:e.payload.chain,to_address:e.payload.to_address,amount:e.payload.amount,stable_coin:e.payload.stable_coin,device_id_str:d,idempotency_key:y},extraCookies:T,timeoutMs:gs})}catch{throw new s("wallet.headless_sign_failed","Headless signed transfer network call failed; the transaction may have been broadcast \u2014 verify on-chain before retrying.",{idempotency_key:y})}let O=_.json?.data?.tx_hash;if(_.status!==200||typeof O!="string"||!ze.test(O))throw new s("wallet.headless_sign_failed",`Headless signed transfer failed (HTTP ${_.status}). The transaction may have been broadcast \u2014 verify on-chain before retrying.`,{idempotency_key:y,..._.status===401?{recovery_hint:`HTTP 401 usually means the AllScale access token expired and the transfer was rejected before broadcast \u2014 if nothing shows on-chain, re-login and retry. ${Oe()}`}:{}});return{result_data:{tx_hash:O},idempotency_key:y}}async function ws(e){let{env:t}=e,n,r;try{n=(0,Yr.generateP256KeyPair)(),r=new Qe.ApiKeyStamper({apiPublicKey:n.publicKey,apiPrivateKey:n.privateKey})}catch{throw new s("backend.internal","Failed to generate the ephemeral Turnkey login key.")}let i=e.otpId?.trim(),o=i||(await zt(t,"/v1/otp_init",{otpType:"OTP_TYPE_EMAIL",contact:e.email},"otp_init")).otpId;if(!o)throw new s("backend.internal","Turnkey otp_init returned no otpId.");let a;if(e.otpStdin){let y,_=e.resolveOtp(e.otp,e.otpStdin);try{a=await Promise.race([_,new Promise((O,I)=>{y=setTimeout(()=>I(new s("input.invalid","Timed out waiting for the OTP on stdin (--otp-stdin). Pipe the emailed code within "+Math.round(Kr/1e3)+"s.")),Kr)})])}finally{y&&clearTimeout(y),_.catch(()=>{})}}else a=await e.resolveOtp(e.otp,e.otpStdin);if(!a)throw new s("input.invalid","No OTP code provided. Pass --otp, set ALLSCALE_OTP, or pipe via --otp-stdin.");let c=await zt(t,"/v1/otp_verify",{otpId:o,otpCode:a,publicKey:n.publicKey},"otp_verify").catch(y=>{let _=y instanceof s?y.details?.status:void 0;throw y instanceof s&&y.code==="input.invalid"&&i&&_===401?new s(y.code,y.message+" If you passed --otp-id, the prior otpId may itself have expired; re-run WITHOUT --otp-id to start a fresh OTP flow.",y.details):y});if(!c.verificationToken)throw new s("backend.internal","Turnkey otp_verify returned no verificationToken.");let l=hs(c.verificationToken);if(typeof l.id!="string"||l.id.length===0)throw new s("backend.internal","Turnkey verification token has no id.");let d=JSON.stringify({login:{publicKey:n.publicKey},tokenId:l.id,type:"USAGE_TYPE_LOGIN"}),p;try{p=await r.sign(d,Qe.SignatureFormat.Raw)}catch{throw new s("backend.internal","Failed to stamp the Turnkey login request.")}let f={message:d,publicKey:n.publicKey,scheme:ps,signature:p};await zt(t,"/v1/otp_login",{verificationToken:c.verificationToken,publicKey:n.publicKey,clientSignature:f,organizationId:e.subOrgId},"otp_login");let g=new qr.TurnkeyClient({baseUrl:t.apiBaseUrl},r),h,m,k=g.createApiKeys({type:"ACTIVITY_TYPE_CREATE_API_KEYS_V2",timestampMs:String(Date.now()),organizationId:e.subOrgId,parameters:{apiKeys:[{apiKeyName:`cli-headless-${e.runId}`,publicKey:e.sessionPublicKey,curveType:"API_KEY_CURVE_P256",expirationSeconds:fs}],userId:e.sessionUserId}});try{h=await Promise.race([k,new Promise((y,_)=>{m=setTimeout(()=>_(new s("transport.network","Network error contacting Turnkey API (createApiKeys): timed out. A key registration may still be in flight \u2014 wait \u2265 30s before retrying.",{activity:"createApiKeys",hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"})),Xt)})])}catch(y){if(y instanceof s)throw y;let _=y instanceof TypeError||y instanceof DOMException&&y.name==="AbortError"||y instanceof Error&&(y.name==="FetchError"||y.constructor.name==="FetchError");throw new s(_?"transport.network":"backend.internal",_?"Network error contacting Turnkey API (createApiKeys). A key registration may still be in flight \u2014 wait \u2265 30s before retrying.":"Turnkey API rejected the createApiKeys request.",{activity:"createApiKeys",..._?{hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"}:{}})}finally{m&&clearTimeout(m),k.catch(()=>{})}if(!h.activity?.result?.createApiKeysResult?.apiKeyIds?.[0])throw new s("backend.internal","Turnkey createApiKeys returned no apiKeyId.",{activity_status:h.activity?.status})}function bs(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the invoice status BEFORE retrying: if the transfer already shows there, do NOT run this command again (contact support with the invoice id) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${dt}\` to refresh the session, then retry.`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function ks(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the invoice status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Ss(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.headless_sign_failed",`${e.message.replace(/\.?$/,".")} First check ${t.payment_id?"the invoice status":"the destination address on-chain"} \u2014 if the transfer shows there, do NOT run this command again (give the ids below to support).`,{...t,...n.recovery_hint!==void 0?{recovery_hint:n.recovery_hint}:{},...n.idempotency_key!==void 0?{idempotency_key:n.idempotency_key}:{}})}function Zt(e,t){return!(e instanceof s)||!vr(e.code)?null:e.code==="wallet.bridge_timeout"?bs(e,t):e.code==="wallet.headless_sign_failed"?Ss(e,t):ks(e,t)}var et=class e extends me{static description="Withdraw a stablecoin from your AllScale wallet to an EVM address. Confirms in the browser by default; the CLI prints the transaction hash and explorer URL when the network accepts the transfer. Accounts with Turnkey email-OTP enabled and no passkey can sign without a browser via --headless."+ct;static examples=["$ allscale wallet send --idempotency-key order-1042 --to 0xabc... --amount 100 --chain ethereum","$ allscale wallet send --idempotency-key order-1043 --to 0xabc... --amount 50 --chain polygon --stable-coin USDC","$ allscale wallet send --idempotency-key order-1044 --to 0xabc... --amount 1 --chain base --bridge-timeout 300000","$ allscale wallet send --idempotency-key order-1045 --to 0xabc... --amount 1 --chain bsc # over SSH: open the printed URL on any device, paste the tx hash back","$ allscale wallet send --to 0xabc... --amount 1 --chain base --headless --otp-stdin --idempotency-key order-1042 # reuse the same key only when retrying this operation"];static flags={to:C.Flags.string({helpGroup:"REQUIRED",description:"Recipient EVM address (0x\u2026 40-hex).",required:!0}),amount:C.Flags.string({helpGroup:"REQUIRED",description:"Amount to send as a decimal string (e.g. '100', '1.50'). Min 0.1; at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:C.Flags.string({helpGroup:"REQUIRED",description:"EVM chain to send on.",options:[...Un],required:!0}),"idempotency-key":C.Flags.string({helpGroup:"REQUIRED",description:"Stable key for retrying this same logical transfer (1-128 characters); use a new key for an intentional second payment.",required:!0}),"stable-coin":C.Flags.string({description:"Stablecoin to withdraw.",options:[...xe],default:"USDT"}),"bridge-timeout":C.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the full broker op TTL (~5 min, shared by the loopback and paste channels); pass this to abort sooner. (Browser-bridge only \u2014 not valid with --headless.)",min:1e3,exclusive:["headless"]}),"browser-base":C.Flags.string({description:"Override the base URL of the printed /cli confirmation link (defaults to the session API base). (Browser-bridge only \u2014 not valid with --headless.)",exclusive:["headless"]}),headless:C.Flags.boolean({description:`Sign without a browser via Turnkey email-OTP (accounts with email-OTP enabled and no passkey; passkey accounts must use the browser flow). Supply the OTP via --otp-stdin (recommended for automation) or interactively; --otp / ALLSCALE_OTP work ONLY combined with --otp-id. This removes the in-browser human confirmation, so use it only on a trusted machine.${ct}`,default:!1}),otp:C.Flags.string({description:"Turnkey signing OTP code (with --headless). Only works combined with --otp-id (an externally-triggered flow): without --otp-id the CLI emails a FRESH code at run time, so any pre-set --otp / ALLSCALE_OTP value is stale and fails with 'Invalid or expired OTP code'. For automation prefer --otp-stdin (CLI emails; pipe the fresh code back). Passing --otp as a flag also exposes it in shell history AND the process list (ps / /proc/<pid>/cmdline).",exclusive:["otp-stdin"],dependsOn:["headless"]}),"otp-stdin":C.Flags.boolean({description:"Read the Turnkey signing OTP as one line from stdin (with --headless).",default:!1,dependsOn:["headless"]}),"otp-id":C.Flags.string({dependsOn:["headless"],description:"Skip the OTP-send step and reuse a prior Turnkey otpId (with --headless). The OTP code itself is still required via --otp / ALLSCALE_OTP / --otp-stdin."}),...me.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=Ve(t["idempotency-key"]);if(!n)throw new s("input.invalid","--idempotency-key is required so a retry reuses the same on-chain anti-replay id.");if(!t.headless&&(t.otp||t["otp-stdin"]||t["otp-id"]))throw new s("input.invalid","--otp / --otp-stdin / --otp-id require --headless.");if(t.otp?.trim()&&Vr.stderr.write(`warning: --otp passes the code via argv (visible in shell history and the process list); prefer --otp-stdin.
62
+ `),t.headless&&!Br(t.otp,t["otp-stdin"]))throw new s("input.invalid","Headless signing needs an OTP source: pass --otp, set ALLSCALE_OTP, use --otp-stdin, or run interactively.");let r=t.to.trim();if(!Gn(r))throw new s("input.invalid",`--to is not a valid EVM address: '${r}' (expected 0x followed by 40 hex characters and a valid EIP-55 checksum when mixed-case).`);if(Kn(r))throw new s("input.invalid","--to is a zero/burn address; funds sent there cannot be recovered.");let i=Rr("--amount",t.amount),[o,a=""]=i.split(".");if(o==="0"&&(a[0]??"0")==="0")throw new s("input.invalid",`--amount must be at least 0.1; got '${i}'.`);let c=Fn(t.chain);if(c===null)throw new s("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let l=Mn(t["stable-coin"]);if(l===null)throw new s("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);Pr("--amount",i,Dn(c,l));let d={chain:c,to_address:r,amount:i,stable_coin:l,idempotency_key:n},p=this.resolveContext(t),f;if(t.headless)f=await zr({ctx:p,payload:d,otp:t.otp,otpStdin:t["otp-stdin"],otpId:t["otp-id"]},$r).catch(m=>{throw Zt(m,{to_address:d.to_address,...n?{idempotency_key:n}:{}})??m});else try{f=await Or({ctx:p,op:"withdraw_token",mode:"data",payload:d,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"]})}catch(m){throw Zt(m,{to_address:d.to_address,idempotency_key:n})??m}let g=f.result_data??{},h=typeof g.tx_hash=="string"&&ze.test(g.tx_hash)?g.tx_hash:null;if(!h)throw t.headless?new s("wallet.headless_sign_failed","Headless signing returned no usable tx_hash \u2014 the transaction may have been broadcast; verify on-chain before retrying.",{to_address:r,...f.idempotency_key?{idempotency_key:f.idempotency_key}:{}}):new s("wallet.bridge_invalid_response","Browser returned no tx_hash for the withdrawal. The transaction may have been broadcast; check the destination on-chain before retrying.",{to_address:r,idempotency_key:n});return{tx_hash:h,chain:c,chain_name:jn(c),to_address:r,amount:i,stable_coin:l,stable_coin_name:Yn(l),explorer_url:Hn(c,h)||void 0,idempotency_key:f.idempotency_key??n}}};
63
+ //# sourceMappingURL=send.js.map
@@ -0,0 +1,18 @@
1
+ "use strict";var Vt=Object.create;var z=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var nn=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},ze=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qt(t))!tn.call(e,i)&&i!==n&&z(e,i,{get:()=>t[i],enumerable:!(r=Zt(t,i))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Vt(en(e)):{},ze(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),rn=e=>ze(z({},"__esModule",{value:!0}),e);var yr={};nn(yr,{default:()=>le});module.exports=rn(yr);var w=require("@oclif/core");var qe="public",Xe="https://app.allscale.io";var Ve=["https://app.allscale.io"];var ue="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 Ze(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Qe(e){return Ze(e)!==null}function fe(e){let t=Ze(e);return t!==null&&Ve.includes(t.origin)}function $(){return"".trim()||void 0}function M(){return"public"}function et(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function tt(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return pe()}function pe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:l,keyId:u}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:a.trim(),key:l,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var nt="drop `--headless` and use the browser-bridge flow with an agent-key session.",rt="allscale device-login";var sn="device-login";function me(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ot(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+nt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${me()}\` for headless automation`+"."}function st(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${sn} --profile ${e}\`.`}var an={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},ln=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 _e(e){return(typeof e=="string"?e:String(e??"")).replace(ln,"")}var cn=64;function ge(e,t=new Map,n=0){if(typeof e=="string")return _e(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=cn)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let l of e)a.push(ge(l,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,l]of Object.entries(e))Object.defineProperty(o,a,{value:ge(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(_e(n)),this.code=t,this.details=r&&ge(r),this.name="AllscaleError"}get exitCode(){return an[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function at(e){if(e instanceof c)return e;if(e instanceof Error){if(fn(e)){let t=gn(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var un=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),dn=[/^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 fn(e){if(pn(e))return!0;let t=e.name??"";return un.has(t)?t==="CLIError"?he(e,"parse")||it(e.message):!0:it(e.message)}function pn(e){if(!he(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&he(e,"parse")}function it(e){return e?_e(e).split(`
2
+ `).some(t=>dn.some(n=>n.test(t.trim()))):!1}function he(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function gn(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function lt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var f=E(require("fs")),X=E(require("path")),ht=E(require("crypto"));var hn="...<truncated>",mn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,_n=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,be=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ye=String.raw`(?:proxy[_-]?)?authorization`,yn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ye}"|'${ye}'|${ye})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${be}`,"gi"),Sn=/\b(https?:\/\/)[^\s/?#]+@/gi,Se=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,En=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Se}"|'${Se}'|${Se})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${be}`,"gi"),Ee=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,An=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ee}"|'${Ee}'|${Ee})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${be}`,"g");function ct(e){return e.replace(Sn,"$1<redacted>@").replace(mn,"<redacted-jwt>").replace(yn,"$1$2$3<redacted>").replace(En,"$1$2<redacted>").replace(An,"$1$2<redacted>").replace(_n,"Bearer <redacted>")}function ut(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function dt(e,t,n=hn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",u=0;for(let d of n){let h=Buffer.byteLength(d,"utf8");if(u+h>t)break;l+=d,u+=h}return l}let i=t-r,o="",a=0;for(let l of e){let u=Buffer.byteLength(l,"utf8");if(a+u>i)break;o+=l,a+=u}return`${o}${n}`}function _(e,t=16384){return dt(ut(ct(e)),t)}var Ae=100,wn=8,bn=8*1024;function q(){return{remaining:bn}}function we(e,t){let n=Math.min(16384,t.remaining),r=dt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function N(e,t,n=0,r={}){if(n>wn)return we("<truncated>",t);if(typeof e=="string"){let i=ct(e);return we(r.escapeControls?ut(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ae),o=i.map(a=>N(a,t,n+1,r));return e.length>i.length&&o.push(we(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,l]of o.slice(0,Ae))i[a]=N(l,t,n+1,r);return o.length>Ae&&(i.output_truncated=!0),i}return e}var Le=require("process");var ke=!1;function Te(e){ke=e}function pt(){return ke}var ft="1";function R(e,t){if(ke){let n={...e};delete n.version;let r=q(),i={event:n.event,...n},o=N(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:ft,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:ft,event:o.event,output_truncated:!0})),Le.stderr.write(`${a}
4
+ `)}else Le.stderr.write(t)}var gt="2",x=null,y=null,v=!1;function Ln(){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=ht.randomBytes(4).toString("hex");return X.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Oe=64*1024*1024,kn=null;function mt(){if(v)return;let e=Ln();if(!e)return;x=null;let t=null;try{if((kn??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=X.dirname(e);if(f.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=f.statSync(n),u=l.mode&511;if(!l.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let r=f.constants.O_NOFOLLOW??0;t=f.openSync(e,f.constants.O_APPEND|f.constants.O_CREAT|f.constants.O_WRONLY|(f.constants.O_NONBLOCK??0)|r,384);let i=f.fstatSync(t),o=f.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let a=i.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);f.fchmodSync(t,384)}catch(n){if(t!==null)try{f.closeSync(t)}catch{}R({event:"sidecar_disabled",reason:"open_failed",detail:_(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${_(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}x=e,y=t,v=!0}var Tn=[/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 On(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Tn.some(n=>n.test(t))}function In(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=Cn(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)On(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Cn(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Nn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:In(e.url)}:e}function Pn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=N(i,q()),a=JSON.stringify({version:gt,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:gt,timestamp:t,type:r,output_truncated:!0})),a}function G(e){if(!v||!x||y===null)return;let t=Nn(e),n=Pn(t);try{if(f.fstatSync(y).size+Buffer.byteLength(n,"utf8")+1>Oe){v=!1;try{f.closeSync(y)}catch{}y=null,R({event:"sidecar_disabled",reason:"size_limit",...x===null?{}:{path:_(x)},max_bytes:Oe},`${_(`[allscale] sidecar exceeded ${Oe} bytes; disabling it for the rest of this run. Rotate or remove ${x}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}f.appendFileSync(y,`${n}
7
+ `)}catch(r){if(v=!1,y!==null){try{f.closeSync(y)}catch{}y=null}try{R({event:"sidecar_disabled",reason:"write_failed",detail:_(r.message)},`${_(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}function _t(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function V(){if(v=!1,y!==null){try{f.closeSync(y)}catch{}y=null}}function yt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||_t()||!t}var Y=$()??Xe,U={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function Z(e){return Qe(e)?new URL(e).origin:null}function D(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Ie(e){try{let t=new URL(e);return t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0?e:(t.username="",t.password="",t.search="",t.hash="",`${t.origin}${t.pathname}`)}catch{return"<unparseable URL>"}}function St(){let e=process.env[U.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Ce(){let e=process.env[U.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Q(){let e=process.env[U.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Et(){let e=process.env[U.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function At(){let e=process.env[U.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function wt(){let e=process.env[U.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function bt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if($()===void 0&&Y!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${Y} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
11
+ the old default rather than a deliberate choice.
12
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
+ To move to production, run: ${rt} --api-base ${Y}
14
+ `}var F=E(require("fs")),Lt=E(require("os")),Ne=E(require("path")),Pe=E(require("@iarna/toml"));var vn=".allscale",Bn="config.toml";function Re(){return Ne.join(Lt.homedir(),vn)}function Un(){return Ne.join(Re(),Bn)}function ee(){let e=Un();if(!F.existsSync(e))return{};let t=F.readFileSync(e,"utf-8");try{return Pe.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function kt(e){return Object.keys(e.profile??{}).sort()}function Tt(e,t){return e.profile?.[t]}function Ot(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function xe(e){if(!fe(e))throw new c("input.invalid",`Refusing to send credentials to API base ${D(e)}. `+de)}function It(e){let t=$();if(t===void 0||et(e))return;let n=Z(e),r=tt();if(r.length>0){let o=r.map(l=>Z(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let a=r.map(l=>D(l.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${D(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=Z(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${D(e)} \u2014 this build only signs for ${D(t)}. Re-login against this build's environment, or use a build for that one.`)}var Dn=require("@noble/hashes/sha3");var Ct=["USDT","USDC"];var ri=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Nt=require("@oclif/core"),K=class e extends w.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:w.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:w.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:M()==="public"}),"api-base":w.Flags.string({description:ue,helpGroup:"GLOBAL",hidden:M()==="public"}),"insecure-storage":w.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Te(this.jsonEnabled()),mt(),G({type:"session-start",command:this.id??"",argv:$n(this.argv)});let t=this.constructor;if(M()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Q()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!wt())throw this.argv.length>0&&await this.parse(),new c("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=yt(this.jsonEnabled()),r=this.argv.length===0&&!n&&Wn(t)?this.config.findCommand(this.id??""):void 0;if(r){V();let o=await(0,w.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return G({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||lt(i),{data:i})}catch(t){let n=at(t);G({type:"error",code:n.code,message:_(n.message)}),G({type:"command-end",ok:!1,exitCode:n.exitCode}),V(),this.emitError(n),process.exitCode=n.exitCode;return}finally{Te(!1)}}resolveSessionApiBaseChain(t){let n=ee(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Ce()!==void 0,a=Ot(n,r,Ce()),l=Tt(n,a),u=i??Q(),d=u??l?.api_base??Y,h=bt({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return h&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,R({event:"legacy_staging_profile",api_base:d,profile:a},h)),{apiBase:d,explicitApiBase:u,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||xe(n),n}resolveContext(t){if(M()==="public"){if(t.token!==void 0)throw new c("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 c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Q()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:a,profileApiBase:l,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(xe(i),It(i)),{apiBase:i,profile:a,token:n??St(),insecureStorage:r||Et(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Jn(t)}
15
+ `)}},ne=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"]),Fn=new Set(Array.from(ne).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function $n(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(ne.has(o)){t.push(`${o}=<redacted>`);continue}}}if(ne.has(r)){t.push(r),n+1<e.length&&(ne.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(Fn.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Mn=/(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 Gn(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Mn.test(t)}var Yn=/_(removed|cleared|count|total)$/i;function Kn(e,t){return typeof t=="number"&&Yn.test(e)}var Hn=new Set(Ct);function jn(e,t){return e==="token_symbol"&&typeof t=="string"&&Hn.has(t)}var te=100;function ve(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,te),r=n.map(i=>ve(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,te))n[i]=Gn(i)&&!Kn(i,o)&&!jn(i,o)?"<redacted>":ve(o,t+1);if(r.length>te){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-te} more keys`}return n}return typeof e=="string"?_(e):e}function Jn(e){let t=pt()?void 0:2,n=ve(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:_(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Wn(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function zn(e,t={}){let n;try{n=kt(ee())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",st(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function Pt(e){if(e.profileExplicit){let t=zn(e.profile);if(t)return t}return new c("auth.no_token",ot(e.profile,e.flow))}function Be(e){let t=e.split(".");if(t.length!==3)throw new c("auth.token_expired","Stored token is not a valid JWT.");try{let n=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(n)}catch(n){throw new c("auth.token_expired",`Failed to decode JWT payload: ${n.message}`)}}function Rt(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var jt=E(require("path"));var Fe=require("crypto"),s=E(require("fs")),g=E(require("path"));var re=1024*1024,qn=5e3,Xn=20,Vn=3e4,Ue=4096,Zn=new Int32Array(new SharedArrayBuffer(4)),H=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ie(e){return e instanceof H}var m=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Qn=null;function k(){return new c("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 oe(){return(Qn??process.platform)!=="win32"}function Mt(){if(!oe())throw k()}function Gt(e){try{return s.default.lstatSync(e),!1}catch(t){if(!p(t,"ENOENT"))throw t}try{let t=s.default.lstatSync(g.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(p(t,"ENOENT"))return!0;throw t}}function p(e,t){return typeof e=="object"&&e!==null&&e.code===t}function j(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function J(e,t){return e.dev===t.dev&&e.ino===t.ino}function er(e){Atomics.wait(Zn,0,0,e)}function Yt(e){try{return process.kill(e,0),!0}catch(t){return!p(t,"ESRCH")}}function tr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xt(e,t){let n=g.dirname(e);t&&s.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=s.default.lstatSync(n)}catch(o){if(!t&&p(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=s.default.openSync(n,s.default.constants.O_RDONLY|(s.default.constants.O_DIRECTORY??0)|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0));let o=s.default.fstatSync(i),a=s.default.lstatSync(n);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!J(o,a))throw new Error("credential-store parent changed while it was being inspected");j(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&g.basename(n)===".allscale"&&(s.default.fchmodSync(i,448),l=s.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&s.default.closeSync(i)}return!0}function b(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=s.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&p(o,"ENOENT")?new m:o}if(!J(n,i))throw r.retryOnPathChange?new m:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new H;if(j(n,"credential-store file"),process.platform!=="win32"){s.default.fchmodSync(t,384);let o=s.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function nr(e,t){if(t.size>re)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(re+1),r=0;for(;r<n.length;){let i=s.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>re)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function vt(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(i){if(p(i,"ENOENT"))try{if(s.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(p(o,"ENOENT"))return null;throw o}throw i}let n=s.default.fstatSync(t),r=b(e,t,n);return nr(t,r)}finally{t!==null&&s.default.closeSync(t)}}function Bt(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(i){if(p(i,"ENOENT")&&Gt(e))return;throw i}let n=s.default.fstatSync(t),r=b(e,t,n);T(e,r)}finally{t!==null&&s.default.closeSync(t)}Ht(g.dirname(e))}function rr(e){let t;try{t=s.default.lstatSync(e)}catch(n){if(p(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 H;j(t,"credential-store replacement target")}function ir(e,t){for(let n=0;n<8;n+=1){let r=(0,Fe.randomBytes)(12).toString("hex"),i=g.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:s.default.openSync(i,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_WRONLY|(s.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(p(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Kt(e,t){let n=0;for(;n<t.length;){let r=s.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 Ht(e){if(process.platform==="win32")return;let t=null;try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_DIRECTORY??0)|(s.default.constants.O_NOFOLLOW??0)),s.default.fsyncSync(t)}catch{}finally{if(t!==null)try{s.default.closeSync(t)}catch{}}}function or(e,t){let n=Buffer.from(t,"utf8");if(n.length>re)throw new Error("credential-store file exceeds the maximum supported size");let r=g.dirname(e),i=g.basename(e),o=null,a=null,l=!1;try{let u=ir(r,i);o=u.fd,a=u.tempPath;let d=s.default.fstatSync(o);if((b(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Kt(o,n),s.default.fsyncSync(o),b(a,o,s.default.fstatSync(o));let S=o;o=null,s.default.closeSync(S),rr(e),s.default.renameSync(a,e),l=!0}finally{if(o!==null)try{s.default.closeSync(o)}catch{}if(!l&&a!==null)try{s.default.unlinkSync(a)}catch{}}Ht(r)}function sr(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock`)}function ar(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock-recovery`)}function lr(e,t){if(t.size>Ue)return null;let n=Buffer.alloc(Ue+1),r=0;for(;r<n.length;){let o=s.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ue)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function T(e,t){let n=s.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!J(n,t))throw new Error("credential-store lock changed while it was being inspected");j(n,"credential-store lock"),s.default.unlinkSync(e)}function Ut(e,t){let n=null;try{try{n=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(u){if(p(u,"ENOENT"))try{let d=s.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new m}catch(d){if(p(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=s.default.fstatSync(n),i=b(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=lr(n,i);return{state:(o?.target===t&&o?!Yt(o.pid):Date.now()-i.mtimeMs>=Vn)?"stale":"active",stats:i}}finally{n!==null&&s.default.closeSync(n)}}function cr(e,t){for(let n=0;n<8;n+=1){let r=(0,Fe.randomBytes)(12).toString("hex"),i=g.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},a=null;try{a=s.default.openSync(i,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_WRONLY|(s.default.constants.O_NOFOLLOW??0),384);let l=s.default.fstatSync(a),u=b(i,a,l,{allowMultipleLinks:!0});return Kt(a,Buffer.from(JSON.stringify(o),"utf8")),s.default.fsyncSync(a),{claimPath:i,metadata:o,stats:u}}catch(l){if(p(l,"EEXIST"))continue;try{s.default.unlinkSync(i)}catch{}throw l}finally{a!==null&&s.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function ur(e,t){let n;try{n=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(r){throw p(r,"ENOENT")?new m:r}try{let r=s.default.fstatSync(n),i=b(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!J(i,t))throw new m;return{fd:n,lockPath:e,stats:i}}catch(r){throw s.default.closeSync(n),r}}function Dt(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(n){if(p(n,"ENOENT"))try{let r=s.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new m}catch(r){if(p(r,"ENOENT"))return!1;throw r}throw n}return b(e,t,s.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&s.default.closeSync(t)}}function dr(e){let t;try{t=s.default.openSync(e,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_RDWR|(s.default.constants.O_NOFOLLOW??0),384)}catch(r){if(p(r,"EEXIST"))return null;throw r}let n=null;try{n=s.default.fstatSync(t);let r=b(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{T(e,n)}catch{}throw s.default.closeSync(t),r}}function L(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");er(Xn)}function Ft(e){let t=g.dirname(e),n=g.basename(e),r=sr(e),i=ar(e),o=cr(t,n),a=Date.now()+qn,l=!1,u=!1,d=null,h;try{for(;d===null;)try{if(Dt(i)){L(a,!0);continue}s.default.linkSync(o.claimPath,r),u=!0,d=ur(r,o.stats),l=!0}catch(S){if(u&&!l){try{T(r,o.stats)}catch{}u=!1}if(S instanceof m){L(a,!1);continue}if(!p(S,"EEXIST"))throw S;let ce;try{ce=Ut(r,n)}catch(A){if(A instanceof m){L(a,!1);continue}throw A}if(ce.state==="absent")continue;if(ce.state==="stale"){let A;try{A=dr(i)}catch(C){if(C instanceof m){L(a,!1);continue}throw C}if(A!==null){try{let C;try{C=Ut(r,n)}catch(We){if(We instanceof m){L(a,!1);continue}throw We}C.state==="stale"&&T(r,C.stats)}finally{De(A)}continue}}let Je;try{Je=Dt(i)}catch(A){if(A instanceof m){L(a,!1);continue}throw A}L(a,Je)}}catch(S){h=S}try{T(o.claimPath,o.stats)}catch(S){!p(S,"ENOENT")&&!l&&h===void 0&&(h=S)}if(h!==void 0)throw h;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function De(e){try{T(e.lockPath,e.stats)}finally{s.default.closeSync(e.fd)}}function fr(e,t){let n=tr(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function $t(e){let t=g.dirname(e),n=g.basename(e);for(let r of s.default.readdirSync(t)){let i=fr(r,n);if(i===null||Yt(i))continue;let o=g.join(t,r),a=null;try{try{a=s.default.openSync(o,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(d){if(p(d,"ENOENT")||p(d,"ELOOP"))continue;throw d}let l=s.default.fstatSync(a),u=s.default.lstatSync(o);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!J(l,u))continue;try{j(l,"credential-store orphan")}catch{continue}T(o,l)}catch(l){if(!p(l,"ENOENT"))throw l}finally{a!==null&&s.default.closeSync(a)}}}function W(e,t,n){if(!oe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw k();if(!xt(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw k()}});let a=Ft(e);try{return $t(e),n({read:()=>vt(e),remove:()=>Bt(e),write:()=>{throw k()}})}finally{De(a)}}if(!t.createParent){let o=!1;try{o=Gt(e)}catch{throw k()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw k()}})}throw k()}if(!xt(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Ft(e);try{return $t(e),n({read:()=>vt(e),remove:()=>Bt(e),write:o=>or(e,o)})}finally{De(i)}}var $e="allscale-cli";function Ke(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jt(e){return Ke(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function I(e){return new c("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 Me(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function se(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var O,Ge=!1;function pr(){return At()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function gr(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 hr(){if(O!==void 0)return O;if(pr())return Ge=!1,O=null,O;try{O=require("keytar"),Ge=!1}catch(e){Ge=!gr(e),O=null}return O}function Wt(){let e=oe()?"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 c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Ye(e){try{return await e()}catch{throw Wt()}}var He=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Ye(()=>this.keytar.getPassword($e,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw I("OS keychain")}if(!Jt(r))throw I("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Ye(()=>this.keytar.setPassword($e,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Ye(()=>this.keytar.deletePassword($e,t))}},mr="credentials.json",je=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??jt.join(Re(),mr)}read(t){let n;try{n=t.read()}catch(i){throw ie(i)?Me():I("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw I("plaintext file")}if(!Ke(r)||!Ke(r.profiles))throw I("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ie(r)?Me():se()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Jt(r))throw I("plaintext file");return r}}async get(t){try{return W(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:I("plaintext file")}}async set(t,n){try{W(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof c?r:se()}}async delete(t){try{W(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 c?n:se()}}async clearProfile(t){try{return W(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 c?n:ie(n)?Me():se()}}};function zt(e){if(e.insecureStorage)return Mt(),new je(e.insecureFilePath);let t=hr();if(t)return new He(t);throw Wt()}function ae(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}function qt(e){if(typeof e!="string")return;let t=e.trim();return t.length===0?void 0:t}function _r(e){let t=[e.email,e.email_lower,e.user_name];for(let n of t){let r=ae(n);if(r!==void 0)return r}}var le=class e extends K{static description="Show the current authenticated identity from the stored credential (agent-key sessions report business_id / scopes / expiry; legacy password sessions decode the cached JWT). No network call.";static examples=["$ allscale whoami","$ allscale whoami --profile prod"];static isLocalOnly=!0;static flags={...K.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t);if(n.token)return Xt(n.profile,n.apiBase,n.token,"override");let r=zt({insecureStorage:n.insecureStorage}),i=await r.get(n.profile);if(!i)throw Pt({profile:n.profile,profileExplicit:n.profileExplicit});if(i.agent_key){let o=Math.floor(Date.now()/1e3),a=i.agent_key_expires_at;return i.business_id||process.stderr.write(`No business id stored for profile '${n.profile}' \u2014 this agent-key session predates the backend returning it. Re-run \`allscale device-login --profile ${n.profile}\` (or \`${me(n.profile)}\`) to store it (and to auto-fill --business-id on invoice/store/etc.).
17
+ `),{profile:n.profile,api_base:Ie(n.apiBase),credential:"agent_key",business_id:i.business_id,user_email:ae(i.user_email),user_type:i.user_type,scopes:i.scopes??[],expires_at:typeof a=="number"?new Date(a*1e3).toISOString():void 0,expired:typeof a=="number"?a<o:!1,storage:r.kind}}return Xt(n.profile,n.apiBase,i.access_token,r.kind,i.user_email)}};function Xt(e,t,n,r,i){let o=Be(n);return{profile:e,api_base:Ie(t),credential:"cookie",user_id:qt(o.user_id),user_email:ae(i)??_r(o),expires_at:typeof o.exp=="number"?new Date(o.exp*1e3).toISOString():void 0,expired:Rt(o),storage:r}}
18
+ //# sourceMappingURL=whoami.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";var u=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var S=(n,e)=>{for(var i in e)u(n,i,{get:e[i],enumerable:!0})},y=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of I(e))!h.call(n,r)&&r!==i&&u(n,r,{get:()=>e[r],enumerable:!(t=f(e,r))||t.enumerable});return n};var P=n=>y(u({},"__esModule",{value:!0}),n);var B={};S(B,{default:()=>T});module.exports=P(B);var _="public",p="https://app.allscale.io";function a(){return"".trim()||void 0}function g(){return"public"}function L(){{let n="[]".trim();if(n.length===0)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}return A()}function A(){let n=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(n.length>0)try{let t=JSON.parse(n);if(!Array.isArray(t))return[];let r=[];for(let s of t){if(typeof s!="object"||s===null)continue;let{base:o,key:l,keyId:d}=s;if(typeof o!="string"||o.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let c=typeof d=="string"?d.trim():"";r.push({base:o.trim(),key:l,keyId:c.length>0?c:"cli-1"})}return r}catch{return[]}let e=process.env.ALLSCALE_SIGNING_KEY??"",i=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(e.trim().length>0&&i.length>0){let t=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:i,key:e,keyId:t&&t.length>0?t:"cli-1"}]}return[]}var ee=a()??p;function E(n){try{let e=new URL(n);return`${e.protocol}//${e.host}`}catch{return"<unparseable URL>"}}var b=async function(n){try{let e=n.config.pjson.oclif?.additionalVersionFlags;if(!new Set(["--version",...Array.isArray(e)?e.filter(o=>typeof o=="string"):[]]).has(n.id))return;let t=a();if(t===void 0)return;let r=L().length,s=r>1?` (bound, ${r} endpoints)`:" (bound)";this.log(`build: ${g()} \xB7 api-base ${E(t)}${s}`)}catch{}},T=b;
2
+ //# sourceMappingURL=version-suffix.js.map