@allscale/cli 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +113 -41
  2. package/bin/dev.js +11 -1
  3. package/bin/run-oclif.js +216 -27
  4. package/bin/run.js +19 -1
  5. package/dist/commands/build-info.js +13 -13
  6. package/dist/commands/claim-link/claim.js +14 -14
  7. package/dist/commands/claim-link/create.js +40 -37
  8. package/dist/commands/claim-link/get.js +26 -15
  9. package/dist/commands/claim-link/list.js +15 -15
  10. package/dist/commands/claim-link/status.js +13 -13
  11. package/dist/commands/describe.js +13 -13
  12. package/dist/commands/device-login.js +23 -24
  13. package/dist/commands/invoice/get.js +15 -15
  14. package/dist/commands/invoice/list.js +16 -16
  15. package/dist/commands/invoice/pay.js +40 -41
  16. package/dist/commands/invoice/received.js +16 -16
  17. package/dist/commands/invoice/send.js +42 -34
  18. package/dist/commands/invoice/sent.js +15 -15
  19. package/dist/commands/invoice/update.js +17 -15
  20. package/dist/commands/logout.js +14 -14
  21. package/dist/commands/operations.js +13 -13
  22. package/dist/commands/otp-login.js +21 -20
  23. package/dist/commands/otp-send.js +13 -13
  24. package/dist/commands/payout/send.js +14 -14
  25. package/dist/commands/payout/status.js +15 -15
  26. package/dist/commands/scope.js +17 -16
  27. package/dist/commands/store/create.js +17 -17
  28. package/dist/commands/transaction/get.js +15 -15
  29. package/dist/commands/transaction/list.js +15 -15
  30. package/dist/commands/wallet/list.js +15 -15
  31. package/dist/commands/wallet/send.js +40 -43
  32. package/dist/commands/whoami.js +14 -14
  33. package/dist/hooks/version-suffix.js +1 -1
  34. package/dist/index.js +14 -14
  35. package/dist/lib/help.js +7 -2
  36. package/dist/lib/output/audit-lifecycle.js +7 -0
  37. package/oclif.manifest.json +123 -292
  38. package/package.json +4 -6
  39. package/dist/commands/claim-link/preview.js +0 -18
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allscale/cli",
3
- "version": "0.1.0",
3
+ "version": "1.0.1",
4
4
  "description": "Command-line interface for AllScale — drives the same actions a user can take in app.allscale.io",
5
5
  "keywords": [
6
6
  "allscale",
@@ -50,7 +50,7 @@
50
50
  ],
51
51
  "topics": {
52
52
  "claim-link": {
53
- "description": "Create and fund Claim Links through the browser bridge; inspect, list, claim, and preview them."
53
+ "description": "Create and fund Claim Links through the browser bridge; inspect, list, claim, and check their status."
54
54
  },
55
55
  "invoice": {
56
56
  "description": "Create, list, inspect, update, and pay invoices."
@@ -96,15 +96,13 @@
96
96
  "dev": "node ./bin/dev.js",
97
97
  "sync-schema": "ts-node codegen/sync-schema.ts",
98
98
  "codegen": "ts-node codegen/run.ts",
99
- "codegen:accept-descriptions": "ts-node codegen/run.ts --accept-descriptions"
99
+ "codegen:accept-descriptions": "ts-node codegen/run.ts --accept-descriptions",
100
+ "sync:not-found-codes": "node scripts/sync-not-found-codes.mjs"
100
101
  },
101
102
  "dependencies": {
102
103
  "@iarna/toml": "^2.2.5",
103
104
  "@noble/hashes": "^1.8.0",
104
105
  "@oclif/core": "^4.5.4",
105
- "@turnkey/api-key-stamper": "^0.6.2",
106
- "@turnkey/crypto": "^2.8.11",
107
- "@turnkey/http": "^3.17.0",
108
106
  "handlebars": "^4.7.9"
109
107
  },
110
108
  "optionalDependencies": {
@@ -1,18 +0,0 @@
1
- "use strict";var tr=Object.create;var oe=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var rr=Object.getOwnPropertyNames;var ir=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty;var sr=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rr(t))!or.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(r=nr(t,i))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?tr(ir(e)):{},yt(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ar=e=>yt(oe({},"__esModule",{value:!0}),e);var to={};sr(to,{default:()=>ke});module.exports=ar(to);var I=require("@oclif/core");var wt="public",St="https://app.allscale.io";var Et=["https://app.allscale.io"];var Ie="Override the API base URL (public builds accept only https://app.allscale.io)";var Oe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function At(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 bt(e){return At(e)!==null}function Ce(e){let t=At(e);return t!==null&&Et.includes(t.origin)}function z(){return"".trim()||void 0}function J(){return"public"}function N(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function ve(e){try{return new URL(e).origin}catch{return null}}function V(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Re()}function Re(){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:u,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof u!="string"||u.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.trim(),key:u,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 kt="`allscale device-login` (or `allscale otp-login` for headless automation)";var Lt="drop `--headless` and use the browser-bridge flow with an agent-key session.",Tt="allscale device-login";var cr="device-login";function X(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function xe(){return kt}function Ot(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+Lt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${X()}\` for headless automation`+"."}function Ct(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${cr} --profile ${e}\`.`}var ur={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},dr=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 Be(e){return(typeof e=="string"?e:String(e??"")).replace(dr,"")}var fr=64;function Ne(e,t=new Map,n=0){if(typeof e=="string")return Be(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=fr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let u of e)s.push(Ne(u,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,u]of Object.entries(e))Object.defineProperty(o,s,{value:Ne(u,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(Be(n)),this.code=t,this.details=r&&Ne(r),this.name="AllscaleError"}get exitCode(){return ur[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Rt(e){if(e instanceof c)return e;if(e instanceof Error){if(hr(e)){let t=_r(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var pr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),gr=[/^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 hr(e){if(mr(e))return!0;let t=e.name??"";return pr.has(t)?t==="CLIError"?Pe(e,"parse")||It(e.message):!0:It(e.message)}function mr(e){if(!Pe(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Pe(e,"parse")}function It(e){return e?Be(e).split(`
2
- `).some(t=>gr.some(n=>n.test(t.trim()))):!1}function Pe(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function _r(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function vt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var g=E(require("fs")),ae=E(require("path")),Ut=E(require("crypto"));var yr="...<truncated>",wr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Sr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Me=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,De=String.raw`(?:proxy[_-]?)?authorization`,Er=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${De}"|'${De}'|${De})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Me}`,"gi"),Ar=/\b(https?:\/\/)[^\s/?#]+@/gi,$e=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,br=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${$e}"|'${$e}'|${$e})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Me}`,"gi"),Ue=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)`,kr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ue}"|'${Ue}'|${Ue})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Me}`,"g");function Nt(e){return e.replace(Ar,"$1<redacted>@").replace(wr,"<redacted-jwt>").replace(Er,"$1$2$3<redacted>").replace(br,"$1$2<redacted>").replace(kr,"$1$2<redacted>").replace(Sr,"Bearer <redacted>")}function Pt(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 xt(e,t,n=yr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let u="",l=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(l+f>t)break;u+=d,l+=f}return u}let i=t-r,o="",s=0;for(let u of e){let l=Buffer.byteLength(u,"utf8");if(s+l>i)break;o+=u,s+=l}return`${o}${n}`}function b(e,t=16384){return xt(Pt(Nt(e)),t)}var Fe=100,Lr=8,Tr=8*1024;function se(){return{remaining:Tr}}function Ge(e,t){let n=Math.min(16384,t.remaining),r=xt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function G(e,t,n=0,r={}){if(n>Lr)return Ge("<truncated>",t);if(typeof e=="string"){let i=Nt(e);return Ge(r.escapeControls?Pt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Fe),o=i.map(s=>G(s,t,n+1,r));return e.length>i.length&&o.push(Ge(`<${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,u]of o.slice(0,Fe))i[s]=G(u,t,n+1,r);return o.length>Fe&&(i.output_truncated=!0),i}return e}var Ke=require("process");var Ye=!1;function He(e){Ye=e}function Dt(){return Ye}var Bt="1";function K(e,t){if(Ye){let n={...e};delete n.version;let r=se(),i={event:n.event,...n},o=G(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Bt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Bt,event:o.event,output_truncated:!0})),Ke.stderr.write(`${s}
4
- `)}else Ke.stderr.write(t)}var $t="2",Y=null,k=null,H=!1;function Ir(){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=Ut.randomBytes(4).toString("hex");return ae.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var qe=64*1024*1024,Or=null;function Ft(){if(H)return;let e=Ir();if(!e)return;Y=null;let t=null;try{if((Or??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ae.dirname(e);if(g.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=g.statSync(n),l=u.mode&511;if(!u.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let r=g.constants.O_NOFOLLOW??0;t=g.openSync(e,g.constants.O_APPEND|g.constants.O_CREAT|g.constants.O_WRONLY|(g.constants.O_NONBLOCK??0)|r,384);let i=g.fstatSync(t),o=g.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let s=i.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);g.fchmodSync(t,384)}catch(n){if(t!==null)try{g.closeSync(t)}catch{}K({event:"sidecar_disabled",reason:"open_failed",detail:b(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${b(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}Y=e,k=t,H=!0}var Cr=[/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 Rr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Cr.some(n=>n.test(t))}function Gt(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=vr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Rr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function vr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Nr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Gt(e.url)}:e}function Pr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=G(i,se()),s=JSON.stringify({version:$t,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:$t,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!H||!Y||k===null)return;let t=Nr(e),n=Pr(t);try{if(g.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>qe){H=!1;try{g.closeSync(k)}catch{}k=null,K({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:b(Y)},max_bytes:qe},`${b(`[allscale] sidecar exceeded ${qe} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}g.appendFileSync(k,`${n}
7
- `)}catch(r){if(H=!1,k!==null){try{g.closeSync(k)}catch{}k=null}try{K({event:"sidecar_disabled",reason:"write_failed",detail:b(r.message)},`${b(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var C=Gt;function Mt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function le(){if(H=!1,k!==null){try{g.closeSync(k)}catch{}k=null}}function Kt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Mt()||!t}var Z=z()??St,j={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 R(e){return bt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Yt(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function je(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ce(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Ht(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function qt(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function jt(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Wt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(z()===void 0&&Z!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
- The CLI default is now ${Z} (production), but a saved profile wins over the default,
10
- so this session still uses staging. That pin was written before the default changed, so it may just be
11
- the old default rather than a deliberate choice.
12
- To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
- To move to production, run: ${Tt} --api-base ${Z}
14
- `}var W=E(require("fs")),zt=E(require("os")),We=E(require("path")),ze=E(require("@iarna/toml"));var Dr=".allscale",$r="config.toml";function Je(){return We.join(zt.homedir(),Dr)}function Ur(){return We.join(Je(),$r)}function ue(){let e=Ur();if(!W.existsSync(e))return{};let t=W.readFileSync(e,"utf-8");try{return ze.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function Jt(e){return Object.keys(e.profile??{}).sort()}function Vt(e,t){return e.profile?.[t]}function Xt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function P(e){if(!Ce(e))throw new c("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Oe)}function Ve(e,t){P(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new c("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Zt(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new c("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function de(e){let t=z();if(t===void 0||N(e))return;let n=R(e),r=V();if(r.length>0){let o=r.map(u=>R(u.base)).filter(u=>u!==null);if(n!==null&&o.includes(n))return;let s=r.map(u=>T(u.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=R(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${T(e)} \u2014 this build only signs for ${T(t)}. Re-login against this build's environment, or use a build for that one.`)}var Fr=require("@noble/hashes/sha3");function Qt(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Gr={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},en=["ethereum","bsc","base","polygon","arbitrum","optimism"],fe=["USDT","USDC"];function tn(e){return Gr[e.toLowerCase()]??null}function nn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var Go=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function rn(e){return e===1?"USDT":"USDC"}var v=require("@oclif/core"),Q=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:J()==="public"}),"api-base":I.Flags.string({description:Ie,helpGroup:"GLOBAL",hidden:J()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{He(this.jsonEnabled()),Ft(),y({type:"session-start",command:this.id??"",argv:Kr(this.argv)});let t=this.constructor;if(J()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ce()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!jt())throw this.argv.length>0&&await this.parse(),new c("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=Kt(this.jsonEnabled()),r=this.argv.length===0&&!n&&Vr(t)?this.config.findCommand(this.id??""):void 0;if(r){le();let o=await(0,I.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}let i=await this.runCommand();return y({type:"command-end",ok:!0}),le(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||vt(i),{data:i})}catch(t){let n=Rt(t);y({type:"error",code:n.code,message:b(n.message)}),y({type:"command-end",ok:!1,exitCode:n.exitCode}),le(),this.emitError(n),process.exitCode=n.exitCode;return}finally{He(!1)}}resolveSessionApiBaseChain(t){let n=ue(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||je()!==void 0,s=Xt(n,r,je()),u=Vt(n,s),l=i??ce(),d=l??u?.api_base??Z,f=Wt({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:u?.api_base,profileApiBaseSource:u?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,K({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:l,profileApiBase:u?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||P(n),n}resolveContext(t){if(J()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ce()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:u,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(P(i),de(i)),{apiBase:i,profile:s,token:n??Yt(),insecureStorage:r||Ht(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${Jr(t)}
15
- `)}},ge=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"]),Mr=new Set(Array.from(ge).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Kr(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(ge.has(o)){t.push(`${o}=<redacted>`);continue}}}if(ge.has(r)){t.push(r),n+1<e.length&&(ge.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Mr.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Yr=/(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 Hr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Yr.test(t)}var qr=/_(removed|cleared|count|total)$/i;function jr(e,t){return typeof t=="number"&&qr.test(e)}var Wr=new Set(fe);function zr(e,t){return e==="token_symbol"&&typeof t=="string"&&Wr.has(t)}var pe=100;function Xe(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,pe),r=n.map(i=>Xe(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,pe))n[i]=Hr(i)&&!jr(i,o)&&!zr(i,o)?"<redacted>":Xe(o,t+1);if(r.length>pe){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-pe} more keys`}return n}return typeof e=="string"?b(e):e}function Jr(e){let t=Dt()?void 0:2,n=Xe(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:b(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Vr(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 _n=E(require("path"));var et=require("crypto"),a=E(require("fs")),m=E(require("path"));var he=1024*1024,Xr=5e3,Zr=20,Qr=3e4,Ze=4096,ei=new Int32Array(new SharedArrayBuffer(4)),ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function me(e){return e instanceof ee}var A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},ti=null;function B(){return new c("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function _e(){return(ti??process.platform)!=="win32"}function fn(){if(!_e())throw B()}function pn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!h(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(m.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(h(t,"ENOENT"))return!0;throw t}}function h(e,t){return typeof e=="object"&&e!==null&&e.code===t}function te(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ne(e,t){return e.dev===t.dev&&e.ino===t.ino}function ni(e){Atomics.wait(ei,0,0,e)}function gn(e){try{return process.kill(e,0),!0}catch(t){return!h(t,"ESRCH")}}function ri(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function on(e,t){let n=m.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&h(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=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ne(o,s))throw new Error("credential-store parent changed while it was being inspected");te(o,"credential-store parent");let u=o;if((o.mode&63)!==0&&m.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),u=a.default.fstatSync(i)),(u.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&h(o,"ENOENT")?new A:o}if(!ne(n,i))throw r.retryOnPathChange?new A:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new ee;if(te(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.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 ii(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=a.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 sn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(h(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(h(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return ii(t,r)}finally{t!==null&&a.default.closeSync(t)}}function an(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(h(i,"ENOENT")&&pn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);D(e,r)}finally{t!==null&&a.default.closeSync(t)}mn(m.dirname(e))}function oi(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(h(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ee;te(t,"credential-store replacement target")}function si(e,t){for(let n=0;n<8;n+=1){let r=(0,et.randomBytes)(12).toString("hex"),i=m.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(h(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function hn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function mn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function ai(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=m.dirname(e),i=m.basename(e),o=null,s=null,u=!1;try{let l=si(r,i);o=l.fd,s=l.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");hn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),oi(e),a.default.renameSync(s,e),u=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!u&&s!==null)try{a.default.unlinkSync(s)}catch{}}mn(r)}function li(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock`)}function ci(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock-recovery`)}function ui(e,t){if(t.size>Ze)return null;let n=Buffer.alloc(Ze+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ze)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 D(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ne(n,t))throw new Error("credential-store lock changed while it was being inspected");te(n,"credential-store lock"),a.default.unlinkSync(e)}function ln(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(l){if(h(l,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new A}catch(d){if(h(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ui(n,i);return{state:(o?.target===t&&o?!gn(o.pid):Date.now()-i.mtimeMs>=Qr)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function di(e,t){for(let n=0;n<8;n+=1){let r=(0,et.randomBytes)(12).toString("hex"),i=m.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let u=a.default.fstatSync(s),l=O(i,s,u,{allowMultipleLinks:!0});return hn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(u){if(h(u,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw u}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function fi(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw h(r,"ENOENT")?new A:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ne(i,t))throw new A;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function cn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(h(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new A}catch(r){if(h(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function pi(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(h(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{D(e,n)}catch{}throw a.default.closeSync(t),r}}function x(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");ni(Zr)}function un(e){let t=m.dirname(e),n=m.basename(e),r=li(e),i=ci(e),o=di(t,n),s=Date.now()+Xr,u=!1,l=!1,d=null,f;try{for(;d===null;)try{if(cn(i)){x(s,!0);continue}a.default.linkSync(o.claimPath,r),l=!0,d=fi(r,o.stats),u=!0}catch(p){if(l&&!u){try{D(r,o.stats)}catch{}l=!1}if(p instanceof A){x(s,!1);continue}if(!h(p,"EEXIST"))throw p;let w;try{w=ln(r,n)}catch(L){if(L instanceof A){x(s,!1);continue}throw L}if(w.state==="absent")continue;if(w.state==="stale"){let L;try{L=pi(i)}catch(S){if(S instanceof A){x(s,!1);continue}throw S}if(L!==null){try{let S;try{S=ln(r,n)}catch(ie){if(ie instanceof A){x(s,!1);continue}throw ie}S.state==="stale"&&D(r,S.stats)}finally{Qe(L)}continue}}let _;try{_=cn(i)}catch(L){if(L instanceof A){x(s,!1);continue}throw L}x(s,_)}}catch(p){f=p}try{D(o.claimPath,o.stats)}catch(p){!h(p,"ENOENT")&&!u&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function Qe(e){try{D(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function gi(e,t){let n=ri(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 dn(e){let t=m.dirname(e),n=m.basename(e);for(let r of a.default.readdirSync(t)){let i=gi(r,n);if(i===null||gn(i))continue;let o=m.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(h(d,"ENOENT")||h(d,"ELOOP"))continue;throw d}let u=a.default.fstatSync(s),l=a.default.lstatSync(o);if(!u.isFile()||l.isSymbolicLink()||!l.isFile()||!ne(u,l))continue;try{te(u,"credential-store orphan")}catch{continue}D(o,u)}catch(u){if(!h(u,"ENOENT"))throw u}finally{s!==null&&a.default.closeSync(s)}}}function re(e,t,n){if(!_e()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw B();if(!on(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw B()}});let s=un(e);try{return dn(e),n({read:()=>sn(e),remove:()=>an(e),write:()=>{throw B()}})}finally{Qe(s)}}if(!t.createParent){let o=!1;try{o=pn(e)}catch{throw B()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw B()}})}throw B()}if(!on(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=un(e);try{return dn(e),n({read:()=>sn(e),remove:()=>an(e),write:o=>ai(e,o)})}finally{Qe(i)}}var tt="allscale-cli";function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yn(e){return ot(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function U(e){return new c("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function nt(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function ye(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var $,rt=!1;function hi(){return qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function mi(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 _i(){if($!==void 0)return $;if(hi())return rt=!1,$=null,$;try{$=require("keytar"),rt=!1}catch(e){rt=!mi(e),$=null}return $}function wn(){let e=_e()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function it(e){try{return await e()}catch{throw wn()}}var st=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await it(()=>this.keytar.getPassword(tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw U("OS keychain")}if(!yn(r))throw U("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await it(()=>this.keytar.setPassword(tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await it(()=>this.keytar.deletePassword(tt,t))}},yi="credentials.json",at=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??_n.join(Je(),yi)}read(t){let n;try{n=t.read()}catch(i){throw me(i)?nt():U("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw U("plaintext file")}if(!ot(r)||!ot(r.profiles))throw U("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw me(r)?nt():ye()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!yn(r))throw U("plaintext file");return r}}async get(t){try{return re(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:U("plaintext file")}}async set(t,n){try{re(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof c?r:ye()}}async delete(t){try{re(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:ye()}}async clearProfile(t){try{return re(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof c?n:me(n)?nt():ye()}}};function Sn(e){if(e.insecureStorage)return fn(),new at(e.insecureFilePath);let t=_i();if(t)return new st(t);throw wn()}var lt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new c("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function we(){return new lt}var Se="allscale_access_token",ct="allscale_refresh_token";function En(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 ut(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function dt(e,t){return e.find(n=>n.name===t)?.value??null}var An=E(require("crypto")),bn=E(require("fs")),kn=E(require("path"));var wi="key-id",Si="x-allscale-cli-version",ft="cli-1",Ei="aScaLe_cli_obf_v1",Ai="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function bi(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 ki=bi(Ai,Ei),Ln=`Bearer ${ki}`;function Tn(e,t){let n=ve(e);if(n!==null)return t.find(r=>ve(r.base)===n)}function Li(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Tn(e,t);if(r)return r.key;if(N(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:N(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 Ti(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Tn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&N(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():ft}if(!N(t[0].base))return ft}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():ft}function Ii(){return"0.1.0"}function Oi(){return new c("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 pt(e,t){let n=Li(t);if(!n)throw Oi();let r=Ti(t),i=Math.floor(Date.now()/1e3).toString(),o=An.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Si]:Ii()};return r.length>0&&(s[wi]=r),s}function In(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Ci(e,t={}){let n;try{n=Jt(ue())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",Ct(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function On(e){if(e.profileExplicit){let t=Ci(e.profile);if(t)return t}return new c("auth.no_token",Ot(e.profile,e.flow))}var gt=256*1024,Ee=class extends c{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"}},Ae=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 ht(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 Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],u=0,l,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,w)=>{l=setTimeout(()=>{w(new Ae(e.status,d))},d),l.unref?.()});try{for(;;){let p=o.read(),{done:w,value:_}=f?await Promise.race([p,f]):await p;if(w)break;if(u+=_.byteLength,u>t)throw o.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(_))}}catch(p){throw p instanceof Ae&&o.cancel(p).catch(()=>{}),p}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var Ri="X-AllScale-Api-Key",vi=3e4,Ni=32*1024*1024,Pi=4*1024*1024;function xi(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 Bi(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 Di(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${C(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Pn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Di(e.status,e.url)}}var Cn="--dns-result-order=ipv4first";async function be(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)??"",u=/^\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||u)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new c("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=${Cn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${Cn}`})}var F=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??vi;if(!Number.isFinite(r)||r<1)throw new c("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),de(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=xi(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new c("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof c)?new c("transport.network",`Request to ${C(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();Zt(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",u=xn(t.path),l=s==="required"?!0:s==="none"?!1:Fi(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw On({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=In(t.body),f=!!o||!!r?.access_token;l&&f&&!this.opts.override&&Ve(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:l&&f,bodyForSig:d,tokens:r,extra:t.headers}),w=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let _;try{_=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(S){throw new c("transport.network",`Network error contacting ${C(i)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:_.status,durationMs:Date.now()-w}),l&&!!r?.access_token&&!o&&_.status===401&&!t._isRefresh&&!this.opts.override){let S=await Bi(this.refreshSingleFlight(),t.signal),ie=this.buildHeaders({attachAuth:l&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),er=Date.now();y({type:"request",method:t.method??"GET",url:i});let Le;try{Le=await fetch(i,{method:t.method??"GET",headers:ie,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Te){throw new c("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Te instanceof Error?Te.message:String(Te)}`)}return y({type:"response",status:Le.status,durationMs:Date.now()-er}),Rn(Le,{withMetadata:n.withMetadata,authBearing:l,responseKind:vn(t)})}return Rn(_,{withMetadata:n.withMetadata,authBearing:l&&f,agentKeyAuth:l&&!!o,responseKind:vn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...pt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Ln;let i=t.tokens;if(i?.agent_key)return r[Ri]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=ut([{name:Se,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new c("auth.token_expired",`No refresh token available; log in again \u2014 ${xe()}.`);if(Ve(this.opts.apiBase,t.api_base),t.agent_key)throw new c("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=ut([{name:Se,value:t.access_token},{name:ct,value:t.refresh_token}]),i=pt("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,u=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(_){throw y({type:"refresh",ok:!1}),new c("transport.network",s&&_ instanceof Error&&_.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${_ instanceof Error?_.message:String(_)}`)}finally{clearTimeout(u)}y({type:"response",status:l.status,durationMs:0});try{await Pn(l)}catch(_){throw y({type:"refresh",ok:!1}),_}if(l.status!==200){y({type:"refresh",ok:!1}),await be(l);let _=await Ki(l);throw await be(l,_),Bn(l.status,_),new c("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${xe()}.`,{status:l.status})}let d=En(l.headers),f=dt(d,Se),p=dt(d,ct);if(!f||!p)throw y({type:"refresh",ok:!1}),new c("auth.token_expired","Refresh response did not include new access/refresh cookies.");let w={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,w),y({type:"refresh",ok:!0}),w}},$i=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function xn(e){let t=e.split(/[?#]/,1)[0];return $i.some(n=>t===n||t.startsWith(`${n}/`))}var Ui=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function mt(e){let t=e.split(/[?#]/,1)[0];return Ui.some(n=>n.test(t))}function Fi(e){return xn(e)||mt(e)}async function Rn(e,t={}){await Pn(e);let n=e.status>=200&&e.status<300;n||await be(e);let r=t.responseKind??"mutation",o=await ht(e,n?r==="query"?Ni:Pi:gt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await be(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,f)=>{l[f]=d}),{status:e.status,headers:l,body:s}}return s}let u=Yi(s)??`HTTP ${e.status}`;if(Bn(e.status,s),e.status===401){if(t.agentKeyAuth)throw new c("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 c(l,u,{status:401,body:s})}throw e.status===403?new c("auth.permission_denied",u,{status:403,body:s}):e.status===404?new c("not_found",u,{status:404,body:s}):e.status===429?new c("rate_limited",u,{status:429,body:s}):e.status>=500?new c("backend.internal",u,{status:e.status,body:s}):new c("input.invalid",u,{status:e.status,body:s})}function vn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Nn=2014;function Gi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===Nn||n===String(Nn)}var Mi=1e4;async function Ki(e,t=Mi){if(e.status>=200&&e.status<300)return"";try{return await ht(e,gt,{timeoutMs:t})}catch{return""}}function Bn(e,t){if(!(e>=200&&e<300)&&Gi(t))throw new c("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}function Yi(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 Hi=/^\/(api\/)?(v1\/)?public\//;function Dn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Hi.test(n),i=n&&mt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new F({apiBase:e.apiBase,tokenStore:we(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new F({apiBase:e.apiBase,tokenStore:we(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new F({apiBase:e.apiBase,tokenStore:Sn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new F({apiBase:e.apiBase,tokenStore:we(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var $n=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:all"]),Un=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Fn(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Gn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var qi={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"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",create_store:"store:all",auto_payout_session_status:"claim_link:read_only",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},ji={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"},Wi=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,zi=/is not available to API keys/i,Mn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Kn(e){if(typeof e!="string")return;let t=Wi.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=zi.test(n),o=!i&&Mn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(l=>l.trim()).filter(l=>Mn.test(l));s=u.length>0?u:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Yn(e){let t=ji[e];if(t!==void 0)return{ungrantableReason:t};let n=qi[e];if(n!==void 0)return{scope:n}}function Hn(e){if(Un.has(Fn(e)))return{kind:"ungrantable"};for(let t of $n)if(Gn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function qn(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function jn(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("; ")}function zn(e,t){let n=Jn(e),r={graphql_error_count:Ji(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Vi(e,t,r);if(n===3400)throw new c("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(qn(e))throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${jn(e)}`,r);if(n!==void 0)throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function Jn(e){let t=Wn(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=Wn(r.code);if(i!==void 0)return i}}function Wn(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 Ji(e){return Array.isArray(e)?e.length:e==null?0:1}function Vi(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Kn(Xi(e,Jn(e))),s=Yn(t.operationName),u=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,f=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let p=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new c("auth.permission_denied",`${r} is not available to agent keys${p}. Re-authorizing will NOT help \u2014 no scope grants it.${f} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let p=Hn(l),w=p.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:p.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${X()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${X()}\` with \`--scopes ${l}\`.`;return new c("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${f} ${w}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...p.kind==="ungrantable"?{ungrantable:!0}:{}})}return new c("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${f} Re-run \`allscale device-login\` (or \`${X()}\`) and grant the required scope.`,i)}function Xi(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var Zi="/api/secure/graphql";var Xn="amount network_fee service_fee total per_transfer_gas gas_shares";async function Zn(e,t){t.showDoc&&process.stderr.write(`${t.document}
17
- `);let r=await Dn(e).request({method:"POST",path:Zi,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});zn(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var Qi=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,eo=/^0(?:\.0+)?$/,Vn=128;function _t(e,t,n={}){if(t.length>Vn)throw new c("input.invalid",`${e} is too long; decimal values may contain at most ${Vn} characters.`);let r=t.trim();if(!Qi.test(r))throw new c("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&eo.test(r))throw new c("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Qn(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new c("input.invalid",`${e} supports at most ${n} effective decimal places for the selected token and chain; got '${t}'. The CLI will not round a funds amount.`);return t}var ke=class e extends Q{static description="Preview Claim Link fees without creating a link. Mirrors create_claim_link validation.";static examples=["$ allscale claim-link preview --amount 10 --chain base --per-transfer-gas 0.02"];static flags={amount:v.Flags.string({helpGroup:"REQUIRED",description:"Receiver amount as a decimal string in token units; at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:v.Flags.string({helpGroup:"REQUIRED",description:"EVM chain for the claim link.",options:[...en],required:!0}),"per-transfer-gas":v.Flags.string({helpGroup:"REQUIRED",description:"One ERC-20 transfer's gas estimate in token units.",required:!0}),"stable-coin":v.Flags.string({description:"Stablecoin for the link.",options:[...fe],default:"USDT"}),"show-doc":v.Flags.boolean({description:"Print the GraphQL document to stderr.",default:!1}),...Q.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=tn(t.chain);if(n===null)throw new c("input.invalid",`Unsupported --chain '${t.chain}'.`);let r=nn(t["stable-coin"]);if(r===null)throw new c("input.invalid",`Unsupported --stable-coin '${t["stable-coin"]}'.`);let i=Qn("--amount",_t("--amount",t.amount),Qt(n,r)),o=`query claim_link_fee_preview($amount: String!, $chain: Int!, $token_symbol: String!, $per_transfer_gas: String!) { claim_link_fee_preview(amount: $amount, chain: $chain, token_symbol: $token_symbol, per_transfer_gas: $per_transfer_gas) { ${Xn} } }`,s=this.resolveContext(t);return Zn(s,{kind:"query",operationName:"claim_link_fee_preview",document:o,variables:{amount:i,chain:n,token_symbol:rn(r),per_transfer_gas:_t("--per-transfer-gas",t["per-transfer-gas"],{allowZero:!0})},showDoc:!!t["show-doc"]})}};
18
- //# sourceMappingURL=preview.js.map