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