snoutdata 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -7
- package/dist/snoutdata.mjs +591 -248
- package/package.json +1 -1
package/dist/snoutdata.mjs
CHANGED
|
@@ -1,32 +1,236 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
var Rh=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tl=(e,t)=>{for(var n in t)Rh(e,n,{get:t[n],enumerable:!0})};function Ol(e){let t=[],n={};for(let r=0;r<e.length;r++){let o=e[r];if(!o.startsWith("-")){t.push(o);continue}if(o==="--"){t.push(...e.slice(r+1));break}let[s,a]=Nh(o);if(Th.has(s)){let l=a??e[++r];if(l===void 0)throw new y(`--${s} needs a value`);n[s]=l;continue}if(a!==void 0)throw new y(`--${s} does not take a value`);if(!Oh.has(s))throw new y(`unknown option --${s}`);n[s]=!0}return{command:t,flags:n,json:n.json===!0}}function Nh(e){let t=e.replace(/^--?/,""),n=t.indexOf("=");return n===-1?[t,void 0]:[t.slice(0,n),t.slice(n+1)]}function R(e,t){let n=e.flags[t];return typeof n=="string"?n:void 0}function W(e,t){return e.flags[t]===!0}function Le(e,t){let n=R(e,t);if(n===void 0)return;let r=Number(n);if(!Number.isInteger(r))throw new y(`--${t} must be a whole number, not "${n}"`);return r}var y,Th,Oh,ve=z(()=>{"use strict";y=class extends Error{},Th=new Set(["name","sort","at","region","servers","max-size","size","ref","profile","file","provider","domain","expires","project","timeout","out","team","dir","days","schema","db-url","data-api-version","postgrest-version","port","entrypoint","memory","concurrency","tail","registry-user","dockerfile","client-id","site-url","allow","subject","p8","key-id","team-id","topic","environment","email","channel","since","level","note","grace","admin","token","host","dbname","sslmode","peer-host","to","key-type","ranges","seed","nodes","column","distribution-key","keyspace","schemas","min-bytes","interval-ms","instances","range","node","value","add","remove","max-write-pause-ms","drain-timeout-ms","ack-timeout-ms","copy-mb-per-s","set","sample-ms","source","model","base-url","price-in","price-out","access-key-id","auth-header","models","amount","period","by","prompt","limit"]);Oh=new Set(["json","slack","all","window","help","version","force","no-verify-jwt","reset","errors","follow","stdin","clear-registry","quiet","yes","plan","status","no-wait","no-join","queue","no-browser","device","sso","env","dry-run","out-of-order","allow-delete","local","no-migrations","history","tables","show-url","check","watch","soft"])});import{chmodSync as Ih,existsSync as Tr,mkdirSync as Ns,readdirSync as Ch,readFileSync as Is,rmSync as Cl,writeFileSync as Cs}from"node:fs";import{homedir as St}from"node:os";import{dirname as Or,join as Ln,parse as Lh,resolve as Mh}from"node:path";function on(e){if(!Ls.test(e))throw new Os(`"${e}" is not a profile name: use letters, digits, - and _ (up to 40), starting with a letter or digit`);return e}function Ll(e){Tt=on(e)}function ke(){return Tt}function Ms(e){let t=e.environment??process.env;if(e.flag!==void 0)return{name:on(e.flag),from:"flag"};if(t.SNOUTDATA_PROFILE)return{name:on(t.SNOUTDATA_PROFILE),from:"environment"};let n=qt(e.cwd??process.cwd())?.profile;if(n)return{name:on(n),from:"link"};let r=Dh(e.home);return r?{name:r,from:"chosen"}:{name:be,from:"default"}}function Ml(e=St()){return Ln(e,".snoutdata","profile")}function Dh(e=St()){try{let t=Is(Ml(e),"utf8").trim();return Ls.test(t)?t:null}catch{return null}}function Dl(e,t=St()){let n=Ml(t);if(on(e)===be){Cl(n,{force:!0});return}Ns(Or(n),{recursive:!0}),Cs(n,`${e}
|
|
3
|
+
`)}function Ds(e=St(),t=Tt){return Ln(e,".snoutdata",t===be?"auth.json":`auth.${on(t)}.json`)}function Nr(e=St()){let t=Ln(e,".snoutdata");if(!Tr(t))return[];let n=Ch(t).map(r=>/^auth\.(.+)\.json$/.exec(r)?.[1]).filter(r=>r!==void 0&&Ls.test(r)&&r!==be).sort();return[...Tr(Ln(t,"auth.json"))?[be]:[],...n]}function js(e=St(),t=Tt){let n=Ds(e,t);if(!Tr(n))return null;try{let r=JSON.parse(Is(n,"utf8"));return typeof r.accessToken=="string"?r:null}catch{return null}}function Ir(e=St(),t=Tt){let n=process.env.SNOUTDATA_ACCESS_TOKEN;return n?{accessToken:n}:js(e,t)}function lt(e,t=St(),n=Tt){let r=Ds(t,n);Ns(Or(r),{recursive:!0}),Cs(r,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384}),Ih(r,384)}function Us(e=St(),t=Tt){Cl(Ds(e,t),{force:!0})}function jl(e,t=Date.now()){return e.expiresAt?e.expiresAt*1e3-6e4<=t:!1}function Ul(e){return Ln(e,".snoutdata","project.json")}function qt(e){let t=Mh(e),n=Lh(t).root;for(;;){let r=Ul(t);if(Tr(r))try{let o=JSON.parse(Is(r,"utf8"));if(typeof o.ref=="string"&&o.ref)return{ref:o.ref,directory:t,...typeof o.local=="string"&&o.local?{local:o.local}:{},...typeof o.profile=="string"&&o.profile?{profile:o.profile}:{}}}catch{}if(t===n)return null;t=Or(t)}}function sn(e,t,n=Tt){let r=Ul(e);Ns(Or(r),{recursive:!0});let o={ref:t.ref,...t.name!==void 0?{name:t.name}:{},...t.local!==void 0?{local:t.local}:{},...n!==be?{profile:n}:{}};return Cs(r,`${JSON.stringify(o,null,2)}
|
|
5
|
+
`),r}function Mn(e){let t=e.environment??process.env;return e.flag?e.flag:t.SNOUTDATA_PROJECT?t.SNOUTDATA_PROJECT:qt(e.cwd??process.cwd())?.ref??null}function Fl(e){let t=e.environment??process.env,n=qt(e.cwd??process.cwd())?.ref??null;if(e.flag)return n===e.flag?{kind:"linked",ref:n}:{kind:"link",ref:e.flag,replaces:n};let r=t.SNOUTDATA_PROJECT;return r?n===r?{kind:"linked",ref:n}:{kind:"environment",ref:r}:n?{kind:"linked",ref:n}:{kind:"create"}}var be,Ls,Os,Tt,Ot=z(()=>{"use strict";be="default",Ls=/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/,Os=class extends Error{};Tt=be});import{existsSync as Fs,readFileSync as Bl}from"node:fs";import{homedir as jh}from"node:os";import{isAbsolute as Uh,join as Nt,resolve as an}from"node:path";function Fh(e=process.env,t=process.platform,n=jh()){let r;return t==="win32"?r=e.APPDATA??Nt(n,"AppData","Roaming"):t==="darwin"?r=Nt(n,"Library","Application Support"):r=e.XDG_CONFIG_HOME??Nt(n,".config"),["snoutdata","snoutdata-dev"].map(o=>Nt(r,o,"localProjects.json"))}function Cr(e=Fh()){let t=[];for(let n of e)if(Fs(n))try{let r=JSON.parse(Bl(n,"utf8"));for(let o of r.projects??[])typeof o.folder=="string"&&o.folder&&!t.some(s=>s.folder===o.folder)&&t.push({name:o.name??null,folder:o.folder,ref:o.ref??null})}catch{}return t}function Lr(e){let t=new Map;for(let n of e.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;let o=r.indexOf("=");if(o<=0)continue;let s=r.slice(0,o).trim(),a=r.slice(o+1).trim();a.length>=2&&(a[0]==='"'||a[0]==="'")&&a.endsWith(a[0])&&(a=a.slice(1,-1)),t.set(s,a)}return t}function Dn(e){return Fs(Nt(e,"compose.yaml"))&&Fs(Nt(e,".env"))}function It(e,t=null){let n=an(e);if(!Dn(n))throw new Error(`${n} is not a SnoutData stack folder: it needs compose.yaml and .env (see github.com/snoutdata/snout-stack)`);let r=Lr(Bl(Nt(n,".env"),"utf8")),o=r.get("SNOUT_REF"),s=r.get("POSTGRES_OWNER_PASSWORD");if(!o||!s)throw new Error(`${Nt(n,".env")} has no ${o?"POSTGRES_OWNER_PASSWORD":"SNOUT_REF"}, so this stack was not set up with \`snout-stack init\``);let a=Number(r.get("API_PORT")??8e3)||8e3,l=Number(r.get("DB_PORT")??5432)||5432;return{folder:n,ref:o,name:t,apiUrl:(r.get("API_EXTERNAL_URL")||`http://127.0.0.1:${a}`).replace(/\/$/,""),apiPort:a,dbPort:l,appKey:r.get("APP_KEY")||r.get("ANON_KEY")||null,serverKey:r.get("SERVER_KEY")||r.get("SERVICE_ROLE_KEY")||null,ownerPassword:s}}function Hl(e,t=process.cwd(),n=Cr()){if(!e){if(Dn(t))return It(t);let[d]=n;if(n.length===1&&d)return It(d.folder,d.name);throw n.length===0?new Error("there is no local project to link: set one up in Studio (Projects, Local), or pass the folder of a stack you made with snout-stack"):new Error(`there are ${n.length} local projects; name one: ${n.map(c=>c.name??c.folder).join(", ")}`)}let r=Uh(e)?e:an(t,e);if(Dn(r)){let d=n.find(c=>an(c.folder)===an(r));return It(r,d?.name??null)}let o=e.toLowerCase(),s=n.filter(d=>d.name?.toLowerCase()===o||d.ref===e),[a]=s;if(s.length===1&&a)return It(a.folder,a.name);let l=n.map(d=>d.name??d.folder);throw new Error(s.length>1?`more than one local project is called ${e}; link it by its folder`:`no local project called ${e}, and it is not a stack folder${l.length?`. The local projects are ${l.join(", ")}`:""}`)}function Gl(e){let t=`${e.ref}_owner`;return{ref:e.ref,host:"127.0.0.1",port:e.dbPort,database:e.ref,user:t,password:e.ownerPassword,ssl:"disable",uri:`postgresql://${t}:${encodeURIComponent(e.ownerPassword)}@127.0.0.1:${e.dbPort}/${e.ref}`,appKey:e.appKey,serverKey:e.serverKey,keysIssuedAt:null,keysExpireAt:null,wakesInstantly:!0,state:"local"}}function ql(e,t,n=Cr()){if(t&&Dn(t))try{let r=n.find(s=>an(s.folder)===an(t)),o=It(t,r?.name??null);if(o.ref===e)return o}catch{}for(let r of n)if(r.ref===e&&Dn(r.folder))return It(r.folder,r.name);return null}var jn=z(()=>{"use strict"});function Q(e,t,n){throw new O(e,t,n)}function kt(e,t){return t==="no-capacity"?"no-capacity":e===400&&t==="region"?"usage":e===403?"forbidden":e===404?"not-found":e===409?"conflict":e===402||e===429||t==="provider_billing"?"quota":t==="timeout"?"timeout":t!=null&&Bh.has(t)?"server":e===503?"not-ready":e===504?"timeout":e===410?"outdated":e>=500?"server":"failed"}function Kl(e){let t=e;return!t||typeof t!="object"||t.code!=="ENOENT"||typeof t.path!="string"||t.syscall==="spawn"?null:`no file at ${t.path}`}function Mr(e){let t=[e],n=e;for(let r=0;r<4&&n instanceof Error&&n.cause;r+=1)n=n.cause,t.push(n);for(let r of t){let o=typeof r=="object"&&r&&"code"in r?String(r.code):"";if(Hh.has(o))return"network";if(o==="ABORT_ERR"||o==="ETIMEDOUT")return"timeout"}return e instanceof Error&&/fetch failed|network|socket hang up/i.test(e.message)?"network":"failed"}var ct,O,Bh,Hh,_e=z(()=>{"use strict";ct={ok:0,failed:1,usage:2,"not-signed-in":3,"not-ready":4,forbidden:5,"not-found":6,conflict:7,quota:8,network:9,timeout:10,outdated:11,"no-capacity":12,"tool-missing":127,server:1},O=class extends Error{code;details;constructor(t,n,r){super(n),this.name="CliFailure",this.code=t,this.details=r}get exitCode(){return ct[this.code]}};Bh=new Set(["provider_auth","upstream_error","transport","egress_refused"]);Hh=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","CERT_HAS_EXPIRED","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT"])});function Dr(e){let t=e.env.SNOUTDATA_NO_INTERACTIVE;if(t!==void 0&&t!==""&&t!=="0"&&t!=="false")return{canAsk:!1,reason:"opted-out"};if(e.json)return{canAsk:!1,reason:"json"};for(let n of Gh){let r=e.env[n];if(r!==void 0&&r!==""&&r!=="0"&&r!=="false")return{canAsk:!1,reason:"ci"}}return e.isTty?{canAsk:!0}:{canAsk:!1,reason:"not-a-tty"}}function ln(e){switch(e){case"json":return"running with --json, so nothing was asked";case"opted-out":return"SNOUTDATA_NO_INTERACTIVE is set, so nothing was asked";case"ci":return"this looks like CI, so nothing was asked";case"not-a-tty":return"there is no terminal to ask at"}}function zl(e){Bs=e}function Pe(){return(Bs??Dr({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).canAsk}function cn(){return(Bs??Dr({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).reason}var Gh,Bs,Ct=z(()=>{"use strict";Gh=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD"];Bs=null});import{createHmac as qh,randomBytes as Kh,timingSafeEqual as zh}from"node:crypto";import{existsSync as Wh,readFileSync as Jh}from"node:fs";import{homedir as Hs,hostname as Vh}from"node:os";import{join as dn}from"node:path";function Yh(e,t,n){if(t==="win32"){let r=n.APPDATA??dn(Hs(),"AppData","Roaming");return dn(r,e)}return t==="darwin"?dn(Hs(),"Library","Application Support",e):dn(n.XDG_CONFIG_HOME??dn(Hs(),".config"),e)}function Jl(e=process.platform,t=process.env){return t.SNOUTDATA_DESKTOP_CONFIG?[t.SNOUTDATA_DESKTOP_CONFIG]:["snoutdata","snoutdata-dev"].map(n=>dn(Yh(n,e,t),"mcp.json"))}function Xh(e=process.platform,t=process.env){return Jl(e,t)[0]}function Zh(e=Xh()){if(!Wh(e))return null;try{let t=JSON.parse(Jh(e,"utf8"));return typeof t.port!="number"||typeof t.token!="string"||!t.token?null:t}catch{return null}}function Qh(e){return e?e.enabled===!1?"server-disabled":e.signInHandoff===!1?"handoff-disabled":null:"no-config"}function ty(e,t,n){return qh("sha256",e).update(`${ey}
|
|
5
6
|
${t}
|
|
6
|
-
${n}`).digest("base64url")}function
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
<
|
|
14
|
-
<
|
|
15
|
-
<div
|
|
16
|
-
|
|
17
|
-
<
|
|
18
|
-
</div>
|
|
19
|
-
<
|
|
20
|
-
<
|
|
21
|
-
<
|
|
22
|
-
|
|
7
|
+
${n}`).digest("base64url")}function ny(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&zh(n,r)}async function Yl(e){let t=e.port;if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>65535||!e.token)return!1;let n=Kh(32).toString("base64url");try{let r=await fetch(`http://127.0.0.1:${t}/cli/prove?nonce=${n}`,{redirect:"error",signal:AbortSignal.timeout(Vl)});if(!r.ok)return!1;let o=await r.json();return typeof o.proof=="string"&&ny(o.proof,ty(e.token,t,n))}catch{return!1}}async function qs(e,t,n,r=Yl){if(!await r(e).catch(()=>!1))throw new jr(e.port);return fetch(`http://127.0.0.1:${e.port}${t}`,{...n,redirect:"error",headers:{...n.headers,Authorization:`Bearer ${e.token}`}})}async function Ur(e,t=Yl){if(e!==void 0)return Wl(e,t);let n="no-config";for(let r of Jl()){let o=Zh(r);if(!o)continue;let s=await Wl(o,t);if(s.available)return s;(s.skip!=="not-running"&&s.skip!=="not-verified"||n==="no-config")&&(n=s.skip)}return{available:!1,skip:n}}async function Wl(e,t){let n=Qh(e);if(n)return{available:!1,skip:n};let r=e,o;try{let s=await qs(r,"/cli/whoami",{signal:AbortSignal.timeout(Vl)},t);if(!s.ok)return{available:!1,skip:"not-running"};o=await s.json()}catch(s){return s instanceof jr?{available:!1,skip:"not-verified"}:{available:!1,skip:"not-running"}}return o.signedIn?o.canMintToken?{available:!0,who:o,config:r}:{available:!1,skip:"cannot-mint"}:{available:!1,skip:"signed-out"}}async function Xl(e,t){let n=await qs(e,"/cli/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client:"snoutdata-cli",command:t}),signal:AbortSignal.timeout(6e4)}),r=await n.json().catch(()=>({}));return n.ok&&r.ok&&r.token?{token:r.token,name:r.name??"SnoutData CLI"}:{declined:!0,reason:r.error??`SnoutData Studio refused (${n.status})`}}function Fr(){return Vh()}async function Gs(e,t,n,r){let o=await qs(e,"/mcp",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:t,params:n}),signal:AbortSignal.timeout(r)});if(!o.ok)throw new Error(`the app answered ${o.status}`);let s=await o.json();if(s.error)throw new Error(s.error.message??"SnoutData Studio refused");return s.result}async function Zl(e){return await Gs(e,"initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"snoutdata-cli",version:"0"}},3e3),(await Gs(e,"tools/list",{},3e3)).tools??[]}async function Ql(e,t,n){return Gs(e,"tools/call",{name:t,arguments:n},12e4)}var Vl,ey,jr,Br=z(()=>{"use strict";Vl=1500,ey="snoutdata-studio-proof-v1";jr=class extends Error{constructor(t){super(`the process on 127.0.0.1:${t} did not prove it is SnoutData Studio, so Studio's token was not sent to it`),this.name="PeerNotVerified"}}});function Ks(e){try{return new URL(e).host}catch{return e}}function Gr(e,t=""){return{path:`/v1/fn/${e}${t}`,oldPath:`/functions/v1/${e}${t}`}}function tc(e){return{path:`/v1/data${e}`,oldPath:`/rest/v1${e}`}}function st(e,t){return{path:`/v1/identity${e}`,oldPath:`/auth/v1${t}`}}function sy(e){return Hr.has(Ks(e))}function ay(e,t,n){return t===void 0?e:{...e,[n?oy:ry]:t}}async function Be(e,t,n={},r=fetch){let o=Ks(e),s=n.headers??{};function a(c){return r(`${e}${c?t.oldPath:t.path}`,{method:n.method??"GET",headers:ay(s,n.key,c),body:n.body})}if(Hr.has(o))return a(!0);let l=await a(!1);if(l.status!==404)return l;let d=await a(!0);return d.status===404?l:(Hr.add(o),d)}async function nc(e,t,n,r=fetch){if(!Hr.has(Ks(e)))try{await Be(e,st("/health","/health"),{key:n},r)}catch{}return`${e}${sy(e)?t.oldPath:t.path}`}var ry,oy,Hr,qr=z(()=>{"use strict";ry="Snout-Key",oy="apikey",Hr=new Set});import{basename as iy}from"node:path";function Kr(e={bun:typeof process.versions.bun=="string",execPath:process.execPath,script:process.argv[1]??""}){let t=iy(e.execPath.replace(/\\/g,"/")).toLowerCase();if(e.bun&&t.startsWith("snoutdata"))return"binary";let n=e.script.replace(/\\/g,"/");return/\/_npx\//.test(n)?"npx":/\/node_modules\/snoutdata\//.test(n)?"npm":"source"}function ly(e=Kr(),t=process.platform){switch(e){case"binary":case"npm":return"snoutdata upgrade";case"npx":return"npx snoutdata@latest";case"source":return t==="win32"?_t:Fn}}function zs(e={}){let t=e.kind??Kr(),n=e.platform??process.platform,r=e.minimum?`${e.minimum} or later is required`:"a newer version is required",o=n==="win32"?_t:`${Fn} (or ${_t})`;return`snoutdata ${$e} is installed and ${r}. Run \`${ly(t,n)}\`, or install again: ${o}`}function Ws(e,t){if(e==="dev"||t==="dev")return!1;let n=e.split("-")[0].split(".").map(Number),r=t.split("-")[0].split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o+=1){let s=n[o]??0,a=r[o]??0;if(Number.isNaN(s)||Number.isNaN(a))return!1;if(s!==a)return s<a}return!1}var $e,Un,Fn,_t,Bn=z(()=>{"use strict";$e="0.22.0",Un=`snoutdata-cli/${$e}`,Fn="curl -fsSL https://snoutdata.com/install.sh | sh",_t="npm install -g snoutdata@latest"});async function rc(e,t){let n=await Be(He,Gr(e),{method:"POST",key:Ge,headers:{"Content-Type":"application/json","x-client-info":Un},body:JSON.stringify(t)});Jr(n);let r=await n.json().catch(()=>({}));if(n.status===410){let o=r.error;throw Vr(n,typeof o=="string"?o:"This version of the snoutdata CLI is no longer supported.")}return{status:n.status,body:r}}async function zr(e={}){let{status:t,body:n}=await rc("cloud-device-start",{client:e});return t===429&&Q("quota",n.error??"too many pairing attempts from here: wait a few minutes"),t===404&&Q("not-found","this SnoutData does not have the pairing flow (cloud-device-start is not deployed). Use `snoutdata login` to sign in with a browser, or set SNOUTDATA_ACCESS_TOKEN."),(t!==200||!n.code||!n.secret)&&Q("server",n.error??`could not start a pairing (${t})`),n}async function Wr(e,t){let n=t.intervalMs,r=Date.parse(t.expiresAt);for(;;){Date.now()>r&&Q("timeout","that pairing code expired before it was approved. Run the command again for a new one."),await new Promise(a=>setTimeout(a,n));let{status:o,body:s}=await rc("cloud-device-poll",{secret:e});switch(o===404&&Q("not-found","that pairing is not known to the server. Run the command again for a new code."),o===400&&Q("usage",s.error??"that is not a pairing secret"),o!==200&&Q("server",s.error??`the pairing could not be checked (${o})`),s.status){case"approved":return{token:s.token,name:s.name};case"denied":Q("forbidden",s.error??"that pairing was refused in the browser");case"used":Q("conflict",s.error??"that pairing has already been completed");case"expired":Q("timeout",s.error??"that pairing code expired before it was approved");case"slow-down":n=Math.max(n*2,(s.interval??2)*1e3);break;default:s.interval&&(n=Math.max(n,s.interval*1e3));break}t.onWait?.(Math.max(0,Math.round((r-Date.now())/1e3)))}}var Js=z(()=>{"use strict";me();qr();_e();Bn()});function dt(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Yr(e,t=!1){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>SnoutData</title>
|
|
8
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
9
|
+
<meta name="referrer" content="no-referrer">
|
|
10
|
+
<style>${uy}</style></head>
|
|
11
|
+
<body><main class="gate"><div class="gate-card${t?" wide":""}">
|
|
12
|
+
<img class="brand-mark" src="${dy}" width="40" height="40" alt="">
|
|
13
|
+
${e}
|
|
14
|
+
</div></main></body></html>`}function oc(e){return`<p class="small muted where">Signing in the <code>snoutdata</code> CLI on this computer${e?` as profile <strong>${dt(e)}</strong>`:""}. Your terminal carries on once you are in.</p>`}function sc(e){return e?`<p class="error" role="alert">${dt(e)}</p>`:""}function ac(e){let t=encodeURIComponent(e.token),n=e.google?`<a class="btn btn-provider" href="/google?t=${t}">${fy}Continue with Google</a>`:"";return Yr(`<h1>SnoutData</h1>
|
|
15
|
+
<p class="small muted">Sign in with the same account as the app and the dashboard.</p>
|
|
16
|
+
<div class="stack">
|
|
17
|
+
${n}
|
|
18
|
+
<a class="btn btn-provider" href="/github?t=${t}">${gy}Continue with GitHub</a>
|
|
19
|
+
<div class="or">or</div>
|
|
20
|
+
<form method="post" action="/email">
|
|
21
|
+
<input type="hidden" name="t" value="${dt(e.token)}">
|
|
22
|
+
<label for="email">Work email</label>
|
|
23
|
+
<input id="email" name="email" type="email" autocomplete="email" placeholder="you@company.com" required value="${dt(e.email??"")}"${e.email?"":" autofocus"}>
|
|
24
|
+
${sc(e.error)}
|
|
25
|
+
<button class="btn-primary" type="submit">Continue</button>
|
|
26
|
+
</form>
|
|
27
|
+
<p class="small muted">Your company's identity provider if it has one, or a code sent to that address.</p>
|
|
23
28
|
</div>
|
|
24
|
-
|
|
25
|
-
`),e.noBrowser?d("Open that in a browser, on any machine, and sign in."):(d("Opening that in your browser. If nothing opens, paste it into one."),rh(i))},i=>{o.close(),n(i)})}),o.on("error",n),setTimeout(()=>{o.close(),n(new Error("timed out waiting for the browser"))},e.timeoutMs??3e5).unref()})}async function Ol(e,t){let n=await Xe(Ze,xt("/session?via=pkce","/token?grant_type=pkce"),{method:"POST",key:Qe,headers:{"Content-Type":"application/json"},body:JSON.stringify({auth_code:e,code_verifier:t})});if(!n.ok)throw new Error(`could not exchange the code: ${(await n.text()).slice(0,200)}`);return Nl(await n.json())}async function dh(e,t,n){let r=await fetch(sh,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:xs(),client_secret:ah(),code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:n})}),o=await r.json().catch(()=>({}));if(!r.ok||!o.id_token)throw new Error(`Google would not exchange the code: ${o.error_description??o.error??`HTTP ${r.status}`}`);return o.id_token}async function uh(e){if(!xs())throw new Error("this build of snoutdata has no Google sign-in (it was built for testing). Sign in with a released snoutdata, then run this one.");let{verifier:t,challenge:n}=Ps(),{raw:r,hashed:o}=ih(),s=Ir($s(16)),{code:a,redirectUri:c}=await Es({state:s,timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:l=>lh({redirectUri:l,challenge:n,hashedNonce:o,state:s,loginHint:e.email})}),i=await dh(a,t,c),u=await Xe(Ze,xt("/session?via=id_token","/token?grant_type=id_token"),{method:"POST",key:Qe,headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:"google",id_token:i,nonce:r})});if(!u.ok)throw new Error(`could not turn the Google sign-in into a session: ${(await u.text()).slice(0,200)}`);return Nl(await u.json())}function Nl(e){let t=e,n={accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,email:t.user?.email};return nt(n),n}function Rl(e){let t=e.trim().toLowerCase();if(!t||/\s/.test(t))return null;let n=t.indexOf("@");if(n===0||t.indexOf("@",n+1)!==-1)return null;let r=n===-1?t:t.slice(n+1);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(r))return null;let o=r.slice(r.lastIndexOf(".")+1);return/^[a-z]{2,}$/.test(o)?r:null}function ph(e){try{let t=JSON.parse(e);for(let n of["error_description","msg","message","error"]){let r=t[n];if(typeof r=="string"&&r)return r}}catch{return""}return""}function mh(e,t,n){let r=ph(t);return e===404||/no sso provider/i.test(r)?new C("not-found",`No single sign-on is set up for ${n}. Check the address, or ask whoever administers your team to connect your identity provider.`,{domain:n}):/saml.*(disabled|not enabled)/i.test(r)?new C("failed",`Single sign-on is not available for ${n} yet. Ask whoever administers your team to connect your identity provider.`,{domain:n}):new C(pt(e),r||`Could not start single sign-on for ${n}.`,{domain:n})}async function fh(e){let t=await Xe(Ze,xt("/sso/start","/sso"),{method:"POST",key:Qe,headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e.domain,redirect_to:e.redirectTo,skip_http_redirect:!0,code_challenge:e.challenge,code_challenge_method:"s256"})}),n=await t.text();if(!t.ok)throw mh(t.status,n,e.domain);let r;try{r=JSON.parse(n).url}catch{r=void 0}if(typeof r!="string"||!r)throw new C("server",`Single sign-on for ${e.domain} was accepted but came back without somewhere to send the browser.`,{domain:e.domain});return r}async function gh(e){if(e!==void 0){let r=Rl(e);if(!r)throw new h(`--domain wants a work email or a company domain, like you@yourcompany.com, not "${e}"`);return r}if(!Se()){let r=en();throw new h(`login --sso needs --domain <your work email or company domain>${r?`, because ${Qt(r)}`:""}`)}let t=eh({input:process.stdin,output:process.stderr}),n=new Promise((r,o)=>{t.once("close",()=>o(new h("nothing left to read: pass --domain <your work email or company domain>")))});n.catch(()=>{});try{for(let r=0;r<3;r+=1){let o=await Promise.race([t.question("Your work email address: "),n]),s=Rl(o);if(s)return s;d("That is not a work email or a company domain. Try something like you@yourcompany.com.")}}finally{t.close()}throw new h("no domain to sign in with: pass --domain <your work email or company domain>")}async function hh(e){let t=await gh(e.domain),{verifier:n,challenge:r}=Ps();d(`Signing in with the identity provider for ${M(t)}.`);let{code:o}=await Es({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:s=>fh({domain:t,redirectTo:s,challenge:r})});return Ol(o,n)}function yh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}}async function bh(e,t=yh(),n=fetch){if(!t||!e)return null;let r=Xe(Ze,kl("/rpc/set_my_timezone"),{method:"POST",key:Qe,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({want_timezone:t,want_source:"signin"})},n).then(async a=>a.ok?null:`HTTP ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`,a=>a instanceof Error?a.message:String(a)),o,s=new Promise(a=>{o=setTimeout(()=>a("timed out"),wh),o.unref()});try{return await Promise.race([r,s])}finally{clearTimeout(o)}}async function Cr(e={}){let t=As(e.email,await Sh(e)),n=await bh(t.accessToken);return n&&process.env.SNOUTDATA_DEBUG&&ce(`could not record the timezone: ${n}`),t}function As(e,t){if(!e)return t;let n={...t,expectedEmail:e};return nt(n),t.email&&!Rs(t.email,e)&&ce(`Signed in as ${t.email}, not ${e}. Run \`snoutdata login --email ${e}\` and pick that account.`),n}function Rs(e,t){return e.trim().toLowerCase()===t.trim().toLowerCase()}async function Sh(e){if(e.sso)return hh({...e,domain:e.domain??e.email});let t=e.provider??"google";if(t==="google")return uh(e);let{verifier:n,challenge:r}=Ps(),{code:o}=await Es({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:async s=>{let a=new URL(await _l(Ze,xt("/provider/start","/authorize"),Qe));return a.searchParams.set("provider",t),a.searchParams.set("redirect_to",s),a.searchParams.set("code_challenge",r),a.searchParams.set("code_challenge_method","s256"),a.searchParams.set("prompt","select_account"),a.toString()}});return Ol(o,n)}function kh(e){return e.replace(/[&<>"]/g,t=>({"&":"&","<":"<",">":">",'"':"""})[t])}var oh,sh,wh,Mr=W(()=>{"use strict";pe();Pr();Ae();_t();be();Pt();de();oh="https://accounts.google.com/o/oauth2/v2/auth",sh="https://oauth2.googleapis.com/token";wh=3e3});import{createInterface as _h}from"node:readline/promises";async function Ts(e){let t=_h({input:process.stdin,output:process.stderr});try{let n=(await t.question(`${e} [Y/n] `)).trim().toLowerCase();return n===""||n==="y"||n==="yes"}finally{t.close()}}async function vh(){let e=await Sr();if(!e.available)return(e.skip==="handoff-disabled"||e.skip==="server-disabled")&&d(v("SnoutData Studio is running but is not set to hand out sign-ins.")),null;let t=e.who.email??"the signed-in account";d("");let n=De();if(d(`SnoutData Studio is open here, signed in as ${M(t)}.`),n!==Me&&d(`Its token would be kept as profile ${M(n)}.`),d(v("It can create an access token for this terminal. Your sign-in itself is not handed over,")),d(v("and you can revoke the token later with `snoutdata tokens revoke`.")),!await Ts("Use it?"))return null;d("Asking SnoutData Studio. Approve it there.");let r=await yl(e.config,process.argv.slice(2).join(" ").slice(0,60)||"snoutdata");if("declined"in r)return d(`The app did not create a token: ${r.reason}`),null;let o={accessToken:r.token};return nt(o),d(`Signed in with "${r.name}".`),o}async function $h(){if(!await Ts("Sign in with a browser?"))return null;try{let e=await Cr({});return d(`Signed in${e.email?` as ${e.email}`:""}.`),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}catch(e){return d(`That did not finish: ${e instanceof Error?e.message:String(e)}`),null}}async function Ph(){if(!await Ts("Sign in by typing a code into a browser on another machine?"))return null;let e=await Ar({name:kr(),platform:process.platform});d(""),d(` Open ${M(e.verifyUrl)}`),d(` Type ${M(e.code)}`),d(""),d(v("The code is typed rather than in the link on purpose: it is what proves the person")),d(v("at the browser is the person at this terminal. Waiting\u2026"));let t=await Rr(e.secret,{intervalMs:Math.max(1,e.interval)*1e3,expiresAt:e.expiresAt}),n={accessToken:t.token};return nt(n),d(`Signed in${t.name?` with "${t.name}"`:""}.`),n}async function Il(){if(!Se())return null;let e=await vh();if(e)return e;let t=await $h();return t||Ph()}var Cl=W(()=>{"use strict";_t();_r();vs();Pt();Mr();de()});var et={};Ji(et,{ACCOUNTS_URL:()=>Ze,APP_KEY:()=>Qe,ApiError:()=>Re,NotSignedIn:()=>Et,call:()=>R,connection:()=>He,errorSentence:()=>jl,exportStatus:()=>nn,isSettled:()=>Ll,listProjects:()=>We,listTeams:()=>Lr,localStack:()=>ht,noticeFrom:()=>Tr,outdated:()=>Or,requestExport:()=>In,serverCodeOf:()=>Dl,unreadableAnswer:()=>jr,waitForReady:()=>Mn,waitForSettled:()=>Cn,whoami:()=>Lt,withKeyNames:()=>Dr});function xh(){let e=en(),t=De(),n=t===Me?"":` as profile ${t}`;return e?`not signed in${n}, and ${Qt(e)}. Set SNOUTDATA_ACCESS_TOKEN to a token made at https://dashboard.snoutdata.com/#/tokens, or by \`snoutdata tokens create\` on a machine that is signed in.`:`not signed in${n}: run \`snoutdata login${t===Me?"":` --profile ${t}`}\`, or set SNOUTDATA_ACCESS_TOKEN`}async function Eh(){let e=mr();if(e||(e=await Il()),!e)throw new Et;if(!ol(e)||!e.refreshToken)return e.accessToken;let t=await Xe(Ze,xt("/session?via=renew","/token?grant_type=refresh_token"),{method:"POST",key:Qe,headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refreshToken})});if(!t.ok)throw new Et;let n=await t.json(),r={...e,accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at};return nt(r),r.accessToken}async function R(e,t={},n="POST"){let r=typeof t=="object"&&t?t.ref:void 0;if(typeof r=="string"){let u=ht(r);if(u)throw new C("usage",`${r} is a local project (${u.folder}), and this command is about SnoutData Cloud. Locally: db url, db psql, db push, gen types, keys, status, start, stop, functions, secrets.`,{ref:r,local:u.folder})}let o=await Eh(),s=n==="GET"&&typeof t=="object"&&t?`?${new URLSearchParams(t).toString()}`:"",a=await Xe(Ze,$r(e,s),{method:n,key:Qe,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-client-info":xr},body:n==="GET"?void 0:JSON.stringify(t)});Tr(a);let c=await a.text(),i;try{i=c?JSON.parse(c):{}}catch{throw new Re(a.status,jr(a.status,a.statusText,c))}if(!a.ok){let u=jl(i)??`${a.status} ${a.statusText}`;throw a.status===401?new Et(u):a.status===410?Or(a,u):new Re(a.status,u,Dl(i),i)}return i}function Dl(e){if(typeof e!="object"||e===null)return null;let{code:t,error:n}=e;return typeof t=="string"?t:typeof n=="object"&&n!==null&&typeof n.code=="string"?n.code:null}function Tr(e){let t=e.headers.get("x-snoutdata-cli-notice");!t||Ml||(Ml=!0,ce(`${t} ${_s({minimum:e.headers.get("x-snoutdata-cli-minimum")})}`))}function Or(e,t){let n=e.headers.get("x-snoutdata-cli-minimum");return new C("outdated",`${t.replace(/\s+$/,"")} ${_s({minimum:n})}`,{status:410,installed:ke,minimum:n??null})}async function Lt(){return R("cloud-whoami")}async function We(){return R("cloud-project-list")}async function He(e){let t=ht(e);return t?cl(t):Dr(await R("cloud-project-connection",{ref:e}))}function Dr(e){let{anonKey:t,serviceRoleKey:n,...r}=e;return{...r,appKey:e.appKey??t??null,serverKey:e.serverKey??n??null}}function ht(e){return dl(e,Dt(process.cwd())?.local??null)}async function Lr(){return R("cloud-team-list")}async function In(e){return R("cloud-project-export",{ref:e})}async function nn(e){return R("cloud-project-export",{ref:e},"GET")}async function Cn(e,t,n={}){let r=Date.now()+(n.timeoutMs??3e5);for(;;){let{projects:o}=await We(),s=o.find(c=>c.ref===e)??null,a=s?.state??"deleted";if(n.onTick?.(a),Ll(t,a))return s;if(Date.now()>=r)throw new Re(504,`${e} is still ${a} after waiting`);await new Promise(c=>setTimeout(c,2e3))}}function Ll(e,t){let n={pause:"paused",resume:"ready",delete:"deleted"}[e];return t===n||t==="error"}async function Mn(e,t={}){let n=Date.now()+(t.timeoutMs??3e5);for(;;){let{projects:r}=await We(),o=r.find(s=>s.ref===e);if(!o)throw new Re(404,`no project ${e}`);if(t.onTick?.(o.state),o.state==="ready")return o;if(Date.now()>=n)throw new Re(504,`${e} is still ${o.state} after waiting`);await new Promise(s=>setTimeout(s,2e3))}}function jl(e){if(typeof e!="object"||!e)return null;let t=e;return typeof t.error=="string"&&t.error?t.error:typeof t.message=="string"&&t.message?typeof t.hint=="string"&&t.hint?`${t.message} ${t.hint}`:t.message:null}function jr(e,t,n){return/^\s*</.test(n)||!n.trim()?`SnoutData Cloud answered ${e}${t?` ${t}`:""} with no message. Try again in a minute.`:n.slice(0,300)}var Ze,Qe,Re,Et,Ml,pe=W(()=>{"use strict";_t();An();be();Pt();Cl();de();Tn();Pr();Ze=process.env.SNOUTDATA_ACCOUNTS_URL??"https://accounts.snoutdata.com",Qe=process.env.SNOUTDATA_APP_KEY??process.env.SNOUTDATA_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzbm91dGRhdGEiLCJyb2xlIjoic25vdXRfYXBwIiwiaWF0IjoxNzkyMDc2NTQyLCJleHAiOjIxMDQ4NzU1MjR9.hWSbcDfbGuyDHHSFLoZzD8KVSg9bWVZzzQ_eftW6TPM",Re=class extends Error{status;serverCode;body;constructor(t,n,r=null,o){super(n),this.status=t,this.serverCode=r,this.body=o}},Et=class extends Error{constructor(t){super(t??xh())}};Ml=!1});var Nu,NS,Iu=W(()=>{"use strict";Nu="snoutpod_isolation",NS=`table bridge ${Nu}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
${oc(e.profile)}`)}function Xr(e){let t=dt(e.token);return Yr(`<h1>Check your email</h1>
|
|
30
|
+
<p class="small muted">We sent a code to <strong>${dt(e.email)}</strong>.</p>
|
|
31
|
+
<form method="post" action="/code">
|
|
32
|
+
<input type="hidden" name="t" value="${t}">
|
|
33
|
+
<label for="code">Code</label>
|
|
34
|
+
<input id="code" class="code" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9 ]{6,8}" maxlength="8" required autofocus>
|
|
35
|
+
${sc(e.error)}
|
|
36
|
+
${e.notice?`<p class="small muted" role="status">${dt(e.notice)}</p>`:""}
|
|
37
|
+
<button class="btn-primary" type="submit">Sign in</button>
|
|
38
|
+
</form>
|
|
39
|
+
<form method="post" action="/resend">
|
|
40
|
+
<input type="hidden" name="t" value="${t}">
|
|
41
|
+
<button class="link" type="submit">Send another code</button>
|
|
42
|
+
</form>
|
|
43
|
+
<form method="get" action="/">
|
|
44
|
+
<input type="hidden" name="t" value="${t}">
|
|
45
|
+
<button class="link" type="submit">Use another way to sign in</button>
|
|
46
|
+
</form>
|
|
47
|
+
${oc(e.profile)}`)}function ic(e={}){let t=e.email?`<p class="muted">as <strong style="color:var(--fg)">${dt(e.email)}</strong></p>`:"",n=e.profile?` --profile ${dt(e.profile)}`:"";return Yr(`<div class="badge" style="--badge:var(--live)">${py}</div>
|
|
48
|
+
<h1>Signed in</h1>
|
|
49
|
+
${t}
|
|
50
|
+
<p class="small muted where">Your terminal is signed in. Next, try:</p>
|
|
51
|
+
<span class="terminal"><span class="prompt">$ </span>snoutdata projects list${n}</span>
|
|
52
|
+
<p class="small muted">You can close this tab.</p>`,!0)}function Zr(e){return Yr(`<div class="badge" style="--badge:var(--error)">${my}</div>
|
|
53
|
+
<h1>Sign-in failed</h1>
|
|
54
|
+
<p class="muted">${dt(e??"Something went wrong.")}</p>
|
|
55
|
+
<span class="terminal"><span class="prompt">$ </span>snoutdata login</span>
|
|
56
|
+
<p class="small muted">Run that in your terminal to try again.</p>`)}var dy,uy,py,my,fy,gy,lc=z(()=>{"use strict";dy="https://snoutdata.com/logo-mark.png",uy=`
|
|
57
|
+
:root {
|
|
58
|
+
color-scheme: light dark;
|
|
59
|
+
--bg-app: light-dark(#f7f7f4, #0a0c10);
|
|
60
|
+
--bg-card: light-dark(#ffffff, #12161f);
|
|
61
|
+
--bg-input: light-dark(#ffffff, #151a24);
|
|
62
|
+
--bg-hover: light-dark(#f0efe9, #1b212e);
|
|
63
|
+
--border: light-dark(#e5e3da, #232a38);
|
|
64
|
+
--border-soft: light-dark(#edece5, #1a212c);
|
|
65
|
+
--fg: light-dark(#26251e, #f1f4f9);
|
|
66
|
+
--fg-dim: light-dark(#76756d, #8a94a8);
|
|
67
|
+
--btn-bg: light-dark(#26251e, #f1f4f9);
|
|
68
|
+
--btn-fg: light-dark(#f7f7f4, #0a0c10);
|
|
69
|
+
--btn-bg-hover: light-dark(#38362d, #ffffff);
|
|
70
|
+
--btn-secondary: light-dark(#ecebe4, #1b212e);
|
|
71
|
+
--btn-secondary-hover: light-dark(#e3e1d8, #232a38);
|
|
72
|
+
--live: light-dark(#2f9a78, #4fc29c);
|
|
73
|
+
--error: light-dark(#c0392b, #f48771);
|
|
74
|
+
--ring: color-mix(in srgb, var(--fg) 45%, transparent);
|
|
75
|
+
--radius: 12px;
|
|
76
|
+
--radius-xl: 22px;
|
|
77
|
+
--shadow-pop: 0 6px 22px light-dark(rgba(20, 18, 12, 0.1), rgba(0, 0, 0, 0.55)), 0 1px 3px light-dark(rgba(20, 18, 12, 0.06), rgba(0, 0, 0, 0.4));
|
|
78
|
+
--ease: cubic-bezier(0.2, 0, 0, 1);
|
|
79
|
+
--dur: 140ms;
|
|
80
|
+
--font-ui: -apple-system, BlinkMacSystemFont, system-ui, 'Segoe UI', Ubuntu, sans-serif;
|
|
81
|
+
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
82
|
+
}
|
|
83
|
+
* { box-sizing: border-box; }
|
|
84
|
+
body {
|
|
85
|
+
margin: 0;
|
|
86
|
+
background: var(--bg-app);
|
|
87
|
+
color: var(--fg);
|
|
88
|
+
font-family: var(--font-ui);
|
|
89
|
+
font-size: 15px;
|
|
90
|
+
line-height: 1.55;
|
|
91
|
+
}
|
|
92
|
+
.gate { display: grid; place-items: center; min-height: 100vh; padding: 20px; }
|
|
93
|
+
.gate-card {
|
|
94
|
+
width: min(400px, 100%);
|
|
95
|
+
display: flex;
|
|
96
|
+
flex-direction: column;
|
|
97
|
+
gap: 14px;
|
|
98
|
+
background: var(--bg-card);
|
|
99
|
+
border: 1px solid var(--border);
|
|
100
|
+
border-radius: var(--radius-xl);
|
|
101
|
+
box-shadow: var(--shadow-pop);
|
|
102
|
+
padding: 28px;
|
|
103
|
+
text-align: center;
|
|
104
|
+
animation: rise 320ms var(--ease) both;
|
|
105
|
+
}
|
|
106
|
+
.brand-mark { display: block; width: 40px; height: 40px; margin: 0 auto; }
|
|
107
|
+
h1 { margin: 0; font-size: 28px; font-weight: 700; letter-spacing: -0.02em; }
|
|
108
|
+
p { margin: 0; }
|
|
109
|
+
.muted { color: var(--fg-dim); }
|
|
110
|
+
.small { font-size: 13px; }
|
|
111
|
+
.stack { display: flex; flex-direction: column; gap: 10px; }
|
|
112
|
+
button, a.btn {
|
|
113
|
+
font: inherit;
|
|
114
|
+
font-size: 14px;
|
|
115
|
+
font-weight: 500;
|
|
116
|
+
color: var(--fg);
|
|
117
|
+
background: var(--btn-secondary);
|
|
118
|
+
border: 1px solid var(--border-soft);
|
|
119
|
+
border-radius: var(--radius);
|
|
120
|
+
padding: 9px 12px;
|
|
121
|
+
cursor: pointer;
|
|
122
|
+
text-decoration: none;
|
|
123
|
+
transition: background var(--dur) var(--ease), border-color var(--dur) var(--ease), transform var(--dur) var(--ease);
|
|
124
|
+
}
|
|
125
|
+
button:where(:hover), a.btn:where(:hover) { background: var(--btn-secondary-hover); }
|
|
126
|
+
button:active, a.btn:active { transform: scale(0.97); }
|
|
127
|
+
button:focus-visible, a:focus-visible, input:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
|
|
128
|
+
.btn-provider { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; }
|
|
129
|
+
.btn-primary { background: var(--btn-bg); border-color: transparent; color: var(--btn-fg); width: 100%; }
|
|
130
|
+
.btn-primary:hover { background: var(--btn-bg-hover); }
|
|
131
|
+
.or { display: flex; align-items: center; gap: 10px; color: var(--fg-dim); font-size: 12px; }
|
|
132
|
+
.or::before, .or::after { content: ''; flex: 1; height: 1px; background: var(--border); }
|
|
133
|
+
form { display: flex; flex-direction: column; gap: 9px; text-align: left; margin: 0; }
|
|
134
|
+
label { font-size: 13px; font-weight: 500; }
|
|
135
|
+
input {
|
|
136
|
+
font-family: var(--font-ui);
|
|
137
|
+
font-size: 14px;
|
|
138
|
+
line-height: 1.5;
|
|
139
|
+
color: var(--fg);
|
|
140
|
+
background: var(--bg-input);
|
|
141
|
+
border: 1px solid var(--border);
|
|
142
|
+
border-radius: var(--radius);
|
|
143
|
+
padding: 10px 12px;
|
|
144
|
+
width: 100%;
|
|
145
|
+
}
|
|
146
|
+
input.code { font-family: var(--font-mono); font-size: 20px; letter-spacing: 0.3em; text-align: center; }
|
|
147
|
+
.error { font-size: 13px; color: var(--error); text-align: left; }
|
|
148
|
+
.link { align-self: flex-start; padding: 0; border: 0; background: none; font-size: 13px; color: var(--fg-dim); text-decoration: underline; }
|
|
149
|
+
.link:hover { background: none; color: var(--fg); }
|
|
150
|
+
.where { border-top: 1px solid var(--border); padding-top: 14px; }
|
|
151
|
+
code, .terminal { font-family: var(--font-mono); font-size: 13px; }
|
|
152
|
+
.terminal {
|
|
153
|
+
display: block;
|
|
154
|
+
text-align: left;
|
|
155
|
+
background: var(--bg-app);
|
|
156
|
+
border: 1px solid var(--border);
|
|
157
|
+
border-radius: var(--radius);
|
|
158
|
+
padding: 12px 14px;
|
|
159
|
+
color: var(--fg);
|
|
160
|
+
font-size: 12.5px;
|
|
161
|
+
overflow-wrap: anywhere;
|
|
162
|
+
}
|
|
163
|
+
.gate-card.wide { width: min(440px, 100%); }
|
|
164
|
+
.terminal .prompt { color: var(--fg-dim); user-select: none; }
|
|
165
|
+
.terminal .ok { color: var(--live); }
|
|
166
|
+
.badge {
|
|
167
|
+
width: 56px;
|
|
168
|
+
height: 56px;
|
|
169
|
+
margin: 2px auto 0;
|
|
170
|
+
border-radius: 50%;
|
|
171
|
+
display: grid;
|
|
172
|
+
place-items: center;
|
|
173
|
+
background: color-mix(in srgb, var(--badge) 14%, transparent);
|
|
174
|
+
color: var(--badge);
|
|
175
|
+
animation: pop 420ms var(--ease) both 80ms;
|
|
176
|
+
}
|
|
177
|
+
.badge svg path { stroke-dasharray: 30; stroke-dashoffset: 30; animation: draw 360ms var(--ease) forwards 300ms; }
|
|
178
|
+
@keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
|
|
179
|
+
@keyframes pop { from { transform: scale(0.6); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
180
|
+
@keyframes draw { to { stroke-dashoffset: 0; } }
|
|
181
|
+
@media (prefers-reduced-motion: reduce) {
|
|
182
|
+
.gate-card, .badge { animation: none; }
|
|
183
|
+
.badge svg path { animation: none; stroke-dashoffset: 0; }
|
|
184
|
+
button, a.btn { transition: none; }
|
|
185
|
+
}
|
|
186
|
+
`;py='<svg width="26" height="26" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 12.5l4.2 4.2L19 7" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',my='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M7 7l10 10M17 7L7 17" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></svg>';fy='<svg width="17" height="17" viewBox="0 0 18 18" aria-hidden="true"><path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62Z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 0 0 9 18Z"/><path fill="#FBBC05" d="M3.97 10.72a5.4 5.4 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.01-2.33Z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.46.9 11.43 0 9 0A9 9 0 0 0 .96 4.95l3.01 2.33C4.68 5.16 6.66 3.58 9 3.58Z"/></svg>',gy='<svg width="17" height="17" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.4 7.4 0 0 1 2-.27c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/></svg>'});function Gn(e){Hn=e}function dc(e){cc=e}function Lt(){return Hn}function $(e){return uc?`\x1B[2m${e}\x1B[0m`:e}function N(e){return uc?`\x1B[1m${e}\x1B[0m`:e}function w(e,t){if(Hn){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
187
|
+
`);return}t()}function u(e){!Hn&&!cc&&process.stderr.write(`${e}
|
|
188
|
+
`)}function $t(e,t,n){process.stderr.write(`${t}
|
|
189
|
+
`),Hn&&process.stdout.write(`${JSON.stringify({ok:!1,code:e,error:t,...n},null,2)}
|
|
190
|
+
`)}function ce(e){process.stderr.write(`${e}
|
|
191
|
+
`)}function V(e){if(e.length===0)return"";let t=e[0].map((n,r)=>Math.max(...e.map(o=>(o[r]??"").length)));return e.map(n=>n.map((r,o)=>r.padEnd(t[o]??0)).join(" ").trimEnd()).join(`
|
|
192
|
+
`)}function We(e){if(!e)return"never";let t=Math.round((Date.now()-Date.parse(e))/1e3),n=t<0,r=Math.abs(t);if(r<60)return n?"in a moment":"just now";let o=[[60,"minute"],[60,"hour"],[24,"day"],[30,"month"]],s=r,a="second";for(let[d,c]of o){if(s<d)break;s=Math.round(s/d),a=c}let l=`${s} ${a}${s===1?"":"s"}`;return n?`in ${l}`:`${l} ago`}var Hn,cc,uc,pe=z(()=>{"use strict";Hn=!1,cc=!1;uc=process.stdout.isTTY&&!process.env.NO_COLOR});import{createHash as mc,randomBytes as qn}from"node:crypto";import{createServer as fc}from"node:http";import{createInterface as hy}from"node:readline/promises";import{spawn as yy}from"node:child_process";function pn(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Vs(e,t,n){let r=ke()===be?void 0:ke();return e==="ok"?ic({email:n,profile:r}):Zr(t)}function un(){let e=pn(qn(32)),t=pn(mc("sha256").update(e).digest());return{verifier:e,challenge:t}}function wy(e,t){return e==="darwin"?{command:"open",args:[t],verbatim:!1}:e==="win32"?{command:"cmd.exe",args:["/c","start",'""',`"${t}"`],verbatim:!0}:{command:"xdg-open",args:[t],verbatim:!1}}function gc(e){let{command:t,args:n,verbatim:r}=wy(process.platform,e),o=yy(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}function Qr(){return"1064562458607-9fqmghjoqjr7d56b98agkvjt9vt26pdc.apps.googleusercontent.com"}function ky(){return"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"}function hc(e){let t=e??pn(qn(32));return{raw:t,hashed:mc("sha256").update(t).digest("hex")}}function yc(e){return`${by}?${new URLSearchParams({...e.loginHint?{login_hint:e.loginHint}:{},client_id:Qr(),redirect_uri:e.redirectUri,response_type:"code",scope:"openid email profile",code_challenge:e.challenge,code_challenge_method:"S256",nonce:e.hashedNonce,state:e.state,prompt:"select_account"}).toString()}`}function wc(e,t){let n=new URL(e,"http://127.0.0.1");if(!n.searchParams.has("code")&&!n.searchParams.has("error"))return{kind:"ignore"};let r=n.searchParams.get("error_description")??n.searchParams.get("error");if(r)return{kind:"error",message:r};let o=n.searchParams.get("code");return o?t!==void 0&&n.searchParams.get("state")!==t?{kind:"error",message:"the browser came back with a state that did not match"}:{kind:"ok",code:o}:{kind:"error",message:"the browser came back without a code"}}async function Xs(e){return new Promise((t,n)=>{let r="",o=fc((a,l)=>{let d=wc(a.url??"/",e.state);if(d.kind==="ignore"){l.writeHead(404).end();return}l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(d.kind==="ok"?Vs("ok"):Vs("failed",d.message)),o.close(),d.kind==="ok"?t({code:d.code,redirectUri:r}):n(new Error(d.message))});o.listen(0,"127.0.0.1",()=>{let a=o.address();r=`http://127.0.0.1:${typeof a=="object"&&a?a.port:0}${e.callbackPath??""}`,Promise.resolve().then(()=>e.authorizeUrl(r)).then(d=>{process.stdout.write(`${d}
|
|
193
|
+
`),e.noBrowser?u("Open that in a browser, on any machine, and sign in."):(u("Opening that in your browser. If nothing opens, paste it into one."),gc(d))},d=>{o.close(),n(d)})}),o.on("error",n),setTimeout(()=>{o.close(),n(new Error("timed out waiting for the browser"))},e.timeoutMs??3e5).unref()})}async function Zs(e,t){let n=await Be(He,st("/session?via=pkce","/token?grant_type=pkce"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({auth_code:e,code_verifier:t})});if(!n.ok)throw new Error(`could not exchange the code: ${(await n.text()).slice(0,200)}`);return Qs(await n.json())}async function bc(e,t,n){let r=await fetch(Sy,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:Qr(),client_secret:ky(),code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:n})}),o=await r.json().catch(()=>({}));if(!r.ok||!o.id_token)throw new Error(`Google would not exchange the code: ${o.error_description??o.error??`HTTP ${r.status}`}`);return o.id_token}async function _y(e){if(!Qr())throw new Error("this build of snoutdata has no Google sign-in (it was built for testing). Sign in with a released snoutdata, then run this one.");let{verifier:t,challenge:n}=un(),{raw:r,hashed:o}=hc(),s=pn(qn(16)),{code:a,redirectUri:l}=await Xs({state:s,timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:c=>yc({redirectUri:c,challenge:n,hashedNonce:o,state:s,loginHint:e.email})}),d=await bc(a,t,l);return Sc(d,r)}async function Sc(e,t){let n=await Be(He,st("/session?via=id_token","/token?grant_type=id_token"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:"google",id_token:e,nonce:t})});if(!n.ok)throw new Error(`could not turn the Google sign-in into a session: ${(await n.text()).slice(0,200)}`);return Qs(await n.json())}function Qs(e){let t=e,n={accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,email:t.user?.email};return lt(n),n}function Ys(e){let t=e.trim().toLowerCase();if(!t||/\s/.test(t))return null;let n=t.indexOf("@");if(n===0||t.indexOf("@",n+1)!==-1)return null;let r=n===-1?t:t.slice(n+1);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(r))return null;let o=r.slice(r.lastIndexOf(".")+1);return/^[a-z]{2,}$/.test(o)?r:null}function ea(e){try{let t=JSON.parse(e);for(let n of["error_description","msg","message","error"]){let r=t[n];if(typeof r=="string"&&r)return r}}catch{return""}return""}function $y(e,t,n){let r=ea(t);return e===404||/no sso provider/i.test(r)?new O("not-found",`No single sign-on is set up for ${n}. Check the address, or ask whoever administers your team to connect your identity provider.`,{domain:n}):/saml.*(disabled|not enabled)/i.test(r)?new O("failed",`Single sign-on is not available for ${n} yet. Ask whoever administers your team to connect your identity provider.`,{domain:n}):new O(kt(e),r||`Could not start single sign-on for ${n}.`,{domain:n})}async function kc(e){let t=await Be(He,st("/sso/start","/sso"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e.domain,redirect_to:e.redirectTo,skip_http_redirect:!0,code_challenge:e.challenge,code_challenge_method:"s256"})}),n=await t.text();if(!t.ok)throw $y(t.status,n,e.domain);let r;try{r=JSON.parse(n).url}catch{r=void 0}if(typeof r!="string"||!r)throw new O("server",`Single sign-on for ${e.domain} was accepted but came back without somewhere to send the browser.`,{domain:e.domain});return r}async function vy(e){if(e!==void 0){let r=Ys(e);if(!r)throw new y(`--domain wants a work email or a company domain, like you@yourcompany.com, not "${e}"`);return r}if(!Pe()){let r=cn();throw new y(`login --sso needs --domain <your work email or company domain>${r?`, because ${ln(r)}`:""}`)}let t=hy({input:process.stdin,output:process.stderr}),n=new Promise((r,o)=>{t.once("close",()=>o(new y("nothing left to read: pass --domain <your work email or company domain>")))});n.catch(()=>{});try{for(let r=0;r<3;r+=1){let o=await Promise.race([t.question("Your work email address: "),n]),s=Ys(o);if(s)return s;u("That is not a work email or a company domain. Try something like you@yourcompany.com.")}}finally{t.close()}throw new y("no domain to sign in with: pass --domain <your work email or company domain>")}async function Py(e){let t=await vy(e.domain),{verifier:n,challenge:r}=un();u(`Signing in with the identity provider for ${N(t)}.`);let{code:o}=await Xs({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:s=>kc({domain:t,redirectTo:s,challenge:r})});return Zs(o,n)}function xy(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}}async function Ay(e,t=xy(),n=fetch){if(!t||!e)return null;let r=Be(He,tc("/rpc/set_my_timezone"),{method:"POST",key:Ge,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({want_timezone:t,want_source:"signin"})},n).then(async a=>a.ok?null:`HTTP ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`,a=>a instanceof Error?a.message:String(a)),o,s=new Promise(a=>{o=setTimeout(()=>a("timed out"),Ey),o.unref()});try{return await Promise.race([r,s])}finally{clearTimeout(o)}}async function Ry(e){let t="";for await(let n of e)if(t+=String(n),t.length>4096)break;return new URLSearchParams(t)}async function pc(e){let t=await Be(He,st("/code","/otp"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,create_user:!0})});return t.ok?null:ea(await t.text())||"Could not send a code just now. Try again in a moment."}async function Ty(e,t){let n="";for(let o of["email","signup"]){let s=await Be(He,st("/confirm","/verify"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,token:t,type:o})}),a=await s.text();if(s.ok)return Qs(JSON.parse(a));if(n=a,s.status!==403&&!/otp_expired|expired|invalid/i.test(a))break}let r=ea(n);return/expired|invalid/i.test(r)||!r?"That code did not work. It may be from an older email, or already used. Send another.":r}async function Oy(e){let t=pn(qn(18)),n=ke()===be?void 0:ke(),r=!!Qr(),o=null,s=null;return new Promise((a,l)=>{let d="",c=!1,i=(U,B,C=200)=>{U.writeHead(C,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),U.end(B)},p=(U,B)=>{c||(c=!0,i(U,B instanceof Error?Zr(B.message):Vs("ok",void 0,B.email)),A.close(),B instanceof Error?l(B):a(B))},g=(U,B={})=>i(U,ac({token:t,google:r,profile:n,email:B.email??e.email,error:B.error})),E=async(U,B)=>{let C=new URL(U.url??"/","http://127.0.0.1"),ue=C.searchParams.get("t")===t;if((C.pathname==="/"||C.pathname==="/callback")&&(C.searchParams.has("code")||C.searchParams.has("error"))){let G=o?.kind==="google"&&C.pathname==="/"?o.state:void 0,se=wc(U.url??"/",G);if(se.kind==="ignore"){B.writeHead(404).end();return}if(se.kind==="error"||!o){p(B,new Error(se.kind==="error"?se.message:"the browser came back to a sign-in that was not started"));return}try{if(o.kind==="google"){let ee=await bc(se.code,o.verifier,d);p(B,await Sc(ee,o.rawNonce))}else p(B,await Zs(se.code,o.verifier))}catch(ee){p(B,ee instanceof Error?ee:new Error(String(ee)))}return}if(U.method==="GET"&&C.pathname==="/"&&ue){g(B);return}if(U.method==="GET"&&C.pathname==="/google"&&ue&&r){let{verifier:G,challenge:se}=un(),{raw:ee,hashed:fe}=hc(),it=pn(qn(16));o={kind:"google",verifier:G,rawNonce:ee,state:it},B.writeHead(302,{Location:yc({redirectUri:d,challenge:se,hashedNonce:fe,state:it,loginHint:e.email})}).end();return}if(U.method==="GET"&&C.pathname==="/github"&&ue){let{verifier:G,challenge:se}=un();o={kind:"pkce",verifier:G},B.writeHead(302,{Location:await _c("github",`${d}/callback`,se)}).end();return}if(U.method==="POST"){let G=await Ry(U);if(G.get("t")!==t){B.writeHead(403).end();return}if(C.pathname==="/email"){let se=(G.get("email")??"").trim().toLowerCase(),ee=Ys(se);if(!ee||!se.includes("@")){g(B,{email:se,error:"Enter your work email, for example you@company.com."});return}let{verifier:fe,challenge:it}=un();try{let Ye=await kc({domain:ee,redirectTo:`${d}/callback`,challenge:it});o={kind:"pkce",verifier:fe},B.writeHead(302,{Location:Ye}).end();return}catch(Ye){if(!(Ye instanceof O&&Ye.code==="not-found")){g(B,{email:se,error:Ye instanceof Error?Ye.message:String(Ye)});return}}let bt=await pc(se);if(bt){g(B,{email:se,error:bt});return}s=se,i(B,Xr({token:t,email:se,profile:n}));return}if(C.pathname==="/code"&&s){let se=(G.get("code")??"").replace(/\s+/g,""),ee=await Ty(s,se);if(typeof ee=="string"){i(B,Xr({token:t,email:s,profile:n,error:ee}));return}p(B,ee);return}if(C.pathname==="/resend"&&s){let se=await pc(s);i(B,Xr({token:t,email:s,profile:n,...se?{error:se}:{notice:"Another code is on its way."}}));return}}B.writeHead(404).end()},A=fc((U,B)=>{E(U,B).catch(C=>{B.headersSent||i(B,Zr(C instanceof Error?C.message:String(C)),500)})});A.listen(0,"127.0.0.1",()=>{let U=A.address();d=`http://127.0.0.1:${typeof U=="object"&&U?U.port:0}`;let C=`${d}/?t=${t}`;process.stdout.write(`${C}
|
|
194
|
+
`),e.noBrowser?u("Open that in a browser on this machine and sign in."):(u("Opening the sign-in page in your browser. If nothing opens, paste that into one."),gc(C))}),A.on("error",l),setTimeout(()=>{c||(c=!0,A.close(),l(new Error("timed out waiting for the browser")))},e.timeoutMs??3e5).unref()})}async function eo(e={}){let t=ta(e.email,await Ny(e)),n=await Ay(t.accessToken);return n&&process.env.SNOUTDATA_DEBUG&&ce(`could not record the timezone: ${n}`),t}function ta(e,t){if(!e)return t;let n={...t,expectedEmail:e};return lt(n),t.email&&!na(t.email,e)&&ce(`Signed in as ${t.email}, not ${e}. Run \`snoutdata login --email ${e}\` and pick that account.`),n}function na(e,t){return e.trim().toLowerCase()===t.trim().toLowerCase()}async function Ny(e){if(e.sso)return Py({...e,domain:e.domain??e.email});if(!e.provider)return Oy(e);let t=e.provider;if(t==="google")return _y(e);let{verifier:n,challenge:r}=un(),{code:o}=await Xs({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:s=>_c(t,s,r)});return Zs(o,n)}async function _c(e,t,n){let r=new URL(await nc(He,st("/provider/start","/authorize"),Ge));return r.searchParams.set("provider",e),r.searchParams.set("redirect_to",t),r.searchParams.set("code_challenge",n),r.searchParams.set("code_challenge_method","s256"),r.searchParams.set("prompt","select_account"),r.toString()}var by,Sy,Ey,to=z(()=>{"use strict";me();qr();ve();Ot();lc();_e();Ct();pe();by="https://accounts.google.com/o/oauth2/v2/auth",Sy="https://oauth2.googleapis.com/token";Ey=3e3});import{createInterface as Iy}from"node:readline/promises";async function ra(e){let t=Iy({input:process.stdin,output:process.stderr});try{let n=(await t.question(`${e} [Y/n] `)).trim().toLowerCase();return n===""||n==="y"||n==="yes"}finally{t.close()}}async function Cy(){let e=await Ur();if(!e.available)return(e.skip==="handoff-disabled"||e.skip==="server-disabled")&&u($("SnoutData Studio is running but is not set to hand out sign-ins.")),null;let t=e.who.email??"the signed-in account";u("");let n=ke();if(u(`SnoutData Studio is open here, signed in as ${N(t)}.`),n!==be&&u(`Its token would be kept as profile ${N(n)}.`),u($("It can create an access token for this terminal. Your sign-in itself is not handed over,")),u($("and you can revoke the token later with `snoutdata tokens revoke`.")),!await ra("Use it?"))return null;u("Asking SnoutData Studio. Approve it there.");let r=await Xl(e.config,process.argv.slice(2).join(" ").slice(0,60)||"snoutdata");if("declined"in r)return u(`The app did not create a token: ${r.reason}`),null;let o={accessToken:r.token};return lt(o),u(`Signed in with "${r.name}".`),o}async function Ly(){if(!await ra("Sign in with a browser?"))return null;try{let e=await eo({});return u(`Signed in${e.email?` as ${e.email}`:""}.`),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}catch(e){return u(`That did not finish: ${e instanceof Error?e.message:String(e)}`),null}}async function My(){if(!await ra("Sign in by typing a code into a browser on another machine?"))return null;let e=await zr({name:Fr(),platform:process.platform});u(""),u(` Open ${N(e.verifyUrl)}`),u(` Type ${N(e.code)}`),u(""),u($("The code is typed rather than in the link on purpose: it is what proves the person")),u($("at the browser is the person at this terminal. Waiting\u2026"));let t=await Wr(e.secret,{intervalMs:Math.max(1,e.interval)*1e3,expiresAt:e.expiresAt}),n={accessToken:t.token};return lt(n),u(`Signed in${t.name?` with "${t.name}"`:""}.`),n}async function $c(){if(!Pe())return null;let e=await Cy();if(e)return e;let t=await Ly();return t||My()}var vc=z(()=>{"use strict";Ot();Br();Js();Ct();to();pe()});var et={};Tl(et,{ACCOUNTS_URL:()=>He,APP_KEY:()=>Ge,ApiError:()=>xe,NotSignedIn:()=>vt,call:()=>T,connection:()=>Me,databaseToken:()=>sa,errorSentence:()=>aa,exportStatus:()=>mn,isSettled:()=>Ec,listProjects:()=>Qe,listTeams:()=>ro,localStack:()=>Pt,noticeFrom:()=>Jr,outdated:()=>Vr,requestExport:()=>Kn,serverCodeOf:()=>oa,unreadableAnswer:()=>Jn,waitForReady:()=>Wn,waitForSettled:()=>zn,whoami:()=>Kt,withKeyNames:()=>no});function Dy(){let e=cn(),t=ke(),n=t===be?"":` as profile ${t}`;return e?`not signed in${n}, and ${ln(e)}. Set SNOUTDATA_ACCESS_TOKEN to a token made at https://dashboard.snoutdata.com/#/tokens, or by \`snoutdata tokens create\` on a machine that is signed in.`:`not signed in${n}: run \`snoutdata login${t===be?"":` --profile ${t}`}\`, or set SNOUTDATA_ACCESS_TOKEN`}async function xc(){let e=Ir();if(e||(e=await $c()),!e)throw new vt;if(!jl(e)||!e.refreshToken)return e.accessToken;let t=await Be(He,st("/session?via=renew","/token?grant_type=refresh_token"),{method:"POST",key:Ge,headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refreshToken})});if(!t.ok)throw new vt;let n=await t.json(),r={...e,accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at};return lt(r),r.accessToken}async function T(e,t={},n="POST"){let r=typeof t=="object"&&t?t.ref:void 0;if(typeof r=="string"){let c=Pt(r);if(c)throw new O("usage",`${r} is a local project (${c.folder}), and this command is about SnoutData Cloud. Locally: db url, db psql, db push, gen types, keys, status, start, stop, functions, secrets.`,{ref:r,local:c.folder})}let o=await xc(),s=n==="GET"&&typeof t=="object"&&t?`?${new URLSearchParams(t).toString()}`:"",a=await Be(He,Gr(e,s),{method:n,key:Ge,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-client-info":Un},body:n==="GET"?void 0:JSON.stringify(t)});Jr(a);let l=await a.text(),d;try{d=l?JSON.parse(l):{}}catch{throw new xe(a.status,Jn(a.status,a.statusText,l))}if(!a.ok){let c=aa(d)??`${a.status} ${a.statusText}`;throw a.status===401?new vt(c):a.status===410?Vr(a,c):new xe(a.status,c,oa(d),d)}return d}function oa(e){if(typeof e!="object"||e===null)return null;let{code:t,error:n}=e;return typeof t=="string"?t:typeof n=="object"&&n!==null&&typeof n.code=="string"?n.code:null}function Jr(e){let t=e.headers.get("x-snoutdata-cli-notice");!t||Pc||(Pc=!0,ce(`${t} ${zs({minimum:e.headers.get("x-snoutdata-cli-minimum")})}`))}function Vr(e,t){let n=e.headers.get("x-snoutdata-cli-minimum");return new O("outdated",`${t.replace(/\s+$/,"")} ${zs({minimum:n})}`,{status:410,installed:$e,minimum:n??null})}async function Kt(){return T("cloud-whoami")}async function sa(e){let t=await xc();if(t.startsWith("sdt_"))throw new O("forbidden","A database token is given to a person, not to an access token. Sign in with `snoutdata login` and ask again.");let n=await Be(He,st("/db/session-token","/db/session-token"),{method:"POST",key:Ge,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-client-info":Un},body:JSON.stringify({project_ref:e})}),r=await n.text(),o={};try{o=r?JSON.parse(r):{}}catch{throw new xe(n.status,Jn(n.status,n.statusText,r))}if(!n.ok){let s=aa(o)??`${n.status} ${n.statusText}`;throw n.status===401?new vt(s):new xe(n.status,s,oa(o),o)}return o}async function Qe(){return T("cloud-project-list")}async function Me(e){let t=Pt(e);return t?Gl(t):no(await T("cloud-project-connection",{ref:e}))}function no(e){let{anonKey:t,serviceRoleKey:n,...r}=e;return{...r,appKey:e.appKey??t??null,serverKey:e.serverKey??n??null}}function Pt(e){return ql(e,qt(process.cwd())?.local??null)}async function ro(){return T("cloud-team-list")}async function Kn(e){return T("cloud-project-export",{ref:e})}async function mn(e){return T("cloud-project-export",{ref:e},"GET")}async function zn(e,t,n={}){let r=Date.now()+(n.timeoutMs??3e5);for(;;){let{projects:o}=await Qe(),s=o.find(l=>l.ref===e)??null,a=s?.state??"deleted";if(n.onTick?.(a),Ec(t,a))return s;if(Date.now()>=r)throw new xe(504,`${e} is still ${a} after waiting`);await new Promise(l=>setTimeout(l,2e3))}}function Ec(e,t){let n={pause:"paused",resume:"ready",delete:"deleted"}[e];return t===n||t==="error"}async function Wn(e,t={}){let n=Date.now()+(t.timeoutMs??3e5);for(;;){let{projects:r}=await Qe(),o=r.find(s=>s.ref===e);if(!o)throw new xe(404,`no project ${e}`);if(t.onTick?.(o.state),o.state==="ready")return o;if(Date.now()>=n)throw new xe(504,`${e} is still ${o.state} after waiting`);await new Promise(s=>setTimeout(s,2e3))}}function aa(e){if(typeof e!="object"||!e)return null;let t=e;return typeof t.error=="string"&&t.error?t.error:typeof t.message=="string"&&t.message?typeof t.hint=="string"&&t.hint?`${t.message} ${t.hint}`:t.message:null}function Jn(e,t,n){return/^\s*</.test(n)||!n.trim()?`SnoutData Cloud answered ${e}${t?` ${t}`:""} with no message. Try again in a minute.`:n.slice(0,300)}var He,Ge,xe,vt,Pc,me=z(()=>{"use strict";Ot();jn();_e();Ct();vc();pe();Bn();qr();He=process.env.SNOUTDATA_ACCOUNTS_URL??"https://accounts.snoutdata.com",Ge=process.env.SNOUTDATA_APP_KEY??process.env.SNOUTDATA_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzbm91dGRhdGEiLCJyb2xlIjoic25vdXRfYXBwIiwiaWF0IjoxNzkyMDc2NTQyLCJleHAiOjIxMDQ4NzU1MjR9.hWSbcDfbGuyDHHSFLoZzD8KVSg9bWVZzzQ_eftW6TPM",xe=class extends Error{status;serverCode;body;constructor(t,n,r=null,o){super(n),this.status=t,this.serverCode=r,this.body=o}},vt=class extends Error{constructor(t){super(t??Dy())}};Pc=!1});var bp,Wk,Sp=z(()=>{"use strict";bp="snoutpod_isolation",Wk=`table bridge ${bp}
|
|
195
|
+
delete table bridge ${bp}
|
|
196
|
+
`});var lA,cA,kp=z(()=>{"use strict";lA=["application/vnd.oci.image.index.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.v2+json"].join(", "),cA=1024**3});function ii(e,t){let n=256-256%t.length;for(;;){let r=e(1)[0];if(r<n)return t[r%t.length]}}function $p(e,t,n){let r="";for(;r.length<n;)r+=ii(e,t);return r}var ai,_p,vp=z(()=>{"use strict";ai="0123456789abcdefghjkmnpqrstvwxyz",_p="abcdefghjkmnpqrstvwxyz"});function Ep(e){return ii(e,Pp)+$p(e,ai,xp-1)}function Vk(e){return Jk.test(e)}function ae(e){if(!Vk(e))throw new Error(`not a project ref: ${JSON.stringify(e)}`);return e}function J(e,t=Yk){return ae(e),{ref:e,database:e,ownerRole:`${e}_owner`,pod:`snoutpod-${e}`,host:`${e}.${t}`}}var Pp,xp,Jk,Yk,Ie=z(()=>{"use strict";vp();Pp=_p,xp=13,Jk=new RegExp(`^[${Pp}][${ai}]{${xp-1}}$`);Yk="db.snoutdata.com"});var Ap=z(()=>{"use strict"});import{createHash as Xk}from"node:crypto";function Et(e){return`${J(e).pod}-${ye}`}function gt(e){return e.layout==="separated"}function li(e){return gt(e)?[]:e.services??[]}function ci(e){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new Error(`a separated router needs its own pod port (routerPodPort), and has ${JSON.stringify(e??null)}`);let t={postgres:e+Rp*1e3,admin:e+Rp*1e3+Uo,passthrough:e+Zk*1e3};if(t.passthrough>65535)throw new Error(`routerPodPort ${e} puts the router's ports past 65535`);return t}function Tp(e,t){let n={...t};return delete n.LEPIS_HOMES,n.LEPIS_HOME=`${J(ae(e)).pod}:5432`,n.LEPIS_PASSTHROUGH_PORT=String(kn),n}function Op(e,t){let n=ae(e);return t?["\\getenv router_password SNOUTPOD_ROUTER_PASSWORD",`do $$ begin if not exists (select from pg_roles where rolname = '${je}') then create role ${je}; end if; end $$;`,`alter role ${je} with login noinherit nosuperuser nocreatedb nocreaterole noreplication nobypassrls connection limit 64 password :'router_password';`,`create schema if not exists ${je} authorization snoutpod_admin;`,`create or replace function ${je}.verifier(role_name text) returns text`," language sql stable security definer set search_path = pg_catalog","as $f$"," select a.rolpassword from pg_catalog.pg_authid a"," where a.rolname = role_name and a.rolcanlogin and not a.rolsuper and not a.rolreplication"," and (a.rolvaliduntil is null or a.rolvaliduntil > now())"," and a.rolname not like 'snoutpod\\_%' and a.rolname <> 'postgres'","$f$;",`revoke all on schema ${je} from public;`,`revoke all on function ${je}.verifier(text) from public;`,`grant usage on schema ${je} to ${je};`,`grant execute on function ${je}.verifier(text) to ${je};`,`grant connect on database "${n}" to ${je};`,""].join(`
|
|
197
|
+
`):[`do $$ begin if exists (select from pg_roles where rolname = '${je}') then alter role ${je} nologin; end if; end $$;`,""].join(`
|
|
198
|
+
`)}function cr(e){return`${J(e).pod}-lepis-tls`}function e_(e){return Xk("sha256").update(`snout-lepis-admin:${e}`).digest("hex")}function di(e,t){let n={...e},r=n[Mo],o=n[Do];delete n[Mo],delete n[Do];for(let[s,a,l]of[[Mo,r,t],[Do,o,e_(t)]])if(a!==void 0){if(!Qk.test(a))throw new Error(`${s} names ${JSON.stringify(a)}, which is not a variable name`);n[a]=l}return n}var ye,Mo,Do,jo,Uo,Fo,Rp,bA,kn,Zk,Ut,je,Bo,Np,Qk,t_,SA,dr=z(()=>{"use strict";Ie();Ap();ye="lepis",Mo="SNOUTPOD_ADMIN_PASSWORD_ENV",Do="SNOUTPOD_ADMIN_TOKEN_ENV",jo=7433,Uo=1e3,Fo=7432,Rp=4,bA={LEPIS_HOST:"0.0.0.0",LEPIS_PORT:String(Fo),LEPIS_HOME:"127.0.0.1:5432",LEPIS_HOME_SSLMODE:"disable",LEPIS_SERVICE_USER:"snoutpod_admin",[Mo]:"LEPIS_SERVICE_PASSWORD",LEPIS_ADMIN_ADDR:`0.0.0.0:${jo}`,LEPIS_TLS_CERT:"/tls/cert.pem",LEPIS_TLS_KEY:"/tls/key.pem",[Do]:"LEPIS_ADMIN_TOKEN",LEPIS_LOG:"info"},kn=7434,Zk=7,Ut="snoutpod.lepis";je="snoutpod_router";Bo="/tls",Np=["set -e","if [ ! -s /tls/cert.pem ] || [ ! -s /tls/key.pem ]; then"," openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3650 -subj /CN=lepis -addext subjectAltName=DNS:lepis,IP:127.0.0.1 -keyout /tls/key.pem -out /tls/cert.pem 2>/dev/null","fi","chmod 755 /tls","chmod 644 /tls/cert.pem /tls/key.pem"].join(`
|
|
199
|
+
`),Qk=/^[A-Z][A-Z0-9_]{0,63}$/;t_=["snout_app","snout_member","snout_server","snout_gate","anon","authenticated","service_role","authenticator","snout_oauth","snout_oauth_read"],SA=`do $lepis$
|
|
200
|
+
declare
|
|
201
|
+
grantee text;
|
|
202
|
+
target text;
|
|
203
|
+
begin
|
|
204
|
+
if pg_catalog.to_regnamespace('lepis') is null then
|
|
205
|
+
return;
|
|
206
|
+
end if;
|
|
207
|
+
for grantee in
|
|
208
|
+
select 'public'
|
|
209
|
+
union all
|
|
210
|
+
select pg_catalog.quote_ident(r.rolname)
|
|
211
|
+
from pg_catalog.pg_roles r
|
|
212
|
+
where not r.rolsuper
|
|
213
|
+
and (
|
|
214
|
+
r.rolname = pg_catalog.current_database() || '_owner'
|
|
215
|
+
or r.rolname = any (array[${t_.map(e=>`'${e}'`).join(", ")}]::text[])
|
|
216
|
+
or r.rolname ~ '^oauth_[0-9a-f]{32}$'
|
|
217
|
+
)
|
|
218
|
+
loop
|
|
219
|
+
foreach target in array array['schema lepis', 'all tables in schema lepis', 'all sequences in schema lepis', 'all functions in schema lepis'] loop
|
|
220
|
+
begin
|
|
221
|
+
execute pg_catalog.format('revoke all on %s from %s', target, grantee);
|
|
222
|
+
exception when others then
|
|
223
|
+
raise warning 'lepis: revoke all on % from %: %', target, grantee, sqlerrm;
|
|
224
|
+
end;
|
|
225
|
+
end loop;
|
|
226
|
+
end loop;
|
|
227
|
+
end
|
|
228
|
+
$lepis$;
|
|
229
|
+
`});function Lp(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[];for(let r of t){let s=(r?.labels??{})[n_],l=(Array.isArray(r?.subnets)?r.subnets:[]).map(c=>c?.subnet).find(c=>typeof c=="string"&&r_.test(c)),d=r?.network_interface;typeof s=="string"&&/^[a-z0-9]{1,40}$/.test(s)&&l&&typeof d=="string"&&o_.test(d)&&n.push({ref:s,subnet:l,bridge:d})}return n}var Ip,xA,Cp,n_,r_,o_,ui=z(()=>{"use strict";kp();dr();Ip="snoutct_db",xA=`table ip ${Ip}
|
|
230
|
+
delete table ip ${Ip}
|
|
231
|
+
`,Cp="io.snoutdata.container",n_="io.snoutdata.container.ref",r_=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(3[0-2]|[12]?[0-9])$/,o_=/^[A-Za-z0-9_.-]{1,15}$/});var Mp=z(()=>{"use strict";Ie()});function jp(e,t){let n=Dp(e,7),r=Dp(t,24);return Math.max(2,Math.ceil(n*24/r))}function Dp(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var pi=z(()=>{"use strict"});function Up(e){return ae(e),["select pg_database_size(coalesce(",`(select oid from pg_database where datname = '${e}'),`,"(select oid from pg_database where datname not in ('postgres', 'template0', 'template1')","order by pg_database_size(oid) desc limit 1)))"].join(" ")}function mi(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)?n:null}var NA,fi=z(()=>{"use strict";Ie();NA=2*60*60});var Fp=z(()=>{"use strict"});function Hp(e){let n=(e.trim().split(`
|
|
232
|
+
`)[0]??"").split("|");if(n.length!==7||n[0]!=="t"&&n[0]!=="f"||n[5]!=="t"&&n[5]!=="f")return null;let r=Number(n[1]);return!Number.isFinite(r)||r<0?null:{inRecovery:n[0]==="t",checksumFailures:r,syncNames:n[2],streaming:n[3]===""?[]:n[3].split(","),lastArchivedWal:/^[0-9A-F]{24}$/.test(n[4])?n[4]:"",keeperReady:n[5]==="t",certSha256:/^[0-9a-f]{64}$/.test(n[6])?n[6]:""}}function l_(e){if(!s_.test(e))throw new Error(`not a keeper name: ${e}`);return`keeper_${e.replace(/-/g,"_")}`}function Gp(e){let t=e.map(r=>`'${l_(r)}'`).join(", "),n=`from pg_replication_slots where slot_name like 'keeper\\_%'${e.length===0?"":` and slot_name not in (${t})`}`;return[`select pg_drop_replication_slot(slot_name) ${n} and not active`,`select count(*) ${n} and active`]}function qp(e){if(e!==""&&!i_.test(e))throw new Error(`not a synchronous_standby_names value: ${e}`);return[e===""?"alter system reset synchronous_standby_names":`alter system set synchronous_standby_names = '${e}'`,"select pg_reload_conf()"]}function d_(e){return typeof e=="string"&&c_.test(e)}function u_(e){return e===$n||d_(e)}function hi(e){if(!u_(e))throw new Error(`not an IPv4 address or ${$n}: ${JSON.stringify(e)}`);return`hostssl replication ${_n} ${e===$n?$n:`${e}/32`} scram-sha-256`}function Kp(e,t=!0){if(!gi.test(e))throw new Error("not a SCRAM-SHA-256 verifier");let n=[`do $$ begin if not exists (select 1 from pg_roles where rolname = '${_n}') then create role ${_n} with login replication; end if; end $$`,`alter role ${_n} with login replication noinherit password '${e}'`];return t?[...n,`select pg_drop_replication_slot(slot_name) from pg_replication_slots where slot_name = '${Ho}' and wal_status = 'lost' and not active`,`select pg_create_physical_replication_slot('${Ho}', true) where not exists (select 1 from pg_replication_slots where slot_name = '${Ho}')`]:[...n,yi]}var s_,a_,Ft,gi,Bp,Go,i_,_n,Ho,c_,$n,yi,qo=z(()=>{"use strict";Ie();s_=/^[a-z0-9][a-z0-9-]*$/,a_=20,Ft="snoutpod_keeper",gi=/^SCRAM-SHA-256\$[0-9]{4,6}:[A-Za-z0-9+/]+=*\$[A-Za-z0-9+/]+=*:[A-Za-z0-9+/]+=*$/,Bp=`select pg_is_in_recovery(), coalesce((select sum(checksum_failures) from pg_stat_database), 0), current_setting('synchronous_standby_names'), coalesce((select string_agg(application_name, ',') from pg_stat_replication where state = 'streaming' and (reply_time is null or reply_time > now() - interval '${a_} seconds')), ''), coalesce((select last_archived_wal from pg_stat_archiver), ''), exists (select 1 from pg_roles where rolname = '${Ft}' and rolreplication) and exists (select 1 from pg_hba_file_rules where database = '{replication}' and '${Ft}' = any (user_name)) and current_setting('ssl') = 'on', case when current_setting('ssl') = 'on' then encode(sha256(pg_read_binary_file(current_setting('ssl_cert_file'))), 'hex') else '' end`;Go=/^-----BEGIN CERTIFICATE-----\n[A-Za-z0-9+/=\n]{64,12000}-----END CERTIFICATE-----\n$/,i_=/^(?:"[a-z0-9-]+"|(?:ANY|FIRST) [1-9] \("[a-z0-9-]+"(?:, "[a-z0-9-]+")+\))$/;_n="snoutpod_replica",Ho="snoutpod_replica",c_=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;$n="samehost";yi=`select pg_drop_replication_slot(slot_name) from pg_replication_slots where slot_name = '${Ho}' and not active`});function Wp(e,t){return Vp(e,t,"swap")}function Jp(e,t){return Vp(e,t,"adopt")}function Vp(e,t,n){let r=null,o=!1;for(let s of e.split(`
|
|
233
|
+
`)){let a=s.trim();a.startsWith(`${n}-error`)?r=a.slice(`${n}-error`.length).trim()||`the ${n} failed`:a===`${n}-done`&&(o=!0)}return r||(o&&t===0?null:`the ${n} ended without finishing (exit ${t})`)}var zp,wi,bi,Si,ki=z(()=>{"use strict";zp='snoutpod-pgbackrest archive-get %f "%p"',wi=String.raw`set -u
|
|
30
234
|
A=$1
|
|
31
235
|
B=$2
|
|
32
236
|
fail() { echo "swap-error $*"; exit 3; }
|
|
@@ -45,9 +249,9 @@ kept=""
|
|
|
45
249
|
if [ -f "$C" ]; then
|
|
46
250
|
kept=$(grep -v -E '^[[:space:]]*(primary_conninfo|primary_slot_name|restore_command|synchronous_standby_names)[[:space:]]*=' "$C")
|
|
47
251
|
fi
|
|
48
|
-
{ [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+
|
|
252
|
+
{ [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+zp.replace(/"/g,'\\"')+String.raw`'"; } > "$C" || fail "postgresql.auto.conf could not be written"
|
|
49
253
|
echo "swap-done"
|
|
50
|
-
`;
|
|
254
|
+
`;bi=String.raw`set -u
|
|
51
255
|
A=$1
|
|
52
256
|
B=$2
|
|
53
257
|
fail() { echo "adopt-error $*"; exit 3; }
|
|
@@ -74,13 +278,13 @@ kept=""
|
|
|
74
278
|
if [ -f "$C" ]; then
|
|
75
279
|
kept=$(grep -v -E '^[[:space:]]*(primary_conninfo|primary_slot_name|restore_command|synchronous_standby_names)[[:space:]]*=' "$C")
|
|
76
280
|
fi
|
|
77
|
-
{ [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+
|
|
281
|
+
{ [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+zp.replace(/"/g,'\\"')+String.raw`'"; } > "$C" || fail "postgresql.auto.conf could not be written"
|
|
78
282
|
echo "adopt-done"
|
|
79
|
-
`;
|
|
80
|
-
`}var
|
|
81
|
-
`)){let[s,a]=o.trim().split(/\s+/),
|
|
82
|
-
`)[0]??"").split("|");return t==="t"&&n!==void 0&&
|
|
83
|
-
D=${
|
|
283
|
+
`;Si=["select pg_promote(true, 120)","alter system reset synchronous_standby_names","alter system reset primary_conninfo","alter system reset primary_slot_name","alter system reset restore_command","select pg_reload_conf()"]});function Zp(e){return`*:*:*:snoutpod_replica:${e.replace(/[\\:]/g,"\\$&")}
|
|
284
|
+
`}var Yp,Xp,FA,_i=z(()=>{"use strict";ki();qo();Yp="/tmp/snoutpod/replica.pgpass",Xp="/tmp/snoutpod/primary.crt";FA=Buffer.from([0,0,0,8,4,210,22,47])});import{createHash as p_,createHmac as Qp,pbkdf2Sync as m_,randomBytes as GA}from"node:crypto";function ur(e,t){let n=f_.exec(e.trim());if(!n)return!1;let[,r,o,s,a]=n,l=Number(r);if(!Number.isInteger(l)||l<1||l>1e6)return!1;let d=m_(t.normalize("NFKC"),Buffer.from(o,"base64"),l,32,"sha256"),c=Qp("sha256",d).update("Client Key").digest(),i=p_("sha256").update(c).digest(),p=Qp("sha256",d).update("Server Key").digest();return i.equals(Buffer.from(s,"base64"))&&p.equals(Buffer.from(a,"base64"))}var f_,Ko=z(()=>{"use strict";f_=/^SCRAM-SHA-256\$(\d+):([^$]+)\$([^:]+):(.+)$/});function em(e){return/^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/.test(e.host)&&Number.isInteger(e.port)&&e.port>=1&&e.port<=65535?`${e.host}:${e.port}`:null}function nm(e,t){let n=new Map;for(let[o,s]of t)n.set(s,o);let r=new Map;for(let o of e.split(`
|
|
285
|
+
`)){let[s,a]=o.trim().split(/\s+/),l=s?n.get(s):void 0;l&&(a==="0"||a==="1"?r.set(l,!0):a==="2"&&r.set(l,!1))}return r}var tm,$i=z(()=>{"use strict";tm='for t in "$@"; do ( h=${t%:*}; p=5432; case "$t" in *:*) p=${t##*:} ;; esac; pg_isready -q -h "$h" -p "$p" -U snoutpod_admin -d postgres -t 3; echo "$t $?" ) & done; wait'});function h_(e){return/^[0-9A-F]{1,8}\/[0-9A-F]{1,8}$/i.test(e)}function om(e){let[t,n]=(e.trim().split(`
|
|
286
|
+
`)[0]??"").split("|");return t==="t"&&n!==void 0&&h_(n)?n:null}var g_,zA,rm,vi=z(()=>{"use strict";g_="/var/lib/postgresql/data",zA=`set -u
|
|
287
|
+
D=${g_}
|
|
84
288
|
W="$D/pg_wal"
|
|
85
289
|
fail() { echo "salvage-error $*"; exit 3; }
|
|
86
290
|
[ -d "$W" ] || fail "the volume has no pg_wal"
|
|
@@ -119,27 +323,24 @@ for s in $segs; do
|
|
|
119
323
|
echo "salvage-pushed $s"
|
|
120
324
|
done
|
|
121
325
|
echo "salvage-done"
|
|
122
|
-
`;
|
|
326
|
+
`;rm="select pg_is_in_recovery(), coalesce(pg_last_wal_replay_lsn()::text, '')"});var VA,sm=z(()=>{"use strict";Ie();VA=7*24});var XA,am=z(()=>{"use strict";XA=7*24*60*60*1e3});var y_,im=z(()=>{"use strict";am();y_=60*60*1e3});var lm=z(()=>{"use strict"});var Pi,oR,cm=z(()=>{"use strict";Pi="snoutdata_realtime",oR=`do $snoutpod$
|
|
123
327
|
begin
|
|
124
|
-
if exists (select 1 from pg_publication where pubname = '${
|
|
328
|
+
if exists (select 1 from pg_publication where pubname = '${Pi}') then
|
|
125
329
|
return;
|
|
126
330
|
end if;
|
|
127
|
-
create publication ${
|
|
128
|
-
execute format('alter publication ${
|
|
331
|
+
create publication ${Pi};
|
|
332
|
+
execute format('alter publication ${Pi} owner to %I',
|
|
129
333
|
(select pg_get_userbyid(datdba) from pg_database where datname = current_database()));
|
|
130
334
|
end
|
|
131
335
|
$snoutpod$;
|
|
132
|
-
`});var
|
|
133
|
-
`)}function
|
|
134
|
-
delete table inet ${
|
|
135
|
-
`;
|
|
136
|
-
|
|
137
|
-
`)}function Xn(e){return`${H(e).pod}-lepis-tls`}function ak(e){return rk("sha256").update(`snout-lepis-admin:${e}`).digest("hex")}function ei(e,t){let n={...e},r=n[Ro],o=n[To];delete n[Ro],delete n[To];for(let[s,a,c]of[[Ro,r,t],[To,o,ak(t)]])if(a!==void 0){if(!sk.test(a))throw new Error(`${s} names ${JSON.stringify(a)}, which is not a variable name`);n[a]=c}return n}var ge,Ro,To,Oo,No,Xa,xp,kE,fn,ok,Nt,Ne,Io,Rp,sk,Co=W(()=>{"use strict";Le();Pp();ge="lepis",Ro="SNOUTPOD_ADMIN_PASSWORD_ENV",To="SNOUTPOD_ADMIN_TOKEN_ENV",Oo=7433,No=1e3,Xa=7432,xp=4,kE={LEPIS_HOST:"0.0.0.0",LEPIS_PORT:String(Xa),LEPIS_HOME:"127.0.0.1:5432",LEPIS_HOME_SSLMODE:"disable",LEPIS_SERVICE_USER:"snoutpod_admin",[Ro]:"LEPIS_SERVICE_PASSWORD",LEPIS_ADMIN_ADDR:`0.0.0.0:${Oo}`,LEPIS_TLS_CERT:"/tls/cert.pem",LEPIS_TLS_KEY:"/tls/key.pem",[To]:"LEPIS_ADMIN_TOKEN",LEPIS_LOG:"info"},fn=7434,ok=7,Nt="snoutpod.lepis";Ne="snoutpod_router";Io="/tls",Rp=["set -e","if [ ! -s /tls/cert.pem ] || [ ! -s /tls/key.pem ]; then"," openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3650 -subj /CN=lepis -addext subjectAltName=DNS:lepis,IP:127.0.0.1 -keyout /tls/key.pem -out /tls/cert.pem 2>/dev/null","fi","chmod 755 /tls","chmod 644 /tls/cert.pem /tls/key.pem"].join(`
|
|
138
|
-
`),sk=/^[A-Z][A-Z0-9_]{0,63}$/});function ti(e){return Tp.includes(e)}async function ni(e,t){if(!ti(t))throw new Error(`no password is derived for role ${JSON.stringify(t)}: only ${Tp.join(", ")}`);if(e==="")throw new Error("no admin password to derive a role password from");let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",r,n.encode(`role:${t}`))),s="";for(let a of o)s+=String.fromCharCode(a);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Tp,ri=W(()=>{"use strict";Tp=["snout_gate","snout_auth_admin","snout_storage_admin","snout_realtime_admin","snout_psyche_admin","snout_push_admin","snoutpod_router"]});var AE,RE,Op=W(()=>{"use strict";Le();Ao();AE=6*60*60,RE=5*60});var Np=W(()=>{"use strict"});var Ip=W(()=>{"use strict"});var IE,Cp=W(()=>{"use strict";IE=15*6e4});var jE,Mp=W(()=>{"use strict";Cp();jE=2*1024**3});var Dp=W(()=>{"use strict";Ip();Mp()});function jp(e){if(!Array.isArray(e))throw new Error("the database access list is not a list");let t=new Set;return e.map(n=>{let r=n,o=r?.role,s=r?.level;if(typeof o!="string"||!lk.test(o))throw new Error(`not a database access role: ${JSON.stringify(o)}`);if(typeof s!="string"||!ik.includes(s))throw new Error(`not a database access level: ${JSON.stringify(s)}`);if(t.has(o))throw new Error(`${o} is on the database access list twice`);return t.add(o),{role:o,level:s}})}function Up(e,t){return`${e}.nspname !~ '^pg_'
|
|
139
|
-
and ${e}.nspname <> all (array[${Lp.map(n=>`'${n}'`).join(", ")}]::text[])
|
|
336
|
+
`});var aR,iR,dm=z(()=>{"use strict";aR=2*1024*1024,iR=64*1024});var um=z(()=>{"use strict"});function Vo(e,t={name:Oe,subnet:Wo,gateway:gm}){if(e.length===0)throw new Error("a peer network needs at least one peer");let n=["network","create","--subnet",t.subnet,"--gateway",t.gateway,"--disable-dns","--opt","no_default_route=1"];for(let r of[...new Set(e)].sort()){if(zo(Yt("a peer",r,mr),t.subnet))throw new Error(`the peer ${r} is on the peer network's bridge itself, which needs no route`);n.push("--route",`${r}/32,${t.gateway}`)}return n.push(t.name),n}function hm(e){if(!Ei.test(e))throw new Error(`not a project's group: ${JSON.stringify(e)}`);return`${Jo}${e}`}function Yo(e){let t=e.startsWith(Jo)?e.slice(Jo.length):"";return Ei.test(t)?t:null}function Xt(e){let t=/^10\.96\.([0-9]{1,3})\.([0-9]{1,3})\/28$/.exec(e),n=t?Number(t[1]):-1,r=t?Number(t[2]):-1;return n<1||n>255||r<0||r>240||r%16!==0?null:{subnet:e,gateway:`10.96.${n}.${r+1}`}}function Ai(e){let t=new Set(e);for(let n=1;n<=255;n+=1)for(let r=0;r<=240;r+=16){let o=`10.96.${n}.${r}/28`;if(!t.has(o))return o}return null}function ym(e,t){if(!Ei.test(e))throw new Error(`not a project's group: ${JSON.stringify(e)}`);let n=Yt("a cluster peer",t,mr).split(".").map(Number);return`${Jo}${e}-${n.map(r=>r.toString(16).padStart(2,"0")).join("")}`}function vn(e){let t=w_.exec(e);if(!t)return null;let n=t[2],r=[0,2,4,6].map(o=>parseInt(n.slice(o,o+2),16)).join(".");return{group:t[1],peer:r}}function Ri(e){return Yo(e)!==null||vn(e)!==null}function b_(e){let t=[],n=[...e].sort((r,o)=>r.subnet<o.subnet?-1:r.subnet>o.subnet?1:r.peer<o.peer?-1:r.peer>o.peer?1:0);for(let r of n){if(!Xt(r.subnet))throw new Error(`not a peer network's subnet: ${r.subnet}`);if(Yt("a peer",r.peer,mr),r.ports===null){t.push({from:r.subnet,to:r.peer,match:"all",verdict:"accept"},{from:r.peer,to:r.subnet,match:"all",verdict:"accept"});continue}let o=[...new Set(r.ports)].sort((s,a)=>s-a);for(let s of o)if(!Number.isInteger(s)||s<1||s>65535)throw new Error(`not a port: ${s}`);o.length!==0&&t.push({from:r.subnet,to:r.peer,match:"dport",ports:o,verdict:"accept"},{from:r.peer,to:r.subnet,match:"sport",ports:o,verdict:"accept"},{from:r.peer,to:r.subnet,match:"icmp",verdict:"accept"})}return t.push({from:xi,to:"0.0.0.0/0",match:"all",verdict:"drop"},{from:"0.0.0.0/0",to:xi,match:"all",verdict:"drop"}),t}function wm(e){let t=n=>{let r=l=>l.length===1?String(l[0]):`{ ${l.join(", ")} }`,o=(l,d)=>d==="0.0.0.0/0"?"":`ip ${l} ${d}`,s=n.verdict==="drop"?n.from===xi?`ip saddr != ${Wo}`:`ip daddr != ${Wo}`:"",a=n.match==="dport"?`tcp dport ${r(n.ports)}`:n.match==="sport"?`tcp sport ${r(n.ports)}`:n.match==="icmp"?"ip protocol icmp":"";return[" "+[o("saddr",n.from),o("daddr",n.to),s,a,n.verdict==="drop"?"counter drop":"accept"].filter(Boolean).join(" ")].join("")};return[`table inet ${pr}`,`delete table inet ${pr}`,`table inet ${pr} {`," chain forward {"," type filter hook forward priority 0; policy accept;",...b_(e).map(t)," }","}",""].join(`
|
|
337
|
+
`)}function Xo(e,t,n={subnet:Wo,gateway:gm}){let r;try{let l=JSON.parse(e);r=Array.isArray(l)?l[0]:l}catch{return!1}if(!r||r.internal===!0||r.dns_enabled===!0||!(r.subnets??[]).some(l=>l.subnet===n.subnet))return!1;let o=r.options?.no_default_route;if(o!=="1"&&o!=="true")return!1;let s=(r.routes??[]).map(l=>`${l.destination??""},${l.gateway??""}`).sort(),a=[...new Set(t)].sort().map(l=>`${l}/32,${n.gateway}`);return s.length===a.length&&s.every((l,d)=>l===a[d])}function Zo(e,t){let n;try{let o=JSON.parse(e);n=(Array.isArray(o)?o[0]:o)?.routes}catch{return[]}let r=new Set((Array.isArray(n)?n:[]).map(o=>String(o.destination??"")));return t.filter(o=>r.has(`${o}/32`))}function Yt(e,t,n){if(!n.test(t))throw new Error(`${e} is not a value this can route: ${JSON.stringify(t)}`);return t}function Qo(e){let t=["network","create"],n=e.allow,r=e.deny;if(n!=null&&r!=null)throw new Error("a network is policed by an allow-list or by a deny-list, not by both");if((e.peers?.length??0)>0&&r==null)throw new Error("a peer is an exception to a deny-list, so it needs one");if(r!=null)return S_(e,r);if(n==null){if(e.subnet||e.gateway)throw new Error("a subnet or gateway was given with no egress policy, which does nothing");return t.push(e.name),t}if(n.length>0)throw new Error("an egress allow-list is not expressible on this runtime: --internal blocks everything or nothing, and a route-based block does not block (measured on podman 5.8.6 / netavark 1.17.2)");if(e.subnet||e.gateway)throw new Error("a subnet or gateway was given with no allowance to route through it");return t.push("--internal",e.name),t}function S_(e,t){if(t.length===0)throw new Error("an empty deny-list is not a policy: leave it absent to create an ordinary network");let n=e.subnet,r=e.sink;if(!n||!r)throw new Error("a deny-list needs a pinned subnet and a sink address on it");if(Yt("the subnet",n,pm),Yt("the sink",r,mr),!zo(r,n))throw new Error(`the sink ${r} is not inside ${n}, so denied traffic would be routed at the host`);if(e.gateway&&!zo(e.gateway,n))throw new Error(`the gateway ${e.gateway} is not inside ${n}`);if(e.gateway&&e.gateway===r)throw new Error("the sink is the gateway, which routes denied traffic at the host rather than nowhere");let o=["network","create","--subnet",n];e.gateway&&o.push("--gateway",e.gateway);for(let s of t)o.push("--route",`${Yt("a denied prefix",s,pm)},${r}`);for(let s of e.peers??[]){if(!e.gateway)throw new Error("a peer is reached through the gateway, so it needs a pinned gateway");if(zo(Yt("a peer",s,mr),n))throw new Error(`the peer ${s} is on the bridge itself, which needs no route`);o.push("--route",`${s}/32,${e.gateway}`)}return o.push(e.name),o}function mm(e){return e.split(".").reduce((t,n)=>t*256+Number(n),0)}function zo(e,t){let[n,r]=t.split("/"),o=Number(r),s=o===0?0:4294967295<<32-o>>>0;return(mm(e)&s)>>>0===(mm(n??"")&s)>>>0}function Sm(e){return e?.internal===!0}var fm,Oe,Wo,gm,Jo,Ei,w_,xi,pr,bm,pm,mr,es=z(()=>{"use strict";fm=["169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"],Oe="snoutpeer",Wo="10.96.0.0/24",gm="10.96.0.1";Jo=`${Oe}-`,Ei=/^[a-z][0-9a-z]{12}$/;w_=/^snoutpeer-([a-z][0-9a-z]{12})-([0-9a-f]{8})$/;xi="10.96.0.0/16";pr="snoutpod_peers";bm=`table inet ${pr}
|
|
338
|
+
delete table inet ${pr}
|
|
339
|
+
`;pm=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(3[0-2]|[12]?[0-9])$/,mr=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/});var k_,ts=z(()=>{"use strict";k_=7*24*60*60});function P_(e,t){let[n,r]=e.split("/");if(r!=="24"||!n?.endsWith(".0")||!t.startsWith(n.slice(0,-1)))throw new Error(`${t} is not an address of the /24 ${e}`);let o=n.slice(0,-1),s=Number(t.slice(o.length)),a=[];for(let l=32;l>=25;l--){let d=2**(32-l);a.push(`${o}${(s^d)&~(d-1)&255}/${l}`)}return a}var $_,v_,vR,km=z(()=>{"use strict";Ie();dm();um();es();ts();$_="10.93.0.0/24",v_="10.93.0.1",vR=[...fm,"100.64.0.0/10",...P_($_,v_)]});function Ti(e){return _m.includes(e)}async function Oi(e,t){if(!Ti(t))throw new Error(`no password is derived for role ${JSON.stringify(t)}: only ${_m.join(", ")}`);if(e==="")throw new Error("no admin password to derive a role password from");let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",r,n.encode(`role:${t}`))),s="";for(let a of o)s+=String.fromCharCode(a);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var _m,Ni=z(()=>{"use strict";_m=["snout_gate","snout_auth_admin","snout_storage_admin","snout_realtime_admin","snout_psyche_admin","snout_push_admin","snoutpod_router"]});var OR,NR,$m=z(()=>{"use strict";Ie();ts();OR=6*60*60,NR=5*60});var vm=z(()=>{"use strict"});var Pm=z(()=>{"use strict"});var MR,xm=z(()=>{"use strict";MR=15*6e4});var BR,Em=z(()=>{"use strict";xm();BR=2*1024**3});var Am=z(()=>{"use strict";Pm();Em()});function Tm(e){if(!Array.isArray(e))throw new Error("the database access list is not a list");let t=new Set;return e.map(n=>{let r=n,o=r?.role,s=r?.level;if(typeof o!="string"||!E_.test(o))throw new Error(`not a database access role: ${JSON.stringify(o)}`);if(typeof s!="string"||!x_.includes(s))throw new Error(`not a database access level: ${JSON.stringify(s)}`);if(t.has(o))throw new Error(`${o} is on the database access list twice`);return t.add(o),{role:o,level:s}})}function Om(e,t){return`${e}.nspname !~ '^pg_'
|
|
340
|
+
and ${e}.nspname <> all (array[${Rm.map(n=>`'${n}'`).join(", ")}]::text[])
|
|
140
341
|
and not ${t}.rolsuper
|
|
141
|
-
and ${t}.rolname !~ '${
|
|
142
|
-
`)){let r=/^(created-group|created|applied|dropped-group|dropped|refused|ignored) (\S+)$/.exec(n.trim());r&&t.push({action:r[1],role:r[2]})}return t}function
|
|
342
|
+
and ${t}.rolname !~ '${A_.source}'`}function Im(e){let t=[];for(let n of e.split(`
|
|
343
|
+
`)){let r=/^(created-group|created|applied|dropped-group|dropped|refused|ignored) (\S+)$/.exec(n.trim());r&&t.push({action:r[1],role:r[2]})}return t}function Cm(e,t){return ae(e),JSON.stringify(Tm(t).map(n=>({role:n.role,level:n.level})))}var x_,Pn,E_,le,Rm,A_,rs,R_,ns,T_,Nm,Ii=z(()=>{"use strict";Ie();x_=["full","read"],Pn="snout_oauth",E_=/^oauth_[0-9a-f]{32}$/,le="snout_oauth_read",Rm=["information_schema","auth","storage","realtime","snout_realtime","_realtime","push","graphql","graphql_public","extensions","snout_identity","snout_files","snout_live","snout_graph","snout_ext","cron","net","vault","pgsodium","pgbouncer","snouttime","snouttime_internal","lepis"],A_=/^(snout_[a-z]+_admin|snout_gate|authenticator|pgbouncer)$/;rs="SNOUTPOD_DB_ACCESS",R_=/^[a-z_][a-z0-9_]*$/;for(let e of Rm)if(!R_.test(e))throw new Error(`not a schema name: ${JSON.stringify(e)}`);ns="snoutpod_oauth_read_new_schema",T_=`do $home$
|
|
143
344
|
declare
|
|
144
345
|
-- snout_ext in the own layout, extensions in a database not yet renamed (docs/cloud/OWN-LAYOUT.md).
|
|
145
346
|
home text := case
|
|
@@ -148,7 +349,7 @@ declare
|
|
|
148
349
|
end;
|
|
149
350
|
begin
|
|
150
351
|
execute pg_catalog.format('create schema if not exists %I', home);
|
|
151
|
-
execute pg_catalog.replace($fn$create or replace function @home@.${
|
|
352
|
+
execute pg_catalog.replace($fn$create or replace function @home@.${ns}() returns event_trigger
|
|
152
353
|
language plpgsql
|
|
153
354
|
security invoker
|
|
154
355
|
set search_path = pg_catalog, pg_temp
|
|
@@ -157,7 +358,7 @@ declare
|
|
|
157
358
|
created record;
|
|
158
359
|
owner_role text := pg_catalog.current_database() || '_owner';
|
|
159
360
|
begin
|
|
160
|
-
if not exists (select from pg_catalog.pg_roles where rolname = '${
|
|
361
|
+
if not exists (select from pg_catalog.pg_roles where rolname = '${le}') then
|
|
161
362
|
return;
|
|
162
363
|
end if;
|
|
163
364
|
for created in
|
|
@@ -168,29 +369,29 @@ begin
|
|
|
168
369
|
where c.command_tag = 'CREATE SCHEMA'
|
|
169
370
|
and c.classid = 'pg_catalog.pg_namespace'::pg_catalog.regclass
|
|
170
371
|
and not c.in_extension
|
|
171
|
-
and ${
|
|
372
|
+
and ${Om("n","r")}
|
|
172
373
|
loop
|
|
173
374
|
begin
|
|
174
|
-
execute pg_catalog.format('grant usage on schema %I to ${
|
|
175
|
-
execute pg_catalog.format('grant select on all tables in schema %I to ${
|
|
176
|
-
execute pg_catalog.format('grant select on all sequences in schema %I to ${
|
|
177
|
-
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on tables to ${
|
|
178
|
-
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on sequences to ${
|
|
375
|
+
execute pg_catalog.format('grant usage on schema %I to ${le}', created.nspname);
|
|
376
|
+
execute pg_catalog.format('grant select on all tables in schema %I to ${le}', created.nspname);
|
|
377
|
+
execute pg_catalog.format('grant select on all sequences in schema %I to ${le}', created.nspname);
|
|
378
|
+
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on tables to ${le}', owner_role, created.nspname);
|
|
379
|
+
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on sequences to ${le}', owner_role, created.nspname);
|
|
179
380
|
exception when others then
|
|
180
381
|
raise warning 'snoutpod: read access reaches schema % at the next apply, not now: %', created.nspname, sqlerrm;
|
|
181
382
|
end;
|
|
182
383
|
end loop;
|
|
183
384
|
end
|
|
184
385
|
$snoutpod$$fn$, '@home@', pg_catalog.quote_ident(home));
|
|
185
|
-
if not exists (select from pg_catalog.pg_event_trigger where evtname = '${
|
|
186
|
-
execute pg_catalog.format('create event trigger ${
|
|
386
|
+
if not exists (select from pg_catalog.pg_event_trigger where evtname = '${ns}') then
|
|
387
|
+
execute pg_catalog.format('create event trigger ${ns} on ddl_command_end
|
|
187
388
|
when tag in (''CREATE SCHEMA'')
|
|
188
|
-
execute function %I.${
|
|
389
|
+
execute function %I.${ns}()', home);
|
|
189
390
|
end if;
|
|
190
391
|
end
|
|
191
392
|
$home$;
|
|
192
|
-
`,
|
|
193
|
-
${
|
|
393
|
+
`,Nm=`\\getenv db_access ${rs}
|
|
394
|
+
${T_}create function pg_temp.snoutpod_member(member_name text, group_name text)
|
|
194
395
|
returns boolean
|
|
195
396
|
language sql
|
|
196
397
|
stable
|
|
@@ -211,7 +412,7 @@ create function pg_temp.snoutpod_customer_schema(schema_oid oid)
|
|
|
211
412
|
set search_path = pg_catalog, pg_temp
|
|
212
413
|
as $snoutpod$
|
|
213
414
|
-- isCustomerSchema in dbAccess.ts, from the same SYSTEM_SCHEMAS and PLATFORM_OWNER.
|
|
214
|
-
select ${
|
|
415
|
+
select ${Om("n","r")}
|
|
215
416
|
from pg_namespace n
|
|
216
417
|
join pg_roles r on r.oid = n.nspowner
|
|
217
418
|
where n.oid = schema_oid
|
|
@@ -246,9 +447,9 @@ begin
|
|
|
246
447
|
end if;
|
|
247
448
|
any_read := exists (select from jsonb_array_elements(wanted) w where w->>'level' = 'read');
|
|
248
449
|
|
|
249
|
-
if not exists (select from pg_roles where rolname = '${
|
|
250
|
-
create role ${
|
|
251
|
-
change := 'created-group'; role_name := '${
|
|
450
|
+
if not exists (select from pg_roles where rolname = '${Pn}') then
|
|
451
|
+
create role ${Pn} nologin;
|
|
452
|
+
change := 'created-group'; role_name := '${Pn}'; return next;
|
|
252
453
|
end if;
|
|
253
454
|
|
|
254
455
|
-- Taken away: every member of the group the list does not name.
|
|
@@ -257,7 +458,7 @@ begin
|
|
|
257
458
|
from pg_auth_members am
|
|
258
459
|
join pg_roles g on g.oid = am.roleid
|
|
259
460
|
join pg_roles m on m.oid = am.member
|
|
260
|
-
where g.rolname = '${
|
|
461
|
+
where g.rolname = '${Pn}'
|
|
261
462
|
order by 1
|
|
262
463
|
loop
|
|
263
464
|
continue when exists (select from jsonb_array_elements(wanted) w where w->>'role' = found_role);
|
|
@@ -276,21 +477,21 @@ begin
|
|
|
276
477
|
|
|
277
478
|
-- What a read person may read: the customer's schemas, and nothing of ours (dbAccess.ts).
|
|
278
479
|
if any_read then
|
|
279
|
-
if not exists (select from pg_roles where rolname = '${
|
|
280
|
-
create role ${
|
|
281
|
-
change := 'created-group'; role_name := '${
|
|
480
|
+
if not exists (select from pg_roles where rolname = '${le}') then
|
|
481
|
+
create role ${le} nologin;
|
|
482
|
+
change := 'created-group'; role_name := '${le}'; return next;
|
|
282
483
|
end if;
|
|
283
484
|
-- Stated whole, as a person's role is, and a member of nothing: whatever it held would reach
|
|
284
485
|
-- every read person.
|
|
285
|
-
alter role ${
|
|
486
|
+
alter role ${le} with nologin nosuperuser nocreatedb nocreaterole noreplication nobypassrls password null;
|
|
286
487
|
for target in
|
|
287
488
|
select g.rolname as of_role, pg_get_userbyid(am.grantor) as grantor
|
|
288
489
|
from pg_auth_members am
|
|
289
490
|
join pg_roles g on g.oid = am.roleid
|
|
290
491
|
join pg_roles m on m.oid = am.member
|
|
291
|
-
where m.rolname = '${
|
|
492
|
+
where m.rolname = '${le}'
|
|
292
493
|
loop
|
|
293
|
-
execute pg_catalog.format('revoke %I from ${
|
|
494
|
+
execute pg_catalog.format('revoke %I from ${le} granted by %I', target.of_role, target.grantor);
|
|
294
495
|
end loop;
|
|
295
496
|
for target in
|
|
296
497
|
select n.nspname, pg_temp.snoutpod_customer_schema(n.oid) as customer
|
|
@@ -299,16 +500,16 @@ begin
|
|
|
299
500
|
order by 1
|
|
300
501
|
loop
|
|
301
502
|
if target.customer then
|
|
302
|
-
execute pg_catalog.format('grant usage on schema %I to ${
|
|
303
|
-
execute pg_catalog.format('grant select on all tables in schema %I to ${
|
|
304
|
-
execute pg_catalog.format('grant select on all sequences in schema %I to ${
|
|
305
|
-
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on tables to ${
|
|
306
|
-
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on sequences to ${
|
|
503
|
+
execute pg_catalog.format('grant usage on schema %I to ${le}', target.nspname);
|
|
504
|
+
execute pg_catalog.format('grant select on all tables in schema %I to ${le}', target.nspname);
|
|
505
|
+
execute pg_catalog.format('grant select on all sequences in schema %I to ${le}', target.nspname);
|
|
506
|
+
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on tables to ${le}', owner_role, target.nspname);
|
|
507
|
+
execute pg_catalog.format('alter default privileges for role %I in schema %I grant select on sequences to ${le}', owner_role, target.nspname);
|
|
307
508
|
else
|
|
308
509
|
-- Ours. Nothing was ever granted here unless the list or an owner changed since.
|
|
309
|
-
execute pg_catalog.format('revoke all on schema %I from ${
|
|
310
|
-
execute pg_catalog.format('revoke all on all tables in schema %I from ${
|
|
311
|
-
execute pg_catalog.format('revoke all on all sequences in schema %I from ${
|
|
510
|
+
execute pg_catalog.format('revoke all on schema %I from ${le}', target.nspname);
|
|
511
|
+
execute pg_catalog.format('revoke all on all tables in schema %I from ${le}', target.nspname);
|
|
512
|
+
execute pg_catalog.format('revoke all on all sequences in schema %I from ${le}', target.nspname);
|
|
312
513
|
end if;
|
|
313
514
|
end loop;
|
|
314
515
|
for target in
|
|
@@ -317,10 +518,10 @@ begin
|
|
|
317
518
|
from pg_default_acl d
|
|
318
519
|
join pg_namespace n on n.oid = d.defaclnamespace
|
|
319
520
|
where not pg_temp.snoutpod_customer_schema(n.oid)
|
|
320
|
-
and exists (select from aclexplode(d.defaclacl) a where a.grantee = '${
|
|
521
|
+
and exists (select from aclexplode(d.defaclacl) a where a.grantee = '${le}'::regrole)
|
|
321
522
|
loop
|
|
322
523
|
continue when target.kind is null;
|
|
323
|
-
execute pg_catalog.format('alter default privileges for role %I in schema %I revoke all on %s from ${
|
|
524
|
+
execute pg_catalog.format('alter default privileges for role %I in schema %I revoke all on %s from ${le}', target.for_role, target.nspname, target.kind);
|
|
324
525
|
end loop;
|
|
325
526
|
end if;
|
|
326
527
|
|
|
@@ -329,7 +530,7 @@ begin
|
|
|
329
530
|
wanted_role := entry->>'role';
|
|
330
531
|
wanted_level := entry->>'level';
|
|
331
532
|
if exists (select from pg_roles where rolname = wanted_role) then
|
|
332
|
-
if not pg_temp.snoutpod_member(wanted_role, '${
|
|
533
|
+
if not pg_temp.snoutpod_member(wanted_role, '${Pn}') then
|
|
333
534
|
-- The name is right and the role is not ours: made by somebody else, who holds
|
|
334
535
|
-- ADMIN on it. Never adopted (see dbAccess.ts).
|
|
335
536
|
change := 'refused'; role_name := wanted_role; return next;
|
|
@@ -337,7 +538,7 @@ begin
|
|
|
337
538
|
end if;
|
|
338
539
|
change := 'applied';
|
|
339
540
|
else
|
|
340
|
-
execute pg_catalog.format('create role %I login in role ${
|
|
541
|
+
execute pg_catalog.format('create role %I login in role ${Pn}', wanted_role);
|
|
341
542
|
change := 'created';
|
|
342
543
|
end if;
|
|
343
544
|
-- No password, ever: the pg_hba line for the group is oauth, and a password could not be
|
|
@@ -350,8 +551,8 @@ begin
|
|
|
350
551
|
execute pg_catalog.format('revoke pg_read_all_data from %I', wanted_role);
|
|
351
552
|
end if;
|
|
352
553
|
if wanted_level = 'full' then
|
|
353
|
-
if pg_temp.snoutpod_member(wanted_role, '${
|
|
354
|
-
execute pg_catalog.format('revoke ${
|
|
554
|
+
if pg_temp.snoutpod_member(wanted_role, '${le}') then
|
|
555
|
+
execute pg_catalog.format('revoke ${le} from %I', wanted_role);
|
|
355
556
|
end if;
|
|
356
557
|
execute pg_catalog.format('alter role %I nobypassrls', wanted_role);
|
|
357
558
|
if not pg_temp.snoutpod_member(wanted_role, owner_role) then
|
|
@@ -366,8 +567,8 @@ begin
|
|
|
366
567
|
execute pg_catalog.format('revoke %I from %I', owner_role, wanted_role);
|
|
367
568
|
perform pg_terminate_backend(pid) from pg_stat_activity where usename = wanted_role;
|
|
368
569
|
end if;
|
|
369
|
-
if not pg_temp.snoutpod_member(wanted_role, '${
|
|
370
|
-
execute pg_catalog.format('grant ${
|
|
570
|
+
if not pg_temp.snoutpod_member(wanted_role, '${le}') then
|
|
571
|
+
execute pg_catalog.format('grant ${le} to %I with inherit true, set false', wanted_role);
|
|
371
572
|
end if;
|
|
372
573
|
execute pg_catalog.format('alter role %I bypassrls', wanted_role);
|
|
373
574
|
execute pg_catalog.format('alter role %I in database %I reset role', wanted_role, db);
|
|
@@ -378,30 +579,107 @@ begin
|
|
|
378
579
|
|
|
379
580
|
-- Nobody reads any more: the group goes, and with it every grant and default it held, so a
|
|
380
581
|
-- project that stops using the level carries nothing of it.
|
|
381
|
-
if not any_read and exists (select from pg_roles where rolname = '${
|
|
582
|
+
if not any_read and exists (select from pg_roles where rolname = '${le}') then
|
|
382
583
|
begin
|
|
383
584
|
for target in
|
|
384
585
|
select m.rolname as member_role, pg_get_userbyid(am.grantor) as grantor
|
|
385
586
|
from pg_auth_members am
|
|
386
587
|
join pg_roles g on g.oid = am.roleid
|
|
387
588
|
join pg_roles m on m.oid = am.member
|
|
388
|
-
where g.rolname = '${
|
|
589
|
+
where g.rolname = '${le}'
|
|
389
590
|
loop
|
|
390
|
-
execute pg_catalog.format('revoke ${
|
|
591
|
+
execute pg_catalog.format('revoke ${le} from %I granted by %I', target.member_role, target.grantor);
|
|
391
592
|
end loop;
|
|
392
|
-
drop owned by ${
|
|
393
|
-
drop role ${
|
|
394
|
-
change := 'dropped-group'; role_name := '${
|
|
593
|
+
drop owned by ${le};
|
|
594
|
+
drop role ${le};
|
|
595
|
+
change := 'dropped-group'; role_name := '${le}'; return next;
|
|
395
596
|
exception when others then
|
|
396
597
|
-- Holding something in another database, which this never grants. Kept, and said.
|
|
397
|
-
raise warning 'snoutpod: could not drop ${
|
|
598
|
+
raise warning 'snoutpod: could not drop ${le}: %', sqlerrm;
|
|
398
599
|
end;
|
|
399
600
|
end if;
|
|
400
601
|
end
|
|
401
602
|
$snoutpod$;
|
|
402
603
|
select change || ' ' || role_name from pg_temp.snoutpod_db_access(:'db_access'::jsonb);
|
|
403
|
-
`});var
|
|
404
|
-
`).slice(-3).join("; ");throw new Error(`${t} ${n[0]??""} failed (${o.code}): ${s}`)}return o.stdout}var
|
|
604
|
+
`});var Lm,oO,sO,aO,iO,lO,cO,Mm=z(()=>{"use strict";Sp();ui();Mp();pi();fi();Fp();qo();_i();Ko();$i();vi();sm();im();lm();cm();km();dr();Ni();$m();vm();Am();ts();Ii();Lm=120,oO=10*6e4,sO=2*6e4,aO=15*60*1e3,iO=60*60*1e3,lO=5*60*1e3,cO=10*60*1e3});import{execFile as O_}from"node:child_process";function Dm(){return(e,t,n={})=>new Promise((r,o)=>{let s=O_(e,[...t],{timeout:n.timeoutMs??0,maxBuffer:8388608,env:n.env?{...process.env,...n.env}:process.env},(a,l,d)=>{if(a&&typeof a.code=="string"){o(a);return}let c=a&&typeof a.code=="number"?a.code:0;r({code:c,stdout:String(l),stderr:String(d)})});n.stdin!==void 0&&s.stdin?.end(n.stdin)})}async function L(e,t,n,r){let o=await e(t,n,r);if(o.code!==0){let s=(o.stderr||o.stdout).trim().split(`
|
|
605
|
+
`).slice(-3).join("; ");throw new Error(`${t} ${n[0]??""} failed (${o.code}): ${s}`)}return o.stdout}var fr=z(()=>{"use strict"});import{readdir as N_,readFile as fO,rename as gO,writeFile as hO}from"node:fs/promises";async function jm(e,t,n={}){let r=n.binary??"podman",o=J(t).pod,s=await e(r,["volume","inspect",o,"--format","json"]);if(s.code!==0)return!1;let a=JSON.parse(s.stdout||"[]"),d=(Array.isArray(a)?a[0]:a)?.Mountpoint;return d?await(n.look??I_)(d)!=="empty":!1}async function I_(e){try{return(await N_(e)).length>0?"data":"empty"}catch(t){return t.code==="ENOENT"?"empty":"hidden"}}var bO,Um=z(()=>{"use strict";Ie();fr();bO=15*6e4});function Mi(e){return ae(e),{owner:`${e}_owner`,b:`${e}_owner_b`}}function Fm(e){let{owner:t,b:n}=Mi(e);return`select r.rolname, coalesce(r.rolpassword, ''), coalesce(extract(epoch from r.rolvaliduntil)::text, ''),
|
|
606
|
+
(r.rolname = '${n}'
|
|
607
|
+
and r.rolcanlogin and r.rolinherit and not r.rolsuper and not r.rolcreaterole and not r.rolcreatedb
|
|
608
|
+
and not r.rolreplication and not r.rolbypassrls and r.rolconnlimit = -1
|
|
609
|
+
and exists (select from pg_auth_members m join pg_roles o on o.oid = m.roleid
|
|
610
|
+
where m.member = r.oid and o.rolname = '${t}' and m.inherit_option and m.set_option and not m.admin_option)
|
|
611
|
+
and not exists (select from pg_auth_members m join pg_roles o on o.oid = m.roleid
|
|
612
|
+
where m.member = r.oid and o.rolname <> '${t}')
|
|
613
|
+
and not exists (select from pg_auth_members m where m.roleid = r.oid)
|
|
614
|
+
and exists (select from pg_db_role_setting s
|
|
615
|
+
where s.setrole = r.oid and s.setdatabase = 0 and s.setconfig = array['role=${t}'])
|
|
616
|
+
and not exists (select from pg_db_role_setting s
|
|
617
|
+
where s.setrole = r.oid and (s.setdatabase <> 0 or s.setconfig <> array['role=${t}']))
|
|
618
|
+
)::text
|
|
619
|
+
from pg_authid r where r.rolname in ('${t}', '${n}')`}function Bm(e){let t=new Map;for(let n of e.split(`
|
|
620
|
+
`)){let r=n.trim().split("|");if(r.length!==4||!/^[a-z][a-z0-9_]*$/.test(r[0]))continue;let[o,s,a,l]=r,d=a===""||a==="Infinity"?null:Number(a);t.set(o,{verifier:s,validUntil:d===null||Number.isFinite(d)?d:null,shaped:l==="true"})}return t}function L_(e){let{owner:t,b:n}=Mi(e);return`do $snoutpod$
|
|
621
|
+
declare
|
|
622
|
+
owner_name text := '${t}';
|
|
623
|
+
login_name text := '${n}';
|
|
624
|
+
stray record;
|
|
625
|
+
begin
|
|
626
|
+
if not exists (select from pg_catalog.pg_roles where rolname = login_name) then
|
|
627
|
+
execute pg_catalog.format('create role %I with login', login_name);
|
|
628
|
+
end if;
|
|
629
|
+
execute pg_catalog.format(
|
|
630
|
+
'alter role %I with login inherit nosuperuser nocreaterole nocreatedb noreplication nobypassrls connection limit -1',
|
|
631
|
+
login_name);
|
|
632
|
+
-- Nobody is a member of it and nobody holds ADMIN on it (ADMIN is a membership row too), however
|
|
633
|
+
-- it was made: GRANTED BY, because a superuser's REVOKE removes only the grants it made itself.
|
|
634
|
+
for stray in
|
|
635
|
+
select m.rolname as member, g.rolname as grantor
|
|
636
|
+
from pg_catalog.pg_auth_members am
|
|
637
|
+
join pg_catalog.pg_roles m on m.oid = am.member
|
|
638
|
+
join pg_catalog.pg_roles g on g.oid = am.grantor
|
|
639
|
+
where am.roleid = (select oid from pg_catalog.pg_roles where rolname = login_name)
|
|
640
|
+
loop
|
|
641
|
+
execute pg_catalog.format('revoke %I from %I granted by %I cascade', login_name, stray.member, stray.grantor);
|
|
642
|
+
end loop;
|
|
643
|
+
-- A member of nothing but the owner, and of the owner with INHERIT and SET and without ADMIN.
|
|
644
|
+
for stray in
|
|
645
|
+
select r.rolname as role, g.rolname as grantor, am.admin_option, am.inherit_option, am.set_option
|
|
646
|
+
from pg_catalog.pg_auth_members am
|
|
647
|
+
join pg_catalog.pg_roles r on r.oid = am.roleid
|
|
648
|
+
join pg_catalog.pg_roles g on g.oid = am.grantor
|
|
649
|
+
where am.member = (select oid from pg_catalog.pg_roles where rolname = login_name)
|
|
650
|
+
loop
|
|
651
|
+
if stray.role <> owner_name or stray.admin_option or not stray.inherit_option or not stray.set_option then
|
|
652
|
+
execute pg_catalog.format('revoke %I from %I granted by %I cascade', stray.role, login_name, stray.grantor);
|
|
653
|
+
end if;
|
|
654
|
+
end loop;
|
|
655
|
+
if not exists (
|
|
656
|
+
select from pg_catalog.pg_auth_members am
|
|
657
|
+
where am.member = (select oid from pg_catalog.pg_roles where rolname = login_name)
|
|
658
|
+
and am.roleid = (select oid from pg_catalog.pg_roles where rolname = owner_name)
|
|
659
|
+
) then
|
|
660
|
+
execute pg_catalog.format('grant %I to %I with inherit true, set true', owner_name, login_name);
|
|
661
|
+
end if;
|
|
662
|
+
-- One setting, role-wide: start every session as the owner. Lepis copies role-wide settings to
|
|
663
|
+
-- every node (roles.rs); a per-database one would not be, so none is kept.
|
|
664
|
+
for stray in
|
|
665
|
+
select d.datname
|
|
666
|
+
from pg_catalog.pg_db_role_setting s
|
|
667
|
+
join pg_catalog.pg_database d on d.oid = s.setdatabase
|
|
668
|
+
where s.setrole = (select oid from pg_catalog.pg_roles where rolname = login_name)
|
|
669
|
+
loop
|
|
670
|
+
execute pg_catalog.format('alter role %I in database %I reset all', login_name, stray.datname);
|
|
671
|
+
end loop;
|
|
672
|
+
if not exists (
|
|
673
|
+
select from pg_catalog.pg_db_role_setting s
|
|
674
|
+
where s.setrole = (select oid from pg_catalog.pg_roles where rolname = login_name)
|
|
675
|
+
and s.setdatabase = 0 and s.setconfig = array['role=' || owner_name]
|
|
676
|
+
) then
|
|
677
|
+
execute pg_catalog.format('alter role %I reset all', login_name);
|
|
678
|
+
execute pg_catalog.format('alter role %I set role = %L', login_name, owner_name);
|
|
679
|
+
end if;
|
|
680
|
+
end
|
|
681
|
+
$snoutpod$;`}function Hm(e,t){let{owner:n,b:r}=Mi(e.ref),o=e.ownerLogin??n;if(o!==n&&o!==r)throw new Error(`the spec names ${o} as the owner login, which is not ${n} or ${r}`);let s=e.previousOwnerLogin??null;if(s){if(s.login===o||s.login!==n&&s.login!==r)throw new Error(`the spec names ${s.login} as the previous owner login beside ${o}`);if(!C_.test(s.validUntil)||Number.isNaN(Date.parse(s.validUntil)))throw new Error(`the previous owner login's end is not a UTC time: ${s.validUntil}`)}let a=o===r||s?.login===r,l=[],d={},c=[],i=t.get(r);a&&!i?.shaped&&l.push(L_(e.ref));let p=t.get(o);if((!p||!ur(p.verifier,e.ownerPassword))&&(d[Ci]=e.ownerPassword,l.push(`alter role "${o}" with password :'owner_password';`)),p&&p.validUntil!==null&&l.push(`alter role "${o}" valid until 'infinity';`),s){let E=t.get(s.login);(!E||!ur(E.verifier,s.password))&&(d[Li]=s.password,l.push(`alter role "${s.login}" with password :'previous_password';`));let A=Date.parse(s.validUntil)/1e3;(!E||E.validUntil===null||Math.abs(E.validUntil-A)>=1)&&l.push(`alter role "${s.login}" valid until '${s.validUntil}';`),s.endSessions&&c.push(`select pg_catalog.count(pg_catalog.pg_terminate_backend(pid)) from pg_catalog.pg_stat_activity where usename = '${s.login}' and pid <> pg_catalog.pg_backend_pid();`)}if(!a&&i&&i.verifier!==""&&l.push(`alter role "${r}" with password null;`),l.length===0&&c.length===0)return null;let g=[];return d[Ci]!==void 0&&g.push(`\\getenv owner_password ${Ci}`),d[Li]!==void 0&&g.push(`\\getenv previous_password ${Li}`),l.length>0&&g.push("begin;",...l,"commit;"),g.push(...c,""),{script:g.join(`
|
|
682
|
+
`),env:d}}var Ci,Li,C_,Gm=z(()=>{"use strict";Ie();Ko();Ci="SNOUTPOD_OWNER_PASSWORD",Li="SNOUTPOD_PREVIOUS_OWNER_PASSWORD",C_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/});function qm(e,t,n){if(!n.test(t))throw new Error(`${e} is not a value this can pass to a pod: ${JSON.stringify(t)}`);return t}async function Wm(e,t){if(!t)return e??null;let n=await t();return{...e??{},key:n.accessKeyId,secret:n.secretAccessKey,token:n.sessionToken}}function Jm(e){let t=!!(e?.key&&e?.secret),n=["--env",`SNOUTPOD_S3_KEY_TYPE=${t?"shared":"auto"}`];return e&&(t&&(n.push("--env",`SNOUTPOD_S3_KEY=${qm("the access key",e.key,D_)}`),n.push("--env",Km),e.token&&n.push("--env",zm)),e.endpoint&&n.push("--env",`SNOUTPOD_S3_ENDPOINT=${qm("the endpoint",e.endpoint,M_)}`),e.uriStyle&&n.push("--env",`SNOUTPOD_S3_URI_STYLE=${e.uriStyle==="path"?"path":"host"}`),e.verifyTls===!1&&n.push("--env","SNOUTPOD_S3_VERIFY_TLS=n")),n}function Vm(e){if(!e?.key||!e?.secret)return{};if(/[\r\n]/.test(e.secret))throw new Error("the repository secret contains a newline, which would write a second setting");if(e.token&&/[\r\n]/.test(e.token))throw new Error("the session token contains a newline, which would write a second setting");return{[Km]:e.secret,...e.token?{[zm]:e.token}:{}}}var Km,zm,M_,D_,Ym=z(()=>{"use strict";Km="SNOUTPOD_S3_SECRET",zm="SNOUTPOD_S3_TOKEN",M_=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/i,D_=/^[A-Za-z0-9/+=_.-]{1,256}$/});function Qm(e){if(!ji.includes(e))throw new Error(`not a role kept out of the query statistics: ${e}`);return`alter role ${e} set pg_stat_statements.track = 'none';`}var Di,Xm,Zm,ji,ef=z(()=>{"use strict";Di=["snout_gate","authenticator"],Xm=`do $snoutpod$
|
|
405
683
|
declare
|
|
406
684
|
wanted text[];
|
|
407
685
|
begin
|
|
@@ -419,7 +697,7 @@ begin
|
|
|
419
697
|
end loop;
|
|
420
698
|
end
|
|
421
699
|
$snoutpod$;
|
|
422
|
-
`,
|
|
700
|
+
`,Zm=`do $snoutpod$
|
|
423
701
|
begin
|
|
424
702
|
if not exists (
|
|
425
703
|
select from pg_catalog.pg_stat_sys_tables
|
|
@@ -430,8 +708,8 @@ begin
|
|
|
430
708
|
end if;
|
|
431
709
|
end
|
|
432
710
|
$snoutpod$;
|
|
433
|
-
`,
|
|
434
|
-
`)){let r=n.split(
|
|
711
|
+
`,ji=["snout_psyche_admin"]});function nf(e){let t=[];for(let n of e.split(`
|
|
712
|
+
`)){let r=n.split(Fi);if(r.length!==4||!Ui.includes(r[0]))continue;let[o,s,a,l]=r;t.push(l?{name:o,from:s,error:l}:{name:o,from:s,to:a})}return t}var Ui,Fi,tf,rf=z(()=>{"use strict";Ui=["snouttime"];for(let e of Ui)if(!/^[a-z][a-z0-9_]{0,62}$/.test(e))throw new Error(`not an extension name: ${JSON.stringify(e)}`);Fi="",tf=`
|
|
435
713
|
SET search_path = pg_catalog, pg_temp;
|
|
436
714
|
CREATE TEMP TABLE snoutpod_extension_updates (name text, from_version text, to_version text, error text);
|
|
437
715
|
DO $snoutpod$
|
|
@@ -445,7 +723,7 @@ BEGIN
|
|
|
445
723
|
SELECT e.extname, e.extversion
|
|
446
724
|
FROM pg_extension e
|
|
447
725
|
JOIN pg_available_extensions a ON a.name = e.extname
|
|
448
|
-
WHERE e.extname = ANY (ARRAY[${
|
|
726
|
+
WHERE e.extname = ANY (ARRAY[${Ui.map(e=>`'${e}'`).join(", ")}])
|
|
449
727
|
AND a.default_version IS DISTINCT FROM e.extversion
|
|
450
728
|
LOOP
|
|
451
729
|
BEGIN
|
|
@@ -476,131 +754,133 @@ BEGIN
|
|
|
476
754
|
END
|
|
477
755
|
$snoutpod$;
|
|
478
756
|
SELECT name, from_version, coalesce(to_version, ''), coalesce(error, '') FROM snoutpod_extension_updates ORDER BY name;
|
|
479
|
-
`});function
|
|
480
|
-
`).find(s=>s.startsWith(r));if(o===void 0)return null;try{let s=new URL(o.slice(r.length).trim());return s.protocol!=="postgres:"||decodeURIComponent(s.username)!==n||s.password===""?null:decodeURIComponent(s.password)}catch{return null}}function
|
|
481
|
-
`)}function Wk(e){return/^(\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com)\//.exec(e)?.[1]??null}function Jk(e,t){for(let r of e??[]){let o=/^PG_MAJOR=(\d+)$/.exec(r.trim());if(o)return o[1]??null}let n=t.split("@")[0]??"";return/:(\d+)(?:[.-][^/:]*)?$/.exec(n)?.[1]??null}function vi(e){let t=(e??"").trim();return/^\d+(?:\.\d+)?$/.test(t)?t:null}function Vk(e,t){return t.image===null||t.data===null||t.image===t.data?null:`${e} was not started: its data directory was made by Postgres ${t.data} and it was handed a Postgres ${t.image} image. A data directory starts only on the major that made it. Its data is untouched, and it starts again on a ${t.data} image.`}async function Yk(e,t,n,r){return{image:await Xk(e,t,r),data:await Zk(e,t,n)}}async function Xk(e,t,n){let r=null;try{let o=await e(t,["image","inspect","--format","{{json .Config.Env}}",n]);if(o.code===0&&o.stdout.trim()){let s=JSON.parse(o.stdout.trim());r=Array.isArray(s)?s.filter(a=>typeof a=="string"):null}}catch{r=null}return Jk(r,n)}async function Zk(e,t,n){try{let r=await e(t,["volume","inspect","--format","{{.Mountpoint}}",H(n).pod]),o=r.code===0?r.stdout.trim().replace(/\/+$/,""):"";if(!o)return null;let s=await e(t,["unshare","cat",`${o}/PG_VERSION`]);return s.code===0?vi(s.stdout):null}catch{return null}}function Wm(e){return e.filter(t=>!!t.replicaPeer||t.guard!==void 0||t.hostRole==="standby").map(t=>({ref:t.ref,group:t.group??t.ref,container:H(t.ref).pod})).sort((t,n)=>t.ref<n.ref?-1:t.ref>n.ref?1:0)}function Qk(e,t,n){if(t.size>1)return`the ${xe} network already holds more than one project (${[...t].sort().join(", ")}), so nothing more joins it`;let r=t.size===1?[...t][0]:n;return e.group===r?null:`the ${xe} network holds ${r}'s copies, and another project may not share its bridge`}function e_(e,t){let n=new Map,r=new Set(t.length>0?Wm(e.filter(o=>!(o.guard!==void 0&&o.peerAddress))).map(o=>o.ref):[]);for(let o of e){if(o.state==="deleted"||!o.groupPeers||o.groupPeers.length===0)continue;let s=o.group??o.ref;for(let a of[...new Set(o.groupPeers)].sort()){if(a===o.peerAddress||r.has(o.ref)&&t.includes(a))continue;let c=Sp(s,a),i=n.get(c)??{group:s,peer:a,containers:[]};i.containers.push(H(o.ref).pod),o.ref===s&&i.containers.push(bt(o.ref)),n.set(c,i)}}return n}function t_(e,t){let n=[];for(let[r,o]of[...t].sort(([s],[a])=>s<a?-1:s>a?1:0)){if(!Ht(o))continue;let s=vo(r);if(s!==null){let i=e.find(u=>u.guard!==void 0&&u.state!=="deleted"&&!!u.peerAddress&&(u.group??u.ref)===s);i&&n.push({subnet:o,peer:i.peerAddress,ports:i.peerPorts?[...i.peerPorts]:null});continue}let a=mn(r);if(a===null)continue;let c=e.filter(i=>i.state!=="deleted"&&(i.group??i.ref)===a.group&&(i.groupPeers??[]).includes(a.peer));c.length>0&&n.push({subnet:o,peer:a.peer,ports:[...new Set(c.flatMap(i=>i.groupPeerPorts?.[a.peer]??[]))]})}return n}function Lm(e,t){let n=kn(t);return(e.Ports??[]).some(r=>{let o=r.host_ip??"";return o!==""&&o!=="0.0.0.0"&&o!=="::"&&!n.includes(o)})}function a_(e){if(!e)return[];let t=[],n=/^[1-9][0-9]{0,6}(kB|MB|GB)$/;typeof e.sharedBuffers=="string"&&n.test(e.sharedBuffers)&&t.push(`SNOUTPOD_SHARED_BUFFERS=${e.sharedBuffers}`),typeof e.workMem=="string"&&n.test(e.workMem)&&t.push(`SNOUTPOD_WORK_MEM=${e.workMem}`);let r=typeof e.maxConnections=="number"&&Number.isInteger(e.maxConnections)&&e.maxConnections>=1&&e.maxConnections<=1e4?e.maxConnections:jm;return t.push(`SNOUTPOD_MAX_CONNECTIONS=${Math.max(r,jm)}`),typeof e.privilegedExtensions=="string"&&/^[a-z][a-z0-9_-]*(,[a-z][a-z0-9_-]*)*$/.test(e.privilegedExtensions)&&t.push(`SNOUTPOD_PRIVILEGED_EXTENSIONS=${e.privilegedExtensions}`),t}function i_(e){let t=null;return()=>(t===null&&(t=n()),t);async function n(){if(e.runtime===null)return[];let r=e.runtime??Kk;return e.runtime!==void 0&&e.runtime!==""?["--runtime",r]:await Gk(r,{look:e.lookExecutable})===null?[]:["--runtime",r]}}function Vm(e){let t=e.binary??"podman",n=e.exec,r=i_(e),o=e.probe??zm;async function s(p){try{await n(t,["exec",..._e,"--interactive",H(p).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",p,"--quiet","--file","-"],{timeoutMs:zk,stdin:qk()})}catch{}}async function a(){let[p,f,g]=await Promise.all([N(n,t,["ps","--all","--filter",`label=${je}`,"--format","json"]),N(n,t,["ps","--all","--filter",`label=${Nt}`,"--format","json"]),N(n,t,["ps","--all","--filter",`label=${St}`,"--format","json"])]),w=await T(p.trim()?JSON.parse(p):[],!0),S=new Map;for(let F of g.trim()?JSON.parse(g):[]){let B=y(F);B&&S.set(B,(S.get(B)??!1)||F.State==="running")}let k=[...w.flatMap(F=>{let B=F.Labels?.[Ge]?F.Labels?.[St]:void 0;return B===void 0?[F]:S.has(B)?[S.get(B)?F:{...F,State:"exited"}]:[]}),...(f.trim()?JSON.parse(f):[]).flatMap(F=>{let B=F.Labels?.[Nt];return B?[{...F,Labels:{...F.Labels,[je]:B,[Ge]:ge}}]:[]})],x=new Map,_=new Map,I=new Map,j=new Map,z=new Set([...S.keys(),...(f.trim()?JSON.parse(f):[]).flatMap(F=>F.Labels?.[Nt]??[])]);for(let F of k){let B=F.Labels?.[je],D=F.Labels?.[Ge];if(!B||!D)continue;if(Im(yi(F))){j.set(B,[...j.get(B)??[],D]);continue}let Y=x.get(B)??[];Y.push(D),x.set(B,Y),wi(F.State)==="stopped"&&_.set(B,[..._.get(B)??[],D]);let me=Number(F.Labels?.[Sn]??0),Te=Number.isInteger(me)?me:0;I.set(B,Math.max(I.get(B)??Te,Te))}let L=k.filter(F=>F.Labels?.[je]&&!F.Labels?.[Ge]),$=L.map(F=>u_(F,Date.now())?"stopped":wi(F.State)),U=await c_(L,l_,(F,B)=>$[B]==="running"?Promise.resolve(!0):e.hasData(F.Labels?.[je]??""));return L.map((F,B)=>{let D=F.Labels?.[je]??"",Y=Number(F.Labels?.[hi]);return{ref:D,status:$[B]??"unknown",generation:Number.isInteger(Y)?Y:null,hasData:U[B]??!1,services:x.get(D)??[],servicesStopped:_.get(D)??[],...z.has(D)?{separated:!0}:{},...j.has(D)?{setAside:j.get(D)}:{},...Lm(F,e.podBind)?{boundElsewhere:!0}:{},...I.has(D)?{servicesGeneration:I.get(D)}:{}}})}async function c(){let p=await N(n,t,["ps","--all","--filter",`label=${je}`,"--format","json"]);return(p.trim()?JSON.parse(p):[]).filter(g=>g.Labels?.[je]&&!g.Labels?.[Ge]).length}async function i(p){let f=await(e.majors??((g,w)=>Yk(n,t,g,w)))(p.ref,p.image);return Vk(p.ref,f)}async function u(p){let f=H(p.ref),g=await i(p);if(g)throw new Error(g);let w=e.credentials,S=await Xp(e.repository,w?()=>w.forProject(p.ref,p.bucket):null),k={SNOUTPOD_OWNER_PASSWORD:p.ownerPassword,POSTGRES_PASSWORD:p.adminPassword,...Qp(S)},x=[...await r(),"run","--detach","--name",f.pod,"--label",`${je}=${p.ref}`,"--label",`${hi}=${p.generation}`,"--userns=auto","--memory",`${p.memoryMb}m`,"--pids-limit",String(n_),...f_(p.cpus),"--restart","no",...e.network?["--network",e.network]:[],...p.port?kn(e.podBind).flatMap(_=>["--publish",`${_}:${p.port}:5432`]):[],...jk(Za(p),e.podBind),"--volume",`${f.pod}:/var/lib/postgresql/data:U`,"--env","SNOUTPOD_OWNER_PASSWORD","--env","POSTGRES_PASSWORD","--env",`SNOUTPOD_REF=${p.ref}`,"--env","POSTGRES_USER=snoutpod_admin","--env","POSTGRES_DB=postgres","--env",`SNOUTPOD_S3_BUCKET=${p.bucket}`,"--env",`SNOUTPOD_S3_REGION=${p.region}`,...e.egressDenied?["--env","SNOUTPOD_EGRESS=denied"]:[],...m_(p.oauth),...a_(p.tuning).flatMap(_=>["--env",_]),"--env",`SNOUTPOD_RETENTION_FULL=${Hu(p.backup?.retentionDays,p.backup?.fullIntervalHours)}`,...Zp(S),p.image,"snoutpod-postgres"];await N(n,t,x,{env:k})}async function l(p){return(await le(p)).services}async function m(p){return(await l(p)).filter(f=>!f.setAside)}function y(p){return p.Labels?.[Ge]?void 0:p.Labels?.[St]}async function T(p,f){let g=e.inPlaceRoot;if(g===void 0)return p;let w=await vk(g).catch(()=>[]);if(w.length===0)return p;let S=new Set(p.flatMap(x=>x.Id?[x.Id]:[])),k=new Map;for(let x of w){let _=x.endsWith(".json")?x.slice(0,-5):"";if(!Nm.test(_))continue;if(!S.has(_)){f&&await Pk(qt(g,x),{force:!0});continue}let I=Ik(await _k(qt(g,x),"utf8").catch(()=>""));I!==null&&k.set(_,I)}return p.map(x=>{let _=x.Id&&x.Labels?.[Ge]?k.get(x.Id):void 0;return _===void 0?x:{...x,Labels:{...x.Labels,[Qn]:_.spec,[Sn]:String(_.generation)}}})}async function A(p){let f=await n(t,["container","inspect","--format","{{.HostConfig.Memory}} {{.HostConfig.MemorySwap}}",p]),[g,w]=f.code===0?f.stdout.trim().split(/\s+/).map(Number):[];return g!==void 0&&Number.isInteger(g)&&g>0&&w!==void 0&&Number.isInteger(w)?{bytes:g,swap:w}:null}async function oe(p,f,g){let w=g.swap===-1?["--memory-swap","-1"]:g.swap>g.bytes?["--memory-swap",`${f+Math.floor((g.swap-g.bytes)/wn)}m`]:[];if((await n(t,["update","--memory",`${f}m`,...w,p])).code!==0)return!1;let k=await A(p);return k!==null&&k.bytes===f*wn}async function Z(p,f){let g=e.inPlaceRoot;if(g===void 0||!Nm.test(p))return;await Em(g,{recursive:!0});let w=qt(g,`${p}.json`);await xk(`${w}.tmp`,JSON.stringify(f)),await $k(`${w}.tmp`,w)}async function le(p){let[f,g,w]=await Promise.all([N(n,t,["ps","--all","--filter",`label=${je}=${se(p)}`,"--filter",`label=${Ge}`,"--format","json"]),N(n,t,["ps","--all","--filter",`label=${Nt}=${p}`,"--format","json"]),N(n,t,["ps","--all","--filter",`label=${St}=${p}`,"--format","json"])]),S=await T(f.trim()?JSON.parse(f):[],!1),k=[];for(let _ of S){let I=_.Labels?.[Ge];if(!I)continue;let j=Number(_.Labels?.[Sn]??0),z=Im(yi(_));k.push({name:I,container:z?yi(_)??"":Om(p,I),id:_.Id??"",spec:_.Labels?.[Qn]??"",pod:_.Labels?.[Am]??"",running:_.State==="running",generation:Number.isInteger(j)?j:0,separate:!1,stack:_.Labels?.[St]===p,setAside:z})}for(let _ of g.trim()?JSON.parse(g):[]){if(_.Labels?.[Nt]!==p)continue;let I=Number(_.Labels?.[Sn]??0);k.push({name:ge,container:bt(p),id:_.Id??"",spec:_.Labels?.[Qn]??"",pod:"",running:_.State==="running",generation:Number.isInteger(I)?I:0,separate:!0,stack:!1,setAside:!1})}let x=null;for(let _ of w.trim()?JSON.parse(w):[])y(_)===p&&(x={id:_.Id??"",spec:_.Labels?.[ui]??"",running:_.State==="running"});return{services:k,anchor:x}}async function G(p){let f=await n(t,["container","inspect","--format","{{.Id}}",p]);return f.code===0?f.stdout.trim():""}function ue(p,f){return f?.databaseOnly?{services:p.services.filter(g=>!g.separate&&!g.stack),anchor:null}:p}async function V(p,f,g=new Map){let w=[];for(let z of f){let L=z.dbUriRole??null;z.dbUriEnv&&L&&!w.includes(L)&&w.push(It(L))}let S=new Map;if(w.length===0)return S;let k=await e.fixedRolePasswords?.()??new Map,x={},_=[],I=[];w.some(z=>si.includes(z))&&I.push(tm,nm);for(let z of w.filter(L=>ai.includes(L)))I.push(rm(z));let j=new Map;if(p.derivedServicePasswords===!0)for(let z of w.filter(ti))j.set(z,await ni(p.adminPassword,z));return w.forEach((z,L)=>{let $=k.get(z)??(j.has(z)?void 0:g.get(z));if($!==void 0){S.set(z,$);return}let U=j.get(z)??bk(24).toString("base64url"),F=`SNOUTPOD_SERVICE_PASSWORD_${L}`;S.set(z,U),x[F]=U,_.push("--env",F),I.push(`\\getenv service_password_${L} ${F}`),I.push(`\\set service_role_${L} ${z}`),I.push(`alter role :"service_role_${L}" with password :'service_password_${L}';`)}),I.push(""),await N(n,t,["exec",..._e,"--interactive",..._,H(p.ref).pod,"psql","--username","snoutpod_admin","--dbname",H(p.ref).database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:x,stdin:I.join(`
|
|
482
|
-
`)}),S}async function
|
|
483
|
-
`)){let[_,
|
|
484
|
-
${
|
|
485
|
-
`).filter(Boolean).pop()??`exit ${
|
|
486
|
-
`).map(_=>_.trim().split(" ")).filter(_=>_.length===2&&_[1]!=="").map(([_,
|
|
487
|
-
`),await
|
|
488
|
-
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`),!1;await
|
|
489
|
-
`)[0]}`),!1):(
|
|
490
|
-
`)[0]}`;return
|
|
491
|
-
`).map(D=>D.trim().split(/\s+/)).filter(D=>D.slice(1).includes(
|
|
492
|
-
`)[0]);continue}
|
|
493
|
-
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`);continue}await
|
|
494
|
-
`)[0]}`);continue}k.set(
|
|
495
|
-
`)[0]}`);continue}
|
|
496
|
-
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`);continue}await
|
|
497
|
-
`)[0]}`);continue}x.set(
|
|
498
|
-
`)[0]}`);continue}
|
|
499
|
-
`))(await n(t,["network","disconnect"
|
|
500
|
-
`).pop());return
|
|
501
|
-
`;return f.code===0&&
|
|
502
|
-
`);await
|
|
503
|
-
`)
|
|
504
|
-
`)[
|
|
505
|
-
`)
|
|
506
|
-
`)
|
|
507
|
-
`).at(-1);e
|
|
508
|
-
`).at(-1);return r==="DATA"?"data":r==="EMPTY"?"empty":"hidden"},()=>"hidden")}function Jo(e){let t=Wo()==="darwin"||Wo()==="win32";return zp(we,e,{binary:ie,look:t?E_:void 0})}async function qo(e,t=we,n=Wo()){let r=H(e).pod;if((await t(ie,["volume","exists",r])).code!==0)return null;let o;if(n==="darwin"||n==="win32"){let s=null;for(let a of _n){let c=nr(a).name;if((await t(ie,["image","exists",c])).code===0){s=c;break}}if(!s)throw new Error(`${r} holds a database and there is no pod image on this machine to read its Postgres version with. Set SNOUTPOD_IMAGE to the image it was made with (${_n.map(a=>nr(a).published).join(" or ")}).`);o=await t(ie,["run","--rm","--pull=never","--network=none","--userns=host","--user=0","--entrypoint=cat","--volume",`${r}:/data:ro`,s,"/data/PG_VERSION"])}else{let s=await t(ie,["volume","inspect","--format","{{.Mountpoint}}",r]),a=s.code===0?s.stdout.trim().replace(/\/+$/,""):"";if(!a)throw new Error(`could not find where ${r} is: ${s.stderr.trim()||"no mountpoint"}`);o=await t(ie,["unshare","cat",`${a}/PG_VERSION`])}if(o.code===0)return o.stdout;if(/no such file/i.test(o.stderr))return null;throw new Error(`could not read the Postgres version in ${r}: ${o.stderr.trim()||o.stdout.trim()||`exit ${o.code}`}`)}function nf(e,t=qo){if(!e||process.env.SNOUTPOD_IMAGE)return Promise.resolve(rr(null));se(e);let n=t===qo?zo.get(e):void 0;if(n)return n;let r=t(e).then(o=>{try{return rr(o)}catch(s){throw new Error(`${vn(e)}: ${s instanceof Error?s.message:String(s)}`)}});return t===qo&&(zo.set(e,r),r.catch(()=>zo.delete(e))),r}async function rf(){return{ramFreeMb:4096,ramTotalMb:8192,diskFreeMb:32768,diskTotalMb:65536}}function A_(e){return Vm({exec:we,binary:ie,network:Ct,hasData:Jo,capacity:rf,repository:e})}function vn(e){return H(e).pod}async function R_(e){if(process.env.SNOUTPOD_LOCAL_ALLOW_EGRESS==="1"){await T_()||await we(ie,xo({name:Ct}));return}let t=xo({name:Ct,allow:[]}),n="";for(let r=0;r<10;r+=1){if(await sf())return;await e?.(),await we(ie,["network","rm","--force",Ct]).catch(()=>{});let o=await we(ie,t);if(o.code===0)return;if(n=`${o.stderr}${o.stdout}`.trim(),/invalid route gateway/i.test(n))throw new Error(`${of}: ${n}`);await new Promise(s=>setTimeout(s,500))}throw new Error(`could not create ${Ct} with egress blocked${n?`: ${n}`:""}`)}async function T_(){return(await we(ie,["network","inspect",Ct,"--format","json"])).code===0}async function sf(){let e=await we(ie,["network","inspect",Ct,"--format","json"]);if(e.code!==0)return!1;try{return vp(JSON.parse(e.stdout)?.[0])}catch{return!1}}function af(e){let t=H(e.ref);return`postgres://${t.ownerRole}:${encodeURIComponent(e.ownerPassword)}@127.0.0.1:${e.port}/${t.database}?sslmode=disable`}function lf(e,t={}){return se(e.ref),{ref:e.ref,generation:1,image:t.image??Ei,memoryMb:t.memoryMb??ef,cpus:null,bucket:"",region:"us-east-1",ownerPassword:e.ownerPassword,adminPassword:e.adminPassword,port:e.port,tuning:t.tuning??null,backup:null,services:t.services??null}}function tr(e,t){e.onProgress?.(t)}async function O_(e,t,n={}){let r=n.image??(await nf(t.ref,n.pgVersion)).name,o=lf(t,{...n,image:r}),s=n.timeoutMs??12e4,a=n.hasData??Jo,c=(await e.list()).find(u=>u.ref===t.ref),i=null;if(c?c.status==="stopped"&&(i=await(n.staleImage??Pi)(t.ref,r))?(tr(n,"Starting the database on the newer image. Its data stays as it is."),await e.remove(t.ref),await e.create(o),await(n.dropImage??cf)(i)):c.status==="stopped"?(tr(n,"Starting the database."),await e.start(t.ref),await e.startServices(t.ref)):(tr(n,"The database is already running."),c.status==="running"&&await(n.staleImage??Pi)(t.ref,r)&&tr(n,"A newer database image is on this machine. To move onto it: snoutdata stop, then snoutdata start.")):(tr(n,await a(t.ref)?"Starting the database over its existing data.":"Creating the database."),await e.create(o)),!await e.waitReady(t.ref,s))throw new Error(await I_(t.ref,s,n.podLog??df));return await e.applyOwnerPassword(o),await e.createServices(o),Ai(e,t,n)}function Xm(e){return e.trim().replace(/^sha256:/,"")}async function Pi(e,t){let[n,r]=await Promise.all([we(ie,["container","inspect","--format","{{.Image}}",vn(e)]).catch(()=>null),we(ie,["image","inspect","--format","{{.Id}}",t]).catch(()=>null)]);if(n?.code!==0||r?.code!==0)return null;let o=Xm(n.stdout),s=Xm(r.stdout);return o&&s&&o!==s?o:null}async function cf(e){let t=await we(ie,["image","inspect","--format","{{len .RepoTags}}",e]).catch(()=>null);t?.code===0&&t.stdout.trim()==="0"&&await we(ie,["rmi",e]).catch(()=>{})}async function N_(e,t){let n=H(e.ref);return we(ie,["exec","--interactive","-e","PGPASSWORD",vn(e.ref),"psql","--host","127.0.0.1","--port","5432","--username",n.ownerRole,"--dbname",n.database,"--no-psqlrc","-v","ON_ERROR_STOP=1","-tA","--file","-"],{stdin:t,env:{PGPASSWORD:e.ownerPassword}})}async function df(e){let t=await we(ie,["logs","--tail","20",vn(e)]).catch(()=>null);return t?`${t.stdout}${t.stderr}`:"(no log: the container is not there)"}async function I_(e,t,n){let r=await n(e).catch(()=>"(no log)");return`${vn(e)} never became ready in ${t}ms
|
|
757
|
+
`});function sf(e){if(typeof e!="string"||!/^https?:\/\//.test(e)||e.length>255)throw new Error(`not an OAuth issuer a pod can be given: ${JSON.stringify(e)}`);if(/[\s"\\\u0000-\u001f\u007f]/.test(e))throw new Error(`an OAuth issuer may not hold spaces, quotes, backslashes or control characters: ${JSON.stringify(e)}`);return e}var of,RO,TO,af=z(()=>{"use strict";fr();os();of="SNOUTPOD_OAUTH_ISSUER",RO=256*1024,TO=5*6e4});function xn(e){return`${J(e).pod}-guard`}function lf(e,t,n){if(!Number.isInteger(t)||t<1||t>65535)throw new Error(`not a port: ${t}`);let r=e.leaseMs??1e4;return{LEPIS_GUARD_WITNESS:e.witness,...e.witnessSslmode?{LEPIS_GUARD_WITNESS_SSLMODE:e.witnessSslmode}:{},...e.witnessCa?{LEPIS_GUARD_WITNESS_CA:`${ss}/${Bi}`}:{},LEPIS_GUARD_CLUSTER:e.cluster,LEPIS_GUARD_TOKEN:e.token,LEPIS_GUARD_COPY:e.copy,LEPIS_GUARD_PEER:e.peer,LEPIS_GUARD_PG:`127.0.0.1:${t}`,LEPIS_GUARD_PG_USER:"snoutpod_admin",LEPIS_GUARD_PG_PASSWORD:n,LEPIS_GUARD_STATE:`${ss}/epoch`,LEPIS_GUARD_STATUS:`${ss}/status.json`,LEPIS_GUARD_LEASE_MS:String(r),LEPIS_GUARD_TICK_MS:String(Math.max(1,Math.min(1e3,Math.floor(r/5))))}}function cf(e,t,n,r){let o=e.witnessCa?r(e.witnessCa).slice(0,16):"";return[e.image,e.witness,e.witnessSslmode??"",e.cluster,e.copy,e.peer,e.leaseMs??1e4,t,n,...o?[o]:[]].join("|")}function df(e,t,n){if(ae(e),!n.hostDir.startsWith("/")||n.hostDir.includes(":"))throw new Error(`not a host directory for a volume: ${n.hostDir}`);return["run","--detach","--name",xn(e),"--label",`${as}=${e}`,"--label",`${Hi}=${n.fingerprint}`,"--network","host","--userns","auto","--volume",`${n.hostDir}:${ss}:U`,"--memory","64m","--pids-limit","64","--restart","no",...n.envNames.flatMap(r=>["--env",r]),t.image,"guard"]}function uf(e,t,n,r){let o=2*(r.leaseMs??1e4)/1e3;return n-e<=o+60?!1:t===null||n-t>o}var Bi,ss,as,Hi,pf=z(()=>{"use strict";Ie();Bi="witness-ca.pem";ss="/guard",as="snoutpod.guard",Hi="snoutpod.guard-spec"});function gf(e){return ae(e),{anchor:`snoutpod-${e}-copy`,router:`snoutpod-${e}-copy-lepis`,service:t=>`snoutpod-${e}-copy-${En(t)}`}}var mf,ff,hf=z(()=>{"use strict";Ie();os();mf="snoutpod.copy",ff="snoutpod.copy-service"});import{createHash as j_}from"node:crypto";function ht(e){return`${J(ae(e)).pod}-${is}`}function bf(e){return gt(e)?(e.services??[]).filter(t=>t.name!==ye):[]}function Zt(e,t){return gt(e)&&t.name!==ye}function Sf(e){let t=e.stackPodPort;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>65535)throw new Error(`${e.ref}: a services-only pod needs its own pod port (stackPodPort), and has ${JSON.stringify(t??null)}`);return t}function qi(e,t){if(t.hostPort===null||t.hostPort===void 0)return null;let n=Sf(e);if(typeof e.port!="number"||!Number.isInteger(e.port)||e.port<1)throw new Error(`${e.ref}: ${t.name}'s slot is read off the pod port, and the spec has none`);let r=t.hostPort-e.port;if(r<1e3||r%1e3!==0)throw new Error(`${e.ref}: ${t.name}'s hostPort ${t.hostPort} is on no slot of pod port ${e.port}`);let o=n+r;if(o>65535)throw new Error(`${e.ref}: stackPodPort ${n} puts ${t.name} past 65535`);return o}function Ki(e,t){let n=qi(e,t),r=kf(e,t);return n===null?t:{...t,hostPort:n,...r===null?{}:{adminHostPort:r}}}function kf(e,t){return!t.adminPort||!t.adminHostPort?null:qi(e,{name:`${t.name} admin`,hostPort:t.adminHostPort})}function zi(e){return bf(e).flatMap(t=>{let n=kf(e,t);return n===null||!t.adminPort?[]:[[n,t.adminPort]]}).sort((t,n)=>t[0]-n[0])}function Wi(e){let t=bf(e);return t.length>0&&Sf(e),t.flatMap(n=>{let r=qi(e,n);return r===null?[]:[[r,n.port]]}).sort((n,r)=>n[0]-r[0])}function _f(e,t){let n=zi(e);return j_("sha256").update(`stack:${t}:`).update(JSON.stringify(Wi(e))).update(n.length===0?"":`admin:${JSON.stringify(n)}`).digest("hex").slice(0,32)}var At,Gi,is,yf,wf,$f=z(()=>{"use strict";Ie();dr();At="snoutpod.stack",Gi="snoutpod.stack-spec",is="stack",yf=16,wf=16});import{createHash as hr,randomBytes as F_}from"node:crypto";import{access as B_,constants as H_,mkdir as vf,readFile as G_,readdir as q_,rename as K_,rm as z_,writeFile as W_}from"node:fs/promises";import{delimiter as J_,join as en}from"node:path";function Uf(e,t,n,r){return hr("sha256").update(Xi(e)).update(e.smtpSecretEnv&&t?hr("sha256").update(t).digest("hex"):"").update(n===void 0?"":`router:${n}`).update(r===void 0?"":`@${r}`).digest("hex").slice(0,32)}function V_(e,t){return ci(t),hr("sha256").update(`separated:${t}:${kn}:`).update(Uf(e)).digest("hex").slice(0,32)}function Xi(e){if(Array.isArray(e))return`[${e.map(Xi).join(",")}]`;if(e!==null&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${Xi(t[r])}`).join(",")}}`}return JSON.stringify(e??null)}function En(e){if(!Y_.test(e))throw new Error(`not a service name: ${JSON.stringify(e)}`);return e}function Bt(e){if(!X_.test(e))throw new Error(`not a database role: ${JSON.stringify(e)}`);return e}function Z_(e,t,n,r,o){if(r===void 0)return`postgres://${Bt(t)}:${n}@127.0.0.1:5432/${ae(e)}`;if(o!==void 0&&o!==Et(e))throw new Error(`${o} is not ${e}'s router`);return`postgres://${`${Bt(t)}:${n}@${o??"127.0.0.1"}`}:${Ke(r,"router port")}/${ae(e)}?sslmode=disable`}function Q_(e,t,n){let r=`${t}=`,o=e.split(`
|
|
758
|
+
`).find(s=>s.startsWith(r));if(o===void 0)return null;try{let s=new URL(o.slice(r.length).trim());return s.protocol!=="postgres:"||decodeURIComponent(s.username)!==n||s.password===""?null:decodeURIComponent(s.password)}catch{return null}}function ds(e,t){if(!t.dbUriEnv||!t.dbUriRole||t.name===ye)return;let n=(e.services??[]).find(r=>r.name===ye);if(n)return Di.includes(t.dbUriRole)?n.port:gt(e)?kn:void 0}function Zi(e,t){return gt(e)&&ds(e,t)!==void 0?Et(e.ref):void 0}function Ef(e,t,n,r){let o=di(t.env,e.adminPassword);if(t.dbUriEnv&&t.dbUriRole){let s=t.dbUriRole,a=n.get(s);if(a===void 0)throw new Error(`no password was applied for role ${JSON.stringify(t.dbUriRole)}, which ${JSON.stringify(t.name)} needs to reach its database`);o[t.dbUriEnv]=Z_(e.ref,s,a,ds(e,t),Zi(e,t))}if(t.smtpSecretEnv&&r&&(o[t.smtpSecretEnv]=r),t.adminPortEnv&&t.adminPort){if(!Bf.test(t.adminPortEnv))throw new Error(`${t.name}: not an environment variable name: ${JSON.stringify(t.adminPortEnv)}`);o[t.adminPortEnv]=String(Ke(t.adminPort,`${t.name}: adminPort`))}return o}function Af(e,t){return`${J(e).pod}-${En(t)}`}function e$(e){try{let t=JSON.parse(e);return typeof t.spec=="string"&&/^[0-9a-f]{32}$/.test(t.spec)&&Number.isInteger(t.generation)?{spec:t.spec,generation:t.generation}:null}catch{return null}}function ls(e){return`${e}${Ff}`}function Tf(e){return typeof e=="string"&&e.endsWith(Ff)}function Vi(e){let t=e.Names?.[0];return t===void 0?void 0:t.replace(/^\//,"")}function Qt(e){return`snoutpod-host-${En(e)}`}function t$(e,t){let n=Object.keys(e.env).sort().map(o=>[o,e.env[o]]),r=t&&(t.joins||(t.publishes?.length??0)>0)?[{joins:t.joins??null,publishes:t.publishes??[]}]:[];return hr("sha256").update(JSON.stringify([e.image,e.port,e.hostPort,e.healthPath??null,e.memoryMb,n,e.adminPort??null,e.adminHostPort??null,e.command??null,e.volumes??null,e.network??null,...r])).digest("hex").slice(0,32)}function n$(e){return[...e.filter(t=>!t.joins),...e.filter(t=>t.joins)]}function r$(e){return Object.keys(e.secretEnv??{}).length>0||Object.keys(e.files??{}).length>0||!!e.envFrom||!!e.databaseUrl}function o$(e,t){return t.filter(n=>n.joins===e&&n.hostPort>0).map(n=>[n.hostPort,n.port]).sort((n,r)=>n[0]-r[0])}function el(e){return!e.adminPort||!e.adminHostPort?null:[Ke(e.adminHostPort,`${e.name}: adminHostPort`),Ke(e.adminPort,`${e.name}: adminPort`)]}function s$(e,t){let n=[],r=On(t);for(let o of e??[]){if(En(o.name),Ke(o.port,`${o.name}: port`),o.hostPort===null||o.hostPort===void 0)continue;Ke(o.hostPort,`${o.name}: hostPort`);for(let a of r)n.push("--publish",`${a}:${o.hostPort}:${o.port}`);let s=el(o);if(s&&n.push("--publish",`127.0.0.1:${s[0]}:${s[1]}`),o.name===ye){let a=o.hostPort+Uo;Ke(a,`${o.name}: admin hostPort`);for(let l of r)n.push("--publish",`${l}:${a}:${jo}`)}}return n}function a$(e,t,n){if(ae(e.ref),t.name!==ye)throw new Error(`${t.name} is not the router`);if(!n.network)throw new Error(`${e.ref}: a separated router needs the pod network`);Ke(t.port,`${t.name}: port`);let r=ci(e.routerPodPort),o=([s,a])=>On(n.bind).flatMap(l=>["--publish",`${l}:${Ke(s,"router hostPort")}:${a}`]);return["run","--detach","--name",Et(e.ref),"--label",`${Ut}=${e.ref}`,"--label",`${Tn}=${e.servicesGeneration??0}`,"--label",`${gr}=${n.fingerprint}`,"--network",n.network,"--userns=auto","--memory",`${t.memoryMb}m`,"--pids-limit",String(Kf),"--restart","no",...o([r.postgres,t.port]),...o([r.admin,jo]),...o([r.passthrough,kn]),...Hf(t),"--volume",`${cr(e.ref)}:${Bo}:ro`,...n.envNames.flatMap(s=>["--env",s]),t.image]}function i$(e,t){if(ae(e.ref),!t.network)throw new Error(`${e.ref}: a services-only pod needs the pod network`);return["run","--detach","--name",ht(e.ref),"--label",`${At}=${e.ref}`,"--label",`${Gi}=${t.fingerprint}`,"--network",t.network,"--userns=auto","--memory",`${yf}m`,"--pids-limit",String(wf),"--restart","no","--stop-signal","SIGKILL",...Wi(e).flatMap(([n,r])=>On(t.bind).flatMap(o=>["--publish",`${o}:${Ke(n,"stack hostPort")}:${Ke(r,"service port")}`])),...zi(e).flatMap(([n,r])=>["--publish",`127.0.0.1:${Ke(n,"stack adminHostPort")}:${Ke(r,"admin port")}`]),"--entrypoint","sleep",e.image,"infinity"]}function l$(e){let t;try{t=JSON.parse(e.trim()||"null")}catch{return null}if(t===null)return[];if(typeof t!="object"||Array.isArray(t))return null;let n=[];for(let r of Object.values(t))if(Array.isArray(r))for(let o of r){let s=Number(o?.HostPort);Number.isInteger(s)&&s>0&&!n.includes(s)&&n.push(s)}return n}function On(e){let t=e===void 0?[]:typeof e=="string"?[e]:[...e];return["127.0.0.1",...new Set(t.filter(n=>n!=="127.0.0.1"))]}function Ke(e,t){if(!Number.isInteger(e)||e<1||e>65535)throw new Error(`${t} is not a port: ${JSON.stringify(e)}`);return e}function cs(e){let t=[];for(let n of Object.keys(e)){if(!Bf.test(n))throw new Error(`not an environment variable name: ${JSON.stringify(n)}`);t.push("--env",n)}return t}function Hf(e,t={}){if(t.adminPublished&&e.adminHealthPath&&el(e)){if(!Qi.test(e.adminHealthPath))throw new Error(`${e.name}: not a health path: ${JSON.stringify(e.adminHealthPath)}`);return["--label",`${us}=${e.adminHostPort}:${e.adminHealthPath}`]}let n=e.healthPath;if(n==null||n==="")return[];if(!Qi.test(n))throw new Error(`${e.name}: not a health path: ${JSON.stringify(n)}`);return e.hostPort===null||e.hostPort===void 0?[]:(Ke(e.hostPort,`${e.name}: hostPort`),["--label",`${us}=${e.hostPort}:${n}`])}function c$(e){if(!e)return null;let t=e.indexOf(":");if(t<=0)return null;let n=Number(e.slice(0,t)),r=e.slice(t+1);return!Number.isInteger(n)||n<1||n>65535||!Qi.test(r)?null:{port:n,path:r}}async function u$(e,t={}){let n=t.path??process.env.PATH??"",r=t.look??(o=>B_(o,H_.X_OK));for(let o of n.split(J_))if(o)try{let s=en(o,e);return await r(s),s}catch{}return null}function p$(){return["\\set ON_ERROR_STOP 0","set search_path = pg_catalog, pg_temp;","select 'create extension if not exists pg_prewarm schema public' where exists (select 1 from pg_available_extensions where name = 'pg_prewarm') \\gexec","select pg_catalog.format($snoutpod$with candidate as ("," select c.oid, pg_catalog.pg_relation_size(c.oid) as bytes"," from pg_class c join pg_namespace n on n.oid = c.relnamespace"," where c.relkind in ('r', 'i', 'm')"," and c.relpersistence = 'p'"," and n.nspname not in ('pg_catalog', 'information_schema', 'pg_toast')","), budgeted as ("," select oid, bytes,"," sum(bytes) over (order by bytes, oid rows between unbounded preceding and current row) as running"," from candidate",")","select coalesce(sum(%I.pg_prewarm(oid::pg_catalog.regclass, 'buffer'::pg_catalog.text, 'main'::pg_catalog.text, null::pg_catalog.int8, null::pg_catalog.int8)), 0) from budgeted","where bytes > 0 and running <= pg_size_bytes(current_setting('shared_buffers')) * 3 / 4$snoutpod$, n.nspname)","from pg_extension e join pg_namespace n on n.oid = e.extnamespace where e.extname = 'pg_prewarm' \\gexec",""].join(`
|
|
759
|
+
`)}function f$(e){return/^(\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com)\//.exec(e)?.[1]??null}function g$(e,t){for(let r of e??[]){let o=/^PG_MAJOR=(\d+)$/.exec(r.trim());if(o)return o[1]??null}let n=t.split("@")[0]??"";return/:(\d+)(?:[.-][^/:]*)?$/.exec(n)?.[1]??null}function tl(e){let t=(e??"").trim();return/^\d+(?:\.\d+)?$/.test(t)?t:null}function h$(e,t){return t.image===null||t.data===null||t.image===t.data?null:`${e} was not started: its data directory was made by Postgres ${t.data} and it was handed a Postgres ${t.image} image. A data directory starts only on the major that made it. Its data is untouched, and it starts again on a ${t.data} image.`}async function y$(e,t,n,r){return{image:await w$(e,t,r),data:await b$(e,t,n)}}async function w$(e,t,n){let r=null;try{let o=await e(t,["image","inspect","--format","{{json .Config.Env}}",n]);if(o.code===0&&o.stdout.trim()){let s=JSON.parse(o.stdout.trim());r=Array.isArray(s)?s.filter(a=>typeof a=="string"):null}}catch{r=null}return g$(r,n)}async function b$(e,t,n){try{let r=await e(t,["volume","inspect","--format","{{.Mountpoint}}",J(n).pod]),o=r.code===0?r.stdout.trim().replace(/\/+$/,""):"";if(!o)return null;let s=await e(t,["unshare","cat",`${o}/PG_VERSION`]);return s.code===0?tl(s.stdout):null}catch{return null}}function qf(e){return e.filter(t=>!!t.replicaPeer||t.guard!==void 0||t.hostRole==="standby").map(t=>({ref:t.ref,group:t.group??t.ref,container:J(t.ref).pod})).sort((t,n)=>t.ref<n.ref?-1:t.ref>n.ref?1:0)}function S$(e,t,n){if(t.size>1)return`the ${Oe} network already holds more than one project (${[...t].sort().join(", ")}), so nothing more joins it`;let r=t.size===1?[...t][0]:n;return e.group===r?null:`the ${Oe} network holds ${r}'s copies, and another project may not share its bridge`}function k$(e,t){let n=new Map,r=new Set(t.length>0?qf(e.filter(o=>!(o.guard!==void 0&&o.peerAddress))).map(o=>o.ref):[]);for(let o of e){if(o.state==="deleted"||!o.groupPeers||o.groupPeers.length===0)continue;let s=o.group??o.ref;for(let a of[...new Set(o.groupPeers)].sort()){if(a===o.peerAddress||r.has(o.ref)&&t.includes(a))continue;let l=ym(s,a),d=n.get(l)??{group:s,peer:a,containers:[]};d.containers.push(J(o.ref).pod),o.ref===s&&d.containers.push(Et(o.ref)),n.set(l,d)}}return n}function _$(e,t){let n=[];for(let[r,o]of[...t].sort(([s],[a])=>s<a?-1:s>a?1:0)){if(!Xt(o))continue;let s=Yo(r);if(s!==null){let d=e.find(c=>c.guard!==void 0&&c.state!=="deleted"&&!!c.peerAddress&&(c.group??c.ref)===s);d&&n.push({subnet:o,peer:d.peerAddress,ports:d.peerPorts?[...d.peerPorts]:null});continue}let a=vn(r);if(a===null)continue;let l=e.filter(d=>d.state!=="deleted"&&(d.group??d.ref)===a.group&&(d.groupPeers??[]).includes(a.peer));l.length>0&&n.push({subnet:o,peer:a.peer,ports:[...new Set(l.flatMap(d=>d.groupPeerPorts?.[a.peer]??[]))]})}return n}function Cf(e,t){let n=On(t);return(e.Ports??[]).some(r=>{let o=r.host_ip??"";return o!==""&&o!=="0.0.0.0"&&o!=="::"&&!n.includes(o)})}function E$(e){if(!e)return[];let t=[],n=/^[1-9][0-9]{0,6}(kB|MB|GB)$/;typeof e.sharedBuffers=="string"&&n.test(e.sharedBuffers)&&t.push(`SNOUTPOD_SHARED_BUFFERS=${e.sharedBuffers}`),typeof e.workMem=="string"&&n.test(e.workMem)&&t.push(`SNOUTPOD_WORK_MEM=${e.workMem}`);let r=typeof e.maxConnections=="number"&&Number.isInteger(e.maxConnections)&&e.maxConnections>=1&&e.maxConnections<=1e4?e.maxConnections:Lf;return t.push(`SNOUTPOD_MAX_CONNECTIONS=${Math.max(r,Lf)}`),typeof e.privilegedExtensions=="string"&&/^[a-z][a-z0-9_-]*(,[a-z][a-z0-9_-]*)*$/.test(e.privilegedExtensions)&&t.push(`SNOUTPOD_PRIVILEGED_EXTENSIONS=${e.privilegedExtensions}`),t}function A$(e){let t=null;return()=>(t===null&&(t=n()),t);async function n(){if(e.runtime===null)return[];let r=e.runtime??d$;return e.runtime!==void 0&&e.runtime!==""?["--runtime",r]:await u$(r,{look:e.lookExecutable})===null?[]:["--runtime",r]}}function zf(e){let t=e.binary??"podman",n=e.exec,r=A$(e),o=e.probe??Gf;async function s(m){try{await n(t,["exec",...Ae,"--interactive",J(m).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",m,"--quiet","--file","-"],{timeoutMs:m$,stdin:p$()})}catch{}}async function a(){let[m,f,h]=await Promise.all([L(n,t,["ps","--all","--filter",`label=${qe}`,"--format","json"]),L(n,t,["ps","--all","--filter",`label=${Ut}`,"--format","json"]),L(n,t,["ps","--all","--filter",`label=${At}`,"--format","json"])]),b=await E(m.trim()?JSON.parse(m):[],!0),S=new Map;for(let q of h.trim()?JSON.parse(h):[]){let K=g(q);K&&S.set(K,(S.get(K)??!1)||q.State==="running")}let k=[...b.flatMap(q=>{let K=q.Labels?.[Ve]?q.Labels?.[At]:void 0;return K===void 0?[q]:S.has(K)?[S.get(K)?q:{...q,State:"exited"}]:[]}),...(f.trim()?JSON.parse(f):[]).flatMap(q=>{let K=q.Labels?.[Ut];return K?[{...q,Labels:{...q.Labels,[qe]:K,[Ve]:ye}}]:[]})],x=new Map,_=new Map,M=new Map,F=new Map,X=new Set([...S.keys(),...(f.trim()?JSON.parse(f):[]).flatMap(q=>q.Labels?.[Ut]??[])]);for(let q of k){let K=q.Labels?.[qe],D=q.Labels?.[Ve];if(!K||!D)continue;if(Tf(Vi(q))){F.set(K,[...F.get(K)??[],D]);continue}let ne=x.get(K)??[];ne.push(D),x.set(K,ne),Yi(q.State)==="stopped"&&_.set(K,[..._.get(K)??[],D]);let ge=Number(q.Labels?.[Tn]??0),Ce=Number.isInteger(ge)?ge:0;M.set(K,Math.max(M.get(K)??Ce,Ce))}let j=k.filter(q=>q.Labels?.[qe]&&!q.Labels?.[Ve]),v=j.map(q=>N$(q,Date.now())?"stopped":Yi(q.State)),H=await T$(j,R$,(q,K)=>v[K]==="running"?Promise.resolve(!0):e.hasData(q.Labels?.[qe]??""));return j.map((q,K)=>{let D=q.Labels?.[qe]??"",ne=Number(q.Labels?.[Ji]);return{ref:D,status:v[K]??"unknown",generation:Number.isInteger(ne)?ne:null,hasData:H[K]??!1,services:x.get(D)??[],servicesStopped:_.get(D)??[],...X.has(D)?{separated:!0}:{},...F.has(D)?{setAside:F.get(D)}:{},...Cf(q,e.podBind)?{boundElsewhere:!0}:{},...M.has(D)?{servicesGeneration:M.get(D)}:{}}})}async function l(){let m=await L(n,t,["ps","--all","--filter",`label=${qe}`,"--format","json"]);return(m.trim()?JSON.parse(m):[]).filter(h=>h.Labels?.[qe]&&!h.Labels?.[Ve]).length}async function d(m){let f=await(e.majors??((h,b)=>y$(n,t,h,b)))(m.ref,m.image);return h$(m.ref,f)}async function c(m){let f=J(m.ref),h=await d(m);if(h)throw new Error(h);let b=e.credentials,S=await Wm(e.repository,b?()=>b.forProject(m.ref,m.bucket):null),k={SNOUTPOD_OWNER_PASSWORD:m.ownerPassword,POSTGRES_PASSWORD:m.adminPassword,...Vm(S)},x=[...await r(),"run","--detach","--name",f.pod,"--label",`${qe}=${m.ref}`,"--label",`${Ji}=${m.generation}`,"--userns=auto","--memory",`${m.memoryMb}m`,"--pids-limit",String($$),...L$(m.cpus),"--restart","no",...e.network?["--network",e.network]:[],...m.port?On(e.podBind).flatMap(_=>["--publish",`${_}:${m.port}:5432`]):[],...s$(li(m),e.podBind),"--volume",`${f.pod}:/var/lib/postgresql/data:U`,"--env","SNOUTPOD_OWNER_PASSWORD","--env","POSTGRES_PASSWORD","--env",`SNOUTPOD_REF=${m.ref}`,"--env","POSTGRES_USER=snoutpod_admin","--env","POSTGRES_DB=postgres","--env",`SNOUTPOD_S3_BUCKET=${m.bucket}`,"--env",`SNOUTPOD_S3_REGION=${m.region}`,...e.egressDenied?["--env","SNOUTPOD_EGRESS=denied"]:[],...C$(m.oauth),...E$(m.tuning).flatMap(_=>["--env",_]),"--env",`SNOUTPOD_RETENTION_FULL=${jp(m.backup?.retentionDays,m.backup?.fullIntervalHours)}`,...Jm(S),m.image,"snoutpod-postgres"];await L(n,t,x,{env:k})}async function i(m){return(await B(m)).services}async function p(m){return(await i(m)).filter(f=>!f.setAside)}function g(m){return m.Labels?.[Ve]?void 0:m.Labels?.[At]}async function E(m,f){let h=e.inPlaceRoot;if(h===void 0)return m;let b=await q_(h).catch(()=>[]);if(b.length===0)return m;let S=new Set(m.flatMap(x=>x.Id?[x.Id]:[])),k=new Map;for(let x of b){let _=x.endsWith(".json")?x.slice(0,-5):"";if(!Rf.test(_))continue;if(!S.has(_)){f&&await z_(en(h,x),{force:!0});continue}let M=e$(await G_(en(h,x),"utf8").catch(()=>""));M!==null&&k.set(_,M)}return m.map(x=>{let _=x.Id&&x.Labels?.[Ve]?k.get(x.Id):void 0;return _===void 0?x:{...x,Labels:{...x.Labels,[gr]:_.spec,[Tn]:String(_.generation)}}})}async function A(m){let f=await n(t,["container","inspect","--format","{{.HostConfig.Memory}} {{.HostConfig.MemorySwap}}",m]),[h,b]=f.code===0?f.stdout.trim().split(/\s+/).map(Number):[];return h!==void 0&&Number.isInteger(h)&&h>0&&b!==void 0&&Number.isInteger(b)?{bytes:h,swap:b}:null}async function te(m,f,h){let b=h.swap===-1?["--memory-swap","-1"]:h.swap>h.bytes?["--memory-swap",`${f+Math.floor((h.swap-h.bytes)/An)}m`]:[];if((await n(t,["update","--memory",`${f}m`,...b,m])).code!==0)return!1;let k=await A(m);return k!==null&&k.bytes===f*An}async function U(m,f){let h=e.inPlaceRoot;if(h===void 0||!Rf.test(m))return;await vf(h,{recursive:!0});let b=en(h,`${m}.json`);await W_(`${b}.tmp`,JSON.stringify(f)),await K_(`${b}.tmp`,b)}async function B(m){let[f,h,b]=await Promise.all([L(n,t,["ps","--all","--filter",`label=${qe}=${ae(m)}`,"--filter",`label=${Ve}`,"--format","json"]),L(n,t,["ps","--all","--filter",`label=${Ut}=${m}`,"--format","json"]),L(n,t,["ps","--all","--filter",`label=${At}=${m}`,"--format","json"])]),S=await E(f.trim()?JSON.parse(f):[],!1),k=[];for(let _ of S){let M=_.Labels?.[Ve];if(!M)continue;let F=Number(_.Labels?.[Tn]??0),X=Tf(Vi(_));k.push({name:M,container:X?Vi(_)??"":Af(m,M),id:_.Id??"",spec:_.Labels?.[gr]??"",pod:_.Labels?.[Pf]??"",running:_.State==="running",generation:Number.isInteger(F)?F:0,separate:!1,stack:_.Labels?.[At]===m,setAside:X})}for(let _ of h.trim()?JSON.parse(h):[]){if(_.Labels?.[Ut]!==m)continue;let M=Number(_.Labels?.[Tn]??0);k.push({name:ye,container:Et(m),id:_.Id??"",spec:_.Labels?.[gr]??"",pod:"",running:_.State==="running",generation:Number.isInteger(M)?M:0,separate:!0,stack:!1,setAside:!1})}let x=null;for(let _ of b.trim()?JSON.parse(b):[])g(_)===m&&(x={id:_.Id??"",spec:_.Labels?.[Gi]??"",running:_.State==="running"});return{services:k,anchor:x}}async function C(m){let f=await n(t,["container","inspect","--format","{{.Id}}",m]);return f.code===0?f.stdout.trim():""}function ue(m,f){return f?.databaseOnly?{services:m.services.filter(h=>!h.separate&&!h.stack),anchor:null}:m}async function G(m,f,h=new Map){let b=[];for(let X of f){let j=X.dbUriRole??null;X.dbUriEnv&&j&&!b.includes(j)&&b.push(Bt(j))}let S=new Map;if(b.length===0)return S;let k=await e.fixedRolePasswords?.()??new Map,x={},_=[],M=[];b.some(X=>Di.includes(X))&&M.push(Xm,Zm);for(let X of b.filter(j=>ji.includes(j)))M.push(Qm(X));let F=new Map;if(m.derivedServicePasswords===!0)for(let X of b.filter(Ti))F.set(X,await Oi(m.adminPassword,X));return b.forEach((X,j)=>{let v=k.get(X)??(F.has(X)?void 0:h.get(X));if(v!==void 0){S.set(X,v);return}let H=F.get(X)??F_(24).toString("base64url"),q=`SNOUTPOD_SERVICE_PASSWORD_${j}`;S.set(X,H),x[q]=H,_.push("--env",q),M.push(`\\getenv service_password_${j} ${q}`),M.push(`\\set service_role_${j} ${X}`),M.push(`alter role :"service_role_${j}" with password :'service_password_${j}';`)}),M.push(""),await L(n,t,["exec",...Ae,"--interactive",..._,J(m.ref).pod,"psql","--username","snoutpod_admin","--dbname",J(m.ref).database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:x,stdin:M.join(`
|
|
760
|
+
`)}),S}async function se(m,f,h){let b=new Map;for(let x of h){let _=x.dbUriRole,M=f.find(j=>j.name===x.name);if(!x.dbUriEnv||!_||b.has(_)||M===void 0)continue;let F=await n(t,["container","inspect","--format","{{range .Config.Env}}{{println .}}{{end}}",M.container]),X=F.code===0?Q_(F.stdout,x.dbUriEnv,Bt(_)):null;X!==null&&b.set(_,X)}if(b.size===0)return b;let S=await n(t,["exec",...Ae,J(m.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select rolname || ' ' || coalesce(rolpassword, '') from pg_authid where rolname in (${[...b.keys()].map(x=>`'${x}'`).join(", ")})`]),k=new Map;if(S.code===0)for(let x of S.stdout.split(`
|
|
761
|
+
`)){let[_,M]=x.trim().split(" ");_&&M&&k.set(_,M)}for(let[x,_]of b)ur(k.get(x)??"",_)||b.delete(x);return b}async function ee(m){let f=cr(m.ref);await L(n,t,["volume","create","--ignore",f]),await L(n,t,[...await r(),"run","--rm","--network","none","--volume",`${f}:${Bo}`,"--entrypoint","bash",m.image,"-c",Np])}async function fe(m){let f=await r();if((await n(t,[...f,"image","exists",m])).code===0)return;let h=await n(t,[...f,"pull","--quiet",m]);if(h.code===0)return;let b=f$(m);if(!b||!e.registryLogin)throw new Error(`${m} could not be pulled: ${(h.stderr||h.stdout).trim()}`);await e.registryLogin(b),await L(n,t,[...f,"pull","--quiet",m])}async function it(m){let f=await n(t,["container","inspect","--format","{{json .HostConfig.PortBindings}}",J(m).pod]);return f.code===0?l$(f.stdout):null}async function bt(m,f={}){let h=m.services??[],b=gt(m)?[...h.filter(P=>P.name===ye),...h.filter(P=>P.name!==ye)]:h,{services:S,anchor:k}=await B(m.ref),x=S.filter(P=>!P.setAside),_;b.some(P=>P.smtpSecretEnv)&&(_=await e.smtpSecret?.().catch(()=>{}));let M=new Map(x.map(P=>[P.name,P])),F=P=>gt(m)&&P.name===ye,X=b.filter(P=>Zt(m,P)),j="";if(X.length>0){if(!b.some(P=>P.name===ye))throw new Error(`${m.ref}: a services-only pod reaches its database through the router, and spec.services has no ${ye}`);if(!e.network)throw new Error(`${m.ref}: a services-only pod needs the pod network`);if(X.some(P=>P.name===is))throw new Error(`${m.ref}: a service may not be called ${is}, which is the services-only pod's own name`);j=_f(m,e.network)}let v=X.length>0&&k!==null&&k.running&&k.id!==""&&k.spec===j,H=b.some(P=>!F(P)&&!Zt(m,P))?await C(J(m.ref).pod):"",q=b.some(P=>!F(P)&&!Zt(m,P)&&el(P))?new Set(await it(m.ref)??[]):new Set,K=v?k?.id??"":"",D=P=>Zt(m,P)?K:H,ne=P=>F(P)?V_(P,m.routerPodPort):Uf(Zt(m,P)?Ki(m,P):P,_,ds(m,P),Zi(m,P)),ge=new Map(b.map(P=>[P.name,ne(P)])),Ce=m.servicesGeneration??0,Ze=new Set;if(e.inPlaceRoot!==void 0)for(let P of b){let we=M.get(P.name),Ue=D(P);if(F(P)||!we||!we.running||we.id===""||Ue===""||we.pod!==Ue||we.spec===ge.get(P.name))continue;let ot=await A(we.container);ot===null||ot.bytes%An!==0||ot.bytes/An>=P.memoryMb||ne({...P,memoryMb:ot.bytes/An})===we.spec&&await te(we.container,P.memoryMb,ot)&&(await U(we.id,{spec:ge.get(P.name)??"",generation:Ce}),Ze.add(P.name),e.log?.(`${m.ref}: ${P.name} took ${P.memoryMb} MB in place (was ${ot.bytes/An} MB), not stopped`))}let Ne=new Set(b.filter(P=>{let we=M.get(P.name);if(Ze.has(P.name))return!1;if(!we||!we.running||we.spec!==ge.get(P.name))return!0;let Ue=D(P);return!F(P)&&(Ue===""||we.pod!==Ue)}).map(P=>P.name));if(f.renewPasswords)for(let P of b)P.dbUriEnv&&P.dbUriRole&&Ne.add(P.name);if(Ne.size===0&&Ze.size===0&&b.length>0&&!x.some(P=>P.generation>=Ce))for(let P of b)Ne.add(P.name);let xl=P=>P.dbUriEnv&&P.dbUriRole?P.dbUriRole:null;for(let P=!0;P;){P=!1;let we=new Set(b.filter(Ue=>Ne.has(Ue.name)).map(xl));for(let Ue of b){let ot=xl(Ue);!Ne.has(Ue.name)&&ot!==null&&we.has(ot)&&(Ne.add(Ue.name),P=!0)}}let El=new Set(b.filter(P=>Ne.has(P.name)).map(P=>P.image));(X.length>0&&!v||Ne.has(ye))&&El.add(m.image);for(let P of El)await fe(P);let xh=P=>f.keepSeparated===!0&&(P.separate||P.stack)&&!Ne.has(P.name);for(let P of x)(Ne.has(P.name)||!ge.has(P.name))&&!xh(P)&&await L(n,t,["rm","--force","--ignore",P.container]);if(k!==null&&!v&&!(f.keepSeparated===!0&&X.length===0)&&await L(n,t,["rm","--force","--ignore",ht(m.ref)]),X.length>0&&!v){if(await L(n,t,[...await r(),...i$(m,{network:e.network,bind:e.podBind,fingerprint:j})]),K=await C(ht(m.ref)),K==="")throw new Error(`${m.ref}: the services-only pod was made and its id could not be read`);await f.afterStart?.(ht(m.ref))}let Rr=b.filter(P=>Ne.has(P.name)),Al=S.filter(P=>P.setAside),Es=await G(m,Rr,Al.length>0&&!f.renewPasswords?await se(m,Al,Rr):new Map);Rr.some(P=>P.name===ye)&&await ee(m);for(let P of Rr){if(F(P)){let Rl=di(Tp(m.ref,P.env),m.adminPassword);await L(n,t,[...await r(),...a$(m,P,{network:e.network,bind:e.podBind,fingerprint:ge.get(P.name)??"",envNames:cs(Rl).filter(Ah=>Ah!=="--env")})],{env:Rl}),await f.afterStart?.(Et(m.ref));continue}let we=Zt(m,P),Ue=we?ht(m.ref):J(m.ref).pod,ot=Af(m.ref,P.name),Eh=[...await r(),"run","--detach","--name",ot,"--label",`${qe}=${m.ref}`,"--label",`${Ji}=${m.generation}`,"--label",`${Ve}=${P.name}`,"--label",`${Tn}=${m.servicesGeneration??0}`,"--label",`${gr}=${ge.get(P.name)??""}`,"--label",`${Pf}=${D(P)}`,...we?["--label",`${At}=${m.ref}`]:[],"--network",`container:${Ue}`,"--userns",`container:${Ue}`,"--memory",`${P.memoryMb}m`,"--pids-limit",String(Kf),"--restart","no",...Hf(we?Ki(m,P):P,{adminPublished:we||P.adminHostPort!==null&&P.adminHostPort!==void 0&&q.has(P.adminHostPort)}),...P.name===ye?["--volume",`${cr(m.ref)}:${Bo}:ro`]:[],...cs(Ef(m,P,Es,_)),P.image];Ne.has(ye)||await Ye(m,P,Es),await L(n,t,Eh,{env:Ef(m,P,Es,_)})}}async function Ye(m,f,h){let b=ds(m,f),S=f.dbUriRole,k=S?h.get(S):void 0;if(b===void 0||b===kn||!S||k===void 0)return;let x=J(m.ref),_=Zi(m,f)??"127.0.0.1",{waitMs:M,retryMs:F}=e.routerLogin??{waitMs:v$,retryMs:P$},X=Date.now()+M;for(let j=1;;j++){let v=await n(t,["exec","--env","PGPASSWORD","--env","PGSSLMODE=disable","--env","PGCONNECT_TIMEOUT=3",x.pod,"psql","--host",_,"--port",String(b),"--username",Bt(S),"--dbname",x.database,"--no-password","--tuples-only","--no-align","--command","select 1"],{env:{PGPASSWORD:k}});if(v.code===0){e.log?.(j===1?`${m.ref}: the router took ${S}'s password at once, ${f.name} starts`:`${m.ref}: the router took ${S}'s password on try ${j}, after ${j-1} refused, ${f.name} starts`);return}if(Date.now()>=X){let H=`${v.stderr}
|
|
762
|
+
${v.stdout}`.trim().split(`
|
|
763
|
+
`).filter(Boolean).pop()??`exit ${v.code}`;throw new Error(`${m.ref}: the router did not take ${S}'s new password within ${M}ms (${j} tries; last: ${H}), so ${f.name} was not started`)}await new Promise(H=>setTimeout(H,F))}}async function Sl(m,f){if(f%6!==0)return!1;let h=await n(t,["container","inspect","--format","{{.State.Status}}",J(m).pod]);return h.code===0&&/^(exited|stopped|dead)$/.test(h.stdout.trim())}function Re(m){return["exec",...Ae,J(m).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres"]}async function Qg(m){let f=await n(t,[...Re(m),"-tAc",rm]);return f.code===0?om(f.stdout):null}async function eh(m){let f=await n(t,[...Re(m),"-tAc","select case when pg_is_in_recovery() then '' else pg_current_wal_lsn()::text end"]),h=f.code===0?f.stdout.trim():"";return/^[0-9A-F]{1,8}\/[0-9A-F]{1,8}$/.test(h)?h:null}async function kl(m){let f=await n(t,[...Re(m),"-tAc","select pg_is_in_recovery()"]);if(f.code!==0)return null;let h=f.stdout.trim();return h==="t"?!0:h==="f"?!1:null}async function th(m,f){let h=x=>n(t,[...Re(m),"-tAc",x]),b=async()=>{let x=await h("select case when pg_is_in_recovery() then 'r' when (select timeline_id from pg_control_checkpoint()) = ('x' || substr(pg_walfile_name(pg_current_wal_lsn()), 1, 8))::bit(32)::int then 't' else 'f' end"),_=x.stdout.trim();return x.code===0&&(_==="t"||_==="f"||_==="r")?_:null},S=await b();if(S!=="f")return S==="t";let k=Date.now()+f;do{if((await h("checkpoint")).code!==0)return!1;if(await b()==="t")return!0;await new Promise(_=>setTimeout(_,1e3))}while(Date.now()<k);return!1}async function nh(m){let f=await n(t,[...Re(m),"-tAc",Bp],{timeoutMs:yt});return f.code===0?Hp(f.stdout):null}async function rh(m,f){let h=new Map;for(let S of f){if(typeof S!="string"){ae(S.ref);let k=em(S);k&&h.set(S.ref,k);continue}ae(S),h.set(S,J(S).pod)}if(h.size===0)return new Map;let b=await n(t,["exec",J(m).pod,"timeout",String(10),"sh","-c",tm,"sh",...h.values()]);return b.code===0?nm(b.stdout,h):null}async function oh(m,f){ae(f);let h=[];for(let x of[m,f]){let _=J(x).pod,M=await n(t,["container","inspect","--format","{{.State.Status}}",_]);if(M.code===0&&M.stdout.trim()==="running")throw new Error(`${_} is still running, so its data was not moved`);let F=await n(t,["volume","inspect","--format","{{.Mountpoint}}",_]),X=F.code===0?F.stdout.trim().replace(/\/+$/,""):"";if(!X)throw new Error(`the volume ${_} could not be found, so nothing was moved`);h.push(X)}let S=typeof process.getuid!="function"||process.getuid()!==0?await n(t,["unshare","sh","-c",wi,"sh",h[0],h[1]]):await n("sh",["-c",wi,"sh",h[0],h[1]]),k=Wp(S.stdout,S.code);if(k)throw new Error(k)}async function sh(m,f){ae(m),ae(f);for(let _ of[m,f]){let M=J(_).pod,F=await n(t,["container","inspect","--format","{{.State.Status}}",M]);if(F.code===0&&F.stdout.trim()==="running")throw new Error(`${M} is running, so no data was moved`)}let h=J(m).pod;(await n(t,["volume","exists",h])).code!==0&&await L(n,t,["volume","create",h]);let b=[];for(let _ of[h,J(f).pod]){let M=await n(t,["volume","inspect","--format","{{.Mountpoint}}",_]),F=M.code===0?M.stdout.trim().replace(/\/+$/,""):"";if(!F)throw new Error(`the volume ${_} could not be found, so nothing was moved`);b.push(F)}let k=typeof process.getuid!="function"||process.getuid()!==0?await n(t,["unshare","sh","-c",bi,"sh",b[0],b[1]]):await n("sh",["-c",bi,"sh",b[0],b[1]]),x=Jp(k.stdout,k.code);if(x)throw new Error(x)}async function ah(m){return(await n(t,[...Re(m),"-v","ON_ERROR_STOP=1",...Si.flatMap(h=>["-c",h])])).code===0}async function ih(m){let f=e.guardRoot;if(!f)return;let h=await L(n,t,["ps","--all","--filter",`label=${as}`,"--format","json"]),b=new Map((h.trim()?JSON.parse(h):[]).flatMap(k=>{let x=k.Labels?.[as];return x?[[x,{fingerprint:k.Labels?.[Hi]??"",status:Yi(k.State),startedAt:k.StartedAt??0}]]:[]})),S=new Set(m.map(({spec:k})=>k.ref));for(let k of b.keys())S.has(k)||await L(n,t,["rm","--force","--ignore",xn(k)]);for(let{spec:k,guard:x}of m){if(k.port===null)continue;let _=cf(x,k.port,k.generation,j=>hr("sha256").update(j).digest("hex")),M=b.get(k.ref);if(M?.fingerprint===_){if(M.status!=="running")await L(n,t,["start",xn(k.ref)]);else{let j=en(f,k.ref,"status.json"),v=await n(t,["unshare","stat","-c","%Y",j]),H=v.code===0?Number(v.stdout.trim()):null;uf(M.startedAt,Number.isFinite(H)?H:null,Math.floor(Date.now()/1e3),x)&&await L(n,t,["restart",xn(k.ref)])}continue}await L(n,t,["rm","--force","--ignore",xn(k.ref)]);let F=en(f,k.ref);await vf(F,{recursive:!0,mode:448}),x.witnessCa&&await L(n,t,["unshare","sh","-c",'umask 022 && printf %s "$1" > "$2.tmp" && mv "$2.tmp" "$2"',"witness-ca",x.witnessCa,en(F,Bi)]),await fe(x.image);let X=lf(x,k.port,k.adminPassword);await L(n,t,[...await r(),...df(k.ref,x,{hostDir:F,fingerprint:_,envNames:cs(X).filter(j=>j!=="--env")})],{env:X})}}async function lh(m){return(await n(t,[...Re(m),"-v","ON_ERROR_STOP=1","-c",yi],{timeoutMs:yt})).code===0}async function ch(m,f){return(await n(t,[...Re(m),"-v","ON_ERROR_STOP=1",...qp(f).flatMap(b=>["-c",b])],{timeoutMs:yt})).code===0}async function dh(){let m=e.network;if(!m)return null;let f=(await L(n,t,["network","inspect",m,"--format","{{range .Subnets}}{{.Subnet}} {{end}}"])).trim().split(" ")[0]??"";if(f==="")return null;let h=await L(n,t,["ps","--format","json"]),S=(h.trim()?JSON.parse(h):[]).map(_=>{let M=_.Labels?.[qe],F=_.Labels?.[Rn],X=_.Labels?.[Ut];if(X)return{name:Et(X),ref:X,service:!1,role:"router"};let j=_.Labels?.[At];if(j&&!_.Labels?.[Ve])return{name:ht(j),ref:j,service:!1};let v=_.Labels?.[mf],H=_.Labels?.[ff];if(v&&(!H||H===ye)){let q=gf(v);return{name:H?q.router:q.anchor,ref:v,service:!1}}return M&&!_.Labels?.[Ve]?{name:J(M).pod,ref:M,service:!1,role:"pod"}:F?{name:Qt(F),ref:F,service:!0}:null}).filter(_=>_!==null);if(S.length===0)return{subnet:f,containers:[]};let k=await L(n,t,["inspect","--format",`{{.Name}} {{with index .NetworkSettings.Networks "${m}"}}{{.IPAddress}}{{end}}`,...S.map(_=>_.name)]),x=new Map(k.split(`
|
|
764
|
+
`).map(_=>_.trim().split(" ")).filter(_=>_.length===2&&_[1]!=="").map(([_,M])=>[_,M]));return{subnet:f,containers:S.flatMap(_=>x.has(_.name)?[{ref:_.ref,ip:x.get(_.name),service:_.service,..._.role?{role:_.role}:{}}]:[])}}async function uh(){let m=await n(t,["network","ls","--filter",`label=${Cp}`,"--format","json"]);return m.code===0?Lp(m.stdout):null}async function ph(m,f){if(!e.quotaRequests||!Number.isInteger(f)||f<1)return!1;let{writeFile:h,rename:b}=await import("node:fs/promises"),S=J(m).pod,k=`${e.quotaRequests}/${S}`;return await h(`${e.quotaRequests}/.${S}.tmp`,`${f}
|
|
765
|
+
`),await b(`${e.quotaRequests}/.${S}.tmp`,k),!0}async function _l(m,f,h){if(!Number.isInteger(h)||h<1)return!1;let b=await n(t,[...Re(m),"-tAc",`select setting::bigint * pg_size_bytes(case when unit ~ '^[0-9]' then unit else '1' || unit end) / 1048576 from pg_settings where name = '${f}'`]);return b.code===0&&b.stdout.trim()===String(h)?!0:(await n(t,[...Re(m),"-v","ON_ERROR_STOP=1","-c",`alter system set ${f} = '${h}MB'`,"-c","select pg_reload_conf()"],{timeoutMs:yt})).code===0}function mh(m,f){return _l(m,"temp_file_limit",f)}function fh(m,f){return _l(m,"max_wal_size",f)}async function gh(m){return(await n(t,["unshare","--rootless-netns",If,"-f","-"],{stdin:m,timeoutMs:yt})).code===0}let vs=null,Ps=null,Xe=new Map,Er=0;async function hh(m,f){let h=m.join(",");if(vs===h)return!0;let b=await n(t,["network","inspect",Oe]);if(b.code===0&&Xo(b.stdout,m))return vs=h,f("network",null),!0;if(b.code===0){let k=(await L(n,t,["ps","--all","--filter",`network=${Oe}`,"--format","{{.Names}}"])).trim();if(k!=="")return f("network",`WARNING: the ${Oe} network does not route exactly to ${m.join(", ")}, and ${k.split(`
|
|
766
|
+
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`),!1;await L(n,t,["network","rm",Oe])}let S=await n(t,Vo(m));return S.code!==0?(f("network",`WARNING: the ${Oe} network could not be made: ${(S.stderr||S.stdout).trim().split(`
|
|
767
|
+
`)[0]}`),!1):(vs=h,f("network",null),f("made",null),f("made",`made the ${Oe} network, routing only to ${m.join(", ")}`),!0)}async function yh(m,f={}){let h=await $l(m),b=[...await wh(m),...await bh(m),...await Sh(m,f.groupPeers===!0)],S=await $l(m);return[...h,...b,...S]}let nn=null;async function $l(m){if(Er===0&&Ar===0&&nn===null&&!m.some(x=>xs(x)||(x.groupPeers??[]).length>0))return[];let f=await n(t,["network","ls","--format","json"]);if(f.code!==0)return[];let h=new Map;for(let x of f.stdout.trim()?JSON.parse(f.stdout):[])x.name&&Ri(x.name)&&h.set(x.name,x.subnets?.[0]?.subnet??"");if(h.size===0&&nn===null)return[];let b=h.size===0?bm:wm(_$(m,h)),S=Date.now();if(nn&&nn.script===b&&S-nn.at<15e3)return[];let k=await n(t,["unshare","--rootless-netns",If,"-f","-"],{stdin:b,timeoutMs:yt});if(k.code!==0){let x=`WARNING: the peer networks' filter could not be loaded: ${(k.stderr||k.stdout).trim().split(`
|
|
768
|
+
`)[0]}`;return Xe.get("filter")!==x?(Xe.set("filter",x),[x]):[]}return Xe.delete("filter"),nn=h.size===0?null:{script:b,at:S},[]}function xs(m){return m.guard!==void 0&&m.state!=="deleted"&&!!m.peerAddress}async function wh(m){let f=[...new Set(e.peers??[])].sort(),h=qf(m.filter(D=>!xs(D)));if(f.length===0||h.length===0)return[];let b=[],S=(D,ne)=>{ne===null?Xe.delete(D):Xe.get(D)!==ne&&(Xe.set(D,ne),b.push(ne))},k=await L(n,t,["ps","--format","json"]),x=new Set((k.trim()?JSON.parse(k):[]).flatMap(D=>D.Names??[])),_=h.filter(D=>x.has(D.container));if(_.length===0)return b;let M=f.join(",");if(Ps?.key!==M){let D=e.network?await n(t,["network","inspect",e.network]):null,ne=D?.code===0?Zo(D.stdout,f):[];Ps={key:M,peers:f.filter(ge=>!ne.includes(ge))}}let F=Ps.peers;if(F.length===0||!await hh(F,S))return b;let X=await L(n,t,["inspect","--format","{{.Name}} {{range $name, $value := .NetworkSettings.Networks}}{{$name}} {{end}}",..._.map(D=>D.container)]),j=new Set(X.split(`
|
|
769
|
+
`).map(D=>D.trim().split(/\s+/)).filter(D=>D.slice(1).includes(Oe)).map(D=>D[0])),v=_.filter(D=>!j.has(D.container));if(v.length===0)return b;let H=new Map(m.map(D=>[D.ref,D.group??D.ref])),q=await L(n,t,["ps","--all","--filter",`network=${Oe}`,"--format","json"]),K=new Set((q.trim()?JSON.parse(q):[]).map(D=>D.Labels?.[qe]).filter(D=>!!D).map(D=>H.get(D)??D));for(let D of v){let ne=S$(D,K,v[0].group);if(ne){S(D.container,`${D.container} does not join ${Oe}: ${ne}`);continue}let ge=await n(t,["network","connect",Oe,D.container]);if(ge.code!==0){S(D.container,`WARNING: ${D.container} could not join the ${Oe} network, so it has no route to ${F.join(", ")}: `+(ge.stderr||ge.stdout).trim().split(`
|
|
770
|
+
`)[0]);continue}K.add(D.group),S(D.container,null),b.push(`${D.container} joined the ${Oe} network: its route to ${F.join(", ")} comes from there`)}return b}async function bh(m){let f=m.filter(xs),h=[],b=(j,v)=>{v===null?Xe.delete(j):Xe.get(j)!==v&&(Xe.set(j,v),h.push(v))};if(f.length===0&&Er===0)return h;let S=await n(t,["network","ls","--format","json"]);if(S.code!==0)return h;let k=new Map,x=[];for(let j of S.stdout.trim()?JSON.parse(S.stdout):[])j.name&&Yo(j.name)!==null?k.set(j.name,j.subnets?.[0]?.subnet??""):j.name&&vn(j.name)!==null&&x.push(j.subnets?.[0]?.subnet??"");Er=k.size;let _=await L(n,t,["ps","--format","json"]),M=new Set((_.trim()?JSON.parse(_):[]).flatMap(j=>j.Names??[])),F=f.length>0&&e.network?await n(t,["network","inspect",e.network]):null,X=new Set;for(let j of f){let v=j.group??j.ref,H=hm(v),q=J(j.ref).pod;X.add(H);let K=j.peerAddress;if(F?.code===0&&Zo(F.stdout,[K]).length>0||!M.has(q))continue;let D=k.has(H)?Xt(k.get(H)):null,ne=!1;if(D){let Ze=await n(t,["network","inspect",H]);ne=Ze.code===0&&Xo(Ze.stdout,[K],D)}if(!ne&&k.has(H)){let Ze=(await L(n,t,["ps","--all","--filter",`network=${H}`,"--format","{{.Names}}"])).trim();if(Ze!==""){b(H,`WARNING: the ${H} network does not route exactly to ${K}, and ${Ze.split(`
|
|
771
|
+
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`);continue}await L(n,t,["network","rm",H]),k.delete(H)}if(!ne){let Ze=D&&D.subnet||Ai([...k.values(),...x]);if(D=Ze?Xt(Ze):null,!D){b(H,`WARNING: no /28 is free for the ${H} network, so ${q} has no route to ${K}`);continue}let Ne=await n(t,Vo([K],{name:H,subnet:D.subnet,gateway:D.gateway}));if(Ne.code!==0){b(H,`WARNING: the ${H} network could not be made: ${(Ne.stderr||Ne.stdout).trim().split(`
|
|
772
|
+
`)[0]}`);continue}k.set(H,D.subnet),h.push(`made the ${H} network (${D.subnet}), routing only to ${K}`)}if((await L(n,t,["inspect","--format","{{range $name, $value := .NetworkSettings.Networks}}{{$name}} {{end}}",q])).trim().split(/\s+/).includes(H)){b(H,null);continue}let Ce=await n(t,["network","connect",H,q]);if(Ce.code!==0){b(H,`WARNING: ${q} could not join the ${H} network, so it has no route to ${K}: ${(Ce.stderr||Ce.stdout).trim().split(`
|
|
773
|
+
`)[0]}`);continue}b(H,null),h.push(`${q} joined the ${H} network: its route to ${K} comes from there`)}for(let j of k.keys()){if(X.has(j))continue;(await L(n,t,["ps","--all","--filter",`network=${j}`,"--format","{{.Names}}"])).trim()===""&&(await n(t,["network","rm",j])).code===0&&(k.delete(j),h.push(`removed the ${j} network: its pair is no longer on this host`))}return Er=k.size,h}let Ar=0;async function Sh(m,f){let h=[],b=(v,H)=>{H===null?Xe.delete(v):Xe.get(v)!==H&&(Xe.set(v,H),h.push(H))},S=k$(m,e.peers??[]);if(S.size===0&&Ar===0)return h;let k=await n(t,["network","ls","--format","json"]);if(k.code!==0)return h;let x=new Map,_=[];for(let v of k.stdout.trim()?JSON.parse(k.stdout):[]){let H=v.subnets?.[0]?.subnet??"";v.name&&Ri(v.name)&&_.push(H),v.name&&vn(v.name)!==null&&x.set(v.name,H)}Ar=x.size;let M=await L(n,t,["ps","--format","json"]),F=new Set((M.trim()?JSON.parse(M):[]).flatMap(v=>v.Names??[])),X=S.size>0&&e.network?await n(t,["network","inspect",e.network]):null;for(let[v,H]of[...S].sort(([q],[K])=>q<K?-1:q>K?1:0)){if(X?.code===0&&Zo(X.stdout,[H.peer]).length>0)continue;let q=H.containers.filter(ne=>F.has(ne));if(q.length===0)continue;let K=x.has(v)?Xt(x.get(v)):null,D=!1;if(K){let ne=await n(t,["network","inspect",v]);D=ne.code===0&&Xo(ne.stdout,[H.peer],K)}if(!D&&x.has(v)){let ne=(await L(n,t,["ps","--all","--filter",`network=${v}`,"--format","{{.Names}}"])).trim();if(ne!==""){b(v,`WARNING: the ${v} network does not route exactly to ${H.peer}, and ${ne.split(`
|
|
774
|
+
`).join(", ")} is on it, so it is left as it is: remake it once nothing is connected`);continue}await L(n,t,["network","rm",v]),_.splice(_.indexOf(x.get(v)),1),x.delete(v)}if(!D){let ne=K&&K.subnet||Ai(_);if(K=ne?Xt(ne):null,!K){b(v,`WARNING: no /28 is free for the ${v} network, so ${q.join(", ")} has no route to ${H.peer}`);continue}let ge=await n(t,Vo([H.peer],{name:v,subnet:K.subnet,gateway:K.gateway}));if(ge.code!==0){b(v,`WARNING: the ${v} network could not be made: ${(ge.stderr||ge.stdout).trim().split(`
|
|
775
|
+
`)[0]}`);continue}x.set(v,K.subnet),_.push(K.subnet),h.push(`made the ${v} network (${K.subnet}), routing only to ${H.peer}`)}for(let ne of q){if((await L(n,t,["inspect","--format","{{range $name, $value := .NetworkSettings.Networks}}{{$name}} {{end}}",ne])).trim().split(/\s+/).includes(v)){b(`${v} ${ne}`,null);continue}let Ce=await n(t,["network","connect",v,ne]);if(Ce.code!==0){b(`${v} ${ne}`,`WARNING: ${ne} could not join the ${v} network, so it has no route to ${H.peer}: ${(Ce.stderr||Ce.stdout).trim().split(`
|
|
776
|
+
`)[0]}`);continue}b(`${v} ${ne}`,null),h.push(`${ne} joined the ${v} network: its route to ${H.peer} comes from there`)}}let j=new Set(m.filter(v=>v.state!=="deleted").map(v=>v.group??v.ref));for(let v of[...x.keys()]){if(S.has(v))continue;let H=vn(v);if(j.has(H.group)&&!f)continue;let q=(await L(n,t,["ps","--all","--filter",`network=${v}`,"--format","{{.Names}}"])).trim();for(let K of q===""?[]:q.split(`
|
|
777
|
+
`))(await n(t,["network","disconnect",v,K])).code===0&&h.push(`${K} left the ${v} network: ${H.peer} holds none of its cluster's pods`);(await n(t,["network","rm",v])).code===0&&(x.delete(v),h.push(`removed the ${v} network: ${H.peer} holds none of its cluster's pods`))}return Ar=x.size,h}async function kh(m,f){let h=await n(t,[...Re(m),"-tA","-v","ON_ERROR_STOP=1",...Gp(f).flatMap(S=>["-c",S])],{timeoutMs:yt}),b=Number(h.stdout.trim().split(`
|
|
778
|
+
`).pop());return h.code===0&&Number.isInteger(b)?b:null}async function _h(m){let f=await n(t,[...Re(m),"-tAc","select pg_read_file(current_setting('ssl_cert_file')) where current_setting('ssl') = 'on'"]),h=`${f.stdout.trim()}
|
|
779
|
+
`;return f.code===0&&Go.test(h)?h:null}async function $h(m,f){if(!gi.test(f))throw new Error("not a SCRAM-SHA-256 verifier");return vl(m,{statements:[`do $$ begin if not exists (select 1 from pg_roles where rolname = '${Ft}') then create role ${Ft} with login replication; end if; end $$`,`alter role ${Ft} with login replication noinherit password '${f}'`],role:Ft,line:`hostssl replication ${Ft} all scram-sha-256`,replaceLine:!1})}async function vh(m,f,h,b=!0){let S=e.rootless??(typeof process.getuid!="function"||process.getuid()!==0);return hi(h),vl(m,{statements:Kp(f,b),role:_n,line:hi(S?$n:h),replaceLine:!0})}async function vl(m,f){let h=J(m).pod,b=[...Re(m),"-v","ON_ERROR_STOP=1"];if((await n(t,[...b,...f.statements.flatMap(F=>["-c",F])],{timeoutMs:yt})).code!==0)return!1;let k=await n(t,[...b,"-tAc","show hba_file"]),x=k.stdout.trim();return k.code!==0||!/^\/[A-Za-z0-9/_.-]+$/.test(x)||(await n(t,["exec",h,"sh","-c",f.replaceLine?'{ grep -Ev "^host(ssl)?[[:space:]]+replication[[:space:]]+$2[[:space:]]" "$1"; printf "%s\\n" "$3"; } > "$1.next" && cat "$1.next" > "$1" && rm -f "$1.next"':'grep -Eq "^host(ssl)?[[:space:]]+replication[[:space:]]+$2[[:space:]]" "$1" || printf "%s\\n" "$3" >> "$1"',"sh",x,f.role,f.line])).code!==0||!await Pl(m,x.replace(/\/[^/]+$/,""))?!1:(await n(t,[...b,"-tAc","select pg_reload_conf()"])).code===0}async function Pl(m,f){let h=J(m).pod,b=[...Re(m),"-v","ON_ERROR_STOP=1"],S=await n(t,[...b,"-tAc","show ssl"]);return S.code===0&&S.stdout.trim()!=="on"&&((await n(t,["exec","--user","root",h,"sh","-c",'[ -s "$1/server.key" ] || { openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj "/CN=$2" -keyout "$1/server.key" -out "$1/server.crt" >/dev/null 2>&1 && chown postgres:postgres "$1/server.key" "$1/server.crt" && chmod 0600 "$1/server.key"; }',"sh",f,h])).code!==0||(await n(t,[...b,"-c","alter system set ssl_cert_file = 'server.crt'","-c","alter system set ssl_key_file = 'server.key'","-c","alter system set ssl = on"])).code!==0)?!1:S.code===0}async function Ph(m,f){if(!Go.test(f.certificate))throw new Error("the primary's certificate is not one PEM certificate");let h=J(m).pod;for(let[b,S]of[[Yp,Zp(f.password)],[Xp,f.certificate]]){let k=await n(t,["exec","--interactive","--user","postgres",h,"sh","-c",'umask 077 && mkdir -p "$(dirname "$1")" && cat > "$1.next" && mv -f "$1.next" "$1"',"sh",b],{stdin:S,timeoutMs:yt});if(k.code!==0)throw new Error(`${b} could not be written in ${h}: ${(k.stderr||k.stdout).trim().slice(0,200)}`)}}return{list:a,ensureImage:fe,inRecovery:kl,replayLsn:Qg,currentLsn:eh,settleTimeline:th,podHealth:nh,setSyncNames:ch,...e.guardRoot?{syncGuards:ih}:{},dropKeeperSlots:kh,bridgeContainers:dh,containerNetworks:uh,applyPodIsolation:gh,joinPeerNetwork:yh,requestDiskQuota:ph,ensureTempFileLimit:mh,ensureMaxWalSize:fh,ensureKeeperRole:$h,ensureReplicaRole:vh,dropIdleReplicaSlot:lh,writeFollowFiles:Ph,podCertificate:_h,swapHomeData:oh,adoptHomeData:sh,promoteStandby:ah,nodesAnswer:rh,preflight:d,create:c,createServices:bt,async start(m){let f=(await i(m).catch(()=>[])).filter(h=>h.running&&!h.separate&&!h.stack).map(h=>h.container);f.length>0&&await L(n,t,["stop","--time","5",...f]),await L(n,t,["start",J(m).pod])},async startServices(m){let{services:f,anchor:h}=await B(m);if(h!==null&&!h.running){let S=f.filter(k=>k.stack&&k.running).map(k=>k.container);S.length>0&&await L(n,t,["stop","--time","5",...S]),await L(n,t,["start",ht(m)])}let b=f.filter(S=>!S.stack||h!==null).map(S=>S.container);b.length>0&&await L(n,t,["start",...b])},async publishedPorts(m){return it(m)},async setAsideSidecars(m){let f=(await i(m)).filter(h=>!h.separate&&!h.stack&&!h.setAside);for(let h of f)await L(n,t,["rm","--force","--ignore",ls(h.container)]),await L(n,t,["rename",h.container,ls(h.container)]);return f.map(h=>h.name)},async setAsideStackServices(m){let f=(await i(m)).filter(h=>h.stack&&!h.setAside);for(let h of f)await L(n,t,["rm","--force","--ignore",ls(h.container)]),await L(n,t,["rename",h.container,ls(h.container)]);return f.map(h=>h.name)},async dropSetAside(m){let f=(await i(m)).filter(h=>h.setAside).map(h=>h.container);f.length>0&&await L(n,t,["rm","--force","--ignore",...f])},async routerAnswers(m,f){let h=J(m),b=Date.now()+f;for(;;){if((await n(t,["exec",h.pod,"pg_isready","--host",Et(m),"--port",String(Fo),"--dbname",h.database,"--timeout","2"])).code===0)return!0;if(Date.now()>=b)return!1;await new Promise(k=>setTimeout(k,500))}},async applyHostServices(m){let f=[],h=await L(n,t,["ps","--all","--filter",`label=${Rn}`,"--format","json"]),b=h.trim()?JSON.parse(h):[],S=new Map;for(let _ of b){let M=_.Labels?.[Rn];M&&S.set(M,{spec:_.Labels?.[Of]??"",state:_.State??"",elsewhere:Cf(_,e.podBind),joins:_.Labels?.[Nf]||null})}let k=new Set;for(let _ of n$(m)){let M=S.get(_.name);S.delete(_.name);try{await x(_,M)}catch(F){f.push({name:_.name,action:"failed",reason:F instanceof Error?F.message:String(F)})}}async function x(_,M){let F=_.joins?En(_.joins):null;if(F!==null&&!m.some(ne=>ne.name===F&&!ne.joins))throw new Error(`it joins ${F}, which this host does not run`);let X=e.composeHostService?await e.composeHostService(_):_;if(r$(X))throw new Error("it names host secrets, and this host cannot resolve them");let j=e.hostServiceLocal?.(X,m),v=j?{...X,...j.env&&Object.keys(j.env).length>0?{env:{...X.env,...j.env}}:{},...j.volumes?{volumes:j.volumes}:{},...j.network?{network:j.network}:{}}:X,H=Qt(v.name),q=F===null?o$(v.name,m):[],K=t$(v,{joins:F,publishes:q});if(M&&M.spec===K&&!(M.state!=="running"&&M.elsewhere)){M.state!=="running"?(await L(n,t,["start",H]),f.push({name:v.name,action:"started",reason:M.state}),k.add(v.name)):F!==null&&k.has(F)&&(await L(n,t,["restart",H]),f.push({name:v.name,action:"started",reason:`${F}, whose network it shares, was started again`}));return}let D=M?M.spec===K?"published on another instance's address":"the spec changed":"it was not here";if(await fe(v.image),M){for(let[ne,ge]of S)ge.joins===v.name&&(await L(n,t,["rm","--force","--ignore",Qt(ne)]),S.delete(ne));await L(n,t,["rm","--force","--ignore",H])}await L(n,t,[...await r(),"run","--detach","--name",H,"--label",`${Rn}=${v.name}`,"--label",`${Of}=${K}`,...F!==null?["--label",`${Nf}=${F}`]:[],...v.healthPath&&v.hostPort>0?["--label",`${us}=${v.hostPort}:${v.healthPath}`]:[],"--memory",`${v.memoryMb}m`,"--pids-limit",String(x$),"--restart","no",...F!==null?["--network",`container:${Qt(F)}`]:v.network?["--network",v.network]:e.network?["--network",e.network]:[],...(v.volumes??[]).flatMap(ne=>["--volume",ne]),...F===null?[...v.hostPort>0?[[v.hostPort,v.port]]:[],...q].flatMap(([ne,ge])=>On(e.podBind).flatMap(Ce=>["--publish",`${Ce}:${ne}:${ge}`])):[],...v.adminPort&&v.adminHostPort?["--publish",`127.0.0.1:${v.adminHostPort}:${v.adminPort}`]:[],...cs(v.env),v.image,...v.command??[]],{env:{...v.env}}),f.push({name:v.name,action:M?"recreated":"created",reason:D}),F===null&&k.add(v.name)}for(let _ of[...S.keys()].sort((M,F)=>+!S.get(M)?.joins-+!S.get(F)?.joins))await L(n,t,["rm","--force","--ignore",Qt(_)]),f.push({name:_,action:"removed",reason:"it is no longer on the list"});return f},async hostServiceHealth(m){let f=await L(n,t,["ps","--all","--filter",`label=${Rn}`,"--format","json"]),h=(f.trim()?JSON.parse(f):[]).map(S=>S.Labels?.[Rn]??"").filter(S=>S!=="");if(h.length===0)return[];let b=Date.now()+m;for(;;){let S=[];for(let k of h)S.push(await Mf(n,t,k,Qt(k),o));if(S.every(k=>k.ok)||Date.now()>=b)return S;await new Promise(k=>setTimeout(k,500))}},async serviceHealth(m,f){let h=await p(m);if(h.length===0)return[];let b=Date.now()+f;for(;;){let S=await Promise.all(h.map(k=>Mf(n,t,k.name,k.container,o)));if(S.every(k=>k.ok)||Date.now()>=b)return S;await new Promise(k=>setTimeout(k,500))}},async drain(m,f,h){await new Promise(S=>setTimeout(S,f)),await n(t,[...Re(m),"-c","checkpoint"],{timeoutMs:yt});let b=Date.now()+h;for(;;){let S=await n(t,[...Re(m),"-tAc","select count(*) filter (where state <> 'idle') from (select state, case when state = 'idle' then pg_terminate_backend(pid) end from pg_stat_activity where backend_type = 'client backend' and pid <> pg_backend_pid()) s"]),k=S.code===0&&Number(S.stdout.trim())||0;if(k===0||Date.now()>=b)return{stillRunning:k};await new Promise(x=>setTimeout(x,250))}},async stop(m,f,h){let{services:b,anchor:S}=ue(await B(m),h);for(let k of b)await L(n,t,["stop","--time",String(xf),k.container]);S!==null&&await L(n,t,["stop","--time",String(xf),ht(m)]),await L(n,t,["stop","--time",String(f),J(m).pod])},async remove(m,f){let{services:h,anchor:b}=ue(await B(m),f);for(let S of h)await L(n,t,["rm","--force","--ignore",S.container]);b!==null&&await L(n,t,["rm","--force","--ignore",ht(m)]),await L(n,t,["rm","--force","--ignore","--volumes",J(m).pod])},async removeData(m){await L(n,t,["volume","rm","--force",J(m).pod]);let f=cr(m);(await n(t,["volume","exists",f])).code===0&&await L(n,t,["volume","rm","--force",f])},async applyOwnerPassword(m){let f=await n(t,["exec",...Ae,J(m.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",Fm(m.ref)]),h=Hm(m,f.code===0?Bm(f.stdout):new Map);h!==null&&await L(n,t,["exec",...Ae,"--interactive",...Object.keys(h.env).flatMap(b=>["--env",b]),J(m.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:h.env,stdin:h.script})},async applyRolePassword(m,f,h){let b=["\\getenv role_password SNOUTPOD_ROLE_PASSWORD",`\\set target_role ${Bt(f)}`,`alter role :"target_role" with password :'role_password';`,""].join(`
|
|
780
|
+
`);await L(n,t,["exec",...Ae,"--interactive","--env","SNOUTPOD_ROLE_PASSWORD",J(m).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_ROLE_PASSWORD:h},stdin:b})},async applyRouterLogin(m,f){if(await L(n,t,["exec",...Ae,"--interactive","--env","SNOUTPOD_ROUTER_PASSWORD",J(m).pod,"psql","--username","snoutpod_admin","--dbname",ae(m),"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_ROUTER_PASSWORD:f??""},stdin:Op(m,f!==null)}),f!==null){let h=[...Re(m),"-v","ON_ERROR_STOP=1"],b=await n(t,[...h,"-tAc","show data_directory"]),S=b.stdout.trim();if(b.code!==0||!/^\/[A-Za-z0-9/_.-]+$/.test(S)||!await Pl(m,S))throw new Error(`${m}: TLS for the copies' routers could not be turned on`);await L(n,t,[...h,"-tAc","select pg_reload_conf()"])}},async updateExtensions(m){let f=J(m),h=await n(t,["exec",...Ae,f.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select datname from pg_database where datname = '${f.database}' or (not datistemplate and datname <> 'postgres') order by datname = '${f.database}' desc, datname limit 1`]),b=h.code===0&&/^[a-z][a-z0-9_]{0,62}$/.test(h.stdout.trim())?h.stdout.trim():f.database,S=await L(n,t,["exec",...Ae,"--interactive",f.pod,"psql","--username","snoutpod_admin","--dbname",b,"--quiet","-tA","-F",Fi,"-v","ON_ERROR_STOP=1","--file","-"],{stdin:tf});return nf(S)},async applyDbAccess(m,f){let h=J(m),b=await L(n,t,["exec",...Ae,"--interactive","--env",rs,h.pod,"psql","--username","snoutpod_admin","--dbname",h.database,"--quiet","-tA","-v","ON_ERROR_STOP=1","--file","-"],{env:{[rs]:Cm(m,f)},stdin:Nm,timeoutMs:6e4});return Im(b)},async runProjectSql(m,f){let h=J(m);await L(n,t,["exec",...Ae,"--interactive",h.pod,"psql","--username","snoutpod_admin","--dbname",h.database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:f})},async ensureHostServiceDatabase(m,f,h){let b=Qt(m),S=Bt(f),k=Bt(h),x=M=>["exec",b,"psql","--username",S,"--dbname","postgres","--quiet","-tA","-v","ON_ERROR_STOP=1","-c",M];(await L(n,t,x(`select 1 from pg_database where datname = '${k}'`))).trim()!=="1"&&await L(n,t,x(`create database "${k}"`))},async renameProject(m,f){f!==m.ref&&await L(n,t,["exec",...Ae,"--interactive",J(m.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:I$(f,m.ref)})},async waitReady(m,f){let h=J(m).pod,b=Date.now()+f,S=0;for(;;){let k=await n(t,["exec",...Ae,h,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres","-tAc","select not pg_is_in_recovery()"]);if(k.code===0&&k.stdout.trim()==="t")return s(m),!0;if(Date.now()>=b||await Sl(m,++S))return!1;await new Promise(x=>setTimeout(x,500))}},async waitStandby(m,f){let h=Date.now()+f,b=0;for(;;){if(await kl(m)===!0)return!0;if(Date.now()>=h||await Sl(m,++b))return!1;await new Promise(S=>setTimeout(S,500))}},async capacity(){let[m,f]=await Promise.all([l(),e.capacity()]);return{pods:m,...f}},async databaseBytes(m){let f=await n(t,["exec",...Ae,J(m).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres","-tAc",Up(m)]);return f.code===0?mi(f.stdout):null},async storageBytes(m){let f=await n(t,["exec",...Ae,J(m).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",m,"-tAc","select (xpath('/row/n/text()', query_to_xml(format('select coalesce(sum((metadata->>''size'')::bigint), 0) as n from %s', coalesce(to_regclass('snout_files.files'), to_regclass('storage.objects'))), false, true, '')))[1]::text"]);return f.code===0?mi(f.stdout):null},async setReadOnly(m,f){let h=J(m);await L(n,t,["exec",...Ae,h.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`alter database ${h.database} set default_transaction_read_only = ${f?"on":"off"}`])},async archiveState(m){let f=await n(t,["exec",...Ae,J(m).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",m,"-tA","-F","|","-c",`select coalesce(to_char(last_archived_time, 'YYYY-MM-DD"T"HH24:MI:SS.MSOF'), ''), case when last_failed_time > coalesce(last_archived_time, '-infinity') then failed_count else 0 end from pg_stat_archiver`]);if(f.code!==0)return null;let[h="",b=""]=f.stdout.trim().split(`
|
|
781
|
+
`)[0]?.split("|")??[],S=Number(b);return{lastArchivedAt:h.trim()||null,failures:Number.isInteger(S)&&S>=0?S:0}}}}async function Mf(e,t,n,r,o=Gf){let s=await e(t,["inspect","--format","json",r]);if(s.code!==0)return{name:n,ok:!1,detail:"no such container"};let a,l;try{let p=JSON.parse(s.stdout);a=p[0]?.State,l=p[0]?.Config?.Labels}catch{return{name:n,ok:!1,detail:"podman inspect could not be read"}}let d=a?.Status??"unknown";if(d!=="running")return{name:n,ok:!1,detail:d};let c=c$(l?.[us]);if(!c)return{name:n,ok:!0,detail:"running"};let i=await o(c.port,c.path);return i===null?{name:n,ok:!1,detail:"not answering yet"}:{name:n,ok:!0,detail:`answered ${i}`}}async function T$(e,t,n){let r=new Array(e.length),o=0;async function s(){for(;o<e.length;){let a=o++;r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},s)),r}function N$(e,t){return(e.State??"").toLowerCase()==="created"&&typeof e.Created=="number"&&e.Created>0&&t-e.Created*1e3>O$}function Yi(e){switch((e??"").toLowerCase()){case"running":return"running";case"created":case"configured":return"starting";case"exited":case"stopped":return"stopped";default:return"unknown"}}function I$(e,t){return[`\\set from_db ${e}`,`\\set to_db ${t}`,`\\set from_role ${e}_owner`,`\\set to_role ${t}_owner`,'alter database :"from_db" with allow_connections false;',"set snoutpod.rename_from = :'from_db';","do $$","declare"," db text := current_setting('snoutpod.rename_from');"," remaining text;","begin",` for attempt in 1..${jf} loop`," perform pg_stat_clear_snapshot();"," select string_agg(coalesce(nullif(application_name, ''), backend_type) || ' (pid ' || pid || ')', ', ')"," into remaining from pg_stat_activity where datname = db and pid <> pg_backend_pid();"," if remaining is null then"," return;"," end if;"," perform pg_terminate_backend(pid) from pg_stat_activity where datname = db and pid <> pg_backend_pid();",` perform pg_sleep(${Df/jf});`," end loop;",` raise exception 'database % still has sessions after ${Df}s, not renamed: %', db, remaining;`,"end","$$;",'alter database :"from_db" rename to :"to_db";','alter database :"to_db" with allow_connections true;','alter role :"from_role" rename to :"to_role";',"\\getenv admin_password POSTGRES_PASSWORD","\\if :{?admin_password}","alter role snoutpod_admin with password :'admin_password';","\\endif",`\\set from_b ${e}_owner_b`,`\\set to_b ${t}_owner_b`,"select count(*) as has_b from pg_roles where rolname = :'from_b' \\gset","\\if :has_b",'alter role :"from_b" rename to :"to_b";',"\\endif","alter system reset restore_command;","alter system reset recovery_target_time;","alter system reset recovery_target_action;","checkpoint;",""].join(`
|
|
782
|
+
`)}function C$(e){if(!e?.issuer)return[];try{return["--env",`${of}=${sf(e.issuer)}`]}catch{return[]}}function L$(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?[]:["--cpus",e.toFixed(2)]}var qe,Ji,Ve,Tn,gr,Pf,xf,Y_,X_,Ff,An,Rf,Rn,Of,Nf,Bf,Qi,us,Gf,d$,If,Ae,yt,m$,Lf,$$,Kf,v$,P$,x$,R$,O$,Df,jf,os=z(()=>{"use strict";Ie();pi();es();qo();_i();$i();Ko();Gm();fr();Ym();fi();ef();rf();Ii();af();vi();pf();ki();Ni();hf();ui();dr();$f();qe="snoutpod.ref",Ji="snoutpod.generation",Ve="snoutpod.service",Tn="snoutpod.services-generation",gr="snoutpod.service-spec",Pf="snoutpod.service-pod";xf=10,Y_=/^[a-z][a-z0-9-]{0,30}$/;X_=/^[a-z][a-z0-9_]{0,62}$/;Ff="-set-aside",An=1024*1024,Rf=/^[0-9a-f]{12,64}$/;Rn="snoutpod.host-service",Of="snoutpod.host-service-spec",Nf="snoutpod.host-service-joins";Bf=/^[A-Za-z_][A-Za-z0-9_]*$/;Qi=/^\/[A-Za-z0-9\/_\-.~%?=&]*$/,us="snoutpod.health";Gf=async(e,t)=>{let{request:n}=await import("node:http");return new Promise(r=>{let o=n({host:"127.0.0.1",port:e,path:t,method:"GET",timeout:2e3},s=>{s.resume(),r(s.statusCode??null)});o.on("error",()=>r(null)),o.on("timeout",()=>{o.destroy(),r(null)}),o.end()})},d$="crun";If="/usr/sbin/nft",Ae=["--env","PGOPTIONS=-c search_path=pg_catalog,pg_temp -c synchronous_commit=local"],yt=3e4,m$=3e4;Lf=200,$$=1024,Kf=512,v$=45e3,P$=1e3,x$=4096;R$=8;O$=12e4;Df=30,jf=300});var ig={};Tl(ig,{DEFAULT_LOCAL_MEMORY_MB:()=>Xf,DEFAULT_LOCAL_PORT:()=>F$,ENGINE:()=>de,ENGINE_NAME:()=>nl,IMAGE:()=>sl,NETWORK:()=>Ht,NEW_PROJECT_MAJOR:()=>ol,NO_BLACKHOLE_ROUTES:()=>tg,PUBLIC_IMAGE:()=>q$,PUBLISHED_MAJORS:()=>Nn,capacity:()=>eg,chooseLocalImage:()=>br,dropIfUnused:()=>sg,ensureImage:()=>K$,ensureNetwork:()=>Y$,exec:()=>Se,hasData:()=>gs,localImageFor:()=>Qf,localPsql:()=>Q$,localRuntime:()=>V$,localSpec:()=>og,localStatus:()=>al,localUri:()=>rg,networkPolicyInPlace:()=>ng,newLocalPassword:()=>H$,newLocalRef:()=>B$,podLog:()=>ag,podName:()=>In,podmanReady:()=>W$,removeLocal:()=>nv,staleImage:()=>rl,startLocal:()=>Z$,stopLocal:()=>tv,volumePgVersion:()=>ps});import{randomBytes as Vf}from"node:crypto";import{existsSync as Wf}from"node:fs";import{platform as fs}from"node:os";import{delimiter as M$,join as D$}from"node:path";function j$(){if(process.env.SNOUTPOD_ENGINE)return process.env.SNOUTPOD_ENGINE;let e=fs()==="win32"?["podman.exe","podman"]:["podman"];for(let t of(process.env.PATH??"").split(M$))if(t&&e.some(n=>Wf(D$(t,n))))return"podman";return Wf("/opt/podman/bin/podman")?"/opt/podman/bin/podman":"podman"}function br(e,t=process.env.SNOUTPOD_IMAGE){if(t)return{name:t,published:null,major:null};if(e===null)return wr(ol);let n=Number(tl(e));if(!Nn.includes(n)){let r=e.trim()||"(empty)",o=Nn.map(s=>wr(s).published).join(" or ");throw new Error(`its data directory's PG_VERSION says ${r}, and there is an image only for Postgres ${Nn.join(" and ")}. Set SNOUTPOD_IMAGE to an image of that major (${o} for those).`)}return wr(n)}function wr(e){return{name:`${U$}:${e}`,published:`${Yf}:${e}`,major:e}}function B$(){return Ep(e=>Vf(e))}function H$(){return Vf(18).toString("base64url")}async function K$(e,t=Se,n=br(null)){let r=n.published;if(!r)return null;if((await t(de,["image","exists",n.name])).code===0)return await z$(e,t,n.name,r),null;e?.(`Fetching the database image (${r}). This happens once.`);let o=await t(de,["pull",r],{timeoutMs:Zf}).catch(a=>({code:1,stdout:"",stderr:a instanceof Error?a.message:String(a)}));if(o.code!==0)return`could not fetch the database image ${r}: ${o.stderr.trim()||o.stdout.trim()||"the pull failed"}`;let s=await t(de,["tag",r,n.name]);return s.code!==0?`fetched ${r} but could not tag it as ${n.name}: ${s.stderr.trim()}`:(e?.("Got it."),null)}async function z$(e,t,n,r){let o=await t(de,["image","inspect","--format","{{.Id}}",n,r]).catch(()=>null),[s,a]=o?.code===0?o.stdout.trim().split(`
|
|
783
|
+
`):[];if(!s||s!==a)return;let l=setTimeout(()=>e?.(`Fetching a newer database image (${r}).`),3e3),d=await t(de,["pull",r],{timeoutMs:Zf}).catch(g=>({code:1,stdout:"",stderr:g instanceof Error?g.message:String(g)})).finally(()=>clearTimeout(l));if(d.code!==0){let g=(d.stderr.trim()||d.stdout.trim()||"the pull failed").split(`
|
|
784
|
+
`).at(-1);e?.(`Could not check for a newer database image (${g}); using the one on this machine.`);return}let c=await t(de,["image","inspect","--format","{{.Id}}",r]).catch(()=>null),i=c?.code===0?c.stdout.trim():"";if(!i||i===s)return;let p=await t(de,["tag",r,n]);if(p.code!==0){e?.(`Fetched a newer ${r} but could not tag it as ${n}: ${p.stderr.trim()}`);return}e?.(`Fetched a newer database image (${r}).`)}async function W$(e=G$,t=sl){if(nl!=="podman")return`SNOUTPOD_ENGINE=${nl}: a local project is Podman-only, because a database that works under Docker and not under Podman is a database that works here and not in the cloud`;let n;try{n=await Se(de,["--version"])}catch{return`${de} is not installed. macOS: brew install podman, then podman machine init && podman machine set --rootful=false && podman machine start. Windows: winget install RedHat.Podman, then the same three machine commands. Linux: your distribution's podman package.`}if(n.code!==0)return`${de} --version failed: ${n.stderr.trim()||n.stdout.trim()}`;if((await Se(de,["image","exists",t])).code!==0)return`the pod image ${t} is not on this machine. ${e}`;let o=await Se(de,["machine","inspect","--format","{{.Rootful}}"]);return o.code===0&&o.stdout.trim().startsWith("true")?"the podman machine is ROOTFUL, and the hosts are not: podman machine stop && podman machine set --rootful=false && podman machine start":null}function J$(e){let t=`if out=$(ls -A ${JSON.stringify(e)} 2>/dev/null); then if [ -n "$out" ]; then echo DATA; else echo EMPTY; fi; else echo HIDDEN; fi`;return Se(de,["machine","ssh",t]).then(n=>{let r=n.stdout.trim().split(`
|
|
785
|
+
`).at(-1);return r==="DATA"?"data":r==="EMPTY"?"empty":"hidden"},()=>"hidden")}function gs(e){let t=fs()==="darwin"||fs()==="win32";return jm(Se,e,{binary:de,look:t?J$:void 0})}async function ps(e,t=Se,n=fs()){let r=J(e).pod;if((await t(de,["volume","exists",r])).code!==0)return null;let o;if(n==="darwin"||n==="win32"){let s=null;for(let a of Nn){let l=wr(a).name;if((await t(de,["image","exists",l])).code===0){s=l;break}}if(!s)throw new Error(`${r} holds a database and there is no pod image on this machine to read its Postgres version with. Set SNOUTPOD_IMAGE to the image it was made with (${Nn.map(a=>wr(a).published).join(" or ")}).`);o=await t(de,["run","--rm","--pull=never","--network=none","--userns=host","--user=0","--entrypoint=cat","--volume",`${r}:/data:ro`,s,"/data/PG_VERSION"])}else{let s=await t(de,["volume","inspect","--format","{{.Mountpoint}}",r]),a=s.code===0?s.stdout.trim().replace(/\/+$/,""):"";if(!a)throw new Error(`could not find where ${r} is: ${s.stderr.trim()||"no mountpoint"}`);o=await t(de,["unshare","cat",`${a}/PG_VERSION`])}if(o.code===0)return o.stdout;if(/no such file/i.test(o.stderr))return null;throw new Error(`could not read the Postgres version in ${r}: ${o.stderr.trim()||o.stdout.trim()||`exit ${o.code}`}`)}function Qf(e,t=ps){if(!e||process.env.SNOUTPOD_IMAGE)return Promise.resolve(br(null));ae(e);let n=t===ps?ms.get(e):void 0;if(n)return n;let r=t(e).then(o=>{try{return br(o)}catch(s){throw new Error(`${In(e)}: ${s instanceof Error?s.message:String(s)}`)}});return t===ps&&(ms.set(e,r),r.catch(()=>ms.delete(e))),r}async function eg(){return{ramFreeMb:4096,ramTotalMb:8192,diskFreeMb:32768,diskTotalMb:65536}}function V$(e){return zf({exec:Se,binary:de,network:Ht,hasData:gs,capacity:eg,repository:e})}function In(e){return J(e).pod}async function Y$(e){if(process.env.SNOUTPOD_LOCAL_ALLOW_EGRESS==="1"){await X$()||await Se(de,Qo({name:Ht}));return}let t=Qo({name:Ht,allow:[]}),n="";for(let r=0;r<10;r+=1){if(await ng())return;await e?.(),await Se(de,["network","rm","--force",Ht]).catch(()=>{});let o=await Se(de,t);if(o.code===0)return;if(n=`${o.stderr}${o.stdout}`.trim(),/invalid route gateway/i.test(n))throw new Error(`${tg}: ${n}`);await new Promise(s=>setTimeout(s,500))}throw new Error(`could not create ${Ht} with egress blocked${n?`: ${n}`:""}`)}async function X$(){return(await Se(de,["network","inspect",Ht,"--format","json"])).code===0}async function ng(){let e=await Se(de,["network","inspect",Ht,"--format","json"]);if(e.code!==0)return!1;try{return Sm(JSON.parse(e.stdout)?.[0])}catch{return!1}}function rg(e){let t=J(e.ref);return`postgres://${t.ownerRole}:${encodeURIComponent(e.ownerPassword)}@127.0.0.1:${e.port}/${t.database}?sslmode=disable`}function og(e,t={}){return ae(e.ref),{ref:e.ref,generation:1,image:t.image??sl,memoryMb:t.memoryMb??Xf,cpus:null,bucket:"",region:"us-east-1",ownerPassword:e.ownerPassword,adminPassword:e.adminPassword,port:e.port,tuning:t.tuning??null,backup:null,services:t.services??null}}function yr(e,t){e.onProgress?.(t)}async function Z$(e,t,n={}){let r=n.image??(await Qf(t.ref,n.pgVersion)).name,o=og(t,{...n,image:r}),s=n.timeoutMs??12e4,a=n.hasData??gs,l=(await e.list()).find(c=>c.ref===t.ref),d=null;if(l?l.status==="stopped"&&(d=await(n.staleImage??rl)(t.ref,r))?(yr(n,"Starting the database on the newer image. Its data stays as it is."),await e.remove(t.ref),await e.create(o),await(n.dropImage??sg)(d)):l.status==="stopped"?(yr(n,"Starting the database."),await e.start(t.ref),await e.startServices(t.ref)):(yr(n,"The database is already running."),l.status==="running"&&await(n.staleImage??rl)(t.ref,r)&&yr(n,"A newer database image is on this machine. To move onto it: snoutdata stop, then snoutdata start.")):(yr(n,await a(t.ref)?"Starting the database over its existing data.":"Creating the database."),await e.create(o)),!await e.waitReady(t.ref,s))throw new Error(await ev(t.ref,s,n.podLog??ag));return await e.applyOwnerPassword(o),await e.createServices(o),al(e,t,n)}function Jf(e){return e.trim().replace(/^sha256:/,"")}async function rl(e,t){let[n,r]=await Promise.all([Se(de,["container","inspect","--format","{{.Image}}",In(e)]).catch(()=>null),Se(de,["image","inspect","--format","{{.Id}}",t]).catch(()=>null)]);if(n?.code!==0||r?.code!==0)return null;let o=Jf(n.stdout),s=Jf(r.stdout);return o&&s&&o!==s?o:null}async function sg(e){let t=await Se(de,["image","inspect","--format","{{len .RepoTags}}",e]).catch(()=>null);t?.code===0&&t.stdout.trim()==="0"&&await Se(de,["rmi",e]).catch(()=>{})}async function Q$(e,t){let n=J(e.ref);return Se(de,["exec","--interactive","-e","PGPASSWORD",In(e.ref),"psql","--host","127.0.0.1","--port","5432","--username",n.ownerRole,"--dbname",n.database,"--no-psqlrc","-v","ON_ERROR_STOP=1","-tA","--file","-"],{stdin:t,env:{PGPASSWORD:e.ownerPassword}})}async function ag(e){let t=await Se(de,["logs","--tail","20",In(e)]).catch(()=>null);return t?`${t.stdout}${t.stderr}`:"(no log: the container is not there)"}async function ev(e,t,n){let r=await n(e).catch(()=>"(no log)");return`${In(e)} never became ready in ${t}ms
|
|
509
786
|
--- pod log ---
|
|
510
|
-
${r}`}async function C_(e,t,n={}){se(t);let r=(await e.list()).find(o=>o.ref===t);return r&&r.status!=="stopped"&&await e.stop(t,Kp),Ai(e,{ref:t,port:0,ownerPassword:"",adminPassword:""},n)}async function M_(e,t,n){se(t),await e.remove(t),n&&(await e.removeData(t),zo.delete(t))}async function Ai(e,t,n={}){se(t.ref);let r=(await e.list()).find(a=>a.ref===t.ref),o=r?.status==="running",s=n.hasData??Jo;return{ref:t.ref,exists:!!r,status:r?.status??"absent",ready:o?await e.waitReady(t.ref,1):!1,hasData:r?.hasData??await s(t.ref),port:t.port,databaseBytes:o?await e.databaseBytes(t.ref):null,services:r?.services??[],uri:t.port>0&&t.ownerPassword?af(t):null}}var $i,ie,xi,_n,w_,Qm,Ei,Ct,b_,ef,we,__,v_,tf,zo,of,pf=W(()=>{"use strict";Gp();Zn();Wp();Eo();Lo();Le();$i=process.env.SNOUTPOD_ENGINE??"podman";ie=y_(),xi=18,_n=[17,18],w_="snoutpod/postgres",Qm="ghcr.io/snoutdata/snoutpod-postgres";Ei=rr(null).name,Ct=process.env.SNOUTPOD_LOCAL_NETWORK??"snoutpod-local",b_=54322,ef=512,we=qp();__="cd packages/snoutpod && npm run image:build",v_=`${Qm}:${xi}`;tf=20*60*1e3;zo=new Map;of="this podman cannot blackhole a route, so the local tier cannot isolate its containers"});Ae();var Be=["--admin","--token","--project"],is=["--max-write-pause-ms","--drain-timeout-ms","--ack-timeout-ms","--copy-mb-per-s"],Vt=[...Be,"--plan","--no-wait","--timeout",...is],Ce=[...Vt,"--yes"],ls=[{name:"init",summary:"Create or link a project for this folder, and print its DATABASE_URL or write it to .env",flags:["--name","--region","--env","--ref"]},{name:"login",summary:"Sign in through a browser, with --sso through your company's identity provider, or with --device by typing a code into one anywhere",flags:["--email","--provider","--sso","--domain","--no-browser","--device","--profile","--timeout"]},{name:"logout",summary:"Forget the stored session, of this profile or of every one",flags:["--profile","--all"]},{name:"whoami",summary:"Who this credential belongs to, and whether it is the account login --email asked for; --all lists every profile",flags:["--profile","--all"]},{name:"upgrade",summary:"Install the newest CLI the way this one was installed (binary or npm), checksum verified",flags:["--check"]},{name:"tokens list",summary:"Long-lived access tokens on this account",flags:[]},{name:"tokens create",summary:"Mint an sdt_ token for CI or an agent",flags:["--name","--expires","--project"]},{name:"tokens revoke",args:"<id|sdt_prefix>",summary:"Revoke one by id or prefix",flags:[]},{name:"projects list",summary:"Every project on this account",flags:[]},{name:"projects create",summary:"Make a hosted database, and print its ref",flags:["--name","--region","--servers","--size","--max-size","--team","--no-wait","--timeout","--show-url"]},{name:"projects pause",summary:"Stop a project, and wait until it is paused",flags:["--ref","--no-wait","--timeout"]},{name:"projects resume",summary:"Start a paused project, and wait until it is ready",flags:["--ref","--no-wait","--timeout"]},{name:"projects delete",summary:"Delete a project, and wait until it is gone",flags:["--ref","--no-wait","--timeout"]},{name:"projects scale",args:"[ref]",summary:"More capacity for your app's API (auth, the data API and the router): 1 to 3 instances. Shows the plan and asks first; without --instances, what your plan allows",flags:["--ref","--instances","--yes"]},{name:"projects show",summary:"One project: state, products (Realtime included), functions, secrets, domains",flags:["--ref"]},{name:"products",summary:"Auth, storage, the data API and push: on or off. Realtime is always on, and listed",flags:["--ref"]},{name:"products enable",args:"auth|storage|data-api|push",summary:"Turn auth, storage, data-api or push on",flags:["--ref"]},{name:"products disable",args:"auth|storage|data-api|push",summary:"Turn auth, storage, data-api or push off",flags:["--ref"]},{name:"push credentials",summary:"Push keys: what is set for APNs, FCM and Web Push (never the keys)",flags:["--ref"]},{name:"push credentials set",args:"apns|fcm",summary:"Set the APNs key (a .p8) or the FCM service account, checked before it is stored",flags:["--ref","--p8","--key-id","--team-id","--topic","--environment","--file"]},{name:"push credentials remove",args:"apns|fcm",summary:"Remove the APNs or FCM credentials",flags:["--ref"]},{name:"auth",summary:"Auth settings: Google sign-in and redirect addresses",flags:["--ref"]},{name:"auth google",summary:"Sign in with Google, with your own client (secret on stdin)",flags:["--ref","--client-id","--stdin"]},{name:"auth anonymous",args:"on|off",summary:"Guest sign-in on or off: guestSignIn() gives a browser a session with no email or password",flags:["--ref"]},{name:"auth redirects",summary:"The site URL and the addresses a sign-in may return to",flags:["--ref","--site-url","--allow"]},{name:"auth templates",summary:"The five auth emails, ours or your own",flags:["--ref"]},{name:"auth template",args:"KIND",summary:"Use your own subject and HTML for one, or reset it",flags:["--ref","--file","--subject"]},{name:"realtime inspect",summary:"The channels open now: each client, its roster entry, when it was last heard, and the last minute of messages",flags:["--channel","--watch","--ref"]},{name:"realtime logs",summary:"The connection log: connects, joins, leaves and disconnects, with the reason each ended",flags:["--since","--channel","--ref"]},{name:"ai",summary:"The project's own AI gateway: on or off, its models, budgets and the last 30 days' spend",flags:["--ref"]},{name:"ai enable",summary:"Switch the AI gateway on. Its container joins the pod, which restarts the database once",flags:["--ref"]},{name:"ai disable",summary:"Switch it off. Its providers, models, keys and log stay in the project's database",flags:["--ref"]},{name:"ai models",summary:"The models it serves: provider, upstream id, price and whether each is served",flags:["--ref"]},{name:"ai models add",args:"[name]",summary:"Add a model, with its provider and key when the provider is new. The key comes on stdin and the provider proves it first; without --model, print the steps to find the key and the model's id",flags:["--ref","--source","--model","--provider","--base-url","--region","--price-in","--price-out","--access-key-id","--auth-header","--stdin"]},{name:"ai models remove",args:"<name>",summary:"Stop serving a model",flags:["--ref"]},{name:"ai providers",summary:"Where its models run, and whether each one's key is stored (never the key)",flags:["--ref"]},{name:"ai providers remove",args:"<name>",summary:"Remove a provider no model uses",flags:["--ref"]},{name:"ai routes",summary:"Names that stand for several models, and what each tries in which order",flags:["--ref"]},{name:"ai routes set",args:"<name>",summary:"Make or replace a route: its models, tried in turn when one fails for a reason that is not the caller's",flags:["--ref","--models","--sort"]},{name:"ai routes remove",args:"<name>",summary:"Remove a route; its models stay",flags:["--ref"]},{name:"ai keys",summary:"Keys a server calls the gateway with: created, last used, revoked",flags:["--ref"]},{name:"ai keys create",summary:"Make a key for a server, shown once",flags:["--ref","--name","--models","--expires"]},{name:"ai keys revoke",args:"<id>",summary:"Refuse a key from now on",flags:["--ref"]},{name:"ai budgets",summary:"What may be spent, and by whom",flags:["--ref"]},{name:"ai budgets set",args:"project|users",summary:"The project's budget, or every signed-in user's. A browser call needs both, hard",flags:["--ref","--amount","--period","--soft"]},{name:"ai budgets remove",args:"<id>",summary:"Remove a budget",flags:["--ref"]},{name:"ai usage",summary:"Requests, tokens and cost, grouped",flags:["--ref","--by","--days"]},{name:"ai test",summary:"One chat call through the project's door, with a key made for it and revoked after",flags:["--ref","--model","--prompt"]},{name:"domains",summary:"Your own domains in front of the project API",flags:["--ref"]},{name:"domains add",args:"<hostname>",summary:"Add one, and print the DNS records to publish",flags:["--ref"]},{name:"domains verify",args:"<hostname>",summary:"Check its records and verify it",flags:["--ref"]},{name:"domains remove",args:"<hostname>",summary:"Stop serving it",flags:["--ref"]},{name:"functions deploy",args:"<name>",summary:"Put a folder of TypeScript on the edge",flags:["--ref","--dir","--entrypoint","--no-verify-jwt"]},{name:"functions list",summary:"What this project has deployed",flags:["--ref"]},{name:"functions size",args:"<name>",summary:"Its memory and workers, within the plan",flags:["--ref","--memory","--concurrency","--reset"]},{name:"functions logs",args:"[name]",summary:"What your functions printed, the last seven days",flags:["--ref","--errors","--tail","--follow"]},{name:"functions delete",args:"<name>",summary:"Remove one",flags:["--ref"]},{name:"containers deploy",args:"<name> <image> | <name> --dockerfile <dir>",summary:"Run a Docker image of yours all the time, pinned to the digest its tag points at now, or built from a Dockerfile with your Docker",flags:["--ref","--port","--dockerfile","--registry-user","--stdin","--clear-registry","--no-wait"]},{name:"containers list",summary:"Each container: status, image and URL",flags:["--ref"]},{name:"containers logs",args:"[name]",summary:"What your containers printed, the last seven days",flags:["--ref","--errors","--tail","--follow"]},{name:"containers restart",args:"<name>",summary:"Start one again from its image",flags:["--ref"]},{name:"containers delete",args:"<name>",summary:"Stop one and remove it",flags:["--ref"]},{name:"secrets set",summary:"Set the environment functions and containers run with",flags:["--ref","--stdin"]},{name:"secrets list",summary:"The names, never the values",flags:["--ref"]},{name:"secrets unset",summary:"Remove one",flags:["--ref"]},{name:"keys",summary:"The app key and server key for a project",flags:["--ref"]},{name:"keys rotate",summary:"New keys, breaking every one already issued",flags:["--ref","--force"]},{name:"teams",summary:"Teams this account belongs to",flags:[]},{name:"link",summary:"Point this folder at a project, and at the profile it was linked with",flags:["--ref","--profile"]},{name:"usage",summary:"Size and compute against the plan limit",flags:["--ref","--days","--history"]},{name:"start",summary:"A Postgres on this machine, with your migrations applied",flags:["--port","--dir","--no-migrations","--out-of-order"]},{name:"stop",summary:"Stop the local database. The data stays",flags:[]},{name:"status",summary:"What the local database is doing",flags:[]},{name:"gen types typescript",summary:"The schema as a TypeScript Database type, on stdout",flags:["--ref","--db-url","--local","--schema","--out"]},{name:"db url",summary:"A connection string",flags:["--ref"]},{name:"db psql",summary:"Open psql, or run statements after --",flags:["--ref"]},{name:"db reset-password",summary:"Rotate the project password",flags:["--ref"]},{name:"db access",summary:"Who signs in to the database as themselves with OAuth (Postgres 18), at which level, as which role",flags:["--ref"]},{name:"db access grant",summary:"Let a person sign in to the database as themselves, and print their connection string",flags:["--ref","--level"]},{name:"db access revoke",summary:"Take it away, by email or role; a token already issued can work until it expires (up to 1 hour)",flags:["--ref"]},{name:"db export",summary:"Take or download a dump",flags:["--ref","--out","--status","--timeout"]},{name:"db push",summary:"Apply migrations from a folder",flags:["--dir","--dry-run","--out-of-order"]},{name:"db restore",summary:"Put a dump into a project, or rewind it to a moment into a new project",flags:["--file","--force","--at","--name","--window","--ref"]},{name:"cluster status",summary:"A Lepis cluster: its nodes, keyspaces and their ranges (keyspace:lo), tables, routers and unfinished jobs",flags:[...Be]},{name:"cluster ops",summary:"The operations the router offers, and its default settings",flags:[...Be]},{name:"cluster nodes",summary:"The nodes, their state and how many ranges each owns",flags:[...Be]},{name:"cluster enable",summary:"SnoutData Cloud: make a project a cluster. The router and the services start in pods of their own while the database keeps running. Each node then uses one of the plan project slots",flags:["--project","--plan","--yes"]},{name:"cluster disable",summary:"SnoutData Cloud: turn a cluster of one node back into a plain project. The data is checked, the cluster is taken apart, the router stops and the services move back into the database pod, which restarts the database once",flags:["--project","--plan","--yes"]},{name:"cluster nodes attach",summary:"SnoutData Cloud: hand a ready node pod made with nodes add --no-join to the cluster, as a standby until a range moves onto it",flags:[...Vt]},{name:"cluster nodes add",summary:"Join a Postgres node: checks its version and settings, syncs roles and reference tables. In SnoutData Cloud it makes a node that starts as a copy of the home node, then joins and takes its share of the data on its own (--no-join to attach it by hand); it uses one of the plan project slots",flags:[...Vt,"--host","--port","--dbname","--sslmode","--peer-host","--no-join"]},{name:"cluster spread",summary:"SnoutData Cloud: spread a table over the cluster in one go: a keyspace for its key (shared with tables keyed the same way), the table distributed by it, then a rebalance",flags:["--project","--distribution-key","--key-type","--plan","--yes"]},{name:"cluster retry",summary:"SnoutData Cloud: take up a stopped step again: a node whose join stopped, or --queue for a stopped spread",flags:["--project","--queue"]},{name:"cluster replica add",args:"<node-ref>",summary:"SnoutData Cloud: give a data node a replica, a copy that follows it and takes its place on its own if the node is lost or corrupt. It takes one of the plan project slots, and the node needs its first backup",flags:["--project","--node","--plan","--yes"]},{name:"cluster replica remove",args:"<node-ref>",summary:"SnoutData Cloud: remove a node's replica and free its project slot. If the node is then lost or corrupt, its share of the data is unavailable until it is restored from backups",flags:["--project","--node","--plan","--yes"]},{name:"cluster alerts",summary:"SnoutData Cloud: what happened to the cluster that you must know about (a node lost or corrupt, a failover, a node without its replica), open ones first, with those resolved in the last day",flags:["--project"]},{name:"cluster alerts seen",args:"<id>",summary:"SnoutData Cloud: mark an alert as seen. It stays open until what it is about is over",flags:["--project"]},{name:"cluster nodes drain",summary:"Move every range off a node",flags:[...Ce,"--to"]},{name:"cluster nodes remove",summary:"Detach a drained node",flags:[...Ce]},{name:"cluster keyspace create",summary:"A keyspace: the shard key type and its initial ranges",flags:[...Vt,"--key-type","--ranges","--seed","--nodes"]},{name:"cluster keyspace drop",summary:"Forget a keyspace no table is distributed by",flags:[...Vt]},{name:"cluster table distribute",summary:"Shard a table by a column, moving its rows out from the home node",flags:[...Ce,"--distribution-key","--keyspace"]},{name:"cluster table reference",summary:"Copy a table to every node",flags:[...Ce]},{name:"cluster autopilot",summary:"The autopilot, off unless you set it: say its mode and what it decided last, or set it to off, advise (record what it would run) or auto (run it); auto asks, or takes --yes",flags:["--project","--interval-ms","--yes"]},{name:"cluster table auto",summary:"Choose a distribution key for every table from the schema (the column most tables reference, else the primary key), say why for each, and distribute what it can in one job",flags:[...Ce,"--keyspace","--schemas","--min-bytes"]},{name:"cluster table global",summary:"Bring a table back to the home node alone",flags:[...Ce]},{name:"cluster range split",summary:"One range becomes two, and one half moves",flags:[...Ce,"--keyspace","--range","--at","--to"]},{name:"cluster range merge",summary:"Two adjacent ranges become one",flags:[...Ce]},{name:"cluster range move",summary:"Give a range to another node",flags:[...Ce,"--keyspace","--range","--to"]},{name:"cluster tenant pin",summary:"One key value gets its own range, and optionally its own node",flags:[...Ce,"--keyspace","--value","--node"]},{name:"cluster rebalance",summary:"Even out the ranges across the nodes",flags:[...Ce,"--keyspace"]},{name:"cluster scale",summary:"Add nodes and rebalance, or drain and remove the emptiest",flags:[...Ce,"--add","--remove","--nodes","--dbname","--sslmode"]},{name:"cluster verify",summary:"Row counts and a checksum per range, source against target",flags:[...Vt,"--keyspace"]},{name:"cluster cleanup",summary:"Delete the rows a node no longer owns, then VACUUM",flags:[...Ce,"--node"]},{name:"cluster dissolve",summary:"A standalone cluster of the home node alone: check the data, take the fences off and forget every keyspace and table, then stop the router yourself",flags:[...Ce]},{name:"cluster plan",summary:"The dry run of any operation above: steps, what moves, rows, size, copy time, expected pause",flags:[...Be,...is]},{name:"cluster jobs",summary:"The latest jobs",flags:[...Be]},{name:"cluster jobs show",summary:"One job, its plan and its steps",flags:[...Be]},{name:"cluster jobs watch",summary:"Follow a job until it finishes: exit 0 done, 1 failed or cancelled, 10 timed out",flags:[...Be,"--timeout"]},{name:"cluster jobs cancel",summary:"Stop a job: a move before its cutover rolls back, after it finishes its cleanup",flags:[...Be,"--yes"]},{name:"cluster jobs resume",summary:"Run a failed job again from the step that failed, and follow it",flags:[...Be,"--no-wait","--timeout"]},{name:"cluster settings",summary:"The cluster's cutover and advisor settings, or set them",flags:[...Be,...is,"--set"]},{name:"cluster check",summary:"The design check: whether every table's distribution key, foreign keys, unique keys and indexes let the cluster keep related rows on one node, each finding with its fix (SQL, or the command that does it). Runs nothing; exits 1 when something must be fixed",flags:[...Be]},{name:"cluster advise",summary:"What to split, move or add, from the router's advisor: each recommendation with its reason, its plan and the command that runs it. Runs nothing",flags:[...Be,"--sample-ms"]},{name:"mcp",summary:"Serve these operations as tools over stdio",flags:["--allow-delete"]}],Yi={"--ref":"The project. Defaults to SNOUTDATA_PROJECT, then .snoutdata/project.json here or in a parent","--profile":"Which stored sign-in to use, one per account. Defaults to SNOUTDATA_PROFILE, then the folder's link, then the default","login --profile":"Keep this sign-in as a profile of its own, beside the others; later commands pick it with --profile","link --profile":"Record the profile in the link, so every command in this folder signs in as that account","logout --all":"Forget the session of every profile on this machine","whoami --all":"List every profile signed in on this machine and whose it is, from the stored files, without calling out","projects scale --instances":"How many instances of the app API: 1 to what your plan allows (2 on Pro, 3 on Business). Your database is not copied","projects scale --yes":"Apply the plan without asking. Needed when nothing can ask (a script, CI)","functions logs --errors":"Only what was printed with console.error or console.warn, and the errors that stopped a request","functions logs --tail":"How many of the newest lines to show. Defaults to 100, at most 500","functions logs --follow":"Keep printing new lines as they arrive, about a minute after they are printed","containers deploy --port":"The port the container listens on, also given to it as PORT (default 8080)","containers deploy --dockerfile":"A folder with a Dockerfile (or the Dockerfile): built for linux/arm64 with your Docker and uploaded to the project","containers deploy --registry-user":"The user name for a private registry. The token comes on stdin, with --stdin","containers deploy --stdin":"Read the registry token from a pipe, so it is not in shell history or ps","containers deploy --clear-registry":"Forget the stored registry login, for an image that is public now","containers deploy --no-wait":"Answer once it is recorded, without waiting for the host to start it","containers logs --errors":"Only what was printed to stderr","containers logs --tail":"How many of the newest lines to show. Defaults to 100, at most 500","containers logs --follow":"Keep printing new lines as they arrive, about a minute after they are printed","--name":"The project's name","tokens create --name":"What the token is for and where it lives, shown in tokens list","db restore --name":"The name of the new project the restore makes","--region":"Where the project runs. Defaults to the nearest","projects create --servers":"shared (the default) or dedicated: your account's own servers, when we have set that up with you","projects create --max-size":"A dedicated project's largest size: it grows up to it under load and back down when quiet. Defaults to --size","projects create --size":"A dedicated project's server size: small, medium or large. The first project of a size starts its servers (about 5 minutes)","--env":"Write DATABASE_URL into .env in this folder, and add .env to .gitignore since it holds the password. Without it the URL is printed","--email":"The account to sign in as. The browser offers it, and a different account is reported at once and by whoami","--provider":"google (the default) or github","--sso":"Sign in with your company's identity provider","--domain":"With --sso: your work email or company domain. Only the domain is sent","--no-browser":"Print the sign-in URL instead of opening a browser","--device":"Sign in by typing a code into a browser on any machine: SSH, containers, agents","--timeout":"Seconds to wait before giving up","--check":"Say whether a newer version exists, and install nothing","--expires":"Days until the token stops working. Without it, it works until revoked","--project":"A SnoutData Cloud project ref: its cluster, through the control plane, as you (instead of --admin)","tokens create --project":"Limit the token to one project ref","--team":"Create it in a team (name or id), shared with its members","--no-wait":"Return as soon as it is asked for, without waiting for it to be true","--show-url":"Also print the connection string, which holds the password. Otherwise db url prints it when wanted","--p8":"The APNs .p8 key file (a path, never the key itself)","--key-id":"The APNs key id","--team-id":"Your Apple developer team id","--topic":"The app's bundle id","--environment":"production or sandbox","--file":"A file to read","push credentials set --file":"The FCM service-account JSON","auth template --file":"The email's HTML body","db restore --file":"The dump to restore (from db export or pg_dump -Fc)","--client-id":"Your Google OAuth client id; the secret is read from stdin with --stdin","--stdin":"Read the secret value from a pipe, so it is not in shell history","--site-url":"Where sign-in emails send people by default","--allow":"Comma-separated addresses a sign-in may return to","--subject":"The email's subject line","--dir":"The folder to read from","db push --dir":"The migrations folder (default ./migrations)","start --dir":"The migrations folder (default ./migrations)","functions deploy --dir":"The function's folder (default ./functions/<name>)","--entrypoint":"The file the runtime starts, when it is not index.ts","--no-verify-jwt":"Let anybody with the URL call it (webhooks). By default a caller needs a project key or a user session","--memory":"Memory per worker, in MB, within the plan","--concurrency":"How many workers it may run at once, within the plan","--reset":"Back to the plan's default size","--force":"Do it although it cannot be undone","--days":"How many days of history","--history":"Print the day-by-day table too","--port":"The port the local database listens on (default 54322)","--no-migrations":"Start the database and apply nothing","--out-of-order":"Apply a new migration that sorts before one already applied","--db-url":"Read a postgres:// database instead of a project","--local":"Read the database snoutdata start is running","--schema":"Comma-separated schemas (default public)","--out":"Write to this file instead of stdout","db export --out":"Where to save the dump","--status":"Show the last export without taking another","--dry-run":"Show what would run, and change nothing","--at":"The moment to restore to (an ISO time), into a NEW project","--window":"How far back a point-in-time restore can go","--allow-delete":"Let the agent's delete_project actually delete","--source":"Where the model runs: bedrock, anthropic, openai, openrouter, ollama or compatible","--model":"The model's id, as the provider names it","ai test --model":"The model to call (default: the first chat model served)","ai models add --provider":"The provider to add it to, or the name of a new one (default: the one already connected for --source)","ai models add --region":"Bedrock: the AWS region the model runs in","ai models add --stdin":"Read the provider's key from a pipe (AWS: the secret access key), so it is in neither the shell history nor ps","--base-url":"The provider's OpenAI-compatible address, usually ending in /v1","--price-in":"Dollars per million input tokens. Both rates, or neither to take the shipped catalogue's","--price-out":"Dollars per million output tokens","--access-key-id":"Bedrock with AWS credentials: the access key id (the secret on stdin)","--auth-header":"A header the server checks for its key, instead of a Bearer token","--models":"Comma-separated models the key may call (default: every one)","ai keys create --name":"What the key is for, shown in ai keys","ai routes set --models":"The models to try, comma-separated, in order","ai routes set --sort":"order (as written, the default), price (the cheapest first), or latency or throughput (the fastest first, as measured)","ai keys create --expires":"Days until the key stops working. Without it, it works until revoked","--amount":"Dollars","--period":"day (the default) or month","--soft":"Warn in the log when it is passed, instead of refusing","--by":"Group by day, model, provider, operation, key, user or group (default model)","ai usage --days":"How many days, up to 366 (default 30)","--prompt":"What to ask (default: a five-word hello)","--channel":"Only this channel","--since":"How far back, like 10m, 2h or 1d (default 1h)","--watch":"Keep printing what changes until interrupted","--admin":"The Lepis router's admin API, like http://127.0.0.1:7432 (LEPIS_ADMIN_ADDR). https for any other machine; NODE_EXTRA_CA_CERTS for a private CA. Defaults to LEPIS_ADMIN_URL","--token":"The router's admin token. Prefer LEPIS_ADMIN_TOKEN, which keeps it out of shell history and ps","--plan":"Show the plan (steps, what moves, rows, size, copy time, expected pause) and change nothing","--yes":"Run it without asking. Without a terminal to ask at, an operation that moves or deletes data needs it","cluster jobs cancel --yes":"Cancel without asking","cluster nodes add --port":"The node's port (default 5432)","--host":"The address the router reaches the node at","--dbname":"The database on the node (default postgres)","--sslmode":"disable, require or verify-full (the default)","--peer-host":"The address the other nodes reach it at, when it differs from the router's","--to":"The node (id or name) that receives it","cluster nodes drain --to":"Comma-separated nodes to move its ranges to. Default: the least loaded","--key-type":"The distribution key's Postgres type: bigint, int, text, uuid, ...","--ranges":"How many equal ranges to start with","--seed":"The hash seed","--nodes":"Comma-separated nodes (ids or names) to place the ranges on","--distribution-key":"The distribution key: the column whose value decides which node holds each row (not the primary key, though the primary key must include it). --column is its old name","--no-join":"SnoutData Cloud: leave the new node for you to attach with cluster nodes attach, instead of joining it on its own","--queue":"The stopped request (a table being spread) rather than a node","--keyspace":"The keyspace","--interval-ms":"How often the autopilot asks the advisor, in milliseconds (default 60000, at least 5000)","--schemas":"Comma-separated schemas whose tables table auto reads (default public)","--min-bytes":"The size below which table auto leaves a table keyed only by its own primary key unspread (default 16 MiB)","--range":"The range's lower bound, with --keyspace: the spelling for a bound that starts with a dash","cluster range split --at":"Where to split (a hash value). Default: the middle","--node":"A node, by id or name","cluster cleanup --node":"Only this node. Default: every node","cluster replica add --node":"The node pod's ref, as cluster status lists it (or as the first word)","cluster replica remove --node":"The node pod's ref, as cluster status lists it (or as the first word)","--value":"The key value to pin","--add":"Comma-separated nodes to add, each name=host[:port]","--remove":"How many of the emptiest nodes to drain and remove","cluster scale --nodes":"SnoutData Cloud: how many nodes the project should have, the home included","--max-write-pause-ms":"The longest a cutover may pause writes; one that would take longer is postponed","--drain-timeout-ms":"How long a cutover waits for open transactions to finish","--set":"Settings by their API names, name=value,... (the advisor's advice_* thresholds among them)","--sample-ms":"How long to measure write rates over, in ms (default: the advice_sample_ms setting; 0 skips them)","--ack-timeout-ms":"How long a cutover waits for every router to acknowledge it","--copy-mb-per-s":"The copy rate a plan estimates with (chosen, not measured)","--level":"full (everything the project password can do) or read (reads the project's own tables, never the auth or storage schemas, and writes nothing). Default read"};function cs(e,t){return Yi[`${e} ${t}`]??Yi[t]??""}function Xi(e,t){let n=ls.filter(s=>s.name===e||s.name.startsWith(`${e} `));if(!t)return n;let r=`${e} ${t}`,o=n.filter(s=>s.name===r||s.name.startsWith(`${r} `));return o.length>0?o:n}pe();be();de();import{spawn as Ah}from"node:child_process";function Rh(e){return`snout-${e}`}function rn(e,t,n){return new Promise((r,o)=>{let s=Ah("docker",["compose","-p",Rh(e.ref),"--project-directory",e.folder,...t],{cwd:e.folder,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout.on("data",i=>{a+=String(i)}),s.stderr.on("data",i=>{if(c+=String(i),n)for(let u of String(i).split(/\r?\n/).filter(Boolean))d(v(` ${u.trim()}`))}),s.on("error",i=>{if(i.code==="ENOENT"){o(new C("tool-missing","docker is not installed, or not on PATH. A local project runs in Docker (Docker Desktop on Windows and macOS)."));return}o(new C("failed",String(i)))}),s.on("close",i=>r({code:i??0,out:a,err:c}))})}async function Th(e){let t=await rn(e,["ps","-a","--format","json"],!1);if(t.code!==0)throw new C("failed",t.err.trim()||"docker compose ps failed. Is Docker running?");let n=t.out.trim();return(n.startsWith("[")?JSON.parse(n):n.split(/\r?\n/).filter(Boolean).map(o=>JSON.parse(o))).map(o=>({service:o.Service??"?",state:o.State==="exited"&&o.ExitCode===0?"done":o.State??"?",health:o.Health??""})).sort((o,s)=>o.service.localeCompare(s.service))}async function Ul(e){let t=await Th(e),n=t.filter(o=>o.state==="running").length,r=t.filter(o=>o.state!=="done").length;return b({ref:e.ref,local:e.folder,api:e.apiUrl,dbPort:e.dbPort,running:n,services:t},()=>{if(d(`${M(e.name??e.ref)} (local, ${e.folder})`),t.length===0){d("Not started. `snoutdata start` brings it up.");return}process.stdout.write(`${X([["SERVICE","STATE","HEALTH"],...t.map(o=>[o.service,o.state,o.health])])}
|
|
511
|
-
`),
|
|
512
|
-
`)})}
|
|
513
|
-
`)}${
|
|
514
|
-
`),!0}async function
|
|
515
|
-
`)})}async function
|
|
787
|
+
${r}`}async function tv(e,t,n={}){ae(t);let r=(await e.list()).find(o=>o.ref===t);return r&&r.status!=="stopped"&&await e.stop(t,Lm),al(e,{ref:t,port:0,ownerPassword:"",adminPassword:""},n)}async function nv(e,t,n){ae(t),await e.remove(t),n&&(await e.removeData(t),ms.delete(t))}async function al(e,t,n={}){ae(t.ref);let r=(await e.list()).find(a=>a.ref===t.ref),o=r?.status==="running",s=n.hasData??gs;return{ref:t.ref,exists:!!r,status:r?.status??"absent",ready:o?await e.waitReady(t.ref,1):!1,hasData:r?.hasData??await s(t.ref),port:t.port,databaseBytes:o?await e.databaseBytes(t.ref):null,services:r?.services??[],uri:t.port>0&&t.ownerPassword?rg(t):null}}var nl,de,ol,Nn,U$,Yf,sl,Ht,F$,Xf,Se,G$,q$,Zf,ms,tg,lg=z(()=>{"use strict";Mm();fr();Um();es();os();Ie();nl=process.env.SNOUTPOD_ENGINE??"podman";de=j$(),ol=18,Nn=[17,18],U$="snoutpod/postgres",Yf="ghcr.io/snoutdata/snoutpod-postgres";sl=br(null).name,Ht=process.env.SNOUTPOD_LOCAL_NETWORK??"snoutpod-local",F$=54322,Xf=512,Se=Dm();G$="cd packages/snoutpod && npm run image:build",q$=`${Yf}:${ol}`;Zf=20*60*1e3;ms=new Map;tg="this podman cannot blackhole a route, so the local tier cannot isolate its containers"});ve();var ze=["--admin","--token","--project"],As=["--max-write-pause-ms","--drain-timeout-ms","--ack-timeout-ms","--copy-mb-per-s"],rn=[...ze,"--plan","--no-wait","--timeout",...As],Fe=[...rn,"--yes"],Rs=[{name:"init",summary:"Create or link a project for this folder, and print its DATABASE_URL or write it to .env",flags:["--name","--region","--env","--ref"]},{name:"login",summary:"Sign in through a browser: a page offering Google, GitHub and your work email; --provider goes straight to one, --sso to your company's identity provider, --device types a code into a browser anywhere",flags:["--email","--provider","--sso","--domain","--no-browser","--device","--profile","--timeout"]},{name:"logout",summary:"Forget the stored session, of this profile or of every one",flags:["--profile","--all"]},{name:"profile",summary:"Which profile this command would sign in as, and why (the flag, SNOUTDATA_PROFILE, the folder's link, profile use, or the default)",flags:["--profile"]},{name:"profile use",summary:"Make a signed-in profile this machine's default, so commands need no --profile; profile use default goes back",flags:[]},{name:"whoami",summary:"Who this credential belongs to, and whether it is the account login --email asked for; --all lists every profile",flags:["--profile","--all"]},{name:"upgrade",summary:"Install the newest CLI the way this one was installed (binary or npm), checksum verified",flags:["--check"]},{name:"tokens list",summary:"Long-lived access tokens on this account",flags:[]},{name:"tokens create",summary:"Mint an sdt_ token for CI or an agent",flags:["--name","--expires","--project"]},{name:"tokens revoke",args:"<id|sdt_prefix>",summary:"Revoke one by id or prefix",flags:[]},{name:"projects list",summary:"Every project on this account",flags:[]},{name:"projects create",summary:"Make a hosted database, and print its ref",flags:["--name","--region","--servers","--size","--max-size","--team","--no-wait","--timeout","--show-url"]},{name:"projects pause",summary:"Stop a project, and wait until it is paused",flags:["--ref","--no-wait","--timeout"]},{name:"projects resume",summary:"Start a paused project, and wait until it is ready",flags:["--ref","--no-wait","--timeout"]},{name:"projects delete",summary:"Delete a project, and wait until it is gone",flags:["--ref","--no-wait","--timeout"]},{name:"projects scale",args:"[ref]",summary:"More capacity for your app's API (auth, the data API and the router): 1 to 3 instances. Shows the plan and asks first; without --instances, what your plan allows",flags:["--ref","--instances","--yes"]},{name:"projects show",summary:"One project: state, products (Realtime included), functions, secrets, domains",flags:["--ref"]},{name:"products",summary:"Auth, storage, the data API and push: on or off. Realtime is always on, and listed",flags:["--ref"]},{name:"products enable",args:"auth|storage|data-api|push",summary:"Turn auth, storage, data-api or push on",flags:["--ref"]},{name:"products disable",args:"auth|storage|data-api|push",summary:"Turn auth, storage, data-api or push off",flags:["--ref"]},{name:"push credentials",summary:"Push keys: what is set for APNs, FCM and Web Push (never the keys)",flags:["--ref"]},{name:"push credentials set",args:"apns|fcm",summary:"Set the APNs key (a .p8) or the FCM service account, checked before it is stored",flags:["--ref","--p8","--key-id","--team-id","--topic","--environment","--file"]},{name:"push credentials remove",args:"apns|fcm",summary:"Remove the APNs or FCM credentials",flags:["--ref"]},{name:"auth",summary:"Auth settings: Google sign-in and redirect addresses",flags:["--ref"]},{name:"auth google",summary:"Sign in with Google, with your own client (secret on stdin)",flags:["--ref","--client-id","--stdin"]},{name:"auth anonymous",args:"on|off",summary:"Guest sign-in on or off: guestSignIn() gives a browser a session with no email or password",flags:["--ref"]},{name:"auth redirects",summary:"The site URL and the addresses a sign-in may return to",flags:["--ref","--site-url","--allow"]},{name:"auth templates",summary:"The five auth emails, ours or your own",flags:["--ref"]},{name:"auth template",args:"KIND",summary:"Use your own subject and HTML for one, or reset it",flags:["--ref","--file","--subject"]},{name:"realtime inspect",summary:"The channels open now: each client, its roster entry, when it was last heard, and the last minute of messages",flags:["--channel","--watch","--ref"]},{name:"realtime logs",summary:"The connection log: connects, joins, leaves and disconnects, with the reason each ended",flags:["--since","--channel","--ref"]},{name:"ai",summary:"The project's own AI gateway: on or off, its models, budgets and the last 30 days' spend",flags:["--ref"]},{name:"ai enable",summary:"Switch the AI gateway on. Its container joins the pod, which restarts the database once",flags:["--ref"]},{name:"ai disable",summary:"Switch it off. Its providers, models, keys and log stay in the project's database",flags:["--ref"]},{name:"ai models",summary:"The models it serves: provider, upstream id, price and whether each is served",flags:["--ref"]},{name:"ai models add",args:"[name]",summary:"Add a model, with its provider and key when the provider is new. The key comes on stdin and the provider proves it first; without --model, print the steps to find the key and the model's id",flags:["--ref","--source","--model","--provider","--base-url","--region","--price-in","--price-out","--access-key-id","--auth-header","--stdin"]},{name:"ai models remove",args:"<name>",summary:"Stop serving a model",flags:["--ref"]},{name:"ai providers",summary:"Where its models run, and whether each one's key is stored (never the key)",flags:["--ref"]},{name:"ai providers remove",args:"<name>",summary:"Remove a provider no model uses",flags:["--ref"]},{name:"ai routes",summary:"Names that stand for several models, and what each tries in which order",flags:["--ref"]},{name:"ai routes set",args:"<name>",summary:"Make or replace a route: its models, tried in turn when one fails for a reason that is not the caller's",flags:["--ref","--models","--sort"]},{name:"ai routes remove",args:"<name>",summary:"Remove a route; its models stay",flags:["--ref"]},{name:"ai keys",summary:"Keys a server calls the gateway with: created, last used, revoked",flags:["--ref"]},{name:"ai keys create",summary:"Make a key for a server, shown once",flags:["--ref","--name","--models","--expires"]},{name:"ai keys revoke",args:"<id>",summary:"Refuse a key from now on",flags:["--ref"]},{name:"ai budgets",summary:"What may be spent, and by whom",flags:["--ref"]},{name:"ai budgets set",args:"project|users",summary:"The project's budget, or every signed-in user's. A browser call needs both, hard",flags:["--ref","--amount","--period","--soft"]},{name:"ai budgets remove",args:"<id>",summary:"Remove a budget",flags:["--ref"]},{name:"ai usage",summary:"Requests, tokens and cost, grouped",flags:["--ref","--by","--days"]},{name:"ai test",summary:"One chat call through the project's door, with a key made for it and revoked after",flags:["--ref","--model","--prompt"]},{name:"alerts hooks",summary:"Where the project's alerts go besides the owner's email: webhooks and Slack channels",flags:["--ref"]},{name:"alerts hooks add",args:"<url>",summary:"Send alerts to an https:// webhook (signed; the secret is printed once) or, with --slack, a Slack incoming webhook",flags:["--ref","--slack"]},{name:"alerts hooks remove",args:"<id>",summary:"Stop sending alerts there",flags:["--ref"]},{name:"alerts hooks test",args:"<id>",summary:"Send a test message there now",flags:["--ref"]},{name:"domains",summary:"Your own domains in front of the project API",flags:["--ref"]},{name:"domains add",args:"<hostname>",summary:"Add one, and print the DNS records to publish",flags:["--ref"]},{name:"domains verify",args:"<hostname>",summary:"Check its records and verify it",flags:["--ref"]},{name:"domains remove",args:"<hostname>",summary:"Stop serving it",flags:["--ref"]},{name:"functions deploy",args:"<name>",summary:"Put a folder of TypeScript on the edge",flags:["--ref","--dir","--entrypoint","--no-verify-jwt"]},{name:"functions list",summary:"What this project has deployed",flags:["--ref"]},{name:"functions size",args:"<name>",summary:"Its memory and workers, within the plan",flags:["--ref","--memory","--concurrency","--reset"]},{name:"functions logs",args:"[name]",summary:"What your functions printed, the last seven days",flags:["--ref","--errors","--tail","--follow"]},{name:"functions delete",args:"<name>",summary:"Remove one",flags:["--ref"]},{name:"containers deploy",args:"<name> <image> | <name> --dockerfile <dir>",summary:"Run a Docker image of yours all the time, pinned to the digest its tag points at now, or built from a Dockerfile with your Docker",flags:["--ref","--port","--dockerfile","--registry-user","--stdin","--clear-registry","--no-wait"]},{name:"containers list",summary:"Each container: status, image and URL",flags:["--ref"]},{name:"containers logs",args:"[name]",summary:"What your containers printed, the last seven days",flags:["--ref","--errors","--tail","--follow"]},{name:"containers restart",args:"<name>",summary:"Start one again from its image",flags:["--ref"]},{name:"containers delete",args:"<name>",summary:"Stop one and remove it",flags:["--ref"]},{name:"secrets set",summary:"Set the environment functions and containers run with",flags:["--ref","--stdin"]},{name:"secrets list",summary:"The names, never the values",flags:["--ref"]},{name:"secrets unset",summary:"Remove one",flags:["--ref"]},{name:"keys",summary:"The app key and server key for a project",flags:["--ref"]},{name:"keys rotate",summary:"New keys, breaking every one already issued",flags:["--ref","--force"]},{name:"teams",summary:"Teams this account belongs to",flags:[]},{name:"link",summary:"Point this folder at a project, and at the profile it was linked with",flags:["--ref","--profile"]},{name:"usage",summary:"Size and compute against the plan limit; --tables adds the largest tables",flags:["--ref","--days","--history","--tables","--limit"]},{name:"metrics",summary:"How hard each server works: CPU, memory, disk, connections, transactions, mean statement time and replica lag, now and over the window",flags:["--ref","--project","--node","--window"]},{name:"start",summary:"A Postgres on this machine, with your migrations applied",flags:["--port","--dir","--no-migrations","--out-of-order"]},{name:"stop",summary:"Stop the local database. The data stays",flags:[]},{name:"status",summary:"What the local database is doing",flags:[]},{name:"gen types typescript",summary:"The schema as a TypeScript Database type, on stdout",flags:["--ref","--db-url","--local","--schema","--out"]},{name:"db url",summary:"A connection string",flags:["--ref"]},{name:"db psql",summary:"Open psql, or run statements after --",flags:["--ref"]},{name:"db query",args:'"<sql>"',summary:"Run SQL with no psql installed and print what it returns as tables. Several statements run in one transaction",flags:["--ref"]},{name:"db run",args:"<file.sql>",summary:"Run a .sql file in one transaction with no psql installed: the first statement that fails rolls it all back, and the error says which",flags:["--ref"]},{name:"db slow",summary:"The statements that took the most time in all, from pg_stat_statements: total, mean, calls, rows, share",flags:["--ref","--limit"]},{name:"db reset-password",summary:"Rotate the project password: the new one is on the other of two owner logins, and the old one works for --grace minutes (default 60, 0 to 1440; 0 ends its connections)",flags:["--ref","--grace"]},{name:"db access",summary:"Who signs in to the database as themselves with OAuth (Postgres 18), at which level, as which role",flags:["--ref"]},{name:"db access grant",summary:"Let a person sign in to the database as themselves, and print their connection string",flags:["--ref","--level"]},{name:"db token",summary:"A database token: the password of user snout_token, signing in as you, for an hour, from any driver or tool",flags:["--ref"]},{name:"db access revoke",summary:"Take it away, by email or role; a token already issued can work until it expires (up to 1 hour)",flags:["--ref"]},{name:"db allow",summary:"The addresses that may connect to the database, and whether yours is one; an empty list is every address",flags:["--ref"]},{name:"db allow add",args:"<cidr>",summary:"Let an IPv4 or IPv6 address or range connect (at most 50 entries); again with --note changes its note",flags:["--ref","--note"]},{name:"db allow remove",args:"<cidr>",summary:"Take an address or range off the list",flags:["--ref"]},{name:"db allow clear",summary:"Empty the list, so every address may connect again",flags:["--ref"]},{name:"db export",summary:"Take or download a dump",flags:["--ref","--out","--status","--timeout"]},{name:"db push",summary:"Apply migrations from a folder",flags:["--dir","--dry-run","--out-of-order"]},{name:"db restore",summary:"Put a dump into a project, or rewind it to a moment into a new project",flags:["--file","--force","--at","--name","--window","--ref"]},{name:"cluster status",summary:"A Lepis cluster: its nodes, keyspaces and their ranges (keyspace:lo), tables, routers and unfinished jobs",flags:[...ze]},{name:"cluster ops",summary:"The operations the router offers, and its default settings",flags:[...ze]},{name:"cluster nodes",summary:"The nodes, their state and how many ranges each owns",flags:[...ze]},{name:"cluster enable",summary:"SnoutData Cloud: make a project a cluster. The router and the services start in pods of their own while the database keeps running. Each node then uses one of the plan project slots",flags:["--project","--plan","--yes"]},{name:"cluster disable",summary:"SnoutData Cloud: turn a cluster of one node back into a plain project. The data is checked, the cluster is taken apart, the router stops and the services move back into the database pod, which restarts the database once",flags:["--project","--plan","--yes"]},{name:"cluster nodes attach",summary:"SnoutData Cloud: hand a ready node pod made with nodes add --no-join to the cluster, as a standby until a range moves onto it",flags:[...rn]},{name:"cluster nodes add",summary:"Join a Postgres node: checks its version and settings, syncs roles and reference tables. In SnoutData Cloud it makes a node that starts as a copy of the home node, then joins and takes its share of the data on its own (--no-join to attach it by hand); it uses one of the plan project slots",flags:[...rn,"--host","--port","--dbname","--sslmode","--peer-host","--no-join"]},{name:"cluster spread",summary:"SnoutData Cloud: spread a table over the cluster in one go: a keyspace for its key (shared with tables keyed the same way), the table distributed by it, then a rebalance",flags:["--project","--distribution-key","--key-type","--plan","--yes"]},{name:"cluster retry",summary:"SnoutData Cloud: take up a stopped step again: a node whose join stopped, or --queue for a stopped spread",flags:["--project","--queue"]},{name:"cluster replica add",args:"<node-ref>",summary:"SnoutData Cloud: give a data node a replica, a copy that follows it and takes its place on its own if the node is lost or corrupt. It takes one of the plan project slots, and the node needs its first backup",flags:["--project","--node","--plan","--yes"]},{name:"cluster replica remove",args:"<node-ref>",summary:"SnoutData Cloud: remove a node's replica and free its project slot. If the node is then lost or corrupt, its share of the data is unavailable until it is restored from backups",flags:["--project","--node","--plan","--yes"]},{name:"cluster alerts",summary:"SnoutData Cloud: what happened to the cluster that you must know about (a node lost or corrupt, a failover, a node without its replica), open ones first, with those resolved in the last day",flags:["--project"]},{name:"cluster alerts seen",args:"<id>",summary:"SnoutData Cloud: mark an alert as seen. It stays open until what it is about is over",flags:["--project"]},{name:"cluster nodes drain",summary:"Move every range off a node",flags:[...Fe,"--to"]},{name:"cluster nodes remove",summary:"Detach a drained node",flags:[...Fe]},{name:"cluster keyspace create",summary:"A keyspace: the shard key type and its initial ranges",flags:[...rn,"--key-type","--ranges","--seed","--nodes"]},{name:"cluster keyspace drop",summary:"Forget a keyspace no table is distributed by",flags:[...rn]},{name:"cluster table distribute",summary:"Shard a table by a column, moving its rows out from the home node",flags:[...Fe,"--distribution-key","--keyspace"]},{name:"cluster table reference",summary:"Copy a table to every node",flags:[...Fe]},{name:"cluster autopilot",summary:"The autopilot, off unless you set it: say its mode and what it decided last, or set it to off, advise (record what it would run) or auto (run it); auto asks, or takes --yes",flags:["--project","--interval-ms","--yes"]},{name:"cluster table auto",summary:"Choose a distribution key for every table from the schema (the column most tables reference, else the primary key), say why for each, and distribute what it can in one job",flags:[...Fe,"--keyspace","--schemas","--min-bytes"]},{name:"cluster table global",summary:"Bring a table back to the home node alone",flags:[...Fe]},{name:"cluster range split",summary:"One range becomes two, and one half moves",flags:[...Fe,"--keyspace","--range","--at","--to"]},{name:"cluster range merge",summary:"Two adjacent ranges become one",flags:[...Fe]},{name:"cluster range move",summary:"Give a range to another node",flags:[...Fe,"--keyspace","--range","--to"]},{name:"cluster tenant pin",summary:"One key value gets its own range, and optionally its own node",flags:[...Fe,"--keyspace","--value","--node"]},{name:"cluster rebalance",summary:"Even out the ranges across the nodes",flags:[...Fe,"--keyspace"]},{name:"cluster scale",summary:"Add nodes and rebalance, or drain and remove the emptiest",flags:[...Fe,"--add","--remove","--nodes","--dbname","--sslmode"]},{name:"cluster verify",summary:"Row counts and a checksum per range, source against target",flags:[...rn,"--keyspace"]},{name:"cluster cleanup",summary:"Delete the rows a node no longer owns, then VACUUM",flags:[...Fe,"--node"]},{name:"cluster dissolve",summary:"A standalone cluster of the home node alone: check the data, take the fences off and forget every keyspace and table, then stop the router yourself",flags:[...Fe]},{name:"cluster plan",summary:"The dry run of any operation above: steps, what moves, rows, size, copy time, expected pause",flags:[...ze,...As]},{name:"cluster jobs",summary:"The latest jobs",flags:[...ze]},{name:"cluster jobs show",summary:"One job, its plan and its steps",flags:[...ze]},{name:"cluster jobs watch",summary:"Follow a job until it finishes: exit 0 done, 1 failed or cancelled, 10 timed out",flags:[...ze,"--timeout"]},{name:"cluster jobs cancel",summary:"Stop a job: a move before its cutover rolls back, after it finishes its cleanup",flags:[...ze,"--yes"]},{name:"cluster jobs resume",summary:"Run a failed job again from the step that failed, and follow it",flags:[...ze,"--no-wait","--timeout"]},{name:"cluster settings",summary:"The cluster's cutover and advisor settings, or set them",flags:[...ze,...As,"--set"]},{name:"cluster check",summary:"The design check: whether every table's distribution key, foreign keys, unique keys and indexes let the cluster keep related rows on one node, each finding with its fix (SQL, or the command that does it). Runs nothing; exits 1 when something must be fixed",flags:[...ze]},{name:"cluster advise",summary:"What to split, move or add, from the router's advisor: each recommendation with its reason, its plan and the command that runs it. Runs nothing",flags:[...ze,"--sample-ms"]},{name:"mcp",summary:"Serve these operations as tools over stdio",flags:["--allow-delete"]}],Nl={"--ref":"The project. Defaults to SNOUTDATA_PROJECT, then .snoutdata/project.json here or in a parent","--profile":"Which stored sign-in to use, one per account. Defaults to SNOUTDATA_PROFILE, then the folder's link, then the one profile use chose, then the default","login --profile":"Keep this sign-in as a profile of its own, beside the others; later commands pick it with --profile","link --profile":"Record the profile in the link, so every command in this folder signs in as that account","logout --all":"Forget the session of every profile on this machine","whoami --all":"List every profile signed in on this machine and whose it is, from the stored files, without calling out","projects scale --instances":"How many instances of the app API: 1 to what your plan allows (2 on Pro, 3 on Business). Your database is not copied","projects scale --yes":"Apply the plan without asking. Needed when nothing can ask (a script, CI)","functions logs --errors":"Only what was printed with console.error or console.warn, and the errors that stopped a request","functions logs --tail":"How many of the newest lines to show. Defaults to 100, at most 500","functions logs --follow":"Keep printing new lines as they arrive, about a minute after they are printed","containers deploy --port":"The port the container listens on, also given to it as PORT (default 8080)","containers deploy --dockerfile":"A folder with a Dockerfile (or the Dockerfile): built for linux/arm64 with your Docker and uploaded to the project","containers deploy --registry-user":"The user name for a private registry. The token comes on stdin, with --stdin","containers deploy --stdin":"Read the registry token from a pipe, so it is not in shell history or ps","containers deploy --clear-registry":"Forget the stored registry login, for an image that is public now","containers deploy --no-wait":"Answer once it is recorded, without waiting for the host to start it","containers logs --errors":"Only what was printed to stderr","containers logs --tail":"How many of the newest lines to show. Defaults to 100, at most 500","containers logs --follow":"Keep printing new lines as they arrive, about a minute after they are printed","--name":"The project's name","tokens create --name":"What the token is for and where it lives, shown in tokens list","db restore --name":"The name of the new project the restore makes","--region":"Where the project runs. Defaults to the nearest","projects create --servers":"shared (the default) or dedicated: your account's own servers, when we have set that up with you","projects create --max-size":"A dedicated project's largest size: it grows up to it under load and back down when quiet. Defaults to --size","projects create --size":"A dedicated project's server size: small, medium or large. The first project of a size starts its servers (about 5 minutes)","--env":"Write DATABASE_URL into .env in this folder, and add .env to .gitignore since it holds the password. Without it the URL is printed","--email":"The account to sign in as. The browser offers it, and a different account is reported at once and by whoami","--provider":"google or github, straight to it. Without it, login opens a page offering every way in","--sso":"Sign in with your company's identity provider","--domain":"With --sso: your work email or company domain. Only the domain is sent","--no-browser":"Print the sign-in URL instead of opening a browser","--device":"Sign in by typing a code into a browser on any machine: SSH, containers, agents","--timeout":"Seconds to wait before giving up","--check":"Say whether a newer version exists, and install nothing","--expires":"Days until the token stops working. Without it, it works until revoked","--project":"A SnoutData Cloud project ref: its cluster, through the control plane, as you (instead of --admin)","tokens create --project":"Limit the token to one project ref","--team":"Create it in a team (name or id), shared with its members","--no-wait":"Return as soon as it is asked for, without waiting for it to be true","--show-url":"Also print the connection string, which holds the password. Otherwise db url prints it when wanted","--p8":"The APNs .p8 key file (a path, never the key itself)","--key-id":"The APNs key id","--team-id":"Your Apple developer team id","--topic":"The app's bundle id","--environment":"production or sandbox","--file":"A file to read","push credentials set --file":"The FCM service-account JSON","auth template --file":"The email's HTML body","db restore --file":"The dump to restore (from db export or pg_dump -Fc)","--client-id":"Your Google OAuth client id; the secret is read from stdin with --stdin","--stdin":"Read the secret value from a pipe, so it is not in shell history","--site-url":"Where sign-in emails send people by default","--allow":"Comma-separated addresses a sign-in may return to","--subject":"The email's subject line","--dir":"The folder to read from","db push --dir":"The migrations folder (default ./migrations)","start --dir":"The migrations folder (default ./migrations)","functions deploy --dir":"The function's folder (default ./functions/<name>)","--entrypoint":"The file the runtime starts, when it is not index.ts","--no-verify-jwt":"Let anybody with the URL call it (webhooks). By default a caller needs a project key or a user session","--memory":"Memory per worker, in MB, within the plan","--concurrency":"How many workers it may run at once, within the plan","--reset":"Back to the plan's default size","--force":"Do it although it cannot be undone","--days":"How many days of history","--history":"Print the day-by-day table too","--tables":"The largest tables too: their size with indexes and their rows (an estimate), each partitioned table once with its partitions","--limit":"How many to show","db slow --limit":"How many statements to show, 1 to 1000 (default 10)","usage --limit":"How many tables --tables shows, 1 to 1000 (default 20)","--port":"The port the local database listens on (default 54322)","--no-migrations":"Start the database and apply nothing","--out-of-order":"Apply a new migration that sorts before one already applied","--db-url":"Read a postgres:// database instead of a project","--local":"Read the database snoutdata start is running","--schema":"Comma-separated schemas (default public)","--out":"Write to this file instead of stdout","db export --out":"Where to save the dump","--status":"Show the last export without taking another","--dry-run":"Show what would run, and change nothing","--at":"The moment to restore to (an ISO time), into a NEW project","--window":"How far back a point-in-time restore can go","metrics --project":"The project, as the cluster commands name it (the same as --ref)","metrics --node":"Only this server: a node or replica ref, or the project ref for its own (default: every one)","--grace":"Minutes the old password keeps working after a reset, 0 to 1440 (default 60); 0 cuts it off and ends its connections","metrics --window":"hour (the default), day or week","--allow-delete":"Let the agent's delete_project actually delete","--source":"Where the model runs: bedrock, anthropic, openai, openrouter, ollama or compatible","--model":"The model's id, as the provider names it","ai test --model":"The model to call (default: the first chat model served)","ai models add --provider":"The provider to add it to, or the name of a new one (default: the one already connected for --source)","ai models add --region":"Bedrock: the AWS region the model runs in","ai models add --stdin":"Read the provider's key from a pipe (AWS: the secret access key), so it is in neither the shell history nor ps","--base-url":"The provider's OpenAI-compatible address, usually ending in /v1","--price-in":"Dollars per million input tokens. Both rates, or neither to take the shipped catalogue's","--price-out":"Dollars per million output tokens","--access-key-id":"Bedrock with AWS credentials: the access key id (the secret on stdin)","--auth-header":"A header the server checks for its key, instead of a Bearer token","--models":"Comma-separated models the key may call (default: every one)","ai keys create --name":"What the key is for, shown in ai keys","ai routes set --models":"The models to try, comma-separated, in order","ai routes set --sort":"order (as written, the default), price (the cheapest first), or latency or throughput (the fastest first, as measured)","ai keys create --expires":"Days until the key stops working. Without it, it works until revoked","--amount":"Dollars","--period":"day (the default) or month","--soft":"Warn in the log when it is passed, instead of refusing","--by":"Group by day, model, provider, operation, key, user or group (default model)","ai usage --days":"How many days, up to 366 (default 30)","--prompt":"What to ask (default: a five-word hello)","--channel":"Only this channel","--since":"How far back, like 10m, 2h or 1d (default 1h)","--watch":"Keep printing what changes until interrupted","--admin":"The Lepis router's admin API, like http://127.0.0.1:7432 (LEPIS_ADMIN_ADDR). https for any other machine; NODE_EXTRA_CA_CERTS for a private CA. Defaults to LEPIS_ADMIN_URL","--token":"The router's admin token. Prefer LEPIS_ADMIN_TOKEN, which keeps it out of shell history and ps","--plan":"Show the plan (steps, what moves, rows, size, copy time, expected pause) and change nothing","--yes":"Run it without asking. Without a terminal to ask at, an operation that moves or deletes data needs it","cluster jobs cancel --yes":"Cancel without asking","cluster nodes add --port":"The node's port (default 5432)","--host":"The address the router reaches the node at","--dbname":"The database on the node (default postgres)","--sslmode":"disable, require or verify-full (the default)","--peer-host":"The address the other nodes reach it at, when it differs from the router's","--to":"The node (id or name) that receives it","cluster nodes drain --to":"Comma-separated nodes to move its ranges to. Default: the least loaded","--key-type":"The distribution key's Postgres type: bigint, int, text, uuid, ...","--ranges":"How many equal ranges to start with","--seed":"The hash seed","--nodes":"Comma-separated nodes (ids or names) to place the ranges on","--distribution-key":"The distribution key: the column whose value decides which node holds each row. The primary key and every unique constraint must include it, or the spread is refused (a node can only check uniqueness over its own rows). --column is its old name","--no-join":"SnoutData Cloud: leave the new node for you to attach with cluster nodes attach, instead of joining it on its own","--slack":"The URL is a Slack incoming webhook (https://hooks.slack.com/services/...), posted as a message rather than JSON","--queue":"The stopped request (a table being spread) rather than a node","--keyspace":"The keyspace","--interval-ms":"How often the autopilot asks the advisor, in milliseconds (default 60000, at least 5000)","--schemas":"Comma-separated schemas whose tables table auto reads (default public)","--min-bytes":"The size below which table auto leaves a table keyed only by its own primary key unspread (default 16 MiB)","--range":"The range's lower bound, with --keyspace: the spelling for a bound that starts with a dash","cluster range split --at":"Where to split (a hash value). Default: the middle","--node":"A node, by id or name","cluster cleanup --node":"Only this node. Default: every node","cluster replica add --node":"The node pod's ref, as cluster status lists it (or as the first word)","cluster replica remove --node":"The node pod's ref, as cluster status lists it (or as the first word)","--value":"The key value to pin","--add":"Comma-separated nodes to add, each name=host[:port]","--remove":"How many of the emptiest nodes to drain and remove","cluster scale --nodes":"SnoutData Cloud: how many nodes the project should have, the home included","--max-write-pause-ms":"The longest a cutover may pause writes; one that would take longer is postponed","--drain-timeout-ms":"How long a cutover waits for open transactions to finish","--set":"Settings by their API names, name=value,... (the advisor's advice_* thresholds among them)","--sample-ms":"How long to measure write rates over, in ms (default: the advice_sample_ms setting; 0 skips them)","--ack-timeout-ms":"How long a cutover waits for every router to acknowledge it","--copy-mb-per-s":"The copy rate a plan estimates with (chosen, not measured)","db allow add --note":'What the entry is for, such as "office" or "Fargate NAT", up to 200 characters',"--level":"full (everything the project password can do) or read (reads the project's own tables, never the auth or storage schemas, and writes nothing). Default read"};function Ts(e,t){return Nl[`${e} ${t}`]??Nl[t]??""}function Il(e,t){let n=Rs.filter(s=>s.name===e||s.name.startsWith(`${e} `));if(!t)return n;let r=`${e} ${t}`,o=n.filter(s=>s.name===r||s.name.startsWith(`${r} `));return o.length>0?o:n}me();_e();pe();import{spawn as jy}from"node:child_process";function Uy(e){return`snout-${e}`}function fn(e,t,n){return new Promise((r,o)=>{let s=jy("docker",["compose","-p",Uy(e.ref),"--project-directory",e.folder,...t],{cwd:e.folder,stdio:["ignore","pipe","pipe"]}),a="",l="";s.stdout.on("data",d=>{a+=String(d)}),s.stderr.on("data",d=>{if(l+=String(d),n)for(let c of String(d).split(/\r?\n/).filter(Boolean))u($(` ${c.trim()}`))}),s.on("error",d=>{if(d.code==="ENOENT"){o(new O("tool-missing","docker is not installed, or not on PATH. A local project runs in Docker (Docker Desktop on Windows and macOS)."));return}o(new O("failed",String(d)))}),s.on("close",d=>r({code:d??0,out:a,err:l}))})}async function Fy(e){let t=await fn(e,["ps","-a","--format","json"],!1);if(t.code!==0)throw new O("failed",t.err.trim()||"docker compose ps failed. Is Docker running?");let n=t.out.trim();return(n.startsWith("[")?JSON.parse(n):n.split(/\r?\n/).filter(Boolean).map(o=>JSON.parse(o))).map(o=>({service:o.Service??"?",state:o.State==="exited"&&o.ExitCode===0?"done":o.State??"?",health:o.Health??""})).sort((o,s)=>o.service.localeCompare(s.service))}async function Ac(e){let t=await Fy(e),n=t.filter(o=>o.state==="running").length,r=t.filter(o=>o.state!=="done").length;return w({ref:e.ref,local:e.folder,api:e.apiUrl,dbPort:e.dbPort,running:n,services:t},()=>{if(u(`${N(e.name??e.ref)} (local, ${e.folder})`),t.length===0){u("Not started. `snoutdata start` brings it up.");return}process.stdout.write(`${V([["SERVICE","STATE","HEALTH"],...t.map(o=>[o.service,o.state,o.health])])}
|
|
788
|
+
`),u(`${n} of ${r} services running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}.`)}),0}async function Rc(e){u(`Starting ${e.name??e.ref} (local)\u2026`);let t=await fn(e,["up","-d","--wait","--wait-timeout","600"],!0);if(t.code!==0)throw new O("failed",`docker compose up failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return w({ref:e.ref,api:e.apiUrl,dbPort:e.dbPort,started:!0},()=>{u(`Running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}. \`snoutdata db url\` prints the connection string.`)}),0}async function Tc(e){let t=await fn(e,["stop"],!0);if(t.code!==0)throw new O("failed",`docker compose stop failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return w({ref:e.ref,stopped:!0},()=>u(`Stopped ${e.name??e.ref}. Its data is kept; \`snoutdata start\` brings it back.`)),0}function Oc(e){w({ref:e.ref,name:e.name,local:e.folder,api:e.apiUrl,dbPort:e.dbPort},()=>{process.stdout.write(`${V([["name",e.name??"(not set up by Studio)"],["ref",e.ref],["where",`local, ${e.folder}`],["api",e.apiUrl],["database",`127.0.0.1:${e.dbPort}`]])}
|
|
789
|
+
`)})}jn();import{cpSync as Cc,existsSync as Yn,readdirSync as Jy,readFileSync as Lc,rmSync as Mc,statSync as Vy,writeFileSync as Dc}from"node:fs";import{join as tt,resolve as oo}from"node:path";var By=/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;function Hy(e){return By.test(e)}function zt(e){if(!Hy(e))throw new Error(`not a function name: ${JSON.stringify(e)}. Letters, digits, hyphens and underscores, up to 48 characters, starting with a letter or a digit.`);return e}var Gy=/^[A-Za-z0-9_][A-Za-z0-9._-]*$/;function qy(e){if(e.length===0||e.length>255||e.includes("\\")||e.startsWith("/"))return!1;let t=e.split("/");return t.length>8?!1:t.every(n=>n!=="."&&n!==".."&&Gy.test(n))}var ia=2*1024*1024,Nc=200;function Ic(e){let{entrypoint:t}=e;if(e.files.length===0)throw new Error("there is nothing in this function to deploy");if(e.files.length>Nc)throw new Error(`a function may hold ${Nc} files and this one has ${e.files.length}`);let n=new Set;for(let a of e.files){if(!qy(a.path))throw new Error(`${JSON.stringify(a.path)} is not a path a function may contain`);if(n.has(a.path))throw new Error(`${a.path} appears twice`);n.add(a.path)}if(!n.has(t))throw new Error(`the entrypoint ${JSON.stringify(t)} is not one of the files`);let r=[...e.files].sort((a,l)=>a.path<l.path?-1:a.path>l.path?1:0),o={snoutfn:1,entrypoint:t,files:r},s=Ky(o);if(s.length>ia)throw new Error(`this function is ${Math.round(s.length/1024)} KB and the limit is ${ia/1024} KB. A function is source code; put large files in Storage.`);return o}function Ky(e){let t=e.files.map(r=>`{"path":${JSON.stringify(r.path)},"text":${JSON.stringify(r.text)}}`).join(","),n=`{"snoutfn":${e.snoutfn},"entrypoint":${JSON.stringify(e.entrypoint)},"files":[${t}]}`;return new TextEncoder().encode(n)}var zy=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/;var Wy=["SNOUTDATA_","SNOUT_"];function Vn(e){if(!zy.test(e))return`${JSON.stringify(e)} is not an environment variable name: letters, digits and underscores, not starting with a digit.`;let t=Wy.find(n=>e.startsWith(n));return t?`names beginning with ${t} are set by the platform, so ${e} cannot be one of yours.`:null}var IP=64*1024;_e();ve();pe();function jc(e){let t=tt(e.folder,"functions");return Yn(t)?Jy(t).filter(n=>!n.startsWith(".")&&!n.startsWith("_")&&Vy(tt(t,n)).isDirectory()).sort():[]}async function so(e){u($(" docker compose run --rm functions-deploy"));let t=await fn(e,["run","--rm","functions-deploy"],!0);if(t.code!==0)throw new O("failed",`functions-deploy failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`)}function Uc(e,t,n){let r=tt(e.folder,".env"),o=Lc(r,"utf8"),s=(Lr(o).get("FUNCTIONS_NO_VERIFY_JWT")??"").split(",").map(c=>c.trim()).filter(Boolean),a=n?[...new Set([...s,t])]:s.filter(c=>c!==t);if(a.join(",")===s.join(","))return!1;let l=`FUNCTIONS_NO_VERIFY_JWT=${a.join(",")}`,d=/^FUNCTIONS_NO_VERIFY_JWT=.*$/m;return Dc(r,d.test(o)?o.replace(d,l):`${o.replace(/\n?$/,`
|
|
790
|
+
`)}${l}
|
|
791
|
+
`),!0}async function la(e,t,n){zt(t);let r=oo(n.dir??tt(process.cwd(),"functions",t));if(!Yn(tt(r,"index.ts")))throw new y(`${r} has no index.ts. A local function is a folder with an index.ts in it.`);let o=tt(e.folder,"functions",t);if(oo(o)!==r){Mc(o,{recursive:!0,force:!0}),Cc(r,o,{recursive:!0});let a=tt(r,"..","_shared");Yn(a)&&oo(a)!==oo(tt(e.folder,"functions","_shared"))&&Cc(a,tt(e.folder,"functions","_shared"),{recursive:!0})}let s=Uc(e,t,!n.verifyJwt);if(await so(e),s){let a=await fn(e,["up","-d","--wait","--wait-timeout","600"],!1);if(a.code!==0)throw new O("failed",`docker compose up failed after changing who may call ${t}: ${a.err.trim().split(/\r?\n/).slice(-2).join(" ")}`)}return{ref:e.ref,name:t,url:ca(e,t),verifyJwt:n.verifyJwt,local:e.folder}}async function Fc(e,t,n){let r=await la(e,t,n);w(r,()=>{u(`${N(t)} deployed locally: ${r.url}`),n.verifyJwt||u($(" Callable with no key (FUNCTIONS_NO_VERIFY_JWT), so it must check what calls it itself."))})}function ca(e,t){return`${e.apiUrl}/functions/v1/${t}`}function ao(e){return{ref:e.ref,local:e.folder,functions:jc(e).map(t=>({name:t,url:ca(e,t)}))}}function Bc(e){let t=jc(e);w(ao(e),()=>{if(t.length===0){u(`No functions in ${tt(e.folder,"functions")}.`);return}process.stdout.write(`${V([["NAME","URL"],...t.map(n=>[n,ca(e,n)])])}
|
|
792
|
+
`)})}async function da(e,t){zt(t);let n=tt(e.folder,"functions",t);if(!Yn(n))throw new O("not-found",`this local project has no function called ${t}`);return Mc(n,{recursive:!0,force:!0}),Uc(e,t,!1),await so(e),{ref:e.ref,name:t,removed:!0}}async function Hc(e,t){w(await da(e,t),()=>u(`${t} is gone.`))}function io(e){return tt(e.folder,"functions",".env")}function ua(e){let t=io(e);return Yn(t)?Lr(Lc(t,"utf8")):new Map}function Gc(e,t){let n=r=>r.includes("'")?JSON.stringify(r):`'${r}'`;Dc(io(e),[...t].map(([r,o])=>`${r}=${n(o)}`).join(`
|
|
516
793
|
`)+(t.size?`
|
|
517
|
-
`:""))}async function
|
|
518
|
-
`):`No function secrets in ${
|
|
519
|
-
`)})}function
|
|
520
|
-
`),
|
|
521
|
-
`),
|
|
522
|
-
`)})}async function
|
|
794
|
+
`:""))}async function qc(e,t){for(let r of t){let o=Vn(r.name);if(o)throw new y(o)}let n=ua(e);for(let r of t)n.set(r.name,r.value);Gc(e,n),await so(e),w({ref:e.ref,set:t.map(r=>r.name)},()=>{for(let r of t)u(`${N(r.name)} set in ${io(e)}`)})}function lo(e){return{ref:e.ref,local:e.folder,secrets:[...ua(e).keys()].sort().map(t=>({name:t}))}}function Kc(e){let t=lo(e),n=t.secrets.map(r=>r.name);w(t,()=>{u(n.length?n.join(`
|
|
795
|
+
`):`No function secrets in ${io(e)}.`)})}async function zc(e,t){let n=ua(e);if(!n.delete(t))throw new O("not-found",`${t} is not set for this local project`);Gc(e,n),await so(e),w({ref:e.ref,unset:t},()=>u(`${t} unset.`))}_e();Ct();Ot();Js();Br();pe();to();me();me();ve();_e();Ot();pe();async function Wc(){let{projects:e,allowance:t}=await Qe();w({projects:e,allowance:t},()=>{if(e.length===0){u('No projects yet. `snoutdata projects create --name "my project"`.');return}process.stdout.write(`${V(Yy(e))}
|
|
796
|
+
`)})}function Yy(e){let t=e.some(n=>typeof n.postgresVersion=="number");return[["REF","NAME","STATE","REGION",...t?["POSTGRES"]:[],"LAST CONNECTION"],...e.map(n=>[n.ref,n.name,`${n.readOnly?N("read-only"):n.state==="ready"?n.state:N(n.state)}${n.serverSilent?` ${N("(server not answering)")}`:""}`,n.region,...t?[typeof n.postgresVersion=="number"?String(n.postgresVersion):"-"]:[],We(n.lastConnectionAt)])]}async function pa(e){let t=e.servers==="dedicated";if(e.servers!==void 0&&e.servers!=="dedicated"&&e.servers!=="shared")throw new y("--servers is shared or dedicated");if(t!==(e.size!==void 0))throw new y(t?"--servers dedicated needs --size small, medium or large":"--size goes with --servers dedicated");let n=await T("cloud-project-create",{name:e.name,region:e.region,teamId:e.teamId,...t?{placement:"dedicated",size:e.size,...e.maxSize?{maxSize:e.maxSize}:{}}:{}}),r=n.project.ref;u(`Created ${r}.`);let o=n.project;if(e.wait){u("Waiting for it to start\u2026");let a="";o=await Wn(r,{timeoutMs:e.timeoutMs??(t?15*6e4:void 0),onTick:l=>{l!==a&&(a=l,u($(` ${l}`)))}})}e.link&&sn(e.link,{ref:r,name:o.name});let s=`postgres://${o.user}:${encodeURIComponent(n.password)}@${o.host}:5432/${o.database}?sslmode=require`;w({project:o,ref:r,host:o.host,database:o.database,user:o.user,...e.showUrl?{password:n.password,uri:s}:{connectionString:"snoutdata db url"}},()=>{process.stdout.write(`${e.showUrl?s:r}
|
|
797
|
+
`),u(""),u(`Ready. ${N(r)} in ${o.region}, at ${o.host}.`),u(e.showUrl?"The password is stored for you: `snoutdata db url` prints this again.":"`snoutdata db url` prints the connection string (it holds the password, so it is not shown here).")})}async function Jc(e,t,n={}){let r=`cloud-project-${e}`,o=await T(r,{ref:t}),s=e==="delete"?"deleted":`${e}d`;if(n.wait===!1){w({...o,settled:!1},()=>u(`${t}: asked to be ${s}. \`snoutdata projects list\` shows when it is.`));return}let a=o.project?.state??"",l=await zn(t,e,{timeoutMs:n.timeoutMs,onTick:c=>{c!==a&&(a=c,u($(` ${c}`)))}}),d=l?.state??"deleted";if(d==="error")throw new O("failed",`${t} went to error instead of ${s}${l?.stateDetail?`: ${l.stateDetail}`:""}.`,{ref:t,state:d});w({...o,...l?{project:l}:{},settled:!0},()=>{u(o.changed?`${t}: ${s}.`:`${t} was already ${s}.`)})}async function Vc(e,t){if(t!==void 0&&(t<0||t>1440))throw new y("--grace is a whole number of minutes from 0 to 1440 (24 hours)");let n=await T("cloud-project-reset-password",{ref:e,...t!==void 0?{graceMinutes:t}:{}});w(n,()=>{process.stdout.write(`${n.password}
|
|
798
|
+
`),u(`New password for ${n.user}. It applies ${n.appliesIn}.`),n.previousUser&&n.previousUser!==n.user&&u(`The user name changed from ${n.previousUser} to ${n.user}: update both wherever the URL is kept.`),n.oldPassword&&u(n.oldPassword)})}async function Yc(){let{teams:e}=await ro();w({teams:e},()=>{if(e.length===0){u("You are not on any teams.");return}process.stdout.write(`${V([["NAME","ID","SHARE"],...e.map(t=>[t.name,t.id,t.mayShare?"yes":t.why??"no"])])}
|
|
799
|
+
`)})}async function Xc(e){let{teams:t}=await ro(),n=t.find(s=>s.id===e),r=n?[n]:t.filter(s=>s.name.toLowerCase()===e.toLowerCase());if(r.length===0)throw new Error(t.length===0?`You are not on any teams, so there is no "${e}" to share with.`:`No team called "${e}". You are on: ${t.map(s=>s.name).join(", ")}.`);if(r.length>1)throw new Error(`More than one team is called "${e}". Use the id: ${r.map(s=>s.id).join(", ")}.`);let o=r[0];if(!o.mayShare)throw new Error(`${o.name}: ${o.why??"you cannot share a project into this team"}.`);return o.id}me();ve();_e();Ct();pe();import{createInterface as Zy}from"node:readline/promises";var ut={which:"--instances takes 1, 2 or 3",now:(e,t)=>`${e} runs its app API on ${t===1?"1 instance":`${t} instances`}.`,most:e=>e<=1?"More than 1 instance is on the Pro and Business plans.":`Your plan allows up to ${e} instances.`,notOpen:"Scaling is not open to this account yet.",nothing:e=>`${e} already runs that many instances. Nothing was changed.`,ask:(e,t)=>`Scale ${e} to ${t===1?"1 instance":`${t} instances`}?`,noAsk:"scaling changes where the app API runs, and nothing was asked: pass --yes to apply it",declined:"Not scaled. Nothing was changed.",done:(e,t)=>`${e}: its app API now runs on ${t===1?"1 instance":`${t} instances`}.`},Qy={plan:"quota","not-allowed":"forbidden",sharded:"conflict","not-ready":"conflict","owner-cap":"quota","too-soon":"not-ready",busy:"not-ready",full:"no-capacity"};function Zc(e){let t=Number(e);if(!/^[123]$/.test(e.trim())||!Number.isInteger(t))throw new y(ut.which);return t}async function ew(e){let t=Zy({input:process.stdin,output:process.stderr});try{let n=(await t.question(`${e} [y/N] `)).trim().toLowerCase();return n==="y"||n==="yes"}finally{t.close()}}async function Qc(e,t){if(t.instances===void 0){let s=await T("cloud-project-spread",{ref:e,preview:!0});w(s,()=>{u(ut.now(s.ref,s.current)),u(s.what),u(ut.most(s.most)),s.most>s.current&&!s.open&&u(ut.notOpen)});return}let n=t.instances;if(!t.yes&&!t.ask&&!Pe())throw new y(ut.noAsk);let r=await T("cloud-project-spread",{ref:e,preview:!0,instances:n});if(r.outcome==="refused")throw new O(Qy[r.code??""]??"conflict",r.error??ut.notOpen,{ref:e,instances:n,code:r.code});if(r.outcome==="none"){w({ref:r.ref,instances:n,changed:!1},()=>u(ut.nothing(r.ref)));return}if(process.stderr.write(`${r.what}
|
|
523
800
|
${r.message?`${r.message}
|
|
524
|
-
`:""}`),!t.yes&&!await(t.ask??
|
|
525
|
-
`),
|
|
526
|
-
`)})}async function
|
|
527
|
-
`),
|
|
528
|
-
`),
|
|
529
|
-
`),t.limit.maxFunctions!==null&&
|
|
530
|
-
`)}),!n.follow)return;let s=o.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(
|
|
531
|
-
`),s=c.at}}async function Pc(e,t){let n=await Bs(e,t);b(n,()=>{d(n.live?`${t} is gone.`:`${t} is gone. It stops answering within a few seconds.`)})}pe();import{spawn as xy}from"node:child_process";import{createHash as Ey}from"node:crypto";import{createReadStream as Mc}from"node:fs";import{mkdtemp as Ay,rm as Ry,stat as Gr}from"node:fs/promises";import{request as Ty}from"node:http";import{request as Oy}from"node:https";import{tmpdir as Ny}from"node:os";import{basename as Iy,dirname as Cy,join as Ws}from"node:path";var oy="x-snoutdata-upload-bytes",sy="x-snoutdata-upload-sha256",ay="/done",iy=/^[0-9a-f]{64}$/,ly=/^sha256:[0-9a-f]{64}$/;function cy(e){return iy.test(e)}var Ke=class extends Error{constructor(n,r){super(`the upload failed (${n})`);this.status=n;this.body=r}};function Ks(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function xc(e){let t=String(Ks(e).digest??"");if(!ly.test(t))throw new Ke(502,JSON.stringify({error:"The upload finished without saying what it stored, so there is nothing to deploy. Build again."}));return t}var dy=15*6e4,uy=2e3;async function Ec(e){let{ticketUrl:t,file:n,transport:r}=e;if(!cy(e.sha256))throw new Error("an upload is declared with its SHA-256, in hex");let o=await r.call("POST",t,{[oy]:String(e.bytes),[sy]:e.sha256});if(o.status===405){e.step?.("uploading");let l=await r.put(t,n,{});if(l.status!==200)throw new Ke(l.status,l.body);return xc(l.body)}if(o.status!==200)throw new Ke(o.status,o.body);let s=Ks(o.body);if(typeof s.url!="string"||!s.url.startsWith("https://")||!s.headers||typeof s.headers!="object")throw new Ke(502,JSON.stringify({error:"The project's host did not say where to put the image. Build again in a moment."}));e.step?.("uploading");let a=await r.put(s.url,n,s.headers);if(a.status!==200){let l=/<Code>([^<]+)<\/Code>/.exec(a.body)?.[1],m=l==="BadDigest"||l==="XAmzContentSHA256Mismatch"?"The image changed or was damaged while it was uploading. Build again.":l==="AccessDenied"||l==="SignatureDoesNotMatch"||l==="RequestTimeTooSkewed"?"The upload link was refused (it lasts 15 minutes, and this computer's clock must be right). Build again.":`The upload to storage failed (${a.status}). Build again in a moment.`;throw new Ke(a.status===403?401:502,JSON.stringify({error:m}))}e.step?.("storing");let c=r.now()+(e.waitMs??dy),i=e.pollMs??uy,u=!1;for(;!u;){let l=await r.call("POST",`${t}${ay}`,{});if(l.status===200||l.status===202)u=!0;else if(l.status===429&&r.now()<c)await r.sleep(i*5);else throw new Ke(l.status,l.body)}for(;;){let l=await r.call("GET",t,{});if(l.status!==200)throw new Ke(l.status,l.body);let m=Ks(l.body);if(m.state==="stored")return xc(l.body);if(m.state==="failed")throw new Ke(typeof m.status=="number"?m.status:502,JSON.stringify({error:m.error??"The image could not be stored. Build again in a moment."}));if(r.now()>=c)throw new Ke(504,JSON.stringify({error:"The project's host took too long to store the image. Build again in a moment."}));await r.sleep(i)}}de();var py=/^[a-z0-9][a-z0-9_-]{0,31}$/;function my(e){return py.test(e)}function Rc(e){return my(e)?null:`${JSON.stringify(e)} is not a container name: lower-case letters, digits, hyphens and underscores, up to 32 characters, starting with a letter or a digit.`}var fy=/^sha256:[0-9a-f]{64}$/,gy=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,hy=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/,yy=/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*(?::[0-9]{1,5})?$/;function wy(e){return fy.test(e)}function Tc(e){let t=e.trim();if(t.length===0||t.length>512||/\s/.test(t))return{error:`${JSON.stringify(e)} is not an image reference.`};let n=t,r=null,o=n.indexOf("@");if(o!==-1&&(r=n.slice(o+1),n=n.slice(0,o),!wy(r)))return{error:`${JSON.stringify(r)} is not a sha256 digest.`};let s=null,a=n.lastIndexOf("/"),c=n.lastIndexOf(":");if(c>a&&(s=n.slice(c+1),n=n.slice(0,c),!gy.test(s)))return{error:`${JSON.stringify(s)} is not an image tag.`};let i=n.split("/"),u="docker.io",l=i[0]??"";return i.length>1&&(l.includes(".")||l.includes(":")||l==="localhost")&&(u=l.toLowerCase(),i.shift()),yy.test(u)?((u==="index.docker.io"||u==="registry-1.docker.io")&&(u="docker.io"),u==="docker.io"&&i.length===1&&i.unshift("library"),i.length===0||i.some(m=>!hy.test(m))?{error:`${JSON.stringify(e)} is not an image name: a repository is lower-case letters, digits and separators.`}:(s===null&&r===null&&(s="latest"),{registry:u,repository:i.join("/"),tag:s,digest:r})):{error:`${JSON.stringify(l)} is not a registry address.`}}var xP=["application/vnd.oci.image.index.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.v2+json"].join(", ");function Gs(e){let t=e.split(".");if(t.length!==4)return null;let n=[];for(let r of t){if(!/^\d{1,3}$/.test(r))return null;let o=Number(r);if(o>255)return null;n.push(o)}return n}function by(e){let t=e.replace(/^\[|\]$/g,""),n=t.indexOf("%");if(n!==-1&&(t=t.slice(0,n)),!/^[0-9a-fA-F:.]+$/.test(t)||!t.includes(":"))return null;let r=t.lastIndexOf(":");if(t.slice(r+1).includes(".")){let l=Gs(t.slice(r+1));if(!l)return null;t=`${t.slice(0,r+1)}${(l[0]<<8|l[1]).toString(16)}:${(l[2]<<8|l[3]).toString(16)}`}let o=t.split("::");if(o.length>2)return null;let s=l=>l===""?[]:l.split(":"),a=s(o[0]??""),c=o.length===2?s(o[1]??""):[];if([...a,...c].some(l=>!/^[0-9a-fA-F]{1,4}$/.test(l)))return null;let i=a.length+c.length;if(o.length===1?i!==8:i>7)return null;let u=new Array(8-i).fill(0);return[...a.map(l=>parseInt(l,16)),...u,...c.map(l=>parseInt(l,16))]}function Sy(e,t,n){let r=Gs(t),o=a=>(a[0]<<24|a[1]<<16|a[2]<<8|a[3])>>>0,s=n===0?0:4294967295<<32-n>>>0;return(o(e)&s)===(o(r)&s)}var ky=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];var EP=1024**3;var Ac=16,_y=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/,vy=/^(\d{1,3}(?:\.\d{1,3}){3})(?:\/(\d{1,2}))?$/;function $y(e,t){let n=e??[],r={error:`${t}: ports are up to ${Ac} whole numbers, 1 to 65535.`};if(!Array.isArray(n)||n.length>Ac)return r;let o=n.map(s=>typeof s=="string"&&/^\d{1,5}$/.test(s)?Number(s):s);return o.some(s=>typeof s!="number"||!Number.isInteger(s)||s<1||s>65535)?r:[...new Set(o)].sort((s,a)=>s-a)}function Py(e){let t=e.trim().toLowerCase(),n=vy.exec(t);if(n){let r=Gs(n[1]??""),o=n[2]===void 0?32:Number(n[2]);if(!r||o>32)return{error:`${e} is not an IPv4 address or range.`};let s=(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0,a=o===0?0:4294967295<<32-o>>>0,c=(s&a)>>>0,i=[24,16,8,0].map(u=>c>>>u&255);return ky.some(([u,l])=>o>=l&&Sy(i,u,l))?{error:`${e} is not on the public internet, and a container reaches nothing else.`}:o===32?i.join("."):`${i.join(".")}/${o}`}return by(t)?{error:`${e} is an IPv6 address. Containers send over IPv4 only; list its IPv4 address or its host name.`}:t.startsWith("*.")?{error:`${e}: a wildcard cannot be looked up. List each host name, or the address range.`}:_y.test(t)?t:/^[a-z0-9-]{1,63}$/.test(t)?{error:`${e} is not a whole host name. Give it with its domain, like api.example.com.`}:{error:`${e} is not a host name, an IPv4 address or an IPv4 range.`}}function Oc(e){let t=e.trim(),n=t.lastIndexOf(":"),r=n!==-1&&t.indexOf(":")===n,o=r?t.slice(0,n):t,s=$y(r?t.slice(n+1).split(",").map(c=>c.trim()):[],o.trim());if("error"in s)return s;let a=Py(o);return typeof a!="string"?a:{destination:a,ports:s}}function qs(e){return e.ports.length===0?e.destination:`${e.destination}:${e.ports.join(",")}`}var My=new Set(["pending","pulling","starting","restarting"]),Dy=5*6e4;function Wr(e){let t=Rc(e);if(t)throw new Error(t)}function Js(e,t,n){Wr(t);let r=Tc(n.image);if("error"in r)throw new Error(r.error);return R("cloud-project-containers",{ref:e,action:"deploy",name:t,image:n.image,...n.port===void 0?{}:{port:n.port},...n.registryUser?{registryUser:n.registryUser,registryPassword:n.registryPassword??""}:{},...n.clearCredential?{clearCredential:!0}:{}})}function on(e){return R("cloud-project-containers",{ref:e})}function Vs(e,t){return Wr(t),R("cloud-project-containers",{ref:e,action:"delete",name:t})}function Ys(e,t){return Wr(t),R("cloud-project-containers",{ref:e,action:"restart",name:t})}function qr(e,t){return R("cloud-project-containers",{ref:e,action:"logs",...t.name?{name:t.name}:{},...t.errorsOnly?{errorsOnly:!0}:{},...t.since?{since:t.since}:{},limit:t.limit??100})}async function Dc(e,t){let n=Date.now()+Dy,r=null;for(;Date.now()<n;)if(await new Promise(o=>setTimeout(o,3e3)),r=(await on(e)).containers.find(o=>o.name===t)??null,!r||!My.has(r.status))return r;return r}function Xs(e){if(!e.allowed)return"stopped: not covered by the plan";let t=e.restarts>0?`, ${e.restarts} restart${e.restarts===1?"":"s"}`:"";return`${e.status}${t}`}async function Lc(e,t,n){await jc(e,t,await Js(e,t,n),n.wait!==!1)}async function jc(e,t,n,r){let o=n.containers.find(s=>s.name===t)??null;r&&o&&(d(v(`${t}: ${o.image} pinned to ${o.digest.slice(0,19)}\u2026, waiting for the host`)),o=await Dc(e,t)??o),b({...n,containers:o?[o]:n.containers},()=>{if(!o){d(`${M(t)} deployed.`);return}d(`${M(t)} ${Xs(o)}`),d(` ${o.url}`),o.statusDetail&&d(` ${o.statusDetail}`),d(""),d(v(" Listens on PORT ("+o.port+"). DATABASE_URL and your secrets are in its environment.")),d(M(" Anything written inside the container is lost when it restarts or is redeployed.")),d(v(" Keep what matters in your database.")),n.allowance&&d(v(` ${n.allowance.deployed} of ${n.allowance.maxContainers} containers on this plan, ${n.allowance.memoryMb} MB and ${n.allowance.cpuPercent}% of a core each`))})}var Ly=2*1024**3,jy=3*6e4;async function Uy(e){let t;try{t=await Gr(e)}catch{throw new Error(`${e} does not exist: --dockerfile takes a folder with a Dockerfile in it, or the Dockerfile.`)}if(t.isDirectory()){try{await Gr(Ws(e,"Dockerfile"))}catch{throw new Error(`${e} has no Dockerfile in it.`)}return{context:e,file:null}}return{context:Cy(e),file:e}}function Fy(e){return["buildx","build","--platform","linux/arm64","--provenance=false","--output",`type=oci,dest=${e.archive}`,...e.file?["--file",e.file]:[],e.context]}function Zs(e){return e.replace(/\b\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com(?:\/[^\s"',;)]*)?/g,"SnoutData's registry").replace(/\barn:aws[a-z-]*:[^\s"',;)]*/g,"a SnoutData credential").replace(/\b[a-z0-9.-]*\.amazonaws\.com(?:\/[^\s"',;)]*)?/g,"SnoutData Cloud").replace(/\b\d{12}\b/g,"(an account)")}function By(e,t){let n="";try{let r=JSON.parse(t);n=String(r.error??r.message??"")}catch{}return n?Zs(n):e===413?"the image is too large to upload: a container's image may be at most 1 GB compressed; a slimmer base (alpine, distroless, -slim) usually fixes it.":`the upload failed (${e}); build again in a moment.`}function Hy(e){return new Promise((t,n)=>{let r=xy("docker",e,{stdio:["ignore",2,2]});r.on("error",o=>n(o)),r.on("close",o=>t(o??1))})}function Uc(e,t,n,r){return new Promise((o,s)=>{let a=new URL(e),c=(a.protocol==="http:"?Ty:Oy)(a,{method:t,headers:n});c.on("response",i=>{let u=[];i.on("data",l=>u.push(l)),i.on("end",()=>o({status:i.statusCode??0,body:Buffer.concat(u).toString("utf8")})),i.on("error",s)}),c.on("error",i=>{s(i)}),r(c)})}async function Ky(e,t,n){let r=Object.keys(n).length>0?n:{"content-type":"application/octet-stream","content-length":String((await Gr(t)).size)};return Uc(e,"PUT",r,o=>{let s=Mc(t);s.on("error",a=>o.destroy(a)),s.pipe(o)})}function Gy(e){return new Promise((t,n)=>{let r=Ey("sha256");Mc(e).on("error",n).on("data",o=>r.update(o)).on("end",()=>t(r.digest("hex")))})}var qy={call:(e,t,n)=>Uc(t,e,{"content-length":"0",...n},r=>r.end()),put:Ky,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now()},Fc={docker:Hy,scratch:()=>Ay(Ws(Ny(),"snoutdata-build-")),remove:e=>Ry(e,{recursive:!0,force:!0}),size:async e=>(await Gr(e)).size,hash:Gy,transport:qy,ask:e=>R("cloud-project-containers",e),say:e=>d(v(e)),now:()=>Date.now()};function Nc(e){return`${Math.max(1,Math.round(e/1024**2))} MB`}async function Ic(e,t,n){let r=await e.ask({ref:t,action:"upload-ticket",name:n});if(typeof r.url!="string"||!r.url.startsWith("https://"))throw new Error("SnoutData Cloud did not hand over an upload link; try again in a moment.");return{url:r.url,expiresAt:String(r.expiresAt??"")}}async function zy(e,t,n,r=Fc){try{if(await r.docker(["version","--format","{{.Server.Version}}"])!==0)throw new Error("docker answered with an error")}catch{throw new Error("deploy --dockerfile builds with your own Docker, and none is running here. Start Docker, or deploy an image from a registry.")}try{let o=await Ic(r,e,t),s=await r.scratch();try{let a=Ws(s,"image.tar");if(r.say(`${t}: building ${n.file?Iy(n.file):n.context} for linux/arm64`),await r.docker(Fy({...n,archive:a}))!==0)throw new Error("the build failed; its output is above. If it says the docker driver cannot export OCI, turn on the containerd image store, or run: docker buildx create --use");let c=await r.size(a).catch(()=>0);if(c<=0)throw new Error("docker finished but wrote no image archive, so there is nothing to upload.");if(c>Ly)throw new Error(`the image is ${Nc(c)}, and a container's image may be at most 1 GB compressed. A slimmer base (alpine, distroless, -slim) usually fixes it.`);Date.parse(o.expiresAt)-r.now()>jy||(o=await Ic(r,e,t));let i=await r.hash(a);r.say(`${t}: uploading the image (${Nc(c)})`);try{return await Ec({ticketUrl:o.url,file:a,bytes:c,sha256:i,transport:r.transport,step:u=>{u==="storing"&&r.say(`${t}: storing the image in the project`)}})}catch(u){throw u instanceof Ke?new Error(By(u.status,u.body)):u}}finally{await r.remove(s).catch(()=>{})}}catch(o){throw new Error(Zs(o instanceof Error?o.message:String(o)))}}async function Bc(e,t,n,r=Fc){Wr(t);let o=await Uy(n.path),s=await zy(e,t,o,r),a;try{a=await r.ask({ref:e,action:"deploy",name:t,pushed:s,...n.port===void 0?{}:{port:n.port}})}catch(c){throw new Error(Zs(c instanceof Error?c.message:String(c)))}await jc(e,t,a,n.wait!==!1)}async function Hc(e){let t=await on(e);b(t,()=>{if(t.containers.length===0){d(`No containers on ${e}.`),t.allowance&&t.allowance.maxContainers===0?d(v(" Containers run on the Plus and Pro plans.")):d(v(" snoutdata containers deploy <name> <image>"));return}d(X([["name","status","image","url"],...t.containers.map(r=>[r.name,Xs(r),r.image,r.url])]));for(let r of t.containers)r.statusDetail&&r.status!=="running"&&d(v(` ${r.name}: ${r.statusDetail}`));let n=t.allowance?.egress;n&&n.allowanceBytes>0&&d(v(` Sent this month: ${zs(n.usedBytes)} of ${zs(n.allowanceBytes)}. At ${zs(n.allowanceBytes)} the project's containers stop until the 1st.`))})}async function zr(e,t){if(t===null)return R("cloud-project-containers",{ref:e,action:"egress",clear:!0});let n=[];for(let r of t){let o=Oc(r);if("error"in o)throw new Error(o.error);n.push(o)}return R("cloud-project-containers",{ref:e,action:"egress",allow:n})}function Wy(e){if(e.allowlist===void 0)return["This control plane does not know about allowlists yet."];if(e.allowlist===null)return[`Containers on ${e.ref} may reach the public internet (within the limits on how much and how fast).`,v(" snoutdata containers egress set <host[:port]> ... to allow only some destinations")];let t=[e.allowlist.allow.length===0?`Containers on ${e.ref} may reach nothing outside the project.`:`Containers on ${e.ref} may reach only:`];for(let n of e.allowlist.allow)t.push(` ${qs(n)}${n.ports.length===0?v(" (any port)"):""}`);return t.push(v(` and always: ${e.allowlist.alwaysAllowed.map(qs).join(", ")}, and each other`)),t.push(v(" snoutdata containers egress clear to allow the public internet again")),t}async function Jr(e,t){let n=t.clear?await zr(e,null):t.set?await zr(e,t.set):await on(e);b({ref:n.ref,allowlist:n.allowlist??null},()=>{for(let r of Wy(n))d(r);(t.set||t.clear)&&d(v(" Running containers follow it within a minute; nothing restarts."))})}function zs(e){return`${Math.round(e/1024**3*10)/10} GB`}async function Kc(e,t){await Ys(e,t);let n=await Dc(e,t);b({ref:e,containers:n?[n]:[]},()=>{d(n?`${M(t)} ${Xs(n)}`:`${t} is restarting.`),n?.statusDetail&&d(` ${n.statusDetail}`)})}async function Gc(e,t){let n=await Vs(e,t);b(n,()=>d(`${t} is gone. It stops within a few seconds.`))}function Cc(e){return`${v(e.at.replace("T"," ").slice(0,19))} ${e.name} ${e.stream==="stderr"?M(e.message):e.message}`}async function qc(e,t,n){let r=((await qr(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit})).lines??[]).slice().reverse();if(b({ref:e,lines:r},()=>{if(r.length===0&&!n.follow){d(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),d(v(" Lines show up about a minute after a container prints them."));return}for(let s of r)process.stdout.write(`${Cc(s)}
|
|
532
|
-
`)}),!n.follow)return;let o=r.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(a=>setTimeout(a,5e3));let s=((await
|
|
533
|
-
`),o=a.at}}
|
|
534
|
-
`),
|
|
535
|
-
`).filter(r=>/^pg_restore: error:/.test(r.trim())),n=t.filter(r=>!/must be owner of extension/.test(r));return{total:t.length,harmless:t.length-n.length,fatal:n}}var
|
|
536
|
-
`)){let u=ew(i);if(!u)continue;let{type:l,schema:m,name:y,owner:T}=u;if(l==="TABLE DATA"||l==="SEQUENCE SET"){let oe=/^(schema_migrations|migrations)$/.test(y)&&Vr.has(m);if(/realtime/.test(m)||m==="snout_live"||oe||m==="public"&&y==="spatial_ref_sys"){s++;continue}if(m==="cron"){s++,o.add("Scheduled jobs (pg_cron) are not restored: each names the project it came from. Schedule them again with cron.schedule.");continue}if(m==="push"&&y==="credentials"){s++,o.add("Push credentials are not restored: they are sealed for the project they came from. Set them again with `snoutdata push credentials set`.");continue}let Z=Xy[m];if(Z){Z==="storage"&&(y==="objects"||y==="files")&&o.add("Storage objects are restored as rows; the files themselves are not part of an export. Upload them again into this project."),n.set(Z,[...n.get(Z)??[],u]);continue}if(Vr.has(m)){s++;continue}r.push(u.line);continue}if(l==="COMMENT"&&m==="-"&&/^EXTENSION( |$)/.test(y)||(l==="SCHEMA"?Vr.has(y):Vr.has(m))||Yy.test(y)||Vy.test(T)&&l!=="SCHEMA"){s++;continue}r.push(u.line)}let a=tw(t),c=["auth","storage","push"];return{platformData:c.filter(i=>n.has(i)).map(i=>{let u=n.get(i),l=u.filter(y=>y.type==="TABLE DATA"&&Zy.has(`${y.schema}.${y.name}`)).map(y=>`${y.schema}.${y.name}`),m=u.filter(y=>y.type==="TABLE DATA").map(y=>`${y.schema}.${y.name}`);return{product:i,clear:l,tables:m,lines:nw(u,a)}}),rest:r,products:c.filter(i=>n.has(i)),skipped:s,notes:[...o]}}function nw(e,t){let n=c=>`${c.schema}.${c.name}`,r=new Set(e.map(n)),o=new Set,s=[],a=[...e];for(;a.length>0;){let i=a.find(u=>[...t.get(n(u))??[]].every(l=>!r.has(l)||o.has(l)||l===n(u)))??a[0];o.add(n(i)),s.push(i.line),a=a.filter(u=>u!==i)}return s}pe();Ae();be();de();pe();be();var ta=["max_write_pause_ms","drain_timeout_ms","ack_timeout_ms","copy_mb_per_s"],rd=["advice_sample_ms","advice_min_bytes","advice_split_bytes","advice_skew_pct","advice_hot_pct","advice_min_writes_per_s","advice_pin_pct","advice_node_disk_bytes","advice_disk_pct","advice_conn_pct"],od=["off","advise","auto"];function jn(e){return e==="done"||e==="failed"||e==="cancelled"}function Un(e,t=process.env){if(e.project!==void 0){if(e.admin!==void 0)throw new C("usage","cluster takes --project (a SnoutData Cloud project) or --admin (a standalone router), not both");return new st(iw(e.project))}let n=e.admin??nd(t.LEPIS_ADMIN_URL);if(!n)throw new C("usage","cluster needs a project: --project <ref> for a SnoutData Cloud project, or --admin <url> (or LEPIS_ADMIN_URL) for the admin API of a standalone Lepis router (LEPIS_ADMIN_ADDR)");let r=e.token??nd(t.LEPIS_ADMIN_TOKEN);if(!r)throw new C("not-signed-in","no admin token: set LEPIS_ADMIN_TOKEN to the router's token, or pass --token");return new ea(rw(n),r)}function nd(e){return e===void 0||e===""?void 0:e}function rw(e){let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`,n;try{n=new URL(t)}catch{throw new C("usage",`--admin: not a URL: ${e}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new C("usage",`--admin: http or https, not ${n.protocol.replace(":","")}`);if(n.username||n.password)throw new C("usage","--admin: the URL carries no credentials; the token comes from LEPIS_ADMIN_TOKEN or --token");if(n.protocol==="http:"&&!ow(n.hostname))throw new C("usage",`--admin: ${n.host} is not this machine, and plain http would send the token in the clear. Use https (the router serves it when it has LEPIS_TLS_CERT), or a tunnel to 127.0.0.1`);return n.pathname=n.pathname.replace(/\/+$/,""),n.search="",n.hash="",n}function ow(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)}var sw=6e4,ea=class{target;#t;#n;constructor(t,n){this.#t=t,this.#n=n,this.target=t.toString().replace(/\/$/,"")}status(){return this.#e("GET","/v1/status")}ops(){return this.#e("GET","/v1/ops")}plan(t){return this.#e("POST","/v1/plan",t)}submit(t){return this.#e("POST","/v1/jobs",t)}async jobs(){return(await this.#e("GET","/v1/jobs")).jobs}job(t){return this.#e("GET",`/v1/jobs/${t}`)}cancel(t){return this.#e("POST",`/v1/jobs/${t}/cancel`)}resume(t){return this.#e("POST",`/v1/jobs/${t}/resume`)}settings(t){return this.#e("POST","/v1/settings",t)}advice(t){return this.#e("GET",t===void 0?"/v1/advice":`/v1/advice?sample_ms=${Math.max(0,Math.floor(t))}`)}check(){return this.#e("GET","/v1/check")}autopilot(){return this.#e("GET","/v1/autopilot")}setAutopilot(t){return this.#e("POST","/v1/settings",t)}async#e(t,n,r){let o=`${this.target}${n}`,s;try{s=await fetch(o,{method:t,headers:{authorization:`Bearer ${this.#n}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(r??{})}:{},signal:AbortSignal.timeout(sw)})}catch(i){let u=yr(i),l=i instanceof Error?i.cause instanceof Error?i.cause.message:i.message:String(i);throw new C(u==="failed"?"network":u,`could not reach the Lepis admin API at ${this.target}: ${l}`)}let a=await s.text(),c;try{c=a===""?{}:JSON.parse(a)}catch{throw new C("server",`the admin API at ${this.target} answered ${s.status} with something that is not JSON`,{status:s.status})}if(!s.ok)throw sd(s.status,c);return c}},aw={bad_request:"usage",unauthorized:"not-signed-in",not_found:"not-found",conflict:"conflict",failed:"failed",timeout:"timeout"};function sd(e,t){let n=t?.error??{},r=n.message??`the admin API answered ${e}`,o={status:e};n.code&&(o.apiCode=n.code),n.kind&&(o.kind=n.kind),n.sqlstate&&(o.sqlstate=n.sqlstate);let s=(n.code?aw[n.code]:void 0)??(e===401?"not-signed-in":e===400?"usage":pt(e));return s==="not-signed-in"?new C(s,"the router refused the admin token (LEPIS_ADMIN_TOKEN or --token)",o):new C(s,r,o)}function iw(e){let t=e.trim();if(!/^[a-z][0-9a-z]{12}$/.test(t))throw new C("usage",`--project: not a project ref: ${e} (13 characters, as projects list prints it)`);return t}var lw={"node.add":"add-node","node.attach":"attach","node.drain":"drain","node.remove":"remove","keyspace.create":"keyspace","table.distribute":"distribute","table.reference":"reference","table.global":"global","table.auto":"auto","range.split":"split","range.merge":"merge","range.move":"move","tenant.pin":"pin",rebalance:"rebalance",scale:"scale",verify:"verify",cleanup:"cleanup","keyspace.drop":"drop-keyspace",dissolve:"disable"},cw="cloud-project-shards",st=class{target;ref;#t;constructor(t,n=R){this.ref=t,this.target=`project ${t}`,this.#t=n}async status(){let t=await this.#e({action:"status"}),{cluster:n,...r}=t;return{...n??{catalog:!1},cloud:r}}ops(){return this.#e({action:"ops"})}async plan(t){return this.#n(t),this.#e({action:"plan",request:t})}async submit(t){let n=this.#n(t),r={...t};delete r.op;let o=await this.#e({action:n,request:r});return typeof o.job=="number"?{job:o.job,plan:o.plan}:{done:At(o),answer:o}}async jobs(){return(await this.#e({action:"jobs"})).jobs}job(t){return this.#e({action:"jobs",id:t})}cancel(t){return this.#e({action:"cancel",id:t})}resume(t){return this.#e({action:"resume",id:t})}settings(t){return this.#e({action:"settings",settings:t})}advice(t){return this.#e({action:"advice",...t===void 0?{}:{sampleMs:Math.max(0,Math.floor(t))}})}check(){return this.#e({action:"check"})}autopilot(){return this.#e({action:"autopilot"})}setAutopilot(t){return this.#e({action:"settings",settings:t})}enable(t){return this.#e({action:"enable",...t?{plan:!0}:{}})}spread(t,n){return this.#e({action:"spread",request:t,...n?{plan:!0}:{}})}retry(t){return this.#e({action:"retry",...t})}disable(t){return this.#e({action:"disable",...t?{plan:!0}:{}})}replica(t,n,r){return this.#e({action:n?"remove-replica":"add-replica",node:t,...r?{plan:!0}:{}})}async alerts(){return(await this.status()).cloud?.alerts??[]}acknowledge(t){return this.#e({action:"acknowledge",alert:t})}#n(t){let n=lw[t.op];if(!n)throw new C("usage",`${t.op} is not an operation a SnoutData Cloud project takes`);let r=t;if(t.op==="node.add"&&(r.host!==void 0||r.name!==void 0))throw new C("usage","in SnoutData Cloud a node is a pod the project makes: nodes add takes no name or --host. It joins the cluster on its own once it is ready.");if(t.op==="scale"&&(r.add!==void 0||r.remove!==void 0))throw new C("usage","in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");return n}async#e(t){try{return await this.#t(cw,{ref:this.ref,...t})}catch(n){throw dw(n)}}};function At(e){if(Array.isArray(e.created)){let t=e.created.map(String),n=typeof e.stopped=="string"?` Stopped there: ${e.stopped}`:"",r=t.length===1;return e.joining===!1?`New node${r?"":"s"} ${t.join(", ")}, starting as a copy of the home node. Attach ${r?"it":"each"} once it is ready: snoutdata cluster nodes attach <ref>.${n}`:`New node${r?"":"s"} ${t.join(", ")}, starting as a copy of the home node. ${r?"It joins":"They join"} the cluster and take${r?"s":""} ${r?"its":"their"} share of the data on ${r?"its":"their"} own; follow it with snoutdata cluster status.${n}`}return e.deleted===!0?`The pod of ${String(e.pod)} is being deleted. It owned nothing in the cluster.`:Array.isArray(e.queued)?`${String(e.next??"The table is being spread over the cluster.")} Steps: ${e.queued.map(String).join(", ")}. Follow it with snoutdata cluster status.`:typeof e.joining=="boolean"&&typeof e.node=="string"?e.joining?`${e.node} is joining the cluster again.`:`${e.node} is left as it is.`:e.queue==="retrying"?"The cluster is trying that step again.":typeof e.replica=="string"&&typeof e.node=="string"?`A replica of node ${e.node} is being made (${e.replica}). ${String(e.note??"It protects the node once it is following it.")}`:typeof e.changed=="boolean"&&typeof e.node=="string"&&e.sharded===void 0?e.changed?`The replica of node ${e.node} is being removed, and its project slot freed.`:`node ${e.node} has no replica. Nothing changed.`:e.acknowledged===!0?"Marked as seen. The alert stays open until what it is about is over.":e.unchanged===!0?`The project already has ${String(e.nodes)} nodes. Nothing changed.`:e.sharded===!0?e.changed===!1?"This project is already a cluster.":String(e.note??"This project is a cluster now."):e.sharded===!1?e.changed===!1?"This project is not a cluster.":String(e.note??"This project is not a cluster any more."):typeof e.next=="string"?e.next:"Done."}function dw(e){if(!(e instanceof Re))return e;let t=e.body??{};if(typeof t.apiCode=="string"||typeof t.kind=="string")return sd(e.status,{error:{code:typeof t.apiCode=="string"?t.apiCode:void 0,kind:typeof t.kind=="string"?t.kind:void 0,message:e.message,sqlstate:typeof t.sqlstate=="string"?t.sqlstate:void 0}});let n=t.code==="not-sharded"?"conflict":pt(e.status);return new C(n,e.message,{status:e.status,...typeof t.code=="string"?{kind:t.code}:{}})}function Bn(e){if(Array.isArray(e))return`[${e.map(Bn).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).filter(n=>t[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Bn(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}var oa=class{#t=new Map;#n;#e;constructor(t=15*6e4,n=Date.now){this.#n=t,this.#e=n}remember(t,n=""){this.#t.set(`${n}
|
|
537
|
-
${
|
|
538
|
-
${
|
|
539
|
-
${Bn(t)}`)}},uw=new oa,sa=["node.add","node.drain","node.remove","keyspace.create","table.distribute","table.reference","table.global","table.auto","range.split","range.merge","range.move","tenant.pin","rebalance","scale","verify","cleanup","node.attach","keyspace.drop","dissolve"],pw="2024-11-05";function ee(e,t=[]){return{type:"object",properties:e,additionalProperties:!1,...t.length?{required:t}:{}}}var J={type:"string"},ad={type:"object",description:'The operation as the router takes it, e.g. {"op": "range.split", "keyspace": "k", "range": "-3074457345618258603", "at": "18454348402311335", "to": 3}. Range bounds and seeds are 64-bit, so pass them as strings. cluster_advice returns these ready-made, as `operation`. For a SnoutData Cloud project a node is a pod the project makes: {"op": "node.add"} makes one (no host), {"op": "node.attach", "name": "<its ref>"} hands a ready one to the cluster, and {"op": "scale", "nodes": N} is a node count.',properties:{op:{type:"string",enum:[...sa]}},required:["op"],additionalProperties:!0},Yr={type:"integer",description:"The job id cluster_run returned, or one from cluster_jobs."},yt={type:"string",description:"A SnoutData Cloud project's ref (from list_projects): its cluster, as the signed-in user. Omit for the standalone router this server was started with (LEPIS_ADMIN_URL)."},Kn=[{name:"whoami",description:"Who this CLI is signed in as, and how (a session or a long-lived access token). Use it to check a credential before doing anything else.",inputSchema:ee({})},{name:"list_projects",description:"Every hosted Postgres database on this account, with its ref, name, region, state (ready, paused, error), size, and whether it is read-only because it is over its plan's storage limit. Under `local`, the self-hosted projects on this machine (SnoutData Studio's, or linked with `snoutdata link --local`), whose refs work with get_connection_url, push_migrations, get_project and the function tools.",inputSchema:ee({})},{name:"create_project",description:"Make a new hosted Postgres database and wait for it to be ready. Costs a project against the plan allowance; a free plan includes two. Returns its ref, which every other tool takes.",inputSchema:ee({name:J,region:J,teamId:J},["name"])},{name:"get_connection_url",description:"The postgres:// URL for a project, ready to put in DATABASE_URL. IT CONTAINS A LIVE PASSWORD, so treat it as a credential and do not print it into a log or a file that is committed. Connecting to a paused project wakes it, which takes a few seconds.",inputSchema:ee({ref:J},["ref"])},{name:"pause_project",description:"Stop a project, and wait until it is paused. Its data is kept and the next connection wakes it. A production project refuses this.",inputSchema:ee({ref:J},["ref"])},{name:"scale_project",description:"More capacity for a project's app API (auth, the data API and the router): 1 to 3 instances of it take its calls. The database is not copied by this, and it is not failover: keeping a project running is the cloud's job on every plan. Without instances, says how many it runs now and how many the plan allows. Without confirm: true it only returns the plan for that number and changes nothing: show it to the user, and when they agree call again with confirm: true. A refusal (the plan, not open yet, a sharded project, no room) comes back in a sentence to show as it is.",inputSchema:ee({ref:J,instances:{type:"integer",enum:[1,2,3]},confirm:{type:"boolean"}},["ref"])},{name:"resume_project",description:"Start a paused project without waiting for a connection to wake it, and wait until it is ready.",inputSchema:ee({ref:J},["ref"])},{name:"push_migrations",description:"Run the .sql files in a folder against a project, in name order, once each, recording what ran in a _snoutdata_migrations table. Refuses a file that changed after it ran, a file that has gone, and a new file that sorts before one already applied. Use dryRun first to see what would happen. Needs nothing installed: the CLI connects to the database itself. A file holding a psql command (\\i, \\set), or a COMMIT, END or ROLLBACK that would end the transaction the file runs in, is refused before anything runs; a file starting with -- snoutdata:no-transaction runs as written, outside a transaction.",inputSchema:ee({ref:J,dir:J,dryRun:{type:"boolean"}},["ref"])},{name:"usage",description:"How much storage and compute a project has used against the limit on this plan, and whether it is near it. READ THIS BEFORE a migration or a bulk insert: a project over its storage limit is made read-only, and `list_projects` will say readOnly afterwards without ever saying how much headroom was left. Takes an optional number of days of history (default 30, maximum 365).",inputSchema:ee({ref:J,days:{type:"number"}},["ref"])},{name:"export_status",description:"Whether a copy of this database is being taken, when the last one finished, and a download link if there is a live one. Costs nothing and starts nothing.",inputSchema:ee({ref:J},["ref"])},{name:"start_export",description:"Take a copy of the whole database. Runs a pg_dump on the server and can take minutes, so this STARTS it and returns; poll export_status for the link. Worth doing before a migration you are unsure of. It does not block the database.",inputSchema:ee({ref:J},["ref"])},{name:"reset_password",description:"Rotate the project's database password. THE OLD ONE STOPS WORKING usually within fifteen seconds (longer while the host is busy starting other databases), including any DATABASE_URL already written into a file or a running process; connections already open keep working. Returns the new connection URL, which works once the change applies (wait about fifteen seconds before connecting, and retry a refusal for up to two minutes). Use it when a credential has leaked, not routinely.",inputSchema:ee({ref:J},["ref"])},{name:"list_teams",description:"Teams this account belongs to, with the id create_project takes as teamId. Without this there is no way to discover that id.",inputSchema:ee({})},{name:"list_tokens",description:"The long-lived sdt_ access tokens on this account: id, name, prefix, when each was made and last used. Never the token itself, which is shown once when it is made.",inputSchema:ee({})},{name:"create_token",description:"Mint a long-lived sdt_ access token, for a CI job or another machine. RETURNS THE TOKEN ONCE AND NEVER AGAIN. Without `project` it is as capable as this account, so hand it over deliberately; with a project ref it reaches that one project and nothing else, which is what a CI job for one project should get. Optionally expires, as an ISO date.",inputSchema:ee({name:J,expires:J,project:J},["name"])},{name:"revoke_token",description:"Revoke an access token by its id. Anything using it stops working at once. Safe to do to a token you think has leaked.",inputSchema:ee({id:J},["id"])},{name:"deploy_function",description:"Put a folder of TypeScript on the edge as an HTTP endpoint at https://<ref>.api.snoutdata.com/v1/fn/<name>. Reads functions/<name> unless dir says otherwise. Deno, so no build step and no node_modules. Set openToAnyone ONLY for a webhook receiver whose sender cannot send an API key: it makes the URL callable by anybody who knows it, and the function must then check the sender's signature itself.",inputSchema:ee({ref:J,name:J,dir:J,entrypoint:J,openToAnyone:{type:"boolean"}},["ref","name"])},{name:"list_functions",description:"The functions deployed to a project, their URLs, bundle sizes, whether each one needs an API key, and each one's memory and concurrency with the plan's limits for both. Costs nothing.",inputSchema:ee({ref:J},["ref"])},{name:"size_function",description:"Set one function's memory (MB one worker may use) and concurrency (how many workers it may run at once), within the project's plan. memoryMb x concurrency may not exceed the project's memory; list_functions shows each function's size and the plan's limits (limit.functionMemoryMb, limit.concurrencyMax, limit.podMemoryMb). A size that does not fit is refused with a sentence saying why. Omit one to keep it as it runs now; reset: true goes back to the plan's default. A second worker only helps CPU-bound work: requests that wait on the network share one.",inputSchema:ee({ref:J,name:J,memoryMb:{type:"integer"},concurrency:{type:"integer"},reset:{type:"boolean"}},["ref","name"])},{name:"delete_function",description:"Remove one function from a project. It stops answering within a few seconds. It does not touch the database.",inputSchema:ee({ref:J,name:J},["ref","name"])},{name:"list_containers",description:"The project's Snout Containers: each one's status (pending, pulling, starting, running, restarting, failed, stopped), why when it is not running, its image and pinned digest, restarts, and its public URL. allowed=false means the plan no longer covers it and it is stopped. Also the plan's allowance. Costs nothing.",inputSchema:ee({ref:J},["ref"])},{name:"deploy_container",description:"Run a Docker image all the time beside the project, at https://<ref>.api.snoutdata.com/containers/v1/<name>/ (no API key needed there: the container authenticates its own callers). The image tag is pinned to the digest it points at now and must include linux/arm64. It listens on PORT (port, default 8080) and gets DATABASE_URL and the project's secrets in its environment. STATELESS: anything written inside it is lost on every restart or redeploy, so state belongs in the database. Plus and Pro plans only. A private image needs a person's first deploy with the CLI (no tool takes a registry token); a redeploy reuses the stored login. Returns at once: poll list_containers until the status is running or failed.",inputSchema:ee({ref:J,name:J,image:J,port:{type:"integer"}},["ref","name","image"])},{name:"restart_container",description:"Start one container again from its image. Everything written inside it is lost, which is also how to clear a container stuck in a bad state. Poll list_containers to see it come back.",inputSchema:ee({ref:J,name:J},["ref","name"])},{name:"delete_container",description:"Stop one container and remove it from the project. It does not touch the database.",inputSchema:ee({ref:J,name:J},["ref","name"])},{name:"container_logs",description:"What a project's containers printed to stdout and stderr in the last seven days, newest first: each line's time, container, stream and text. Lines arrive about a minute after they are printed. Use it when list_containers says failed or restarting. name narrows to one container, errorsOnly to stderr, limit is at most 500 (default 100). Costs nothing.",inputSchema:ee({ref:J,name:J,errorsOnly:{type:"boolean"},limit:{type:"integer"}},["ref"])},{name:"container_egress",description:"Where a project's containers may send. allowlist null means the public internet (within the limits on how much and how fast); otherwise allowlist.allow is the only destinations they reach, and alwaysAllowed what they reach whatever the list says (the project's own database and API). The same as `snoutdata containers egress`. Costs nothing.",inputSchema:ee({ref:J},["ref"])},{name:"set_container_egress",description:'Hold a project\'s containers to an allowlist, or let them reach the public internet again. Give EITHER allow, a list of destinations ("api.example.com:443", "api.example.com" for any port, "140.82.112.0/20:443,8443"; an empty list means nothing outside the project), OR clear: true. The list replaces the one there. Running containers follow it within a minute and nothing restarts, so a container that needs a destination left off stops reaching it. The same as `snoutdata containers egress set|clear`.',inputSchema:ee({ref:J,allow:{type:"array",items:J},clear:{type:"boolean"}},["ref"])},{name:"list_function_secrets",description:"The NAMES of the environment variables a project's functions run with, their sizes and when each was last set. Never the values, which are not readable by anything but the runtime. THERE IS NO TOOL THAT SETS ONE: a secret in a tool call is a secret in an audit log, so a person sets it with `snoutdata secrets set`. Use this to check whether one a function needs is there.",inputSchema:ee({ref:J},["ref"])},{name:"function_logs",description:"What a project's functions printed with console.log and console.error in the last seven days, newest first: each line's time, function, level ('error' for console.error and console.warn) and text. Lines arrive about a minute after they are printed. Use it after deploying or calling a function to see why it failed. name narrows to one function, errorsOnly to errors, limit is at most 500 (default 100). Costs nothing.",inputSchema:ee({ref:J,name:J,errorsOnly:{type:"boolean"},limit:{type:"integer"}},["ref"])},{name:"get_project",description:"Everything about one project in one call: its state, region and size, which products are on (auth, storage, data-api), the names of its deployed functions and function secrets, and its custom domains. Never a password, a key or a download link (export_status has the link to the last export).",inputSchema:ee({ref:J},["ref"])},{name:"list_products",description:"Whether a project's auth (user sign-up and sign-in), storage (files) and data API (REST and GraphQL over its tables) are on, and whether the plan allows the data API.",inputSchema:ee({ref:J},["ref"])},{name:"set_product",description:"Turn auth, storage or data-api on or off for a project. It starts within about a minute. All three are on every plan, including free.",inputSchema:ee({ref:J,product:{type:"string",enum:["auth","storage","data-api"]},enabled:{type:"boolean"}},["ref","product","enabled"])},{name:"list_domains",description:"The custom domains in front of a project's API, whether each is verified, and the DNS records each needs.",inputSchema:ee({ref:J},["ref"])},{name:"add_domain",description:"Serve a project's API at the user's own hostname (paid plans). Returns the DNS records the user must publish before verify_domain can succeed.",inputSchema:ee({ref:J,hostname:J},["ref","hostname"])},{name:"verify_domain",description:"Check a custom domain's DNS records and verify it once they are published.",inputSchema:ee({ref:J,hostname:J},["ref","hostname"])},{name:"remove_domain",description:"Stop serving a project at a custom domain.",inputSchema:ee({ref:J,hostname:J},["ref","hostname"])},{name:"restore_window",description:"How far back a point-in-time restore of a project can go, or why it cannot (the plan, or no backup yet). Starts nothing.",inputSchema:ee({ref:J},["ref"])},{name:"restore_to_point",description:"Rewind a project to a moment (ISO 8601, inside restore_window) into a NEW project beside it, never over it. Costs a project slot on the plan. The original is untouched.",inputSchema:ee({ref:J,at:J,name:J},["ref","at"])},{name:"cluster_status",description:"A Lepis cluster (one Postgres database spread over several nodes): a Cloud project's with project, else the router this server was started against with LEPIS_ADMIN_URL. Its nodes, keyspaces and their ranges (a range is keyspace:lo; bounds are strings), tables, routers, unfinished jobs and settings; for a Cloud project also whether it is a cluster, its plan's node limit, and each node pod with the step that follows (attach, delete-pod, wait). Costs nothing.",inputSchema:ee({project:yt})},{name:"cluster_advice",description:"Ask the cluster's advisor what to split, move or add, from each node's size, connections and write rate and each range's measured share. Each recommendation has a reason, its plan, and an `operation` that cluster_run takes as it is. RUNS NOTHING. sampleMs: how long to measure write rates over (the cluster's setting by default; 0 skips them; at most 30000).",inputSchema:ee({project:yt,sampleMs:{type:"integer"}})},{name:"cluster_check",description:"The cluster's design check: reads every table's distribution key, foreign keys, unique keys and indexes, and says what keeps related rows off one node or makes a query scan (a table under a distributed one with no distribution key column, a foreign key without the key, a lookup that should be a reference table, a foreign key with no index). Each finding has a fix, SQL to run, or an `operation` cluster_run takes as it is. RUNS NOTHING.",inputSchema:ee({project:yt})},{name:"cluster_plan",description:"The dry run of one cluster operation: its steps, what moves where, rows, bytes, the estimated copy time and the expected write pause. Changes nothing. Planning an operation is what lets cluster_run run it.",inputSchema:ee({project:yt,operation:ad},["operation"])},{name:"cluster_run",description:"Run one cluster operation as a durable job. IT MOVES DATA, and each cutover pauses writes to what moves for up to the cluster's max_write_pause_ms. Without confirm: true it only returns the plan and runs nothing: show that plan to the user, and when they agree call again with the same operation and confirm: true. confirm runs only an operation planned here (cluster_plan, cluster_advice, or cluster_run without confirm) in the last 15 minutes. Returns the job id; follow it with cluster_watch_job.",inputSchema:ee({project:yt,operation:ad,confirm:{type:"boolean"}},["operation"])},{name:"cluster_jobs",description:"The cluster's latest jobs, or with id one job with each step's state and phase. Costs nothing.",inputSchema:ee({project:yt,id:Yr})},{name:"cluster_watch_job",description:"Wait for a job to finish, up to timeoutSeconds (default 30, at most 120), and return its state and steps: done, failed (with the error; cluster_resume_job runs it again from the failed step) or cancelled. Running out of time stops the waiting, never the job; call again to keep waiting.",inputSchema:ee({project:yt,id:Yr,timeoutSeconds:{type:"integer"}},["id"])},{name:"cluster_cancel_job",description:"Stop a running job. A move cancelled before its cutover rolls back; one cancelled after it finishes its cleanup.",inputSchema:ee({project:yt,id:Yr},["id"])},{name:"cluster_resume_job",description:"Run a failed job again from the step that failed. It carries on the operation that was already approved and planned; follow it with cluster_watch_job.",inputSchema:ee({project:yt,id:Yr},["id"])},{name:"delete_project",description:"Delete a project. THIS DESTROYS A DATABASE. Off unless the person who started this server passed --allow-delete, in which case it still only marks the project deleted and its data is erasable for a grace period.",inputSchema:ee({ref:J},["ref"])}],mw=new Set(["whoami","list_projects","get_connection_url","usage","export_status","list_teams","list_tokens","list_functions","list_function_secrets","function_logs","container_egress","get_project","list_products","list_domains","restore_window","cluster_status","cluster_advice","cluster_check","cluster_plan","cluster_jobs","cluster_watch_job"]),fw=new Set(["delete_project","delete_function","reset_password","revoke_token","remove_domain","cluster_run"]),id=["get_connection_url","push_migrations","get_project","list_functions","deploy_function","delete_function","list_function_secrets"];function aa(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.projects))return{...t,projects:t.projects.map(aa)};let n=t.export;if(n&&typeof n=="object"){let{url:r,rolesSql:o,...s}=n;return{...t,export:{...s,hasLink:typeof r=="string"&&r.length>0}}}return e}function ia(e,t){return t.available?null:t.pitrEnabled?`${e} has no backup to restore from yet.`:`Point-in-time restore is part of the Pro and Business plans, and this project is on ${t.tier??"another plan"}.`}function gw(e){return{...e,annotations:mw.has(e.name)?{readOnlyHint:!0}:{readOnlyHint:!1,destructiveHint:fw.has(e.name)}}}function hw(e){let t=new Set;return e.filter(n=>!t.has(n.name)&&t.add(n.name))}function Hn(e,t){return{jsonrpc:"2.0",id:e,result:t}}function Xr(e,t,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:n}}}function O(e,t,n=!1){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return Hn(e,{content:[{type:"text",text:r}],...n?{isError:!0}:{}})}function yw(e,t=new Date){let n=Date.parse(e);return!Number.isFinite(n)||n<=t.getTime()?null:Math.ceil((n-t.getTime())/864e5)}function Fn(e){return{op:e.op,cutovers:e.cutovers,moves:(e.moves??[]).map(t=>({from:t.source,to:t.targets,tables:t.tables,estimated_rows:t.estimated_rows,estimated_bytes:t.estimated_bytes,estimated_copy_seconds:t.estimated_copy_seconds,expected_pause_ms:t.expected_pause_ms})),steps:(e.steps??[]).map(t=>t.kind),estimated_rows:e.estimated_rows,estimated_bytes:e.estimated_bytes,estimated_copy_seconds:e.estimated_copy_seconds,expected_pause_ms:e.expected_pause_ms,max_write_pause_ms:e.max_write_pause_ms,warnings:e.warnings??[],...e.assumptions?{assumptions:e.assumptions}:{}}}function na(e){return{id:e.id,op:e.op,state:e.state,finished:jn(e.state),error:e.error,steps:e.steps.map(t=>({n:t.n+1,kind:t.kind,state:t.state,...typeof t.detail?.phase=="string"?{phase:t.detail.phase}:{}})),...e.state==="failed"?{next:`cluster_resume_job {"id": ${e.id}} runs it again from the failed step.`}:{}}}function ld(e,t){let n=e.operation;if(!n||typeof n!="object"||Array.isArray(n))return`${t} needs operation: an object like {"op": "range.split", "keyspace": "k", "range": "<lo>"}. cluster_advice returns them ready-made.`;let r=n;if(typeof r.op!="string"||!sa.includes(r.op))return`${t}: operation.op must be one of ${sa.join(", ")}.`;for(let o of["range","at","a","b","seed"]){let s=r[o];if(typeof s=="number"&&!Number.isSafeInteger(s))return`${t}: operation.${o} is a 64-bit number and lost its last digits as a JSON number. Pass it as a string, exactly as cluster_status or cluster_advice wrote it.`}return r}function ra(e){let t=typeof e.id=="string"&&/^\d+$/.test(e.id)?Number(e.id):e.id;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:null}function ww(e){let t=e instanceof Error?e.message:String(e),n=e?.details?.kind;return typeof n=="string"?{error:t,kind:n}:t}var bw="The cluster tools need a cluster: pass project (a SnoutData Cloud project's ref), or start this server with LEPIS_ADMIN_URL (a standalone router's admin API, e.g. http://127.0.0.1:7432) and LEPIS_ADMIN_TOKEN set. Tell the user that is what is missing.";async function Sw(e,t,n,r,o){let s,a=typeof n.project=="string"&&n.project.trim()!==""?n.project.trim():void 0;try{if(!r.shards)return O(e,bw,!0);s=r.shards(a)}catch(u){return O(e,u instanceof Error?u.message:String(u),!0)}let c=o.shardsPlans??uw,i=a??"";try{switch(t){case"cluster_status":return O(e,await s.status());case"cluster_advice":{let u=typeof n.sampleMs=="number"&&n.sampleMs>=0?Math.min(Math.floor(n.sampleMs),3e4):void 0,l=await s.advice(u);for(let m of l.advice)m.plan&&c.remember(m.request,i);return O(e,{summary:l.summary,advice:l.advice.map(m=>({op:m.op,reason:m.reason,metric:m.metric,operation:m.request,...m.plan?{plan:Fn(m.plan)}:{},...m.needs.length>0?{needs:m.needs,note:`Ask the user for ${m.needs.join(", ")}, then plan it with cluster_plan.`}:{},...m.plan_error?{plan_error:m.plan_error}:{}})),facts:l.facts,assumptions:l.assumptions,...l.advice.length>0?{next:"Nothing has run. Show the user a recommendation and its plan; if they agree, call cluster_run with its operation and confirm: true. Ask for advice again after each one runs."}:{}})}case"cluster_check":{let u=await s.check();return O(e,{...u,...u.findings.length>0?{next:"Nothing has run. Show the user the findings, errors first. SQL is theirs to run; an operation is planned with cluster_plan and run with cluster_run."}:{}})}case"cluster_plan":{let u=ld(n,t);if(typeof u=="string")return O(e,u,!0);let l=await s.plan(u);return c.remember(u,i),O(e,{plan:Fn(l),next:"Nothing has run. To run it, show the user this plan, then call cluster_run with the same operation and confirm: true."})}case"cluster_run":{let u=ld(n,t);if(typeof u=="string")return O(e,u,!0);if(n.confirm!==!0||!c.shown(u,i)){let m=await s.plan(u);c.remember(u,i);let y=n.confirm===!0;return O(e,{ran:!1,plan:Fn(m),next:y?"NOT RUN: confirm applies to an operation planned here in the last 15 minutes, and this one was not, so it has been planned now instead. Show the user this plan; if they agree, call cluster_run again with the same operation and confirm: true.":"Nothing has run. Show the user this plan; if they agree, call cluster_run again with the same operation and confirm: true."},y)}let l=await s.submit(u);return c.forget(u,i),l.job===void 0?O(e,{ran:!0,done:l.done,answer:l.answer}):O(e,{ran:!0,job:l.job,plan:Fn(l.plan),next:`Follow it with cluster_watch_job {"id": ${l.job}}.`})}case"cluster_jobs":{if(n.id===void 0)return O(e,{jobs:await s.jobs()});let u=ra(n);if(u===null)return O(e,"cluster_jobs: id is a job number. Call it without id to list them.",!0);let l=await s.job(u);return O(e,{...na(l),plan:l.plan&&Array.isArray(l.plan.steps)?Fn(l.plan):null})}case"cluster_watch_job":{let u=ra(n);if(u===null)return O(e,"cluster_watch_job needs id, the job number cluster_run returned.",!0);let l=typeof n.timeoutSeconds=="number"&&n.timeoutSeconds>0?Math.min(n.timeoutSeconds,120):30,m=Date.now()+l*1e3;for(;;){let y=await s.job(u);if(jn(y.state))return O(e,na(y),y.state!=="done");if(Date.now()>=m)return O(e,{...na(y),note:`Still ${y.state} after ${l}s. It carries on; call cluster_watch_job again to keep waiting.`});await new Promise(T=>setTimeout(T,o.shardsPollMs??1e3))}}case"cluster_cancel_job":case"cluster_resume_job":{let u=ra(n);if(u===null)return O(e,`${t} needs id, a job number.`,!0);let l=t==="cluster_cancel_job"?await s.cancel(u):await s.resume(u);return O(e,{...l,next:`Follow it with cluster_watch_job {"id": ${u}}.`})}default:return Xr(e,-32602,`unknown tool: ${t}`)}}catch(u){return O(e,ww(u),!0)}}function re(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}async function cd(e,t,n){let r=e.id??null,o=e.method??"",s=e.params??{};if(e.id===void 0||e.id===null)return null;switch(o){case"initialize":return Hn(r,{protocolVersion:pw,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"snoutdata",version:n.version}});case"ping":return Hn(r,{});case"tools/list":return Hn(r,{tools:hw([...Kn.map(gw),...n.borrowed??[]])});case"tools/call":return kw(r,s,t,n);default:return Xr(r,-32601,`unknown method: ${o}`)}}async function kw(e,t,n,r){let o=typeof t.name=="string"?t.name:"",s=t.arguments??{};if(!(Kn.some(l=>l.name===o)||(r.borrowed?.some(l=>l.name===o)??!1)))return Xr(e,-32602,`unknown tool: ${o}`);let c=["get_connection_url","pause_project","resume_project","scale_project","delete_project","push_migrations","usage","export_status","start_export","reset_password","get_project","list_products","set_product","list_domains","add_domain","verify_domain","remove_domain","restore_window","restore_to_point"];if(o.startsWith("cluster_")&&Kn.some(l=>l.name===o))return Sw(e,o,s,n,r);let i=re(s,"ref");if(c.includes(o)&&!i)return O(e,`${o} needs a project ref. Call list_projects to see them.`,!0);let u=i&&n.localProject?n.localProject(i):null;if(u&&!id.includes(o))return O(e,`${i} is the self-hosted project in ${u.folder}, and ${o} is about SnoutData Cloud. On a local project these tools work: ${id.join(", ")}.`,!0);try{switch(o){case"whoami":return O(e,await n.whoami());case"list_projects":return O(e,aa(await n.listProjects()));case"create_project":{let l=re(s,"name");return l?O(e,await n.createProject({name:l,region:re(s,"region")??void 0,teamId:re(s,"teamId")??void 0})):O(e,"create_project needs a name.",!0)}case"get_connection_url":{let l=await n.connection(i);return O(e,{url:l.uri,state:l.state,wakesInstantly:l.wakesInstantly,warning:"This URL contains a live database password. Put it in an environment variable, not in a file that is committed."})}case"pause_project":return O(e,await n.setProjectState("pause",i));case"resume_project":return O(e,await n.setProjectState("resume",i));case"scale_project":{let l=s.instances;if(l!==void 0&&l!==1&&l!==2&&l!==3)return O(e,"instances is 1, 2 or 3.",!0);let m=s.confirm===!0&&l!==void 0;return O(e,await n.scaleProject(i,l,m))}case"usage":{let l=typeof s.days=="number"?s.days:void 0;return O(e,await n.usage(i,l))}case"export_status":return O(e,await n.exportStatus(i));case"start_export":return O(e,await n.requestExport(i));case"reset_password":{let l=await n.resetPassword(i),m=await n.connection(i);return O(e,{url:m.uri,appliesIn:l.appliesIn??"within about fifteen seconds",next:"Wait about fifteen seconds before connecting with this URL, and retry a refusal for up to two minutes: until the change applies (usually 5 to 15 seconds, longer while the host is busy) the new password is refused and the old one still works, which does not mean the new one is wrong. Then update DATABASE_URL wherever it is set.",warning:"This URL contains a live database password. Put it in an environment variable, not in a file that is committed."})}case"list_teams":return O(e,await n.listTeams());case"get_project":return O(e,aa(await n.getProject(i)));case"list_products":return O(e,await n.getProducts(i));case"set_product":{let l=re(s,"product");return l!=="auth"&&l!=="storage"&&l!=="data-api"?O(e,"set_product needs product: auth, storage or data-api.",!0):typeof s.enabled!="boolean"?O(e,"set_product needs enabled: true or false.",!0):O(e,await n.setProduct(i,l,s.enabled))}case"list_domains":return O(e,await n.listDomains(i));case"add_domain":case"verify_domain":case"remove_domain":{let l=re(s,"hostname");return l?O(e,await n.domainAction(i,o.split("_")[0],l)):O(e,`${o} needs a hostname, e.g. api.example.com.`,!0)}case"restore_window":{let l=await n.restoreWindow(i),m=l&&l.restore?ia(i,l.restore):null;return O(e,m?{...l,reason:m}:l)}case"restore_to_point":{let l=re(s,"at");return l?O(e,await n.restoreTo(i,l,re(s,"name")??void 0)):O(e,"restore_to_point needs at: an ISO 8601 moment inside restore_window.",!0)}case"deploy_function":{let l=re(s,"ref"),m=re(s,"name");return!l||!m?O(e,"deploy_function needs a project ref and a function name.",!0):O(e,await n.deployFunction(l,m,{dir:re(s,"dir")??void 0,entrypoint:re(s,"entrypoint")??void 0,verifyJwt:s&&typeof s=="object"&&"openToAnyone"in s?s.openToAnyone!==!0:!0}))}case"list_functions":{let l=re(s,"ref");return l?O(e,await n.listFunctions(l)):O(e,"list_functions needs a project ref.",!0)}case"size_function":{let l=re(s,"ref"),m=re(s,"name");if(!l||!m)return O(e,"size_function needs a project ref and a function name.",!0);let y=typeof s.memoryMb=="number"?s.memoryMb:void 0,T=typeof s.concurrency=="number"?s.concurrency:void 0,A=s.reset===!0;return!A&&y===void 0&&T===void 0?O(e,"size_function needs memoryMb, concurrency, or reset: true.",!0):O(e,await n.sizeFunction(l,m,{memoryMb:y,concurrency:T,reset:A}))}case"delete_function":{let l=re(s,"ref"),m=re(s,"name");return!l||!m?O(e,"delete_function needs a project ref and a function name.",!0):O(e,await n.deleteFunction(l,m))}case"list_containers":{let l=re(s,"ref");return l?O(e,await n.listContainers(l)):O(e,"list_containers needs a project ref.",!0)}case"deploy_container":{let l=re(s,"ref"),m=re(s,"name"),y=re(s,"image");if(!l||!m||!y)return O(e,"deploy_container needs a project ref, a container name and an image.",!0);let T=typeof s.port=="number"?s.port:void 0;return O(e,await n.deployContainer(l,m,{image:y,...T===void 0?{}:{port:T}}))}case"restart_container":case"delete_container":{let l=re(s,"ref"),m=re(s,"name");return!l||!m?O(e,`${o} needs a project ref and a container name.`,!0):O(e,o==="restart_container"?await n.restartContainer(l,m):await n.deleteContainer(l,m))}case"container_logs":{let l=re(s,"ref");if(!l)return O(e,"container_logs needs a project ref.",!0);let m=typeof s.limit=="number"?s.limit:void 0;return O(e,await n.containerLogs(l,{name:re(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:m}))}case"container_egress":{let l=re(s,"ref");return l?O(e,await n.containerEgress(l)):O(e,"container_egress needs a project ref.",!0)}case"set_container_egress":{let l=re(s,"ref");if(!l)return O(e,"set_container_egress needs a project ref.",!0);let m=s.clear===!0,y=s.allow;return y!==void 0&&(!Array.isArray(y)||!y.every(T=>typeof T=="string"))?O(e,'set_container_egress takes allow as a list of destinations, such as ["api.example.com:443"].',!0):m===(y!==void 0)?O(e,"set_container_egress takes either allow (a list of destinations; [] for nothing outside the project) or clear: true (the public internet again), and exactly one of them.",!0):O(e,await n.setContainerEgress(l,m?null:y))}case"list_function_secrets":{let l=re(s,"ref");return l?O(e,await n.listFunctionSecrets(l)):O(e,"list_function_secrets needs a project ref.",!0)}case"function_logs":{let l=re(s,"ref");if(!l)return O(e,"function_logs needs a project ref.",!0);let m=typeof s.limit=="number"?s.limit:void 0;return O(e,await n.functionLogs(l,{name:re(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:m}))}case"list_tokens":return O(e,await n.listTokens());case"create_token":{let l=re(s,"name");if(!l)return O(e,"create_token needs a name, so somebody can tell later what it was for.",!0);let m=re(s,"expires"),y=m?yw(m):void 0;return y===null?O(e,`create_token: \`expires\` must be a date in the future, like 2026-12-31. Got "${m}".`,!0):O(e,await n.createToken(l,y,re(s,"project")??void 0))}case"revoke_token":{let l=re(s,"id");return l?O(e,await n.revokeToken(l)):O(e,"revoke_token needs the id of a token. list_tokens has them.",!0)}case"push_migrations":return O(e,await n.pushMigrations(i,{dir:re(s,"dir")??void 0,dryRun:s.dryRun===!0}));case"delete_project":return r.allowDelete?O(e,await n.setProjectState("delete",i)):O(e,"delete_project is off. The person running this server started it without --allow-delete, so deleting a database is theirs to do. Tell them that is what you wanted.",!0);default:return r.borrowed?.some(l=>l.name===o)?n.callBorrowed?Hn(e,await n.callBorrowed(o,s)):O(e,`${o} needs SnoutData Studio, which is no longer answering.`,!0):Xr(e,-32602,`unknown tool: ${o}`)}}catch(l){return O(e,l instanceof Error?l.message:String(l),!0)}}function dd(e){let t=e.split(`
|
|
540
|
-
`),n=t.pop()??"";return{messages:t.map(r=>r.trim()).filter(r=>r.length>0),rest:n}}var
|
|
541
|
-
`);let s=
|
|
542
|
-
`)}async function
|
|
543
|
-
`)});return}if(t!=="add"&&t!=="verify"&&t!=="remove")throw new
|
|
544
|
-
`)})}
|
|
801
|
+
`:""}`),!t.yes&&!await(t.ask??ew)(ut.ask(r.ref,n)))throw new O("failed",ut.declined);let o=await T("cloud-project-spread",{ref:e,instances:n});w({ref:o.ref,instances:o.copies,changed:o.changed,...o.preparing?{preparing:!0,message:o.message}:{}},()=>{u(ut.done(o.ref,o.copies)),o.message&&u(o.message)})}me();pe();async function ed(e){let t=await T("cloud-token-create",{name:e.name,expiresInDays:e.expiresInDays,...e.project?{project:e.project}:{}});w(t,()=>{process.stdout.write(`${t.token}
|
|
802
|
+
`),u(""),u(`${N(t.name)} \u2014 ${t.expiresAt?`expires ${t.expiresAt.slice(0,10)}`:"does not expire"}.`),u(t.project?`Reaches project ${t.project} only.`:"Reaches every project on this account."),u("This is the only time it is shown: only its hash is stored."),u($(" export SNOUTDATA_ACCESS_TOKEN=<that token>"))})}async function td(){let{tokens:e}=await T("cloud-token-list");w({tokens:e},()=>{if(e.length===0){u("No access tokens. `snoutdata tokens create --name ci`.");return}process.stdout.write(`${V([["PREFIX","NAME","PROJECT","STATE","LAST USED","EXPIRES"],...e.map(t=>[t.current?N(t.prefix):t.prefix,t.name,t.project??"all",t.revokedAt?"revoked":t.live?"live":"expired",We(t.lastUsedAt),t.expiresAt?t.expiresAt.slice(0,10):"never"])])}
|
|
803
|
+
`)})}async function nd(e){let t=e.startsWith("sdt_")?{prefix:e}:{id:e},n=await T("cloud-token-revoke",t);w(n,()=>{u(n.changed?`Revoked ${n.token.prefix} (${n.token.name}).`:`${n.token.prefix} was already revoked.`)})}me();ve();pe();async function rd(e){let t=await Me(e);w({ref:t.ref,appKey:t.appKey,serverKey:t.serverKey,issuedAt:t.keysIssuedAt,expiresAt:t.keysExpireAt},()=>{if(!t.appKey||!t.serverKey){u(`${e} has no API keys yet. Ask again in a moment.`);return}process.stdout.write(`${sd(t.appKey,t.serverKey)}
|
|
804
|
+
`),rw(t.keysIssuedAt)})}async function od(e,t){if(!t.force)throw u(`Rotating the keys for ${e} stops every app key and server key already pasted anywhere.`),u("Anything holding one (a deployed app, a CI secret, a teammate) breaks until it is updated."),new y("keys rotate needs --force, because this cannot be undone");let n=no(await T("cloud-project-rotate-jwt",{ref:e}));w(n,()=>{process.stdout.write(`${sd(n.appKey,n.serverKey)}
|
|
805
|
+
`),u(""),u(n.breaks),u($(" snoutdata keys --json to read them again later"))})}function sd(e,t){return V([["KEY","VALUE"],["app key",e],["server key",t]])}function rw(e){u(""),u(`The ${N("app key")} is the public one: it goes in a browser, and row-level security decides what it reads.`),u(`The ${N("server key")} bypasses row-level security. Server side only, never in a client bundle.`),e&&u($(` issued ${e.slice(0,10)}`))}me();ve();pe();import{readdir as sw,readFile as aw,stat as iw}from"node:fs/promises";import{join as fa,relative as lw,sep as cw}from"node:path";var ad=["functions"];async function ma(e){try{return(await iw(e)).isDirectory()}catch{return!1}}async function dw(e,t){if(t){if(!await ma(t))throw new y(`${t} is not a directory`);return t}for(let n of ad){let r=fa(n,e);if(await ma(r))return r}throw new y(`no folder found for ${e} at ${ad[0]}/${e}; use --dir to say where it is.`)}async function id(e){let t=[];async function n(r){for(let o of await sw(r,{withFileTypes:!0})){if(o.name.startsWith(".")||o.name==="node_modules")continue;let s=fa(r,o.name);if(o.isDirectory()){await n(s);continue}if(!o.isFile())continue;let a=await aw(s),l=a.toString("utf8");if(Buffer.compare(Buffer.from(l,"utf8"),a)!==0)throw new y(`${s} is not text, and a function bundle is source code. Put binary assets in Storage.`);t.push({path:lw(e,s).split(cw).join("/"),text:l})}}return await n(e),t}async function uw(e,t,n){let r=await id(t);if(r.length===0)throw new y(`${t} has no files in it`);let o=n??(r.some(l=>l.path==="index.ts")?"index.ts":"");if(!o)throw new y(`${t} has no index.ts, so there is nothing to start. Name the file with --entrypoint.`);let s=fa(t,"..","_shared");if(!await ma(s))return{entrypoint:o,files:r};let a=(await id(s)).map(l=>({path:`_shared/${l.path}`,text:l.text}));return{entrypoint:`${e}/${o}`,files:[...r.map(l=>({path:`${e}/${l.path}`,text:l.text})),...a]}}async function ga(e,t,n){zt(t);let r=await dw(t,n.dir),{entrypoint:o,files:s}=await uw(t,r,n.entrypoint),a=Ic({entrypoint:o,files:s});return{answer:await T("cloud-project-functions",{ref:e,action:"deploy",name:t,verifyJwt:n.verifyJwt,bundle:a}),directory:r,files:s.length,bytes:JSON.stringify(a).length}}async function cd(e,t,n){let{answer:r,directory:o,files:s,bytes:a}=await ga(e,t,n),l=r.functions.find(d=>d.name===t);w(r,()=>{let d=Math.max(1,Math.round(a/1024));u(`${N(t)} deployed from ${o} (${s} file${s===1?"":"s"}, ${d} KB)`),l&&u(` ${l.url}`),n.verifyJwt||(u(""),u(N(" Anybody who knows this URL can run it. No API key is required.")),u($(" That is what a webhook receiver needs. Check the sender signature inside the function."))),r.limit.maxFunctions!==null&&u($(` ${r.limit.deployed} of ${r.limit.maxFunctions} functions on this plan`))})}function ha(e){return T("cloud-project-functions",{ref:e})}function ya(e,t){return zt(t),T("cloud-project-functions",{ref:e,action:"delete",name:t})}function wa(e,t,n){if(zt(t),!n.reset&&n.memoryMb===void 0&&n.concurrency===void 0)throw new y("functions size needs --memory MB, --concurrency N, or --reset");return T("cloud-project-functions",{ref:e,action:"size",name:t,...n.reset?{reset:!0}:{memoryMb:n.memoryMb??null,concurrency:n.concurrency??null}})}function pw(e,t){if(e.memoryMb==null||e.concurrency==null)return null;let n=e.memoryMb*e.concurrency,r=t.podMemoryMb?` of ${t.podMemoryMb} MB`:"";return`${e.memoryMb} MB x ${e.concurrency} worker${e.concurrency===1?"":"s"} = ${n} MB${r}`}function dd(e){return e.functionMemoryMb==null||e.concurrencyMax==null||e.podMemoryMb==null?null:`${e.tier??"this"} plan: up to ${e.functionMemoryMb} MB a worker and ${e.concurrencyMax} workers a function, memory x workers up to ${e.podMemoryMb} MB`}async function ud(e,t,n){let r=await wa(e,t,n),o=r.functions.find(s=>s.name===t);w(r,()=>{let s=o?pw(o,r.limit):null;u(`${N(t)} ${n.reset?"is back to the plan default":"is resized"}${s?`: ${s}`:""}`),u($(" The next request runs at it; workers already running finish what they hold."));let a=dd(r.limit);a&&u($(` ${a}`))})}async function pd(e){let t=await ha(e);w(t,()=>{if(t.functions.length===0){u(`${e} has no functions.`),u($(" snoutdata functions deploy <name> from functions/<name>"));return}process.stdout.write(`${V([["NAME","KEY","SIZE","MEMORY","WORKERS","URL"],...t.functions.map(r=>[r.name,r.verifyJwt?"required":N("open"),r.bytes===null?"-":`${Math.max(1,Math.round(r.bytes/1024))} KB`,r.memoryMb==null?"-":`${r.memoryMb} MB`,r.concurrency==null?"-":String(r.concurrency),r.url])])}
|
|
806
|
+
`),t.limit.maxFunctions!==null&&u($(`${t.limit.deployed} of ${t.limit.maxFunctions} on this plan`));let n=dd(t.limit);n&&u($(`${n}. Change one with: snoutdata functions size <name> --memory MB --concurrency N`))})}function ld(e){let t=e.dropped_before>0?$(`(${e.dropped_before} earlier line(s) were printed too fast to keep) `):"",n=e.cut_bytes?$(` (cut from ${e.cut_bytes} bytes)`):"",r=e.level==="error"?N("error "):"";return`${$(e.at)} ${e.name} ${r}${t}${e.message}${n}`}async function md(e,t,n){let r=a=>T("cloud-project-functions",{ref:e,action:"logs",...t?{name:t}:{},...n.errorsOnly?{errorsOnly:!0}:{},...a?{since:a}:{},limit:n.limit??100}),o=((await r()).lines??[]).slice().reverse();if(w({ref:e,lines:o},()=>{if(o.length===0&&!n.follow){u(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),u($(" Lines show up about a minute after a function prints them."));return}for(let a of o)process.stdout.write(`${ld(a)}
|
|
807
|
+
`)}),!n.follow)return;let s=o.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(l=>setTimeout(l,5e3));let a=((await r(s)).lines??[]).slice().reverse();for(let l of a)process.stdout.write(`${ld(l)}
|
|
808
|
+
`),s=l.at}}async function fd(e,t){let n=await ya(e,t);w(n,()=>{u(n.live?`${t} is gone.`:`${t} is gone. It stops answering within a few seconds.`)})}me();import{spawn as Mw}from"node:child_process";import{createHash as Dw}from"node:crypto";import{createReadStream as vd}from"node:fs";import{mkdtemp as jw,rm as Uw,stat as co}from"node:fs/promises";import{request as Fw}from"node:http";import{request as Bw}from"node:https";import{tmpdir as Hw}from"node:os";import{basename as Gw,dirname as qw,join as $a}from"node:path";var fw="x-snoutdata-upload-bytes",gw="x-snoutdata-upload-sha256",hw="/done",yw=/^[0-9a-f]{64}$/,ww=/^sha256:[0-9a-f]{64}$/;function bw(e){return yw.test(e)}var Je=class extends Error{constructor(n,r){super(`the upload failed (${n})`);this.status=n;this.body=r}};function ba(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function gd(e){let t=String(ba(e).digest??"");if(!ww.test(t))throw new Je(502,JSON.stringify({error:"The upload finished without saying what it stored, so there is nothing to deploy. Build again."}));return t}var Sw=15*6e4,kw=2e3;async function hd(e){let{ticketUrl:t,file:n,transport:r}=e;if(!bw(e.sha256))throw new Error("an upload is declared with its SHA-256, in hex");let o=await r.call("POST",t,{[fw]:String(e.bytes),[gw]:e.sha256});if(o.status===405){e.step?.("uploading");let i=await r.put(t,n,{});if(i.status!==200)throw new Je(i.status,i.body);return gd(i.body)}if(o.status!==200)throw new Je(o.status,o.body);let s=ba(o.body);if(typeof s.url!="string"||!s.url.startsWith("https://")||!s.headers||typeof s.headers!="object")throw new Je(502,JSON.stringify({error:"The project's host did not say where to put the image. Build again in a moment."}));e.step?.("uploading");let a=await r.put(s.url,n,s.headers);if(a.status!==200){let i=/<Code>([^<]+)<\/Code>/.exec(a.body)?.[1],p=i==="BadDigest"||i==="XAmzContentSHA256Mismatch"?"The image changed or was damaged while it was uploading. Build again.":i==="AccessDenied"||i==="SignatureDoesNotMatch"||i==="RequestTimeTooSkewed"?"The upload link was refused (it lasts 15 minutes, and this computer's clock must be right). Build again.":`The upload to storage failed (${a.status}). Build again in a moment.`;throw new Je(a.status===403?401:502,JSON.stringify({error:p}))}e.step?.("storing");let l=r.now()+(e.waitMs??Sw),d=e.pollMs??kw,c=!1;for(;!c;){let i=await r.call("POST",`${t}${hw}`,{});if(i.status===200||i.status===202)c=!0;else if(i.status===429&&r.now()<l)await r.sleep(d*5);else throw new Je(i.status,i.body)}for(;;){let i=await r.call("GET",t,{});if(i.status!==200)throw new Je(i.status,i.body);let p=ba(i.body);if(p.state==="stored")return gd(i.body);if(p.state==="failed")throw new Je(typeof p.status=="number"?p.status:502,JSON.stringify({error:p.error??"The image could not be stored. Build again in a moment."}));if(r.now()>=l)throw new Je(504,JSON.stringify({error:"The project's host took too long to store the image. Build again in a moment."}));await r.sleep(d)}}pe();var _w=/^[a-z0-9][a-z0-9_-]{0,31}$/;function $w(e){return _w.test(e)}function wd(e){return $w(e)?null:`${JSON.stringify(e)} is not a container name: lower-case letters, digits, hyphens and underscores, up to 32 characters, starting with a letter or a digit.`}var vw=/^sha256:[0-9a-f]{64}$/,Pw=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,xw=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/,Ew=/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*(?::[0-9]{1,5})?$/;function Aw(e){return vw.test(e)}function bd(e){let t=e.trim();if(t.length===0||t.length>512||/\s/.test(t))return{error:`${JSON.stringify(e)} is not an image reference.`};let n=t,r=null,o=n.indexOf("@");if(o!==-1&&(r=n.slice(o+1),n=n.slice(0,o),!Aw(r)))return{error:`${JSON.stringify(r)} is not a sha256 digest.`};let s=null,a=n.lastIndexOf("/"),l=n.lastIndexOf(":");if(l>a&&(s=n.slice(l+1),n=n.slice(0,l),!Pw.test(s)))return{error:`${JSON.stringify(s)} is not an image tag.`};let d=n.split("/"),c="docker.io",i=d[0]??"";return d.length>1&&(i.includes(".")||i.includes(":")||i==="localhost")&&(c=i.toLowerCase(),d.shift()),Ew.test(c)?((c==="index.docker.io"||c==="registry-1.docker.io")&&(c="docker.io"),c==="docker.io"&&d.length===1&&d.unshift("library"),d.length===0||d.some(p=>!xw.test(p))?{error:`${JSON.stringify(e)} is not an image name: a repository is lower-case letters, digits and separators.`}:(s===null&&r===null&&(s="latest"),{registry:c,repository:d.join("/"),tag:s,digest:r})):{error:`${JSON.stringify(i)} is not a registry address.`}}var mx=["application/vnd.oci.image.index.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.v2+json"].join(", ");function Sa(e){let t=e.split(".");if(t.length!==4)return null;let n=[];for(let r of t){if(!/^\d{1,3}$/.test(r))return null;let o=Number(r);if(o>255)return null;n.push(o)}return n}function Rw(e){let t=e.replace(/^\[|\]$/g,""),n=t.indexOf("%");if(n!==-1&&(t=t.slice(0,n)),!/^[0-9a-fA-F:.]+$/.test(t)||!t.includes(":"))return null;let r=t.lastIndexOf(":");if(t.slice(r+1).includes(".")){let i=Sa(t.slice(r+1));if(!i)return null;t=`${t.slice(0,r+1)}${(i[0]<<8|i[1]).toString(16)}:${(i[2]<<8|i[3]).toString(16)}`}let o=t.split("::");if(o.length>2)return null;let s=i=>i===""?[]:i.split(":"),a=s(o[0]??""),l=o.length===2?s(o[1]??""):[];if([...a,...l].some(i=>!/^[0-9a-fA-F]{1,4}$/.test(i)))return null;let d=a.length+l.length;if(o.length===1?d!==8:d>7)return null;let c=new Array(8-d).fill(0);return[...a.map(i=>parseInt(i,16)),...c,...l.map(i=>parseInt(i,16))]}function Tw(e,t,n){let r=Sa(t),o=a=>(a[0]<<24|a[1]<<16|a[2]<<8|a[3])>>>0,s=n===0?0:4294967295<<32-n>>>0;return(o(e)&s)===(o(r)&s)}var Ow=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];var fx=1024**3;var yd=16,Nw=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/,Iw=/^(\d{1,3}(?:\.\d{1,3}){3})(?:\/(\d{1,2}))?$/;function Cw(e,t){let n=e??[],r={error:`${t}: ports are up to ${yd} whole numbers, 1 to 65535.`};if(!Array.isArray(n)||n.length>yd)return r;let o=n.map(s=>typeof s=="string"&&/^\d{1,5}$/.test(s)?Number(s):s);return o.some(s=>typeof s!="number"||!Number.isInteger(s)||s<1||s>65535)?r:[...new Set(o)].sort((s,a)=>s-a)}function Lw(e){let t=e.trim().toLowerCase(),n=Iw.exec(t);if(n){let r=Sa(n[1]??""),o=n[2]===void 0?32:Number(n[2]);if(!r||o>32)return{error:`${e} is not an IPv4 address or range.`};let s=(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0,a=o===0?0:4294967295<<32-o>>>0,l=(s&a)>>>0,d=[24,16,8,0].map(c=>l>>>c&255);return Ow.some(([c,i])=>o>=i&&Tw(d,c,i))?{error:`${e} is not on the public internet, and a container reaches nothing else.`}:o===32?d.join("."):`${d.join(".")}/${o}`}return Rw(t)?{error:`${e} is an IPv6 address. Containers send over IPv4 only; list its IPv4 address or its host name.`}:t.startsWith("*.")?{error:`${e}: a wildcard cannot be looked up. List each host name, or the address range.`}:Nw.test(t)?t:/^[a-z0-9-]{1,63}$/.test(t)?{error:`${e} is not a whole host name. Give it with its domain, like api.example.com.`}:{error:`${e} is not a host name, an IPv4 address or an IPv4 range.`}}function Sd(e){let t=e.trim(),n=t.lastIndexOf(":"),r=n!==-1&&t.indexOf(":")===n,o=r?t.slice(0,n):t,s=Cw(r?t.slice(n+1).split(",").map(l=>l.trim()):[],o.trim());if("error"in s)return s;let a=Lw(o);return typeof a!="string"?a:{destination:a,ports:s}}function ka(e){return e.ports.length===0?e.destination:`${e.destination}:${e.ports.join(",")}`}var Kw=new Set(["pending","pulling","starting","restarting"]),zw=5*6e4;function mo(e){let t=wd(e);if(t)throw new Error(t)}function va(e,t,n){mo(t);let r=bd(n.image);if("error"in r)throw new Error(r.error);return T("cloud-project-containers",{ref:e,action:"deploy",name:t,image:n.image,...n.port===void 0?{}:{port:n.port},...n.registryUser?{registryUser:n.registryUser,registryPassword:n.registryPassword??""}:{},...n.clearCredential?{clearCredential:!0}:{}})}function gn(e){return T("cloud-project-containers",{ref:e})}function Pa(e,t){return mo(t),T("cloud-project-containers",{ref:e,action:"delete",name:t})}function xa(e,t){return mo(t),T("cloud-project-containers",{ref:e,action:"restart",name:t})}function uo(e,t){return T("cloud-project-containers",{ref:e,action:"logs",...t.name?{name:t.name}:{},...t.errorsOnly?{errorsOnly:!0}:{},...t.since?{since:t.since}:{},limit:t.limit??100})}async function Pd(e,t){let n=Date.now()+zw,r=null;for(;Date.now()<n;)if(await new Promise(o=>setTimeout(o,3e3)),r=(await gn(e)).containers.find(o=>o.name===t)??null,!r||!Kw.has(r.status))return r;return r}function Ea(e){if(!e.allowed)return"stopped: not covered by the plan";let t=e.restarts>0?`, ${e.restarts} restart${e.restarts===1?"":"s"}`:"";return`${e.status}${t}`}async function xd(e,t,n){await Ed(e,t,await va(e,t,n),n.wait!==!1)}async function Ed(e,t,n,r){let o=n.containers.find(s=>s.name===t)??null;r&&o&&(u($(`${t}: ${o.image} pinned to ${o.digest.slice(0,19)}\u2026, waiting for the host`)),o=await Pd(e,t)??o),w({...n,containers:o?[o]:n.containers},()=>{if(!o){u(`${N(t)} deployed.`);return}u(`${N(t)} ${Ea(o)}`),u(` ${o.url}`),o.statusDetail&&u(` ${o.statusDetail}`),u(""),u($(" Listens on PORT ("+o.port+"). DATABASE_URL and your secrets are in its environment.")),u(N(" Anything written inside the container is lost when it restarts or is redeployed.")),u($(" Keep what matters in your database.")),n.allowance&&u($(` ${n.allowance.deployed} of ${n.allowance.maxContainers} containers on this plan, ${n.allowance.memoryMb} MB and ${n.allowance.cpuPercent}% of a core each`))})}var Ww=2*1024**3,Jw=3*6e4;async function Vw(e){let t;try{t=await co(e)}catch{throw new Error(`${e} does not exist: --dockerfile takes a folder with a Dockerfile in it, or the Dockerfile.`)}if(t.isDirectory()){try{await co($a(e,"Dockerfile"))}catch{throw new Error(`${e} has no Dockerfile in it.`)}return{context:e,file:null}}return{context:qw(e),file:e}}function Yw(e){return["buildx","build","--platform","linux/arm64","--provenance=false","--output",`type=oci,dest=${e.archive}`,...e.file?["--file",e.file]:[],e.context]}function Aa(e){return e.replace(/\b\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com(?:\/[^\s"',;)]*)?/g,"SnoutData's registry").replace(/\barn:aws[a-z-]*:[^\s"',;)]*/g,"a SnoutData credential").replace(/\b[a-z0-9.-]*\.amazonaws\.com(?:\/[^\s"',;)]*)?/g,"SnoutData Cloud").replace(/\b\d{12}\b/g,"(an account)")}function Xw(e,t){let n="";try{let r=JSON.parse(t);n=String(r.error??r.message??"")}catch{}return n?Aa(n):e===413?"the image is too large to upload: a container's image may be at most 1 GB compressed; a slimmer base (alpine, distroless, -slim) usually fixes it.":`the upload failed (${e}); build again in a moment.`}function Zw(e){return new Promise((t,n)=>{let r=Mw("docker",e,{stdio:["ignore",2,2]});r.on("error",o=>n(o)),r.on("close",o=>t(o??1))})}function Ad(e,t,n,r){return new Promise((o,s)=>{let a=new URL(e),l=(a.protocol==="http:"?Fw:Bw)(a,{method:t,headers:n});l.on("response",d=>{let c=[];d.on("data",i=>c.push(i)),d.on("end",()=>o({status:d.statusCode??0,body:Buffer.concat(c).toString("utf8")})),d.on("error",s)}),l.on("error",d=>{s(d)}),r(l)})}async function Qw(e,t,n){let r=Object.keys(n).length>0?n:{"content-type":"application/octet-stream","content-length":String((await co(t)).size)};return Ad(e,"PUT",r,o=>{let s=vd(t);s.on("error",a=>o.destroy(a)),s.pipe(o)})}function eb(e){return new Promise((t,n)=>{let r=Dw("sha256");vd(e).on("error",n).on("data",o=>r.update(o)).on("end",()=>t(r.digest("hex")))})}var tb={call:(e,t,n)=>Ad(t,e,{"content-length":"0",...n},r=>r.end()),put:Qw,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now()},Rd={docker:Zw,scratch:()=>jw($a(Hw(),"snoutdata-build-")),remove:e=>Uw(e,{recursive:!0,force:!0}),size:async e=>(await co(e)).size,hash:eb,transport:tb,ask:e=>T("cloud-project-containers",e),say:e=>u($(e)),now:()=>Date.now()};function kd(e){return`${Math.max(1,Math.round(e/1024**2))} MB`}async function _d(e,t,n){let r=await e.ask({ref:t,action:"upload-ticket",name:n});if(typeof r.url!="string"||!r.url.startsWith("https://"))throw new Error("SnoutData Cloud did not hand over an upload link; try again in a moment.");return{url:r.url,expiresAt:String(r.expiresAt??"")}}async function nb(e,t,n,r=Rd){try{if(await r.docker(["version","--format","{{.Server.Version}}"])!==0)throw new Error("docker answered with an error")}catch{throw new Error("deploy --dockerfile builds with your own Docker, and none is running here. Start Docker, or deploy an image from a registry.")}try{let o=await _d(r,e,t),s=await r.scratch();try{let a=$a(s,"image.tar");if(r.say(`${t}: building ${n.file?Gw(n.file):n.context} for linux/arm64`),await r.docker(Yw({...n,archive:a}))!==0)throw new Error("the build failed; its output is above. If it says the docker driver cannot export OCI, turn on the containerd image store, or run: docker buildx create --use");let l=await r.size(a).catch(()=>0);if(l<=0)throw new Error("docker finished but wrote no image archive, so there is nothing to upload.");if(l>Ww)throw new Error(`the image is ${kd(l)}, and a container's image may be at most 1 GB compressed. A slimmer base (alpine, distroless, -slim) usually fixes it.`);Date.parse(o.expiresAt)-r.now()>Jw||(o=await _d(r,e,t));let d=await r.hash(a);r.say(`${t}: uploading the image (${kd(l)})`);try{return await hd({ticketUrl:o.url,file:a,bytes:l,sha256:d,transport:r.transport,step:c=>{c==="storing"&&r.say(`${t}: storing the image in the project`)}})}catch(c){throw c instanceof Je?new Error(Xw(c.status,c.body)):c}}finally{await r.remove(s).catch(()=>{})}}catch(o){throw new Error(Aa(o instanceof Error?o.message:String(o)))}}async function Td(e,t,n,r=Rd){mo(t);let o=await Vw(n.path),s=await nb(e,t,o,r),a;try{a=await r.ask({ref:e,action:"deploy",name:t,pushed:s,...n.port===void 0?{}:{port:n.port}})}catch(l){throw new Error(Aa(l instanceof Error?l.message:String(l)))}await Ed(e,t,a,n.wait!==!1)}async function Od(e){let t=await gn(e);w(t,()=>{if(t.containers.length===0){u(`No containers on ${e}.`),t.allowance&&t.allowance.maxContainers===0?u($(" Containers run on every paid plan (Plus, Pro and Business).")):u($(" snoutdata containers deploy <name> <image>"));return}u(V([["name","status","image","url"],...t.containers.map(r=>[r.name,Ea(r),r.image,r.url])]));for(let r of t.containers)r.statusDetail&&r.status!=="running"&&u($(` ${r.name}: ${r.statusDetail}`));let n=t.allowance?.egress;n&&n.allowanceBytes>0&&u($(` Sent this month: ${_a(n.usedBytes)} of ${_a(n.allowanceBytes)}. At ${_a(n.allowanceBytes)} the project's containers stop until the 1st.`))})}async function po(e,t){if(t===null)return T("cloud-project-containers",{ref:e,action:"egress",clear:!0});let n=[];for(let r of t){let o=Sd(r);if("error"in o)throw new Error(o.error);n.push(o)}return T("cloud-project-containers",{ref:e,action:"egress",allow:n})}function rb(e){if(e.allowlist===void 0)return["This control plane does not know about allowlists yet."];if(e.allowlist===null)return[`Containers on ${e.ref} may reach the public internet (within the limits on how much and how fast).`,$(" snoutdata containers egress set <host[:port]> ... to allow only some destinations")];let t=[e.allowlist.allow.length===0?`Containers on ${e.ref} may reach nothing outside the project.`:`Containers on ${e.ref} may reach only:`];for(let n of e.allowlist.allow)t.push(` ${ka(n)}${n.ports.length===0?$(" (any port)"):""}`);return t.push($(` and always: ${e.allowlist.alwaysAllowed.map(ka).join(", ")}, and each other`)),t.push($(" snoutdata containers egress clear to allow the public internet again")),t}async function fo(e,t){let n=t.clear?await po(e,null):t.set?await po(e,t.set):await gn(e);w({ref:n.ref,allowlist:n.allowlist??null},()=>{for(let r of rb(n))u(r);(t.set||t.clear)&&u($(" Running containers follow it within a minute; nothing restarts."))})}function _a(e){return`${Math.round(e/1024**3*10)/10} GB`}async function Nd(e,t){await xa(e,t);let n=await Pd(e,t);w({ref:e,containers:n?[n]:[]},()=>{u(n?`${N(t)} ${Ea(n)}`:`${t} is restarting.`),n?.statusDetail&&u(` ${n.statusDetail}`)})}async function Id(e,t){let n=await Pa(e,t);w(n,()=>u(`${t} is gone. It stops within a few seconds.`))}function $d(e){return`${$(e.at.replace("T"," ").slice(0,19))} ${e.name} ${e.stream==="stderr"?N(e.message):e.message}`}async function Cd(e,t,n){let r=((await uo(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit})).lines??[]).slice().reverse();if(w({ref:e,lines:r},()=>{if(r.length===0&&!n.follow){u(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),u($(" Lines show up about a minute after a container prints them."));return}for(let s of r)process.stdout.write(`${$d(s)}
|
|
809
|
+
`)}),!n.follow)return;let o=r.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(a=>setTimeout(a,5e3));let s=((await uo(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit,since:o})).lines??[]).slice().reverse();for(let a of s)process.stdout.write(`${$d(a)}
|
|
810
|
+
`),o=a.at}}me();ve();pe();function Md(e){let t=e.indexOf("=");return t<=0?null:{name:e.slice(0,t),value:e.slice(t+1)}}async function hn(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8").replace(/\n$/,"")}async function Dd(e,t){if(e.length===0)throw new y("secrets set needs NAME=value, or NAME with --stdin");if(t.stdin){if(e.length!==1)throw new y("--stdin sets one secret, so it takes one NAME");return[{name:e[0],value:await hn()}]}return e.map(n=>{let r=Md(n);if(!r)throw new y(`${n} is not NAME=value. Use --stdin to set a value from a pipe.`);return r})}async function jd(e,t,n){if(t.length===0)throw new y("secrets set needs NAME=value, or NAME with --stdin");let r=[];if(n.stdin){if(t.length!==1)throw new y("--stdin sets one secret, so it takes one NAME");r.push({name:t[0],value:await hn()})}else for(let s of t){let a=Md(s);if(!a)throw new y(`${s} is not NAME=value. Use --stdin to set a value from a pipe.`);r.push(a)}for(let s of r){let a=Vn(s.name);if(a)throw new y(a)}let o=null;for(let s of r)o=await T("cloud-project-secrets",{ref:e,action:"set",name:s.name,value:s.value});w(o,()=>{for(let s of r)u(`${N(s.name)} set`);u($(" Functions pick it up within a few seconds. Redeploying is not needed.")),n.stdin||u($(" A value typed here is in your shell history. In CI, use: \u2026 | snoutdata secrets set NAME --stdin"))})}async function Ud(e,t){let n=Vn(t);if(n)throw new y(n);let r=await T("cloud-project-secrets",{ref:e,action:"unset",name:t});w(r,()=>{u(`${t} is gone.`)})}async function Fd(e){let t=await T("cloud-project-secrets",{ref:e});w(t,()=>{if(t.secrets.length===0){u(`${e} has no function secrets.`),u($(" snoutdata secrets set STRIPE_KEY=sk_..."));return}process.stdout.write(`${V([["NAME","SIZE","SET"],...t.secrets.map(n=>[n.name,n.bytes===null?"-":`${n.bytes} B`,We(n.updatedAt)])])}
|
|
811
|
+
`),u($("Values are not readable, here or anywhere. Set one again to change it."))})}import{spawn as sr}from"node:child_process";import{appendFileSync as uu,existsSync as ko,readFileSync as pu,statSync as Gb,unlinkSync as qb,writeFileSync as wn}from"node:fs";import{dirname as Kb,join as _o}from"node:path";import{tmpdir as zb}from"node:os";import{open as mu}from"node:fs/promises";function Bd(e){let t=(r,o)=>String.fromCharCode(...Array.from(e.slice(r,r+o)));return t(0,5)==="PGDMP"?"custom":e.length>=262&&t(257,5)==="ustar"?"tar":Array.from(e.slice(0,256)).every(r=>r===9||r===10||r===13||r>=32&&r<127||r>=128)&&e.length>0?"plain":"unknown"}function Hd(e,t,n={}){return t.readOnly?{ok:!1,code:"read-only",reason:"this project is over its plan's storage limit, so it refuses writes. A restore would fail part way. Delete some rows or change plan first."}:e==="unknown"?{ok:!1,code:"unknown-format",reason:"that file is not a pg_dump archive and does not look like SQL. `snoutdata db export` writes the custom format; psql reads plain .sql."}:!n.force&&t.existingTables>0?{ok:!1,code:"not-empty",reason:`this database already has ${t.existingTables} table${t.existingTables===1?"":"s"}. Restoring into it would leave some objects created and some not. Check --ref is the project you meant, or pass --force.`}:{ok:!0,tool:e==="plain"?"psql":"pg_restore",format:e}}function Gd(e){let t=e.split(`
|
|
812
|
+
`).filter(r=>/^pg_restore: error:/.test(r.trim())),n=t.filter(r=>!/must be owner of extension/.test(r));return{total:t.length,harmless:t.length-n.length,fatal:n}}var Ra={auth:"snout_auth_admin",storage:"snout_storage_admin",push:"snout_push_admin"},sb=/^(snoutpod_admin|snout_[a-z]+_admin)$/,go=new Set(["snout_identity","snout_files","push","snout_live","snout_realtime","_realtime","graphql","snout_graph","snout_ext","net","cron","pgbouncer","vault","pgsodium","lepis","auth","storage","realtime","graphql_public","extensions"]),ab=/^(pgrst_ddl_watch|pgrst_drop_watch|snoutpod_[a-z_]+|snoutdata_realtime|snout_realtime_messages)(\(|$)/,ib={snout_identity:"auth",snout_files:"storage",auth:"auth",storage:"storage",push:"push"},lb=new Set(["push.settings"]),cb=["TABLE DATA","SEQUENCE SET","SEQUENCE OWNED BY","FK CONSTRAINT","CHECK CONSTRAINT","DEFAULT ACL","EVENT TRIGGER","ROW SECURITY","INDEX ATTACH","TABLE ATTACH","MATERIALIZED VIEW DATA","MATERIALIZED VIEW","PUBLICATION TABLES IN SCHEMA","PUBLICATION TABLE","FOREIGN TABLE","FOREIGN DATA WRAPPER","FOREIGN SERVER","USER MAPPING","TEXT SEARCH CONFIGURATION","TEXT SEARCH DICTIONARY","TEXT SEARCH PARSER","TEXT SEARCH TEMPLATE","LARGE OBJECT","PROCEDURAL LANGUAGE","OPERATOR CLASS","OPERATOR FAMILY","ACCESS METHOD","EXTENDED STATISTICS","DATABASE PROPERTIES"];function db(e){let t=/^\d+; \d+ \d+ (.+)$/.exec(e.trim());if(!t)return null;let n=t[1],r=cb.find(d=>n.startsWith(`${d} `))??n.split(" ")[0],o=n.slice(r.length).trim().split(" "),s=o[0]??"-",a=o.length>2?o[o.length-1]:"",l=o.slice(1,o.length>2?-1:void 0).join(" ");return{line:e.trim(),type:r,schema:s,name:l,owner:a}}function ub(e){let t=new Map,n=o=>o.replace(/"/g,""),r=/ALTER TABLE (?:ONLY )?([\w."$]+)\s+ADD CONSTRAINT [^;]*?FOREIGN KEY \([^)]*\) REFERENCES ([\w."$]+)\(/g;for(let o of e.matchAll(r)){let s=n(o[1]),a=n(o[2]);if(s!==a){let l=t.get(s)??new Set;l.add(a),t.set(s,l)}}return t}function qd(e,t){let n=new Map,r=[],o=new Set,s=0;for(let d of e.split(`
|
|
813
|
+
`)){let c=db(d);if(!c)continue;let{type:i,schema:p,name:g,owner:E}=c;if(i==="TABLE DATA"||i==="SEQUENCE SET"){let te=/^(schema_migrations|migrations)$/.test(g)&&go.has(p);if(/realtime/.test(p)||p==="snout_live"||te||p==="public"&&g==="spatial_ref_sys"){s++;continue}if(p==="cron"){s++,o.add("Scheduled jobs (pg_cron) are not restored: each names the project it came from. Schedule them again with cron.schedule.");continue}if(p==="push"&&g==="credentials"){s++,o.add("Push credentials are not restored: they are sealed for the project they came from. Set them again with `snoutdata push credentials set`.");continue}let U=ib[p];if(U){U==="storage"&&(g==="objects"||g==="files")&&o.add("Storage objects are restored as rows; the files themselves are not part of an export. Upload them again into this project."),n.set(U,[...n.get(U)??[],c]);continue}if(go.has(p)){s++;continue}r.push(c.line);continue}if(i==="COMMENT"&&p==="-"&&/^EXTENSION( |$)/.test(g)||(i==="SCHEMA"?go.has(g):go.has(p))||ab.test(g)||sb.test(E)&&i!=="SCHEMA"){s++;continue}r.push(c.line)}let a=ub(t),l=["auth","storage","push"];return{platformData:l.filter(d=>n.has(d)).map(d=>{let c=n.get(d),i=c.filter(g=>g.type==="TABLE DATA"&&lb.has(`${g.schema}.${g.name}`)).map(g=>`${g.schema}.${g.name}`),p=c.filter(g=>g.type==="TABLE DATA").map(g=>`${g.schema}.${g.name}`);return{product:d,clear:i,tables:p,lines:pb(c,a)}}),rest:r,products:l.filter(d=>n.has(d)),skipped:s,notes:[...o]}}function pb(e,t){let n=l=>`${l.schema}.${l.name}`,r=new Set(e.map(n)),o=new Set,s=[],a=[...e];for(;a.length>0;){let d=a.find(c=>[...t.get(n(c))??[]].every(i=>!r.has(i)||o.has(i)||i===n(c)))??a[0];o.add(n(d)),s.push(d.line),a=a.filter(c=>c!==d)}return s}me();ve();_e();pe();me();_e();var Oa=["max_write_pause_ms","drain_timeout_ms","ack_timeout_ms","copy_mb_per_s"],zd=["advice_sample_ms","advice_min_bytes","advice_split_bytes","advice_skew_pct","advice_hot_pct","advice_min_writes_per_s","advice_pin_pct","advice_node_disk_bytes","advice_disk_pct","advice_conn_pct"],Wd=["off","advise","auto"];function Xn(e){return e==="done"||e==="failed"||e==="cancelled"}function Zn(e,t=process.env){if(e.project!==void 0){if(e.admin!==void 0)throw new O("usage","cluster takes --project (a SnoutData Cloud project) or --admin (a standalone router), not both");return new pt(yb(e.project))}let n=e.admin??Kd(t.LEPIS_ADMIN_URL);if(!n)throw new O("usage","cluster needs a project: --project <ref> for a SnoutData Cloud project, or --admin <url> (or LEPIS_ADMIN_URL) for the admin API of a standalone Lepis router (LEPIS_ADMIN_ADDR)");let r=e.token??Kd(t.LEPIS_ADMIN_TOKEN);if(!r)throw new O("not-signed-in","no admin token: set LEPIS_ADMIN_TOKEN to the router's token, or pass --token");return new Ta(mb(n),r)}function Kd(e){return e===void 0||e===""?void 0:e}function mb(e){let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`,n;try{n=new URL(t)}catch{throw new O("usage",`--admin: not a URL: ${e}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new O("usage",`--admin: http or https, not ${n.protocol.replace(":","")}`);if(n.username||n.password)throw new O("usage","--admin: the URL carries no credentials; the token comes from LEPIS_ADMIN_TOKEN or --token");if(n.protocol==="http:"&&!fb(n.hostname))throw new O("usage",`--admin: ${n.host} is not this machine, and plain http would send the token in the clear. Use https (the router serves it when it has LEPIS_TLS_CERT), or a tunnel to 127.0.0.1`);return n.pathname=n.pathname.replace(/\/+$/,""),n.search="",n.hash="",n}function fb(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)}var gb=6e4,Ta=class{target;#t;#n;constructor(t,n){this.#t=t,this.#n=n,this.target=t.toString().replace(/\/$/,"")}status(){return this.#e("GET","/v1/status")}ops(){return this.#e("GET","/v1/ops")}plan(t){return this.#e("POST","/v1/plan",t)}submit(t){return this.#e("POST","/v1/jobs",t)}async jobs(){return(await this.#e("GET","/v1/jobs")).jobs}job(t){return this.#e("GET",`/v1/jobs/${t}`)}cancel(t){return this.#e("POST",`/v1/jobs/${t}/cancel`)}resume(t){return this.#e("POST",`/v1/jobs/${t}/resume`)}settings(t){return this.#e("POST","/v1/settings",t)}advice(t){return this.#e("GET",t===void 0?"/v1/advice":`/v1/advice?sample_ms=${Math.max(0,Math.floor(t))}`)}check(){return this.#e("GET","/v1/check")}autopilot(){return this.#e("GET","/v1/autopilot")}setAutopilot(t){return this.#e("POST","/v1/settings",t)}async#e(t,n,r){let o=`${this.target}${n}`,s;try{s=await fetch(o,{method:t,headers:{authorization:`Bearer ${this.#n}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(r??{})}:{},signal:AbortSignal.timeout(gb)})}catch(d){let c=Mr(d),i=d instanceof Error?d.cause instanceof Error?d.cause.message:d.message:String(d);throw new O(c==="failed"?"network":c,`could not reach the Lepis admin API at ${this.target}: ${i}`)}let a=await s.text(),l;try{l=a===""?{}:JSON.parse(a)}catch{throw new O("server",`the admin API at ${this.target} answered ${s.status} with something that is not JSON`,{status:s.status})}if(!s.ok)throw Jd(s.status,l);return l}},hb={bad_request:"usage",unauthorized:"not-signed-in",not_found:"not-found",conflict:"conflict",failed:"failed",timeout:"timeout"};function Jd(e,t){let n=t?.error??{},r=n.message??`the admin API answered ${e}`,o={status:e};n.code&&(o.apiCode=n.code),n.kind&&(o.kind=n.kind),n.sqlstate&&(o.sqlstate=n.sqlstate);let s=(n.code?hb[n.code]:void 0)??(e===401?"not-signed-in":e===400?"usage":kt(e));return s==="not-signed-in"?new O(s,"the router refused the admin token (LEPIS_ADMIN_TOKEN or --token)",o):new O(s,r,o)}function yb(e){let t=e.trim();if(!/^[a-z][0-9a-z]{12}$/.test(t))throw new O("usage",`--project: not a project ref: ${e} (13 characters, as projects list prints it)`);return t}var wb={"node.add":"add-node","node.attach":"attach","node.drain":"drain","node.remove":"remove","keyspace.create":"keyspace","table.distribute":"distribute","table.reference":"reference","table.global":"global","table.auto":"auto","range.split":"split","range.merge":"merge","range.move":"move","tenant.pin":"pin",rebalance:"rebalance",scale:"scale",verify:"verify",cleanup:"cleanup","keyspace.drop":"drop-keyspace",dissolve:"disable"},bb="cloud-project-shards",pt=class{target;ref;#t;constructor(t,n=T){this.ref=t,this.target=`project ${t}`,this.#t=n}async status(){let t=await this.#e({action:"status"}),{cluster:n,...r}=t;return{...n??{catalog:!1},cloud:r}}ops(){return this.#e({action:"ops"})}async plan(t){return this.#n(t),this.#e({action:"plan",request:t})}async submit(t){let n=this.#n(t),r={...t};delete r.op;let o=await this.#e({action:n,request:r});return typeof o.job=="number"?{job:o.job,plan:o.plan}:{done:Mt(o),answer:o}}async jobs(){return(await this.#e({action:"jobs"})).jobs}job(t){return this.#e({action:"jobs",id:t})}cancel(t){return this.#e({action:"cancel",id:t})}resume(t){return this.#e({action:"resume",id:t})}settings(t){return this.#e({action:"settings",settings:t})}advice(t){return this.#e({action:"advice",...t===void 0?{}:{sampleMs:Math.max(0,Math.floor(t))}})}check(){return this.#e({action:"check"})}autopilot(){return this.#e({action:"autopilot"})}setAutopilot(t){return this.#e({action:"settings",settings:t})}enable(t){return this.#e({action:"enable",...t?{plan:!0}:{}})}spread(t,n){return this.#e({action:"spread",request:t,...n?{plan:!0}:{}})}retry(t){return this.#e({action:"retry",...t})}disable(t){return this.#e({action:"disable",...t?{plan:!0}:{}})}replica(t,n,r){return this.#e({action:n?"remove-replica":"add-replica",node:t,...r?{plan:!0}:{}})}async alerts(){return(await this.status()).cloud?.alerts??[]}acknowledge(t){return this.#e({action:"acknowledge",alert:t})}#n(t){let n=wb[t.op];if(!n)throw new O("usage",`${t.op} is not an operation a SnoutData Cloud project takes`);let r=t;if(t.op==="node.add"&&(r.host!==void 0||r.name!==void 0))throw new O("usage","in SnoutData Cloud a node is a pod the project makes: nodes add takes no name or --host. It joins the cluster on its own once it is ready.");if(t.op==="scale"&&(r.add!==void 0||r.remove!==void 0))throw new O("usage","in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");return n}async#e(t){try{return await this.#t(bb,{ref:this.ref,...t})}catch(n){throw Sb(n)}}};function Mt(e){if(Array.isArray(e.created)){let t=e.created.map(String),n=typeof e.stopped=="string"?` Stopped there: ${e.stopped}`:"",r=t.length===1;return e.joining===!1?`New node${r?"":"s"} ${t.join(", ")}, starting as a copy of the home node. Attach ${r?"it":"each"} once it is ready: snoutdata cluster nodes attach <ref>.${n}`:`New node${r?"":"s"} ${t.join(", ")}, starting as a copy of the home node. ${r?"It joins":"They join"} the cluster and take${r?"s":""} ${r?"its":"their"} share of the data on ${r?"its":"their"} own; follow it with snoutdata cluster status.${n}`}return e.deleted===!0?`The pod of ${String(e.pod)} is being deleted. It owned nothing in the cluster.`:Array.isArray(e.queued)?`${String(e.next??"The table is being spread over the cluster.")} Steps: ${e.queued.map(String).join(", ")}. Follow it with snoutdata cluster status.`:typeof e.joining=="boolean"&&typeof e.node=="string"?e.joining?`${e.node} is joining the cluster again.`:`${e.node} is left as it is.`:e.queue==="retrying"?"The cluster is trying that step again.":typeof e.replica=="string"&&typeof e.node=="string"?`A replica of node ${e.node} is being made (${e.replica}). ${String(e.note??"It protects the node once it is following it.")}`:typeof e.changed=="boolean"&&typeof e.node=="string"&&e.sharded===void 0?e.changed?`The replica of node ${e.node} is being removed, and its project slot freed.`:`node ${e.node} has no replica. Nothing changed.`:e.acknowledged===!0?"Marked as seen. The alert stays open until what it is about is over.":e.unchanged===!0?`The project already has ${String(e.nodes)} nodes. Nothing changed.`:e.sharded===!0?e.changed===!1?"This project is already a cluster.":String(e.note??"This project is a cluster now."):e.sharded===!1?e.changed===!1?"This project is not a cluster.":String(e.note??"This project is not a cluster any more."):typeof e.next=="string"?e.next:"Done."}function Sb(e){if(!(e instanceof xe))return e;let t=e.body??{};if(typeof t.apiCode=="string"||typeof t.kind=="string")return Jd(e.status,{error:{code:typeof t.apiCode=="string"?t.apiCode:void 0,kind:typeof t.kind=="string"?t.kind:void 0,message:e.message,sqlstate:typeof t.sqlstate=="string"?t.sqlstate:void 0}});let n=t.code==="not-sharded"?"conflict":kt(e.status);return new O(n,e.message,{status:e.status,...typeof t.code=="string"?{kind:t.code}:{}})}function er(e){if(Array.isArray(e))return`[${e.map(er).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).filter(n=>t[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${er(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}var Ca=class{#t=new Map;#n;#e;constructor(t=15*6e4,n=Date.now){this.#n=t,this.#e=n}remember(t,n=""){this.#t.set(`${n}
|
|
814
|
+
${er(t)}`,this.#e())}shown(t,n=""){let r=this.#t.get(`${n}
|
|
815
|
+
${er(t)}`);return r!==void 0&&this.#e()-r<=this.#n}forget(t,n=""){this.#t.delete(`${n}
|
|
816
|
+
${er(t)}`)}},kb=new Ca,La=["node.add","node.drain","node.remove","keyspace.create","table.distribute","table.reference","table.global","table.auto","range.split","range.merge","range.move","tenant.pin","rebalance","scale","verify","cleanup","node.attach","keyspace.drop","dissolve"],_b="2024-11-05";function oe(e,t=[]){return{type:"object",properties:e,additionalProperties:!1,...t.length?{required:t}:{}}}var Z={type:"string"},Vd={type:"object",description:'The operation as the router takes it, e.g. {"op": "range.split", "keyspace": "k", "range": "-3074457345618258603", "at": "18454348402311335", "to": 3}. Range bounds and seeds are 64-bit, so pass them as strings. cluster_advice returns these ready-made, as `operation`. For a SnoutData Cloud project a node is a pod the project makes: {"op": "node.add"} makes one (no host), {"op": "node.attach", "name": "<its ref>"} hands a ready one to the cluster, and {"op": "scale", "nodes": N} is a node count.',properties:{op:{type:"string",enum:[...La]}},required:["op"],additionalProperties:!0},ho={type:"integer",description:"The job id cluster_run returned, or one from cluster_jobs."},xt={type:"string",description:"A SnoutData Cloud project's ref (from list_projects): its cluster, as the signed-in user. Omit for the standalone router this server was started with (LEPIS_ADMIN_URL)."},nr=[{name:"whoami",description:"Who this CLI is signed in as, and how (a session or a long-lived access token). Use it to check a credential before doing anything else.",inputSchema:oe({})},{name:"list_projects",description:"Every hosted Postgres database on this account, with its ref, name, region, state (ready, paused, error), size, and whether it is read-only because it is over its plan's storage limit. Under `local`, the self-hosted projects on this machine (SnoutData Studio's, or linked with `snoutdata link --local`), whose refs work with get_connection_url, push_migrations, get_project and the function tools.",inputSchema:oe({})},{name:"create_project",description:"Make a new hosted Postgres database and wait for it to be ready. Costs a project against the plan allowance; a free plan includes two. Returns its ref, which every other tool takes.",inputSchema:oe({name:Z,region:Z,teamId:Z},["name"])},{name:"get_connection_url",description:"The postgres:// URL for a project, ready to put in DATABASE_URL. IT CONTAINS A LIVE PASSWORD, so treat it as a credential and do not print it into a log or a file that is committed. Connecting to a paused project wakes it, which takes a few seconds.",inputSchema:oe({ref:Z},["ref"])},{name:"pause_project",description:"Stop a project, and wait until it is paused. Its data is kept and the next connection wakes it. A production project refuses this.",inputSchema:oe({ref:Z},["ref"])},{name:"scale_project",description:"More capacity for a project's app API (auth, the data API and the router): 1 to 3 instances of it take its calls. The database is not copied by this, and it is not failover: keeping a project running is the cloud's job on every plan. Without instances, says how many it runs now and how many the plan allows. Without confirm: true it only returns the plan for that number and changes nothing: show it to the user, and when they agree call again with confirm: true. A refusal (the plan, not open yet, a sharded project, no room) comes back in a sentence to show as it is.",inputSchema:oe({ref:Z,instances:{type:"integer",enum:[1,2,3]},confirm:{type:"boolean"}},["ref"])},{name:"resume_project",description:"Start a paused project without waiting for a connection to wake it, and wait until it is ready.",inputSchema:oe({ref:Z},["ref"])},{name:"push_migrations",description:"Run the .sql files in a folder against a project, in name order, once each, recording what ran in a _snoutdata_migrations table. Refuses a file that changed after it ran, a file that has gone, and a new file that sorts before one already applied. Use dryRun first to see what would happen. Needs nothing installed: the CLI connects to the database itself. A file holding a psql command (\\i, \\set), or a COMMIT, END or ROLLBACK that would end the transaction the file runs in, is refused before anything runs; a file starting with -- snoutdata:no-transaction runs as written, outside a transaction.",inputSchema:oe({ref:Z,dir:Z,dryRun:{type:"boolean"}},["ref"])},{name:"usage",description:"How much storage and compute a project has used against the limit on this plan, and whether it is near it. READ THIS BEFORE a migration or a bulk insert: a project over its storage limit is made read-only, and `list_projects` will say readOnly afterwards without ever saying how much headroom was left. Takes an optional number of days of history (default 30, maximum 365).",inputSchema:oe({ref:Z,days:{type:"number"}},["ref"])},{name:"export_status",description:"Whether a copy of this database is being taken, when the last one finished, and a download link if there is a live one. Costs nothing and starts nothing.",inputSchema:oe({ref:Z},["ref"])},{name:"start_export",description:"Take a copy of the whole database. Runs a pg_dump on the server and can take minutes, so this STARTS it and returns; poll export_status for the link. Worth doing before a migration you are unsure of. It does not block the database.",inputSchema:oe({ref:Z},["ref"])},{name:"reset_password",description:"Rotate the project's database password. The new password belongs to the other of the project's two owner logins, so the USER NAME in the URL changes too. The old password keeps working for graceMinutes (default 60, 0 to 1440), then new connections with it are refused; connections already open keep working. graceMinutes 0 stops the old password as soon as the change applies and ends its connections: use 0 when a credential has leaked. Returns the new connection URL, which works once the change applies (wait about fifteen seconds before connecting, and retry a refusal for up to two minutes). Not for routine use.",inputSchema:oe({ref:Z,graceMinutes:{type:"number"}},["ref"])},{name:"list_teams",description:"Teams this account belongs to, with the id create_project takes as teamId. Without this there is no way to discover that id.",inputSchema:oe({})},{name:"list_tokens",description:"The long-lived sdt_ access tokens on this account: id, name, prefix, when each was made and last used. Never the token itself, which is shown once when it is made.",inputSchema:oe({})},{name:"create_token",description:"Mint a long-lived sdt_ access token, for a CI job or another machine. RETURNS THE TOKEN ONCE AND NEVER AGAIN. Without `project` it is as capable as this account, so hand it over deliberately; with a project ref it reaches that one project and nothing else, which is what a CI job for one project should get. Optionally expires, as an ISO date.",inputSchema:oe({name:Z,expires:Z,project:Z},["name"])},{name:"revoke_token",description:"Revoke an access token by its id. Anything using it stops working at once. Safe to do to a token you think has leaked.",inputSchema:oe({id:Z},["id"])},{name:"deploy_function",description:"Put a folder of TypeScript on the edge as an HTTP endpoint at https://<ref>.api.snoutdata.com/v1/fn/<name>. Reads functions/<name> unless dir says otherwise. Deno, so no build step and no node_modules. Set openToAnyone ONLY for a webhook receiver whose sender cannot send an API key: it makes the URL callable by anybody who knows it, and the function must then check the sender's signature itself.",inputSchema:oe({ref:Z,name:Z,dir:Z,entrypoint:Z,openToAnyone:{type:"boolean"}},["ref","name"])},{name:"list_functions",description:"The functions deployed to a project, their URLs, bundle sizes, whether each one needs an API key, and each one's memory and concurrency with the plan's limits for both. Costs nothing.",inputSchema:oe({ref:Z},["ref"])},{name:"size_function",description:"Set one function's memory (MB one worker may use) and concurrency (how many workers it may run at once), within the project's plan. memoryMb x concurrency may not exceed the project's memory; list_functions shows each function's size and the plan's limits (limit.functionMemoryMb, limit.concurrencyMax, limit.podMemoryMb). A size that does not fit is refused with a sentence saying why. Omit one to keep it as it runs now; reset: true goes back to the plan's default. A second worker only helps CPU-bound work: requests that wait on the network share one.",inputSchema:oe({ref:Z,name:Z,memoryMb:{type:"integer"},concurrency:{type:"integer"},reset:{type:"boolean"}},["ref","name"])},{name:"delete_function",description:"Remove one function from a project. It stops answering within a few seconds. It does not touch the database.",inputSchema:oe({ref:Z,name:Z},["ref","name"])},{name:"list_containers",description:"The project's Snout Containers: each one's status (pending, pulling, starting, running, restarting, failed, stopped), why when it is not running, its image and pinned digest, restarts, and its public URL. allowed=false means the plan no longer covers it and it is stopped. Also the plan's allowance. Costs nothing.",inputSchema:oe({ref:Z},["ref"])},{name:"deploy_container",description:"Run a Docker image all the time beside the project, at https://<ref>.api.snoutdata.com/containers/v1/<name>/ (no API key needed there: the container authenticates its own callers). The image tag is pinned to the digest it points at now and must include linux/arm64. It listens on PORT (port, default 8080) and gets DATABASE_URL and the project's secrets in its environment. STATELESS: anything written inside it is lost on every restart or redeploy, so state belongs in the database. Paid plans only (Plus, Pro and Business). A private image needs a person's first deploy with the CLI (no tool takes a registry token); a redeploy reuses the stored login. Returns at once: poll list_containers until the status is running or failed.",inputSchema:oe({ref:Z,name:Z,image:Z,port:{type:"integer"}},["ref","name","image"])},{name:"restart_container",description:"Start one container again from its image. Everything written inside it is lost, which is also how to clear a container stuck in a bad state. Poll list_containers to see it come back.",inputSchema:oe({ref:Z,name:Z},["ref","name"])},{name:"delete_container",description:"Stop one container and remove it from the project. It does not touch the database.",inputSchema:oe({ref:Z,name:Z},["ref","name"])},{name:"container_logs",description:"What a project's containers printed to stdout and stderr in the last seven days, newest first: each line's time, container, stream and text. Lines arrive about a minute after they are printed. Use it when list_containers says failed or restarting. name narrows to one container, errorsOnly to stderr, limit is at most 500 (default 100). Costs nothing.",inputSchema:oe({ref:Z,name:Z,errorsOnly:{type:"boolean"},limit:{type:"integer"}},["ref"])},{name:"container_egress",description:"Where a project's containers may send. allowlist null means the public internet (within the limits on how much and how fast); otherwise allowlist.allow is the only destinations they reach, and alwaysAllowed what they reach whatever the list says (the project's own database and API). The same as `snoutdata containers egress`. Costs nothing.",inputSchema:oe({ref:Z},["ref"])},{name:"set_container_egress",description:'Hold a project\'s containers to an allowlist, or let them reach the public internet again. Give EITHER allow, a list of destinations ("api.example.com:443", "api.example.com" for any port, "140.82.112.0/20:443,8443"; an empty list means nothing outside the project), OR clear: true. The list replaces the one there. Running containers follow it within a minute and nothing restarts, so a container that needs a destination left off stops reaching it. The same as `snoutdata containers egress set|clear`.',inputSchema:oe({ref:Z,allow:{type:"array",items:Z},clear:{type:"boolean"}},["ref"])},{name:"list_function_secrets",description:"The NAMES of the environment variables a project's functions run with, their sizes and when each was last set. Never the values, which are not readable by anything but the runtime. THERE IS NO TOOL THAT SETS ONE: a secret in a tool call is a secret in an audit log, so a person sets it with `snoutdata secrets set`. Use this to check whether one a function needs is there.",inputSchema:oe({ref:Z},["ref"])},{name:"function_logs",description:"What a project's functions printed with console.log and console.error in the last seven days, newest first: each line's time, function, level ('error' for console.error and console.warn) and text. Lines arrive about a minute after they are printed. Use it after deploying or calling a function to see why it failed. name narrows to one function, errorsOnly to errors, limit is at most 500 (default 100). Costs nothing.",inputSchema:oe({ref:Z,name:Z,errorsOnly:{type:"boolean"},limit:{type:"integer"}},["ref"])},{name:"get_project",description:"Everything about one project in one call: its state, region and size, which products are on (auth, storage, data-api), the names of its deployed functions and function secrets, and its custom domains. Never a password, a key or a download link (export_status has the link to the last export).",inputSchema:oe({ref:Z},["ref"])},{name:"list_products",description:"Whether a project's auth (user sign-up and sign-in), storage (files) and data API (REST and GraphQL over its tables) are on, and whether the plan allows the data API.",inputSchema:oe({ref:Z},["ref"])},{name:"set_product",description:"Turn auth, storage or data-api on or off for a project. It starts within about a minute. All three are on every plan, including free.",inputSchema:oe({ref:Z,product:{type:"string",enum:["auth","storage","data-api"]},enabled:{type:"boolean"}},["ref","product","enabled"])},{name:"list_domains",description:"The custom domains in front of a project's API, whether each is verified, and the DNS records each needs.",inputSchema:oe({ref:Z},["ref"])},{name:"add_domain",description:"Serve a project's API at the user's own hostname (paid plans). Returns the DNS records the user must publish before verify_domain can succeed.",inputSchema:oe({ref:Z,hostname:Z},["ref","hostname"])},{name:"verify_domain",description:"Check a custom domain's DNS records and verify it once they are published.",inputSchema:oe({ref:Z,hostname:Z},["ref","hostname"])},{name:"remove_domain",description:"Stop serving a project at a custom domain.",inputSchema:oe({ref:Z,hostname:Z},["ref","hostname"])},{name:"restore_window",description:"How far back a point-in-time restore of a project can go, or why it cannot (the plan, or no backup yet). Starts nothing.",inputSchema:oe({ref:Z},["ref"])},{name:"restore_to_point",description:"Rewind a project to a moment (ISO 8601, inside restore_window) into a NEW project beside it, never over it. Costs a project slot on the plan. The original is untouched.",inputSchema:oe({ref:Z,at:Z,name:Z},["ref","at"])},{name:"cluster_status",description:"A Lepis cluster (one Postgres database spread over several nodes): a Cloud project's with project, else the router this server was started against with LEPIS_ADMIN_URL. Its nodes, keyspaces and their ranges (a range is keyspace:lo; bounds are strings), tables, routers, unfinished jobs and settings; for a Cloud project also whether it is a cluster, its plan's node limit, and each node pod with the step that follows (attach, delete-pod, wait). Costs nothing.",inputSchema:oe({project:xt})},{name:"cluster_advice",description:"Ask the cluster's advisor what to split, move or add, from each node's size, connections and write rate and each range's measured share. Each recommendation has a reason, its plan, and an `operation` that cluster_run takes as it is. RUNS NOTHING. sampleMs: how long to measure write rates over (the cluster's setting by default; 0 skips them; at most 30000).",inputSchema:oe({project:xt,sampleMs:{type:"integer"}})},{name:"cluster_check",description:"The cluster's design check: reads every table's distribution key, foreign keys, unique keys and indexes, and says what keeps related rows off one node or makes a query scan (a table under a distributed one with no distribution key column, a foreign key without the key, a lookup that should be a reference table, a foreign key with no index). Each finding has a fix, SQL to run, or an `operation` cluster_run takes as it is. RUNS NOTHING.",inputSchema:oe({project:xt})},{name:"cluster_plan",description:"The dry run of one cluster operation: its steps, what moves where, rows, bytes, the estimated copy time and the expected write pause. Changes nothing. Planning an operation is what lets cluster_run run it.",inputSchema:oe({project:xt,operation:Vd},["operation"])},{name:"cluster_run",description:"Run one cluster operation as a durable job. IT MOVES DATA, and each cutover pauses writes to what moves for up to the cluster's max_write_pause_ms. Without confirm: true it only returns the plan and runs nothing: show that plan to the user, and when they agree call again with the same operation and confirm: true. confirm runs only an operation planned here (cluster_plan, cluster_advice, or cluster_run without confirm) in the last 15 minutes. Returns the job id; follow it with cluster_watch_job.",inputSchema:oe({project:xt,operation:Vd,confirm:{type:"boolean"}},["operation"])},{name:"cluster_jobs",description:"The cluster's latest jobs, or with id one job with each step's state and phase. Costs nothing.",inputSchema:oe({project:xt,id:ho})},{name:"cluster_watch_job",description:"Wait for a job to finish, up to timeoutSeconds (default 30, at most 120), and return its state and steps: done, failed (with the error; cluster_resume_job runs it again from the failed step) or cancelled. Running out of time stops the waiting, never the job; call again to keep waiting.",inputSchema:oe({project:xt,id:ho,timeoutSeconds:{type:"integer"}},["id"])},{name:"cluster_cancel_job",description:"Stop a running job. A move cancelled before its cutover rolls back; one cancelled after it finishes its cleanup.",inputSchema:oe({project:xt,id:ho},["id"])},{name:"cluster_resume_job",description:"Run a failed job again from the step that failed. It carries on the operation that was already approved and planned; follow it with cluster_watch_job.",inputSchema:oe({project:xt,id:ho},["id"])},{name:"delete_project",description:"Delete a project. THIS DESTROYS A DATABASE. Off unless the person who started this server passed --allow-delete, in which case it still only marks the project deleted and its data is erasable for a grace period.",inputSchema:oe({ref:Z},["ref"])}],$b=new Set(["whoami","list_projects","get_connection_url","usage","export_status","list_teams","list_tokens","list_functions","list_function_secrets","function_logs","container_egress","get_project","list_products","list_domains","restore_window","cluster_status","cluster_advice","cluster_check","cluster_plan","cluster_jobs","cluster_watch_job"]),vb=new Set(["delete_project","delete_function","reset_password","revoke_token","remove_domain","cluster_run"]),Yd=["get_connection_url","push_migrations","get_project","list_functions","deploy_function","delete_function","list_function_secrets"];function Ma(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.projects))return{...t,projects:t.projects.map(Ma)};let n=t.export;if(n&&typeof n=="object"){let{url:r,rolesSql:o,...s}=n;return{...t,export:{...s,hasLink:typeof r=="string"&&r.length>0}}}return e}function Da(e,t){return t.available?null:t.pitrEnabled?`${e} has no backup to restore from yet.`:`Point-in-time restore is part of the Pro and Business plans, and this project is on ${t.tier??"another plan"}.`}function Pb(e){return{...e,annotations:$b.has(e.name)?{readOnlyHint:!0}:{readOnlyHint:!1,destructiveHint:vb.has(e.name)}}}function xb(e){let t=new Set;return e.filter(n=>!t.has(n.name)&&t.add(n.name))}function tr(e,t){return{jsonrpc:"2.0",id:e,result:t}}function yo(e,t,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:n}}}function I(e,t,n=!1){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return tr(e,{content:[{type:"text",text:r}],...n?{isError:!0}:{}})}function Eb(e,t=new Date){let n=Date.parse(e);return!Number.isFinite(n)||n<=t.getTime()?null:Math.ceil((n-t.getTime())/864e5)}function Qn(e){return{op:e.op,cutovers:e.cutovers,moves:(e.moves??[]).map(t=>({from:t.source,to:t.targets,tables:t.tables,estimated_rows:t.estimated_rows,estimated_bytes:t.estimated_bytes,estimated_copy_seconds:t.estimated_copy_seconds,expected_pause_ms:t.expected_pause_ms})),steps:(e.steps??[]).map(t=>t.kind),estimated_rows:e.estimated_rows,estimated_bytes:e.estimated_bytes,estimated_copy_seconds:e.estimated_copy_seconds,expected_pause_ms:e.expected_pause_ms,max_write_pause_ms:e.max_write_pause_ms,warnings:e.warnings??[],...e.assumptions?{assumptions:e.assumptions}:{}}}function Na(e){return{id:e.id,op:e.op,state:e.state,finished:Xn(e.state),error:e.error,steps:e.steps.map(t=>({n:t.n+1,kind:t.kind,state:t.state,...typeof t.detail?.phase=="string"?{phase:t.detail.phase}:{}})),...e.state==="failed"?{next:`cluster_resume_job {"id": ${e.id}} runs it again from the failed step.`}:{}}}function Xd(e,t){let n=e.operation;if(!n||typeof n!="object"||Array.isArray(n))return`${t} needs operation: an object like {"op": "range.split", "keyspace": "k", "range": "<lo>"}. cluster_advice returns them ready-made.`;let r=n;if(typeof r.op!="string"||!La.includes(r.op))return`${t}: operation.op must be one of ${La.join(", ")}.`;for(let o of["range","at","a","b","seed"]){let s=r[o];if(typeof s=="number"&&!Number.isSafeInteger(s))return`${t}: operation.${o} is a 64-bit number and lost its last digits as a JSON number. Pass it as a string, exactly as cluster_status or cluster_advice wrote it.`}return r}function Ia(e){let t=typeof e.id=="string"&&/^\d+$/.test(e.id)?Number(e.id):e.id;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:null}function Ab(e){let t=e instanceof Error?e.message:String(e),n=e?.details?.kind;return typeof n=="string"?{error:t,kind:n}:t}var Rb="The cluster tools need a cluster: pass project (a SnoutData Cloud project's ref), or start this server with LEPIS_ADMIN_URL (a standalone router's admin API, e.g. http://127.0.0.1:7432) and LEPIS_ADMIN_TOKEN set. Tell the user that is what is missing.";async function Tb(e,t,n,r,o){let s,a=typeof n.project=="string"&&n.project.trim()!==""?n.project.trim():void 0;try{if(!r.shards)return I(e,Rb,!0);s=r.shards(a)}catch(c){return I(e,c instanceof Error?c.message:String(c),!0)}let l=o.shardsPlans??kb,d=a??"";try{switch(t){case"cluster_status":return I(e,await s.status());case"cluster_advice":{let c=typeof n.sampleMs=="number"&&n.sampleMs>=0?Math.min(Math.floor(n.sampleMs),3e4):void 0,i=await s.advice(c);for(let p of i.advice)p.plan&&l.remember(p.request,d);return I(e,{summary:i.summary,advice:i.advice.map(p=>({op:p.op,reason:p.reason,metric:p.metric,operation:p.request,...p.plan?{plan:Qn(p.plan)}:{},...p.needs.length>0?{needs:p.needs,note:`Ask the user for ${p.needs.join(", ")}, then plan it with cluster_plan.`}:{},...p.plan_error?{plan_error:p.plan_error}:{}})),facts:i.facts,assumptions:i.assumptions,...i.advice.length>0?{next:"Nothing has run. Show the user a recommendation and its plan; if they agree, call cluster_run with its operation and confirm: true. Ask for advice again after each one runs."}:{}})}case"cluster_check":{let c=await s.check();return I(e,{...c,...c.findings.length>0?{next:"Nothing has run. Show the user the findings, errors first. SQL is theirs to run; an operation is planned with cluster_plan and run with cluster_run."}:{}})}case"cluster_plan":{let c=Xd(n,t);if(typeof c=="string")return I(e,c,!0);let i=await s.plan(c);return l.remember(c,d),I(e,{plan:Qn(i),next:"Nothing has run. To run it, show the user this plan, then call cluster_run with the same operation and confirm: true."})}case"cluster_run":{let c=Xd(n,t);if(typeof c=="string")return I(e,c,!0);if(n.confirm!==!0||!l.shown(c,d)){let p=await s.plan(c);l.remember(c,d);let g=n.confirm===!0;return I(e,{ran:!1,plan:Qn(p),next:g?"NOT RUN: confirm applies to an operation planned here in the last 15 minutes, and this one was not, so it has been planned now instead. Show the user this plan; if they agree, call cluster_run again with the same operation and confirm: true.":"Nothing has run. Show the user this plan; if they agree, call cluster_run again with the same operation and confirm: true."},g)}let i=await s.submit(c);return l.forget(c,d),i.job===void 0?I(e,{ran:!0,done:i.done,answer:i.answer}):I(e,{ran:!0,job:i.job,plan:Qn(i.plan),next:`Follow it with cluster_watch_job {"id": ${i.job}}.`})}case"cluster_jobs":{if(n.id===void 0)return I(e,{jobs:await s.jobs()});let c=Ia(n);if(c===null)return I(e,"cluster_jobs: id is a job number. Call it without id to list them.",!0);let i=await s.job(c);return I(e,{...Na(i),plan:i.plan&&Array.isArray(i.plan.steps)?Qn(i.plan):null})}case"cluster_watch_job":{let c=Ia(n);if(c===null)return I(e,"cluster_watch_job needs id, the job number cluster_run returned.",!0);let i=typeof n.timeoutSeconds=="number"&&n.timeoutSeconds>0?Math.min(n.timeoutSeconds,120):30,p=Date.now()+i*1e3;for(;;){let g=await s.job(c);if(Xn(g.state))return I(e,Na(g),g.state!=="done");if(Date.now()>=p)return I(e,{...Na(g),note:`Still ${g.state} after ${i}s. It carries on; call cluster_watch_job again to keep waiting.`});await new Promise(E=>setTimeout(E,o.shardsPollMs??1e3))}}case"cluster_cancel_job":case"cluster_resume_job":{let c=Ia(n);if(c===null)return I(e,`${t} needs id, a job number.`,!0);let i=t==="cluster_cancel_job"?await s.cancel(c):await s.resume(c);return I(e,{...i,next:`Follow it with cluster_watch_job {"id": ${c}}.`})}default:return yo(e,-32602,`unknown tool: ${t}`)}}catch(c){return I(e,Ab(c),!0)}}function ie(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}async function Zd(e,t,n){let r=e.id??null,o=e.method??"",s=e.params??{};if(e.id===void 0||e.id===null)return null;switch(o){case"initialize":return tr(r,{protocolVersion:_b,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"snoutdata",version:n.version}});case"ping":return tr(r,{});case"tools/list":return tr(r,{tools:xb([...nr.map(Pb),...n.borrowed??[]])});case"tools/call":return Ob(r,s,t,n);default:return yo(r,-32601,`unknown method: ${o}`)}}async function Ob(e,t,n,r){let o=typeof t.name=="string"?t.name:"",s=t.arguments??{};if(!(nr.some(i=>i.name===o)||(r.borrowed?.some(i=>i.name===o)??!1)))return yo(e,-32602,`unknown tool: ${o}`);let l=["get_connection_url","pause_project","resume_project","scale_project","delete_project","push_migrations","usage","export_status","start_export","reset_password","get_project","list_products","set_product","list_domains","add_domain","verify_domain","remove_domain","restore_window","restore_to_point"];if(o.startsWith("cluster_")&&nr.some(i=>i.name===o))return Tb(e,o,s,n,r);let d=ie(s,"ref");if(l.includes(o)&&!d)return I(e,`${o} needs a project ref. Call list_projects to see them.`,!0);let c=d&&n.localProject?n.localProject(d):null;if(c&&!Yd.includes(o))return I(e,`${d} is the self-hosted project in ${c.folder}, and ${o} is about SnoutData Cloud. On a local project these tools work: ${Yd.join(", ")}.`,!0);try{switch(o){case"whoami":return I(e,await n.whoami());case"list_projects":return I(e,Ma(await n.listProjects()));case"create_project":{let i=ie(s,"name");return i?I(e,await n.createProject({name:i,region:ie(s,"region")??void 0,teamId:ie(s,"teamId")??void 0})):I(e,"create_project needs a name.",!0)}case"get_connection_url":{let i=await n.connection(d);return I(e,{url:i.uri,state:i.state,wakesInstantly:i.wakesInstantly,warning:"This URL contains a live database password. Put it in an environment variable, not in a file that is committed."})}case"pause_project":return I(e,await n.setProjectState("pause",d));case"resume_project":return I(e,await n.setProjectState("resume",d));case"scale_project":{let i=s.instances;if(i!==void 0&&i!==1&&i!==2&&i!==3)return I(e,"instances is 1, 2 or 3.",!0);let p=s.confirm===!0&&i!==void 0;return I(e,await n.scaleProject(d,i,p))}case"usage":{let i=typeof s.days=="number"?s.days:void 0;return I(e,await n.usage(d,i))}case"export_status":return I(e,await n.exportStatus(d));case"start_export":return I(e,await n.requestExport(d));case"reset_password":{let i=typeof s.graceMinutes=="number"?s.graceMinutes:void 0,p=await n.resetPassword(d,i),g=p.uri?null:await n.connection(d);return I(e,{url:p.uri??g?.uri,appliesIn:p.appliesIn??"within about fifteen seconds",...p.oldPassword?{oldPassword:p.oldPassword}:{},next:"Wait about fifteen seconds before connecting with this URL, and retry a refusal for up to two minutes: until the change applies (usually 5 to 15 seconds, longer while the host is busy) the new password is refused and the old one still works, which does not mean the new one is wrong. Then update DATABASE_URL wherever it is set, user name included: it changes with the password.",warning:"This URL contains a live database password. Put it in an environment variable, not in a file that is committed."})}case"list_teams":return I(e,await n.listTeams());case"get_project":return I(e,Ma(await n.getProject(d)));case"list_products":return I(e,await n.getProducts(d));case"set_product":{let i=ie(s,"product");return i!=="auth"&&i!=="storage"&&i!=="data-api"?I(e,"set_product needs product: auth, storage or data-api.",!0):typeof s.enabled!="boolean"?I(e,"set_product needs enabled: true or false.",!0):I(e,await n.setProduct(d,i,s.enabled))}case"list_domains":return I(e,await n.listDomains(d));case"add_domain":case"verify_domain":case"remove_domain":{let i=ie(s,"hostname");return i?I(e,await n.domainAction(d,o.split("_")[0],i)):I(e,`${o} needs a hostname, e.g. api.example.com.`,!0)}case"restore_window":{let i=await n.restoreWindow(d),p=i&&i.restore?Da(d,i.restore):null;return I(e,p?{...i,reason:p}:i)}case"restore_to_point":{let i=ie(s,"at");return i?I(e,await n.restoreTo(d,i,ie(s,"name")??void 0)):I(e,"restore_to_point needs at: an ISO 8601 moment inside restore_window.",!0)}case"deploy_function":{let i=ie(s,"ref"),p=ie(s,"name");return!i||!p?I(e,"deploy_function needs a project ref and a function name.",!0):I(e,await n.deployFunction(i,p,{dir:ie(s,"dir")??void 0,entrypoint:ie(s,"entrypoint")??void 0,verifyJwt:s&&typeof s=="object"&&"openToAnyone"in s?s.openToAnyone!==!0:!0}))}case"list_functions":{let i=ie(s,"ref");return i?I(e,await n.listFunctions(i)):I(e,"list_functions needs a project ref.",!0)}case"size_function":{let i=ie(s,"ref"),p=ie(s,"name");if(!i||!p)return I(e,"size_function needs a project ref and a function name.",!0);let g=typeof s.memoryMb=="number"?s.memoryMb:void 0,E=typeof s.concurrency=="number"?s.concurrency:void 0,A=s.reset===!0;return!A&&g===void 0&&E===void 0?I(e,"size_function needs memoryMb, concurrency, or reset: true.",!0):I(e,await n.sizeFunction(i,p,{memoryMb:g,concurrency:E,reset:A}))}case"delete_function":{let i=ie(s,"ref"),p=ie(s,"name");return!i||!p?I(e,"delete_function needs a project ref and a function name.",!0):I(e,await n.deleteFunction(i,p))}case"list_containers":{let i=ie(s,"ref");return i?I(e,await n.listContainers(i)):I(e,"list_containers needs a project ref.",!0)}case"deploy_container":{let i=ie(s,"ref"),p=ie(s,"name"),g=ie(s,"image");if(!i||!p||!g)return I(e,"deploy_container needs a project ref, a container name and an image.",!0);let E=typeof s.port=="number"?s.port:void 0;return I(e,await n.deployContainer(i,p,{image:g,...E===void 0?{}:{port:E}}))}case"restart_container":case"delete_container":{let i=ie(s,"ref"),p=ie(s,"name");return!i||!p?I(e,`${o} needs a project ref and a container name.`,!0):I(e,o==="restart_container"?await n.restartContainer(i,p):await n.deleteContainer(i,p))}case"container_logs":{let i=ie(s,"ref");if(!i)return I(e,"container_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return I(e,await n.containerLogs(i,{name:ie(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"container_egress":{let i=ie(s,"ref");return i?I(e,await n.containerEgress(i)):I(e,"container_egress needs a project ref.",!0)}case"set_container_egress":{let i=ie(s,"ref");if(!i)return I(e,"set_container_egress needs a project ref.",!0);let p=s.clear===!0,g=s.allow;return g!==void 0&&(!Array.isArray(g)||!g.every(E=>typeof E=="string"))?I(e,'set_container_egress takes allow as a list of destinations, such as ["api.example.com:443"].',!0):p===(g!==void 0)?I(e,"set_container_egress takes either allow (a list of destinations; [] for nothing outside the project) or clear: true (the public internet again), and exactly one of them.",!0):I(e,await n.setContainerEgress(i,p?null:g))}case"list_function_secrets":{let i=ie(s,"ref");return i?I(e,await n.listFunctionSecrets(i)):I(e,"list_function_secrets needs a project ref.",!0)}case"function_logs":{let i=ie(s,"ref");if(!i)return I(e,"function_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return I(e,await n.functionLogs(i,{name:ie(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"list_tokens":return I(e,await n.listTokens());case"create_token":{let i=ie(s,"name");if(!i)return I(e,"create_token needs a name, so somebody can tell later what it was for.",!0);let p=ie(s,"expires"),g=p?Eb(p):void 0;return g===null?I(e,`create_token: \`expires\` must be a date in the future, like 2026-12-31. Got "${p}".`,!0):I(e,await n.createToken(i,g,ie(s,"project")??void 0))}case"revoke_token":{let i=ie(s,"id");return i?I(e,await n.revokeToken(i)):I(e,"revoke_token needs the id of a token. list_tokens has them.",!0)}case"push_migrations":return I(e,await n.pushMigrations(d,{dir:ie(s,"dir")??void 0,dryRun:s.dryRun===!0}));case"delete_project":return r.allowDelete?I(e,await n.setProjectState("delete",d)):I(e,"delete_project is off. The person running this server started it without --allow-delete, so deleting a database is theirs to do. Tell them that is what you wanted.",!0);default:return r.borrowed?.some(i=>i.name===o)?n.callBorrowed?tr(e,await n.callBorrowed(o,s)):I(e,`${o} needs SnoutData Studio, which is no longer answering.`,!0):yo(e,-32602,`unknown tool: ${o}`)}}catch(i){return I(e,i instanceof Error?i.message:String(i),!0)}}function Qd(e){let t=e.split(`
|
|
817
|
+
`),n=t.pop()??"";return{messages:t.map(r=>r.trim()).filter(r=>r.length>0),rest:n}}var wo=["auth","storage","data-api","push"];function Wt(e){return{error:e instanceof Error?e.message:String(e)}}async function yn(e){let[t,n,r,o]=await Promise.all([T("cloud-project-auth",{ref:e,action:"status"}).then(s=>({enabled:s.enabled===!0,google:s.google?.enabled===!0,saml:s.saml?.enabled===!0}),Wt),T("cloud-project-storage",{ref:e}).then(s=>({enabled:s.storage?.enabled===!0,pending:s.storage?.pending===!0,bytes:s.storage?.bytes??null,files:s.storage?.files??null}),Wt),T("cloud-project-data-api",{ref:e}).then(s=>({enabled:s.dataApi?.enabled===!0,allowedOnPlan:s.dataApi?.allowed===!0}),Wt),T("cloud-project-push",{ref:e}).then(s=>({enabled:s.push?.enabled===!0,scheduling:s.push?.scheduling===!0}),Wt)]);return{ref:e,auth:t,storage:n,dataApi:r,push:o,realtime:Nb}}var Nb={enabled:!0,broadcast:!0,presence:!0,tableChanges:"every paid plan (Plus, Pro and Business)"};function tu(e){let t=(e??"").toLowerCase().replace("_","-").replace(/^dataapi$/,"data-api");if(!wo.includes(t))throw new y(`say which product: ${wo.join(", ")}`);return t}async function ja(e,t,n){if(t==="auth"){let r=await T("cloud-project-auth",{ref:e,action:n?"enable":"disable"});return{ref:e,product:t,enabled:n,note:r.note??(n?"Auth starts within a minute.":"Auth stops. Your users stay in the auth schema.")}}return t==="push"?(await T("cloud-project-push",{ref:e,enable:n}),{ref:e,product:t,enabled:n,note:n?"Push starts within a minute. It runs beside the database, so the database restarts once. Set keys with: snoutdata push credentials":"Push is off. Devices, the log and the keys stay in the push schema."}):(await T(t==="storage"?"cloud-project-storage":"cloud-project-data-api",{ref:e,enable:n}),{ref:e,product:t,enabled:n,note:n?`${t} starts within a minute, when the host picks up the change.`:`${t} is off.`})}async function nu(e){let t=await yn(e);w(t,()=>{let n=(l,d,c="")=>[l,d&&typeof d=="object"&&"error"in d?`could not read: ${d.error}`:d.enabled?N("on"):"off",c],r=t.storage,o=t.dataApi;process.stdout.write(`${V([["PRODUCT","STATE",""],n("auth",t.auth),n("storage",r,"pending"in r&&r.pending?"waiting for the host":""),n("data-api",o,"allowedOnPlan"in o&&!o.allowedOnPlan?"not on this plan":""),n("push",t.push,"scheduling"in t.push&&t.push.enabled&&!t.push.scheduling?"scheduled sends on paid plans":""),n("realtime",t.realtime,"always on: signals, roster; table changes on Plus, Pro and Business")])}
|
|
818
|
+
`);let s=l=>!!(l&&typeof l=="object"&&"enabled"in l&&!l.enabled),a=["auth","storage","data-api","push"].find(l=>s(l==="data-api"?o:t[l]));a&&u($(` snoutdata products enable ${a} --ref ${e}`))})}async function ru(e,t,n){let r=await ja(e,t,n);w(r,()=>u(r.note))}async function bo(e){let t=await T("cloud-project-domain",{ref:e,action:"list"});return{ref:e,domains:t.domains??[]}}async function Ua(e,t,n){if(!n)throw new y(`domains ${t} needs a hostname, e.g. api.example.com`);let r=await T("cloud-project-domain",{ref:e,action:t,hostname:n});return{ref:e,domain:r.domain??null,next:r.next??null}}function eu(e,t){let n=[["TYPE","NAME","VALUE"]];e.record&&n.push([e.record.type,e.record.name,e.record.value]),e.certificateRecord&&n.push([e.certificateRecord.type,e.certificateRecord.name,e.certificateRecord.value]),n.push(["CNAME",e.hostname,`${t}.api.snoutdata.com`]),process.stdout.write(`${V(n)}
|
|
819
|
+
`)}async function ou(e,t,n){if(t===void 0||t==="list"){let o=await bo(e);w(o,()=>{if(o.domains.length===0){u(`No domains on ${e}. \`snoutdata domains add api.example.com\`.`);return}process.stdout.write(`${V([["HOSTNAME","VERIFIED","CERTIFICATE"],...o.domains.map(s=>[s.hostname,s.verified?"yes":N("no"),s.certificate?.state??""])])}
|
|
820
|
+
`)});return}if(t!=="add"&&t!=="verify"&&t!=="remove")throw new y(`unknown command: domains ${t}`);let r=await Ua(e,t,n??"");t==="verify"&&r.domain&&!r.domain.verified&&(Lt()||eu(r.domain,e),Q("not-ready",r.domain.verificationError??`${n} is not verified yet. Publish the records above, then run this again.`,{ref:e,domain:r.domain})),w(r,()=>{if(t==="remove"){u(`${n} removed.`);return}r.domain&&(u(r.domain.verified?`${n} is verified.`:r.domain.verificationError??`${n} is not verified yet. Publish these records, then \`snoutdata domains verify ${n}\`:`),r.domain.verified||eu(r.domain,e)),r.next&&u(r.next)})}async function Fa(e){return T("cloud-project-restore",{ref:e},"GET")}async function Ba(e,t,n){if(Number.isNaN(Date.parse(t)))throw new y(`--at needs a moment, e.g. 2026-09-20T14:30:00Z (got "${t}")`);return T("cloud-project-restore",{ref:e,at:new Date(t).toISOString(),...n?{name:n}:{}})}async function su(e){let t=await Fa(e);w(t,()=>{let n=t.restore,r=Da(e,n);if(r){u(r);return}u(`${e} can be restored to any moment from ${n.earliest} to ${n.latest}.`),u($(` snoutdata db restore --at ${n.latest} --ref ${e}`))})}async function au(e,t,n){let r=await Ba(e,t,n);w(r,()=>{u(`Restoring ${e} as it was at ${r.targetAt} into a new project, ${N(r.project.name)} (${r.project.ref}).`),u($(" snoutdata projects list to see when it is ready"))})}async function Ha(e){let{projects:t}=await Qe(),n=t.find(l=>l.ref===e);if(!n)throw new y(`no project ${e} on this account. \`snoutdata projects list\`.`);let[r,o,s,a]=await Promise.all([yn(e),T("cloud-project-functions",{ref:e}).then(l=>(l.functions??[]).map(d=>d.name),Wt),T("cloud-project-secrets",{ref:e}).then(l=>(l.secrets??[]).map(d=>d.name),Wt),bo(e).then(l=>l.domains.map(d=>({hostname:d.hostname,verified:d.verified})),Wt)]);return{...n,products:r,functions:o,secretNames:s,domains:a}}async function iu(e){let t=await Ha(e);w(t,()=>{let n=t,r=s=>s&&typeof s=="object"&&"enabled"in s?s.enabled?"on":"off":"?",o=s=>Array.isArray(s)?s.length?s.map(a=>typeof a=="string"?a:a.hostname).join(", "):"none":"could not read";process.stdout.write(`${V([["name",n.name],["ref",n.ref],["state",n.serverSilent?`${n.state} (its server is not answering)`:n.state],["region",n.region],...typeof n.postgresVersion=="number"?[["postgres",String(n.postgresVersion)]]:[],["auth / storage / data-api / push",`${r(n.products.auth)} / ${r(n.products.storage)} / ${r(n.products.dataApi)} / ${r(n.products.push)}`],["realtime","on (signals and the roster on every plan; table changes on Plus, Pro and Business)"],["functions",o(n.functions)],["secrets",o(n.secretNames)],["domains",o(n.domains)]])}
|
|
821
|
+
`)})}async function lu(e,t,n,r){let o={ref:e};if(t==="add"){if(!n)throw new y("alerts hooks add needs a URL: an https:// webhook, or a Slack incoming webhook with --slack");o={ref:e,add:{kind:r||n.startsWith("https://hooks.slack.com/")?"slack":"webhook",url:n}}}else if(t==="remove"||t==="test"){if(!n)throw new y(`alerts hooks ${t} needs the destination's id, as alerts hooks lists it`);o={ref:e,[t]:n}}else if(t!==void 0&&t!=="list")throw new y(`unknown command: alerts hooks ${t}. alerts hooks [list], add <url> [--slack], remove <id> or test <id>`);let s=await T("cloud-project-alert-hooks",o);w(s,()=>{if(s.secret?(u(`Added. Its signing secret, shown only now: ${N(s.secret)}`),u($('Each POST carries X-SnoutData-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>" under this secret>.'))):s.added&&u("Added."),s.sent&&u(s.sent.error?`The test was not delivered: ${s.sent.error}`:`The test was delivered (${s.sent.status}).`),s.hooks.length===0){u(`No alert destinations on ${e}; alerts go to the owner's email. Add one: snoutdata alerts hooks add <url> [--slack]`);return}process.stdout.write(`${V([["ID","KIND","URL","LAST SENT"],...s.hooks.map(a=>[a.id,a.kind,a.url,a.lastSentAt?`${a.lastSentAt.slice(0,16).replace("T"," ")} UTC ${a.lastError?N(a.lastError):"ok"}`:"never"])])}
|
|
822
|
+
`)})}me();_e();Ct();me();pe();import{existsSync as Ib,mkdirSync as Cb,readFileSync as Lb,renameSync as Mb,writeFileSync as Db}from"node:fs";import{homedir as Ga}from"node:os";import{dirname as jb,join as Ub}from"node:path";import{rootCertificates as Fb}from"node:tls";var Bb="SNOUTDATA_DB_SSLMODE";function Hb(e=Ga()){let t=Ub(e,".snoutdata","ca-roots.pem"),n=`${Fb.join(`
|
|
545
823
|
`)}
|
|
546
|
-
`,r=null;try{r=
|
|
547
|
-
`)})}async function
|
|
548
|
-
`,{mode:384}),{path:r,replaced:!1,ignored:s};process.platform!=="win32"&&
|
|
824
|
+
`,r=null;try{r=Ib(t)?Lb(t,"utf8"):null}catch{r=null}if(r!==n){Cb(jb(t),{recursive:!0,mode:448});let o=`${t}.${process.pid}.tmp`;Db(o,n,{mode:420}),Mb(o,t)}return t}function rr(e,t=process.env,n=Ga()){if(e==="disable")return{mode:"disable"};let r=t[Bb]?.trim();return r?{mode:r}:{mode:"verify-full",rootCert:t.PGSSLROOTCERT||Hb(n)}}function or(e,t=process.env,n=Ga()){let{mode:r,rootCert:o}=rr(e,t,n);return o?{PGSSLMODE:r,PGSSLROOTCERT:o}:{PGSSLMODE:r}}async function $o(e){try{let{projects:t}=await Qe(),n=t.find(r=>r.ref===e);n?.readOnly?ce(`${e} is read-only: it is over the storage limit on your plan. Reading works; writing does not.`):n?.readOnlyPending&&ce(`${e} is about to become read-only: it has grown past the storage limit on your plan.`)}catch{}}async function Ka(e){await $o(e);let t=await Me(e);w(t,()=>{process.stdout.write(`${t.uri}
|
|
825
|
+
`)})}async function fu(e,t){if(t.length===0&&!Pe()){let o=cn();Q("usage",`db psql with no statements opens an interactive session, and ${o?ln(o):"there is nobody to use it"}. Pass statements after --, or use \`snoutdata db url\` and your own client.`)}await $o(e);let n=await Me(e);n.wakesInstantly||u("This project is paused; the connection will wake it, which takes a few seconds.");let r=sr("psql",["--host",n.host,"--port",String(n.port),"--username",n.user,"--dbname",n.database,...t],{stdio:"inherit",env:{...process.env,PGPASSWORD:n.password,...or(n.ssl)}});return new Promise((o,s)=>{r.on("error",a=>{if(a.code==="ENOENT"){s(new O("tool-missing","psql is not installed. `snoutdata db url` prints a connection string for any client."));return}s(new O("failed",String(a)))}),r.on("close",a=>o(a??0))})}function gu(e,t,n="DATABASE_URL"){let r=_o(e,".env"),o=`${n}=${t}`,s=Wb(e);if(!ko(r))return wn(r,`${o}
|
|
826
|
+
`,{mode:384}),{path:r,replaced:!1,ignored:s};process.platform!=="win32"&&Gb(r).mode&63&&ce(`${r} can be read by other users on this machine, and it holds a database password. \`chmod 600 ${r}\` closes it.`);let a=pu(r,"utf8"),l=new RegExp(`^${n}=.*$`,"m");return l.test(a)?(wn(r,a.replace(l,o)),{path:r,replaced:!0,ignored:s}):(uu(r,a.endsWith(`
|
|
549
827
|
`)?`${o}
|
|
550
828
|
`:`
|
|
551
829
|
${o}
|
|
552
|
-
`),{path:r,replaced:!1,ignored:s})}function
|
|
830
|
+
`),{path:r,replaced:!1,ignored:s})}function Wb(e){let t=e;for(;!ko(_o(t,".git"));){let s=Kb(t);if(s===t)return!1;t=s}let n=_o(e,".gitignore"),r=ko(n)?pu(n,"utf8"):"";return r.split(/\r?\n/).some(s=>/^\/?(\.env|\.env\*|\*\.env|\.env\.\*)$/.test(s.trim()))?!1:(uu(n,r===""||r.endsWith(`
|
|
553
831
|
`)?`.env
|
|
554
832
|
`:`
|
|
555
833
|
.env
|
|
556
|
-
`),!0)}async function
|
|
834
|
+
`),!0)}async function hu(e,t={}){if(t.statusOnly){let{export:a}=await mn(e);return w({ref:e,export:a},()=>qa(a)),0}let n=await Kn(e);if(!n.export.pending&&n.export.url&&!t.out)return w({ref:e,export:n.export},()=>qa(n.export)),0;u("Taking a copy of the database. This runs on the server and can take a few minutes.");let r=await Vb(e,t.timeoutMs);if(r.error&&Q("failed",`The export did not finish: ${r.error}`,{ref:e}),!t.out)return w({ref:e,export:r},()=>qa(r)),0;r.url||Q("failed","The copy was taken, but no download link could be signed. Run this again to get one.",{ref:e});let o=await Yb(r.url,t.out),s=r.rolesSql?Jb(t.out):null;return s&&r.rolesSql&&wn(s,r.rolesSql.endsWith(`
|
|
557
835
|
`)?r.rolesSql:`${r.rolesSql}
|
|
558
|
-
`,"utf8"),
|
|
559
|
-
`),e.urlExpiresAt&&
|
|
560
|
-
${ue.map(
|
|
561
|
-
`)}`,{ref:e,file:n,refusal:"products-off",products:ue})}}if(
|
|
562
|
-
`).map(
|
|
563
|
-
${
|
|
836
|
+
`,"utf8"),w({ref:e,path:t.out,bytes:o,rolesPath:s},()=>{u(`Saved ${Ee(o)} to ${t.out}.`),u($(`Into a SnoutData project: snoutdata db restore --file ${t.out} --ref <ref>`)),s?(u(`Saved the roles it needs to ${s}.`),u($("Into any other Postgres, in this order:")),u($(` psql --dbname <your database> -f ${s}`)),u($(` pg_restore --dbname <your database> ${t.out}`)),u($("The roles are created without passwords. Set them yourself if anything signs in as one."))):(u($("Restore it with: pg_restore --no-owner --no-privileges --dbname <your database> "+t.out)),u($("Owners and grants are skipped: this export carries no roles file.")))}),0}function Jb(e){return e.replace(/\.[^./\\]*$/,"")+".roles.sql"}async function Vb(e,t=30*6e4){let n=Date.now()+t;for(;;){let{export:r}=await mn(e);if(!r.pending)return r;if(Date.now()>=n)throw new Error(`the export of ${e} was still running after waiting`);await new Promise(o=>setTimeout(o,3e3))}}async function Yb(e,t){let n=await fetch(e);if(!n.ok||!n.body)throw new Error(`the download failed: ${n.status} ${n.statusText}`);let r=await mu(t,"w"),o=0;try{for await(let s of n.body)await r.write(s),o+=s.byteLength}finally{await r.close()}return o}function qa(e){if(e.error){ce(`The last export did not finish: ${e.error}`);return}if(e.pending){u("An export is running. Ask again in a minute, or run `snoutdata db export`, which waits for it.");return}if(!e.completedAt){u("This project has never been exported.");return}u(`A copy taken ${We(e.completedAt)}, ${Ee(e.bytes??0)}.`),e.url?(process.stdout.write(`${e.url}
|
|
837
|
+
`),e.urlExpiresAt&&u($(`That link stops working ${We(e.urlExpiresAt)}.`))):u($("The link has expired. Run the export again to sign a new one; the copy is kept."))}function Ee(e){if(e<1024)return`${e} B`;let t=["KB","MB","GB","TB"],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?0:1)} ${t[r]}`}async function yu(e,t){let n=t.file;n||Q("usage","db restore needs --file, pointing at a dump. `snoutdata db export` writes one."),ko(n)||Q("usage",`no file at ${n}`,{file:n});let r=await mu(n,"r"),o=new Uint8Array(512),s=await r.read(o,0,512,0);await r.close();let a=Bd(o.slice(0,s.bytesRead)),l=await Me(e);l.wakesInstantly||u("This project is paused; the connection will wake it, which takes a few seconds.");let{projects:d}=await Qe(),c=d.find(te=>te.ref===e),i=await Xb(l);i===null&&Q("tool-missing","psql is not installed, so the tables in this project could not be counted. Install the Postgres client tools, or restore with your own client using `snoutdata db url`.");let p=Hd(a,{existingTables:i,readOnly:c?.readOnly===!0},{force:t.force});p.ok||Q("conflict",p.reason,{ref:e,file:n,refusal:p.code});let g=null;if(p.tool==="pg_restore"){let te=await du("pg_restore",["--list",n]),U=await du("pg_restore",["--section=post-data","--file=-",n]);if((te.code!==0||U.code!==0)&&Q("failed",`pg_restore could not read ${n}: ${(te.stderr||U.stderr).trim().slice(0,300)}`,{ref:e,file:n}),g=qd(te.stdout,U.stdout),g.products.length>0){let B=await yn(e),C=G=>!!(G&&typeof G=="object"&&"enabled"in G&&G.enabled),ue=g.products.filter(G=>!C(B[G]));ue.length>0&&Q("conflict",`this dump holds ${ue.length>1?`${ue.slice(0,-1).join(", ")} and ${ue[ue.length-1]}`:ue[0]} data, and ${e} has ${ue.length===1?"it":"them"} off. Their tables are the platform's, so the product has to be on to take the rows. Switch ${ue.length===1?"it":"them"} on, wait a minute, and run this again:
|
|
838
|
+
${ue.map(G=>` snoutdata products enable ${G} --ref ${e}`).join(`
|
|
839
|
+
`)}`,{ref:e,file:n,refusal:"products-off",products:ue})}}if(g&&g.platformData.length>0){let te=g.platformData.flatMap(({tables:C})=>C),U=await Zb(l,te);U===null&&Q("failed",`could not check ${e} for the tables this dump loads into.`,{ref:e});let B=g.platformData.filter(({tables:C})=>C.some(ue=>U.includes(ue))).map(({product:C})=>C);B.length>0&&Q("conflict",`${B.join(", ")} on ${e} ${B.length===1?"has":"have"} not finished setting up ${B.length===1?"its":"their"} tables yet. Run this again in a minute.`,{ref:e,file:n,refusal:"products-starting",products:B})}u(`Restoring ${n} into ${e} with ${p.tool} (${p.format} format).`);let E=g?await Qb(l,n,g):await So(l,p.tool,n),A=Gd(E.stderr);for(let te of g?.notes??[])u($(te));return E.code!==0&&A.fatal.length===0&&A.total>0?(w({ref:e,file:n,ok:!0,tool:p.tool,format:p.format,ignoredErrors:A.harmless},()=>{u(`Restored into ${e}.`),u(`${A.harmless} error${A.harmless===1?"":"s"} above ${A.harmless===1?"is":"are"} expected and nothing is missing: a dump carries comments on the extensions this image installs, and your role does not own them.`)}),0):(E.code!==0&&Q("failed",`${p.tool} exited ${E.code}. Nothing here retried it: a half-finished restore is undone by deleting the project and making another.`,{ref:e,file:n,errors:A.fatal}),w({ref:e,file:n,ok:!0,tool:p.tool,format:p.format},()=>u(`Restored into ${e}.`)),0)}async function Xb(e){return new Promise(t=>{let n=sr("psql",["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database,"--no-psqlrc","-tAc","select count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind = 'r' and n.nspname not in ('pg_catalog', 'information_schema') and n.nspname not like 'pg\\_toast%' and not exists (select 1 from pg_depend d where d.objid = c.oid and d.deptype = 'e') and pg_get_userbyid(c.relowner) !~ '^(snoutpod_admin|snout_[a-z]+_admin)$'"],{stdio:["ignore","pipe","pipe"],env:{...process.env,PGPASSWORD:e.password,...or(e.ssl)}}),r="";n.stdout.on("data",o=>r+=String(o)),n.on("error",o=>{ce(o.code==="ENOENT"?"psql is not installed, and db restore needs it (and pg_restore for an archive).":String(o)),t(null)}),n.on("close",o=>t(o===0?Number(r.trim())||0:null))})}function Zb(e,t){if(t.length===0)return Promise.resolve([]);let n=t.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return new Promise(r=>{let o=sr("psql",["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database,"--no-psqlrc","-tAc",`select t from unnest(array[${n}]) t where to_regclass(t) is null`],{stdio:["ignore","pipe","pipe"],env:{...process.env,PGPASSWORD:e.password,...or(e.ssl)}}),s="";o.stdout.on("data",a=>s+=String(a)),o.on("error",()=>r(null)),o.on("close",a=>r(a===0?s.split(`
|
|
840
|
+
`).map(l=>l.trim()).filter(Boolean):null))})}function du(e,t){return new Promise(n=>{let r=sr(e,t,{stdio:["ignore","pipe","pipe"]}),o="",s="";r.stdout.on("data",a=>o+=String(a)),r.stderr.on("data",a=>s+=String(a)),r.on("error",a=>{ce(a.code==="ENOENT"?`${e} is not installed, and this dump needs it.`:String(a)),n({code:127,stdout:o,stderr:s})}),r.on("close",a=>n({code:a??0,stdout:o,stderr:s}))})}async function Qb(e,t,n){let r=_o(zb(),`snoutdata-restore-${process.pid}-${Date.now()}`),o=0,s="";try{for(let{product:l,clear:d,lines:c}of n.platformData){if(d.length>0){wn(`${r}.sql`,`set role ${Ra[l]};
|
|
841
|
+
${d.map(g=>`delete from ${g};`).join(`
|
|
564
842
|
`)}
|
|
565
|
-
`,"utf8");let
|
|
843
|
+
`,"utf8");let p=await So(e,"psql",`${r}.sql`,["--quiet"]);o=o||p.code,s+=p.stderr}wn(`${r}.platform`,`${c.join(`
|
|
566
844
|
`)}
|
|
567
|
-
`,"utf8");let
|
|
845
|
+
`,"utf8");let i=await So(e,"pg_restore",t,["--data-only",`--role=${Ra[l]}`,`--use-list=${r}.platform`]);o=o||i.code,s+=i.stderr}wn(`${r}.rest`,`${n.rest.join(`
|
|
568
846
|
`)}
|
|
569
|
-
`,"utf8");let a=await
|
|
570
|
-
`);let t=e.access.find(n=>n.you);t?.connection&&(
|
|
571
|
-
`),
|
|
847
|
+
`,"utf8");let a=await So(e,"pg_restore",t,[`--use-list=${r}.rest`]);return{code:o||a.code,stderr:s+a.stderr}}finally{for(let a of[".platform",".rest",".sql"])try{qb(`${r}${a}`)}catch{}}}function So(e,t,n,r=[]){let o=["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database],s=t==="psql"?[...o,"--no-psqlrc","-v","ON_ERROR_STOP=1",...r,"-f",n]:[...o,"--no-owner","--no-privileges",...r,n];return new Promise(a=>{let l=sr(t,s,{stdio:["ignore","inherit","pipe"],env:{...process.env,PGPASSWORD:e.password,...or(e.ssl)}}),d="";l.stderr?.on("data",c=>{let i=String(c);d+=i,process.stderr.write(i)}),l.on("error",c=>{ce(c.code==="ENOENT"?`${t} is not installed, and this dump needs it.`:String(c)),a({code:127,stderr:d})}),l.on("close",c=>a({code:c??0,stderr:d}))})}me();ve();pe();function tS(e,t){let[n="list",r,...o]=e;if(o.length>0)throw new y(`db access ${n} takes one argument, not ${1+o.length}`);switch(n){case"list":if(r!==void 0)throw new y("db access list takes no argument");if(t!==void 0)throw new y("--level is for db access grant");return{action:"list"};case"grant":{if(!r||!r.includes("@"))throw new y("db access grant needs an email address: db access grant you@example.com [--level full|read]");let s=t??"read";if(s!=="full"&&s!=="read")throw new y(`--level is full or read, not ${JSON.stringify(s)}`);return{action:"grant",email:r,level:s}}case"revoke":if(!r)throw new y("db access revoke needs an email address or a role name");if(t!==void 0)throw new y("--level is for db access grant");return{action:"revoke",who:r};default:throw new y(`unknown command: db access ${n}. db access list|grant|revoke`)}}async function wu(e,t,n){let r=tS(t,n.level);if(r.action==="list"){let s=await T("cloud-project-db-access",{ref:e,action:"list"});w(s,()=>nS(s));return}if(r.action==="grant"){let s=await T("cloud-project-db-access",{ref:e,action:"grant",email:r.email,level:r.level});w(s,()=>rS(s));return}let o=await T("cloud-project-db-access",{ref:e,action:"revoke",who:r.who});w(o,()=>sS(o))}function nS(e){if(e.note&&u(e.note),e.access.length===0){u(`Nobody signs in to ${e.ref}'s database as themselves yet. \`snoutdata db access grant you@example.com --level full\`.`);return}process.stdout.write(`${V([["EMAIL","LEVEL","ROLE"],...e.access.map(n=>[n.you?N(n.email):n.email,n.level,n.role])])}
|
|
848
|
+
`);let t=e.access.find(n=>n.you);t?.connection&&(u(""),u("You sign in with (psql 18; a browser approves it):"),u($(` psql "${t.connection.keywords}"`)))}function rS(e){e.connection&&process.stdout.write(`${e.connection.keywords}
|
|
849
|
+
`),u("");let t=e.outcome==="unchanged"?"already has":"now has";u(`${e.email} ${t} ${N(e.level)} access to ${e.ref}'s database, as ${e.role}${e.means?`: ${e.means}`:""}.`),e.outcome!=="unchanged"&&u(e.appliesIn),u("They sign in with psql 18 (libpq 18 with OAuth support) and approve the code it prints in a browser:"),e.connection&&u($(` psql "${e.connection.keywords}"`))}function oS(e){return[...e.revoked.map(t=>`Took away ${t.email}'s ${t.level} access to ${e.ref}'s database (${t.role}).`),e.note]}function sS(e){let t=oS(e);for(let n of t.slice(0,-1))u(n);ce(t[t.length-1])}async function bu(e){let t=await sa(e);w({ref:e,token:t.access_token,user:t.user,role:t.db_role,expiresIn:t.expires_in},()=>{process.stdout.write(`${t.access_token}
|
|
850
|
+
`),u(`The password for user ${t.user} on ${e}'s database: you, as ${t.db_role}, for ${Math.round(t.expires_in/60)} minutes.`)})}me();ve();pe();function aS(e,t){let[n="list",r,...o]=e;if(o.length>0)throw new y(`db allow ${n} takes one argument, not ${1+o.length}`);if(t!==void 0&&n!=="add")throw new y("--note is for db allow add");switch(n){case"list":case"clear":if(r!==void 0)throw new y(`db allow ${n} takes no argument`);return{action:n};case"add":if(!r)throw new y('db allow add needs an address or a range: db allow add 203.0.113.0/24 [--note "office"]');return{action:"add",cidr:r,note:t};case"remove":if(!r)throw new y("db allow remove needs the address or range to take off the list");return{action:"remove",cidr:r};default:throw new y(`unknown command: db allow ${n}. db allow list|add|remove|clear`)}}async function Su(e,t,n){let r=aS(t,n.note),o={ref:e,action:r.action};(r.action==="add"||r.action==="remove")&&(o.cidr=r.cidr),r.action==="add"&&r.note!==void 0&&(o.note=r.note);let s=await T("cloud-project-allow-list",o);w(s,()=>cS(s));let a=iS(s);a&&ce(a)}function iS(e){return e.entries.length===0||e.yourAddressListed!==!1?null:`${e.yourAddress?`Your address (${e.yourAddress})`:"Your address"} is not on the list, so the database refuses connections from this machine. Add it with: snoutdata db allow add ${e.yourAddress??"<your address>"}`}function lS(e){let t=e.cidr??"";switch(e.outcome){case"added":return`Added ${t} to ${e.ref}'s allow-list.`;case"changed":return`Changed the note on ${t}.`;case"unchanged":return`${t} was already on the list.`;case"removed":return`Took ${t} off ${e.ref}'s allow-list.`;case"cleared":return`Cleared ${e.ref}'s allow-list: every address may connect again.`;case"none":return t?`${t} was not on the list.`:"The list was already empty.";default:return null}}function cS(e){let t=lS(e);if(t&&u(t),e.entries.length===0){u(`${e.ref}'s database takes connections from every address (the allow-list is empty).`),e.yourAddress&&u($(`Your address: ${e.yourAddress}`));return}process.stdout.write(`${V([["ADDRESS","NOTE","ADDED"],...e.entries.map(n=>[n.cidr,n.note??"",n.addedAt.slice(0,10)])])}
|
|
851
|
+
`),u($(`${e.entries.length} of ${e.limit}. Only these addresses may connect to ${e.ref}'s database.`)),e.yourAddress&&e.yourAddressListed&&u($(`Your address ${N(e.yourAddress)} is on the list.`))}me();ve();pe();var dS=6e4;async function za(e,t={}){return T("cloud-project-realtime",{ref:e,...t.channel?{channel:t.channel}:{},...t.since!==void 0?{since:t.since}:{}})}function uS(e,t=Date.now()){let n=/^(\d+)\s*(s|m|h|d)$/i.exec(e.trim());if(n){let o={s:1e3,m:6e4,h:36e5,d:864e5}[n[2].toLowerCase()];return t-Number(n[1])*o}let r=Date.parse(e);if(Number.isFinite(r))return r;throw new y(`--since wants a duration like 10m, 2h or 1d, or a time like 2026-10-03T14:00, not "${e}"`)}function pS(e){let t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function ku(e){if(e===null)return"-";let t=Math.round(e/1e3);if(t<60)return`${t}s ago`;let n=Math.round(t/60);return n<60?`${n}m ago`:`${Math.round(n/60)}h ago`}var mS={connect:"connected",connect_refused:"refused at connect",join:"joined",join_refused:"join refused",leave:"left",channel_closed:"channel closed by the server",disconnect:"disconnected",handler_failed:"handler failed"};function _u(e){let t=[e.presence_key?e.presence_key:null,e.socket!==void 0?`socket ${e.socket}`:null].filter(Boolean).join(", "),n=[pS(e.at),mS[e.kind]??e.kind];return e.channel&&n.push(e.channel),t&&n.push(`(${t})`),e.reason?`${n.join(" ")}: ${e.reason}`:n.join(" ")}function fS(e){let t=Object.fromEntries(Object.entries(e).filter(([n])=>!n.startsWith("phx_ref")));return JSON.stringify(t)}function gS(e){let t=e.inspect;if(u(N(`Realtime for ${e.ref}`)),u(`${t.connections} connection${t.connections===1?"":"s"}, ${t.connected_users} on a channel. The project's limit is ${t.limits.max_events_per_second} messages a second, counted once per message sent, however many receive it.`),t.channels.length===0){u("No channels are open.");return}for(let n of t.channels){let r=n.messages;if(u(""),u(N(`${n.name}${n.private?" (private)":""}`)+` ${n.clients.length} client${n.clients.length===1?"":"s"}`),u($(` last ${r.window_seconds}s: ${r.broadcasts_received} signal${r.broadcasts_received===1?"":"s"} sent, ${r.broadcasts_delivered} delivered, busiest second ${r.peak_broadcasts_per_second}; ${r.presence_diffs_delivered} roster update${r.presence_diffs_delivered===1?"":"s"} delivered`)),n.clients.length>0){let s=n.clients.map(a=>[String(a.socket),a.presence_key,ku(Date.now()-a.joined_at),ku(a.last_seen_ms_ago)+(a.last_seen_ms_ago!==null&&a.last_seen_ms_ago>dS?" (silent: likely gone)":"")]);u(V([["SOCKET","ROSTER KEY","JOINED","LAST HEARD"],...s]).split(`
|
|
572
852
|
`).map(a=>` ${a}`).join(`
|
|
573
|
-
`))}let o=Object.keys(n.presence);if(o.length>0){
|
|
574
|
-
`);if(s.events.length>0){r=Math.max(...s.events.map(
|
|
575
|
-
`))}}}async function
|
|
576
|
-
`);r.logCapacity!==null&&r.events.length>=r.logCapacity&&d(v(`The log keeps the newest ${r.logCapacity} events; older ones have gone.`))}),0}pe();Ae();be();de();var ro=[{id:"bedrock",name:"Amazon Bedrock",mark:"AB",blurb:"Claude, Llama, Mistral, Qwen and more, in your own AWS account.",kind:"bedrock",suggestedName:"bedrock",region:!0,auth:"bedrock",connect:{console:{label:"AWS IAM console",href:"https://console.aws.amazon.com/iam/home#/users"},steps:["In IAM, make a user for the AI gateway (or reuse one) with a policy allowing bedrock:InvokeModel, bedrock:InvokeModelWithResponseStream and bedrock:Converse on the models you will serve.","Under the user's Security credentials, choose Create access key, for an application running outside AWS, and copy the access key ID and the secret. The secret is shown once.","Or use a Bedrock API key instead: Bedrock console, API keys, Generate.","Pick the region the models are in. Inference profiles starting with us. or global. route across regions from there."]},model:{link:{label:"Bedrock model catalog",href:"https://console.aws.amazon.com/bedrock/home#/model-catalog"},steps:["Open the Bedrock model catalog in the region you picked and choose the model.","If it asks for access, request it under Model access first; Anthropic models ask for a short use-case form once.","Copy its inference profile ID (it starts with us., eu., apac. or global.). A model with no inference profile is called by its model ID."],example:"us.anthropic.claude-sonnet-4-5-20250929-v1:0"},price:{link:{label:"Bedrock pricing",href:"https://aws.amazon.com/bedrock/pricing/"},steps:["Find the model on Bedrock's pricing page under on-demand. AWS quotes per 1,000 tokens for some models: multiply by 1,000 for the per-million rate asked here.",'Leave the prices blank if the shipped catalogue already knows the model; the model list shows "from the catalogue" when it does.']},caching:!0},{id:"anthropic",name:"Anthropic",mark:"An",blurb:"Claude, straight from Anthropic's API.",kind:"anthropic",suggestedName:"anthropic",baseUrl:"https://api.anthropic.com/v1",auth:"api_key",connect:{console:{label:"Anthropic Console, API keys",href:"https://console.anthropic.com/settings/keys"},steps:["In the Anthropic Console, open Settings, API keys, and choose Create key.","Name it after this gateway and copy it. It starts with sk-ant- and is shown once.","Make sure the organisation has credit or a billing plan, or every call is refused."]},model:{link:{label:"Claude models",href:"https://docs.anthropic.com/en/docs/about-claude/models/overview"},steps:["Open Anthropic's models overview and copy the model's API name, not its display name."],example:"claude-sonnet-4-5"},price:{link:{label:"Anthropic API pricing",href:"https://www.anthropic.com/pricing#api"},steps:["Copy the input and output rates per million tokens. Cache reads and cache writes have their own rates on the same page.","Leave the prices blank if the shipped catalogue already knows the model."]},caching:!0},{id:"openai",name:"OpenAI",mark:"OA",blurb:"GPT models, straight from OpenAI's API.",kind:"openai",suggestedName:"openai",baseUrl:"https://api.openai.com/v1",auth:"api_key",connect:{console:{label:"OpenAI API keys",href:"https://platform.openai.com/api-keys"},steps:["On the OpenAI platform, open API keys and choose Create new secret key.","Give it a project and the permission to call models, and copy it. It starts with sk- and is shown once.","Check the project has billing set up; a key without it is refused on the first call."]},model:{link:{label:"OpenAI models",href:"https://platform.openai.com/docs/models"},steps:["Open OpenAI's models page, choose the model and copy its id from the top of its page."],example:"gpt-5-mini"},price:{link:{label:"OpenAI API pricing",href:"https://openai.com/api/pricing/"},steps:['Copy the input and output rates per million tokens; "cached input" is the cache read rate. OpenAI caches by itself, so there is no cache write rate.',"Leave the prices blank if the shipped catalogue already knows the model."]},caching:!1},{id:"openrouter",name:"OpenRouter",mark:"OR",blurb:"Hundreds of models from many providers behind one key.",kind:"openai",suggestedName:"openrouter",baseUrl:"https://openrouter.ai/api/v1",auth:"api_key",connect:{console:{label:"OpenRouter keys",href:"https://openrouter.ai/settings/keys"},steps:["On OpenRouter, open Settings, Keys, and choose Create Key. A credit limit on the key is a good second fence.","Copy it. It starts with sk-or- and is shown once.","Add credits to the account, or every paid model is refused."]},model:{link:{label:"OpenRouter models",href:"https://openrouter.ai/models"},steps:["Find the model on OpenRouter and copy its id from under its name: the provider, a slash and the model."],example:"anthropic/claude-sonnet-4.5"},price:{link:{label:"OpenRouter models",href:"https://openrouter.ai/models"},steps:["Each model's page shows its input and output price per million tokens. Copy those; OpenRouter adds no fee on top of them for a key you pay for with credits."]},caching:!0},{id:"ollama",name:"Ollama",mark:"Ol",blurb:"A model on a machine of your own, such as the home server.",kind:"openai",suggestedName:"home-ollama",editableUrl:!0,urlExample:"https://home-ai.snoutdata.com/v1",auth:"optional",connect:{console:{label:"Ollama documentation",href:"https://github.com/ollama/ollama/blob/main/docs/openai.md"},steps:["The address must reach Ollama from this gateway, so not localhost: a public HTTPS name, such as one through a Cloudflare tunnel, ending in /v1.","Never leave it open: put a check in front of it (a Cloudflare rule that blocks any request without a secret header) and give that header's name and secret here.","Check it from your own machine first: a request to the address plus /models with the header should list the models, and one without it should be refused."]},model:{steps:["On the Ollama machine, run ollama pull with the model first, if it is not there yet.","Run ollama list and copy the NAME column exactly, tag included."],example:"snout-fim:1.0"},price:{steps:["Your machine charges nothing per token, so the price is what you choose to count against a person's budget: a small rate, such as $0.05 in and $0.10 out, keeps a runaway caller inside it.","Do not leave the price blank: the catalogue does not know your models, and a model nothing prices is refused to every signed-in user."]},caching:!1},{id:"compatible",name:"Any OpenAI-compatible server",mark:"{}",blurb:"vLLM, LM Studio, Together, Groq, DeepSeek and the rest.",kind:"openai",suggestedName:"my-provider",editableUrl:!0,urlExample:"https://api.example.com/v1",auth:"optional",connect:{steps:["Find the server's OpenAI-compatible address in its documentation; it usually ends in /v1.","Make an API key in its console and copy it. A server that checks a header of its own instead of a Bearer token takes the header's name too."]},model:{steps:["Copy the model id from the provider's model list, or from what the address plus /models returns."],example:"deepseek-chat"},price:{steps:["Copy the input and output rates per million tokens from the provider's pricing page.","For a server of your own, choose a small rate so budgets still count it; a model nothing prices is refused to every signed-in user."]},caching:!1}];function Cd(e,t){if(t.kind!==e.kind)return!1;if(e.kind!=="openai")return!0;let n=t.base_url.replace(/\/+$/,"");return e.baseUrl?n===e.baseUrl:!ro.some(r=>r.baseUrl&&r.kind==="openai"&&r.baseUrl===n)}function Md(e){return(e.trim().split("/").pop()??"").replace(/^(us|eu|apac|global)\.(anthropic|meta|mistral|amazon|cohere|qwen|deepseek|openai)\./,"").replace(/-v\d+:\d+$/,"").replace(/:/g,"-").toLowerCase()}function Dd(e,t,n){let o=e.auth==="bedrock"&&n.aws===!0?n.accessKeyId?.trim()&&n.secretAccessKey?.trim()?{access_key_id:n.accessKeyId.trim(),secret_access_key:n.secretAccessKey.trim()}:null:n.apiKey?.trim()?{api_key:n.apiKey.trim()}:null;if(e.auth!=="optional"&&!o)return{problem:"Paste the key from the first steps; Psyche checks it with the provider before keeping it."};if(e.kind!=="bedrock"&&!n.baseUrl?.trim())return{problem:"Give the address."};if(e.kind==="bedrock"&&!n.region?.trim())return{problem:"Give the region the model runs in."};let s={kind:e.kind};return e.kind==="bedrock"?s.region=n.region.trim():(s.base_url=n.baseUrl.trim(),n.authHeader?.trim()&&(s.auth_header=n.authHeader.trim())),o&&(s.credential=t),{provider:s,credential:o}}function rb(e){return e===void 0||e.trim()===""?void 0:Number(e)}function Ld(e){if(!e.upstream.trim())return{problem:"Give the model's id, as the provider names it."};let[t,n,r,o,s]=[e.input,e.output,e.cacheRead,e.cacheWrite,e.maxOutput].map(rb);if([t,n,r,o].some(c=>c!==void 0&&(!Number.isFinite(c)||c<0)))return{problem:"Prices are numbers, zero or more."};if(t===void 0!=(n===void 0))return{problem:"Give both the input and the output rate, or neither to take the catalogue's."};let a={provider:e.provider,upstream:e.upstream.trim()};return e.caching!==void 0&&(a.prompt_caching=e.caching),e.enabled!==void 0&&(a.enabled=e.enabled),e.access&&(a.access=e.access),t!==void 0&&n!==void 0&&(a.price={input:t,output:n},r!==void 0&&(a.price.cache_read=r),o!==void 0&&(a.price.cache_write=o)),s!==void 0&&Number.isFinite(s)&&s>0&&(a.max_output_tokens=Math.round(s)),{model:a}}var so=class{send;constructor(t){this.send=t}providers(){return this.list("admin/providers")}putProvider(t,n){return this.call("PUT",`admin/providers/${at(t)}`,n)}deleteProvider(t){return this.none("DELETE",`admin/providers/${at(t)}`)}upstreamModels(t){return typeof t=="string"?this.list(`admin/providers/${at(t)}/upstream-models`):this.call("POST","admin/upstream-models",t).then(n=>n?.data??[])}models(){return this.list("admin/models")}putModel(t,n){return this.call("PUT",`admin/models/${oo(t)}`,n)}deleteModel(t){return this.call("DELETE",`admin/models/${oo(t)}`)}routes(){return this.list("admin/routes")}putRoute(t,n){return this.call("PUT",`admin/routes/${oo(t)}`,n)}deleteRoute(t){return this.none("DELETE",`admin/routes/${oo(t)}`)}health(){return this.list("admin/health")}credentials(){return this.list("admin/credentials")}putCredential(t,n){return this.call("PUT",`admin/credentials/${at(t)}`,n)}deleteCredential(t){return this.none("DELETE",`admin/credentials/${at(t)}`)}keys(){return this.list("admin/keys")}createKey(t){return this.call("POST","admin/keys",t)}revokeKey(t){return this.none("DELETE",`admin/keys/${at(t)}`)}budgets(){return this.list("admin/budgets")}createBudget(t){return this.call("POST","admin/budgets",t)}editBudget(t,n){return this.call("PATCH",`admin/budgets/${at(t)}`,n)}deleteBudget(t){return this.none("DELETE",`admin/budgets/${at(t)}`)}limits(){return this.list("admin/limits")}createLimit(t){return this.call("POST","admin/limits",t)}deleteLimit(t){return this.none("DELETE",`admin/limits/${at(t)}`)}groups(){return this.list("admin/groups")}usage(t={}){return this.call("GET",`admin/usage${jd(t)}`)}requests(t={}){return this.call("GET",`admin/requests${jd(t)}`)}async list(t){return(await this.send("GET",t))?.data??[]}async call(t,n,r){return await this.send(t,n,r)}async none(t,n){await this.send(t,n)}};function at(e){return encodeURIComponent(e)}function oo(e){return e.split("/").map(at).join("/")}function jd(e){let t=Object.entries(e).filter(([,n])=>n!=null&&n!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`);return t.length?`?${t.join("&")}`:""}function Wn(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}async function io(e,t){return R("cloud-project-ai",t===void 0?{ref:e}:{ref:e,enable:t})}function ob(e){if(e instanceof Re){let t=e.body?.error;if(t&&typeof t=="object"&&typeof t.message=="string")return new Re(e.status,t.message,typeof t.code=="string"?t.code:null,e.body)}return e}function sb(e){return async(t,n,r)=>{try{return await R("cloud-project-ai",{ref:e,admin:{method:t,path:n,...r===void 0?{}:{body:r}}})}catch(o){throw ob(o)}}}function Pe(e){return new so(sb(e))}function ab(e){return e instanceof Re&&(e.status===502||e.status===404&&e.serverCode!=="ai-off")}function ya(e){return Number.isInteger(e)?`$${e}`:Math.abs(e*100-Math.round(e*100))<1e-9?`$${e.toFixed(2)}`:`$${e}`}function Fd(e){return e?`${ya(e.input)} in, ${ya(e.output)} out`:"no price"}function Bd(e){return e.every_user?"every user":e.user_id?`user ${e.user_id}`:e.key_id?`key ${e.key_id}`:e.group_id?`group ${e.group_id}`:"the project"}function wa(e){let t=e.period==="rolling"?`per ${e.days??"?"} days`:e.period==="since"?`since ${e.starts_on??"?"}`:`a ${e.period}`,n=Wn(e.amount);return`${n===null?`$${e.amount}`:ya(n)} ${t}, ${e.hard?"hard":"soft"}`}function ib(e){let t=Wn(e);return t===null?"-":`$${t.toFixed(t!==0&&t<.01?4:2)}`}function ao(e){return e===null?"never":new Date(e*1e3).toISOString().slice(0,16).replace("T"," ")}function Hd(e,t=Date.now()){return new Date(t-(e-1)*864e5).toISOString().slice(0,10)}function lb(e,t){return`${e} ${t}${e===1?"":"s"}`}async function Kd(e){let t=await io(e);if(!t.ai.enabled){b({ref:e,enabled:!1,endpoint:t.ai.endpoint},()=>{d(`AI is off for ${e}.`),d(v(` snoutdata ai enable --ref ${e} ${t.ai.restartsDatabase}`))});return}let n=Pe(e),[r,o,s]=await Promise.allSettled([n.models(),n.budgets(),n.usage({by:"day",from:Hd(30)})]),a=[r,o,s].find(y=>y.status==="rejected");if(a&&ab(a.reason)){b({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!1},()=>{d(`AI is on for ${e}, and its gateway is still starting. Try again in a minute.`)});return}if(a)throw a.reason;let c=r.value,i=o.value,u=s.value.data,l=u.reduce((y,T)=>y+(Wn(T.cost)??0),0),m=u.reduce((y,T)=>y+T.requests,0);b({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!0,models:c,budgets:i,last30Days:{requests:m,cost:l}},()=>{d(`${M(`AI for ${e}`)}: on, at ${t.ai.endpoint}`),d(""),c.length===0?(d("No models yet. Add one:"),d(v(" snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):d(qd(c)),d(""),d(i.length===0?"No budgets.":i.map(y=>`Budget: ${Bd(y)}, ${wa(y)}`).join(`
|
|
577
|
-
`)),
|
|
578
|
-
`),
|
|
579
|
-
`),
|
|
580
|
-
`),e.enabled||
|
|
581
|
-
`)}
|
|
853
|
+
`))}let o=Object.keys(n.presence);if(o.length>0){u(" roster:");for(let s of o)for(let a of n.presence[s].metas)u(` ${s} ${fS(a)}`)}}}async function $u(e,t={}){if(t.watch&&Lt())throw new y("--watch is for a person; with --json, poll `realtime inspect --json` or `realtime logs --since 1m --json`");let n=await za(e,{channel:t.channel});if(w(n.inspect,()=>gS(n)),!t.watch)return 0;u(""),u($("Watching. New events appear below as they happen; Ctrl+C to stop."));let r=n.at+1,o=t.intervalMs??2e3;for(;;){await new Promise(a=>setTimeout(a,o));let s=await za(e,{channel:t.channel,since:r});for(let a of s.events)process.stdout.write(`${_u(a)}
|
|
854
|
+
`);if(s.events.length>0){r=Math.max(...s.events.map(l=>l.at))+1;let a=s.inspect.channels.map(l=>`${l.name}: ${Object.keys(l.presence).join(", ")||"nobody tracked"}`).join("; ");process.stdout.write($(` now ${a||"no channels open"}
|
|
855
|
+
`))}}}async function vu(e,t={}){let n=t.since?uS(t.since):0,r=await za(e,{channel:t.channel,since:n});return w({ref:r.ref,events:r.events,capacity:r.logCapacity},()=>{if(r.events.length===0){u(t.since||t.channel?"Nothing in the log for that.":"Nothing in the log yet. It fills as clients connect, and starts again when the project's host restarts.");return}for(let o of r.events)process.stdout.write(`${_u(o)}
|
|
856
|
+
`);r.logCapacity!==null&&r.events.length>=r.logCapacity&&u($(`The log keeps the newest ${r.logCapacity} events; older ones have gone.`))}),0}me();ve();_e();pe();var vo=[{id:"bedrock",name:"Amazon Bedrock",mark:"AB",blurb:"Claude, Llama, Mistral, Qwen and more, in your own AWS account.",kind:"bedrock",suggestedName:"bedrock",region:!0,auth:"bedrock",connect:{console:{label:"AWS IAM console",href:"https://console.aws.amazon.com/iam/home#/users"},steps:["In IAM, make a user for the AI gateway (or reuse one) with a policy allowing bedrock:InvokeModel, bedrock:InvokeModelWithResponseStream and bedrock:Converse on the models you will serve.","Under the user's Security credentials, choose Create access key, for an application running outside AWS, and copy the access key ID and the secret. The secret is shown once.","Or use a Bedrock API key instead: Bedrock console, API keys, Generate.","Pick the region the models are in. Inference profiles starting with us. or global. route across regions from there."]},model:{link:{label:"Bedrock model catalog",href:"https://console.aws.amazon.com/bedrock/home#/model-catalog"},steps:["Open the Bedrock model catalog in the region you picked and choose the model.","If it asks for access, request it under Model access first; Anthropic models ask for a short use-case form once.","Copy its inference profile ID (it starts with us., eu., apac. or global.). A model with no inference profile is called by its model ID."],example:"us.anthropic.claude-sonnet-4-5-20250929-v1:0"},price:{link:{label:"Bedrock pricing",href:"https://aws.amazon.com/bedrock/pricing/"},steps:["Find the model on Bedrock's pricing page under on-demand. AWS quotes per 1,000 tokens for some models: multiply by 1,000 for the per-million rate asked here.",'Leave the prices blank if the shipped catalogue already knows the model; the model list shows "from the catalogue" when it does.']},caching:!0},{id:"anthropic",name:"Anthropic",mark:"An",blurb:"Claude, straight from Anthropic's API.",kind:"anthropic",suggestedName:"anthropic",baseUrl:"https://api.anthropic.com/v1",auth:"api_key",connect:{console:{label:"Anthropic Console, API keys",href:"https://console.anthropic.com/settings/keys"},steps:["In the Anthropic Console, open Settings, API keys, and choose Create key.","Name it after this gateway and copy it. It starts with sk-ant- and is shown once.","Make sure the organisation has credit or a billing plan, or every call is refused."]},model:{link:{label:"Claude models",href:"https://docs.anthropic.com/en/docs/about-claude/models/overview"},steps:["Open Anthropic's models overview and copy the model's API name, not its display name."],example:"claude-sonnet-4-5"},price:{link:{label:"Anthropic API pricing",href:"https://www.anthropic.com/pricing#api"},steps:["Copy the input and output rates per million tokens. Cache reads and cache writes have their own rates on the same page.","Leave the prices blank if the shipped catalogue already knows the model."]},caching:!0},{id:"openai",name:"OpenAI",mark:"OA",blurb:"GPT models, straight from OpenAI's API.",kind:"openai",suggestedName:"openai",baseUrl:"https://api.openai.com/v1",auth:"api_key",connect:{console:{label:"OpenAI API keys",href:"https://platform.openai.com/api-keys"},steps:["On the OpenAI platform, open API keys and choose Create new secret key.","Give it a project and the permission to call models, and copy it. It starts with sk- and is shown once.","Check the project has billing set up; a key without it is refused on the first call."]},model:{link:{label:"OpenAI models",href:"https://platform.openai.com/docs/models"},steps:["Open OpenAI's models page, choose the model and copy its id from the top of its page."],example:"gpt-5-mini"},price:{link:{label:"OpenAI API pricing",href:"https://openai.com/api/pricing/"},steps:['Copy the input and output rates per million tokens; "cached input" is the cache read rate. OpenAI caches by itself, so there is no cache write rate.',"Leave the prices blank if the shipped catalogue already knows the model."]},caching:!1},{id:"openrouter",name:"OpenRouter",mark:"OR",blurb:"Hundreds of models from many providers behind one key.",kind:"openai",suggestedName:"openrouter",baseUrl:"https://openrouter.ai/api/v1",auth:"api_key",connect:{console:{label:"OpenRouter keys",href:"https://openrouter.ai/settings/keys"},steps:["On OpenRouter, open Settings, Keys, and choose Create Key. A credit limit on the key is a good second fence.","Copy it. It starts with sk-or- and is shown once.","Add credits to the account, or every paid model is refused."]},model:{link:{label:"OpenRouter models",href:"https://openrouter.ai/models"},steps:["Find the model on OpenRouter and copy its id from under its name: the provider, a slash and the model."],example:"anthropic/claude-sonnet-4.5"},price:{link:{label:"OpenRouter models",href:"https://openrouter.ai/models"},steps:["Each model's page shows its input and output price per million tokens. Copy those; OpenRouter adds no fee on top of them for a key you pay for with credits."]},caching:!0},{id:"ollama",name:"Ollama",mark:"Ol",blurb:"A model on a machine of your own, such as the home server.",kind:"openai",suggestedName:"home-ollama",editableUrl:!0,urlExample:"https://home-ai.snoutdata.com/v1",auth:"optional",connect:{console:{label:"Ollama documentation",href:"https://github.com/ollama/ollama/blob/main/docs/openai.md"},steps:["The address must reach Ollama from this gateway, so not localhost: a public HTTPS name, such as one through a Cloudflare tunnel, ending in /v1.","Never leave it open: put a check in front of it (a Cloudflare rule that blocks any request without a secret header) and give that header's name and secret here.","Check it from your own machine first: a request to the address plus /models with the header should list the models, and one without it should be refused."]},model:{steps:["On the Ollama machine, run ollama pull with the model first, if it is not there yet.","Run ollama list and copy the NAME column exactly, tag included."],example:"snout-fim:1.0"},price:{steps:["Your machine charges nothing per token, so the price is what you choose to count against a person's budget: a small rate, such as $0.05 in and $0.10 out, keeps a runaway caller inside it.","Do not leave the price blank: the catalogue does not know your models, and a model nothing prices is refused to every signed-in user."]},caching:!1},{id:"compatible",name:"Any OpenAI-compatible server",mark:"{}",blurb:"vLLM, LM Studio, Together, Groq, DeepSeek and the rest.",kind:"openai",suggestedName:"my-provider",editableUrl:!0,urlExample:"https://api.example.com/v1",auth:"optional",connect:{steps:["Find the server's OpenAI-compatible address in its documentation; it usually ends in /v1.","Make an API key in its console and copy it. A server that checks a header of its own instead of a Bearer token takes the header's name too."]},model:{steps:["Copy the model id from the provider's model list, or from what the address plus /models returns."],example:"deepseek-chat"},price:{steps:["Copy the input and output rates per million tokens from the provider's pricing page.","For a server of your own, choose a small rate so budgets still count it; a model nothing prices is refused to every signed-in user."]},caching:!1}];function Pu(e,t){if(t.kind!==e.kind)return!1;if(e.kind!=="openai")return!0;let n=t.base_url.replace(/\/+$/,"");return e.baseUrl?n===e.baseUrl:!vo.some(r=>r.baseUrl&&r.kind==="openai"&&r.baseUrl===n)}function xu(e){return(e.trim().split("/").pop()??"").replace(/^(us|eu|apac|global)\.(anthropic|meta|mistral|amazon|cohere|qwen|deepseek|openai)\./,"").replace(/-v\d+:\d+$/,"").replace(/:/g,"-").toLowerCase()}function Eu(e,t,n){let o=e.auth==="bedrock"&&n.aws===!0?n.accessKeyId?.trim()&&n.secretAccessKey?.trim()?{access_key_id:n.accessKeyId.trim(),secret_access_key:n.secretAccessKey.trim()}:null:n.apiKey?.trim()?{api_key:n.apiKey.trim()}:null;if(e.auth!=="optional"&&!o)return{problem:"Paste the key from the first steps; Psyche checks it with the provider before keeping it."};if(e.kind!=="bedrock"&&!n.baseUrl?.trim())return{problem:"Give the address."};if(e.kind==="bedrock"&&!n.region?.trim())return{problem:"Give the region the model runs in."};let s={kind:e.kind};return e.kind==="bedrock"?s.region=n.region.trim():(s.base_url=n.baseUrl.trim(),n.authHeader?.trim()&&(s.auth_header=n.authHeader.trim())),o&&(s.credential=t),{provider:s,credential:o}}function yS(e){return e===void 0||e.trim()===""?void 0:Number(e)}function Au(e){if(!e.upstream.trim())return{problem:"Give the model's id, as the provider names it."};let[t,n,r,o,s]=[e.input,e.output,e.cacheRead,e.cacheWrite,e.maxOutput].map(yS);if([t,n,r,o].some(l=>l!==void 0&&(!Number.isFinite(l)||l<0)))return{problem:"Prices are numbers, zero or more."};if(t===void 0!=(n===void 0))return{problem:"Give both the input and the output rate, or neither to take the catalogue's."};let a={provider:e.provider,upstream:e.upstream.trim()};return e.caching!==void 0&&(a.prompt_caching=e.caching),e.enabled!==void 0&&(a.enabled=e.enabled),e.access&&(a.access=e.access),t!==void 0&&n!==void 0&&(a.price={input:t,output:n},r!==void 0&&(a.price.cache_read=r),o!==void 0&&(a.price.cache_write=o)),s!==void 0&&Number.isFinite(s)&&s>0&&(a.max_output_tokens=Math.round(s)),{model:a}}var xo=class{send;constructor(t){this.send=t}providers(){return this.list("admin/providers")}putProvider(t,n){return this.call("PUT",`admin/providers/${mt(t)}`,n)}deleteProvider(t){return this.none("DELETE",`admin/providers/${mt(t)}`)}upstreamModels(t){return typeof t=="string"?this.list(`admin/providers/${mt(t)}/upstream-models`):this.call("POST","admin/upstream-models",t).then(n=>n?.data??[])}models(){return this.list("admin/models")}putModel(t,n){return this.call("PUT",`admin/models/${Po(t)}`,n)}deleteModel(t){return this.call("DELETE",`admin/models/${Po(t)}`)}routes(){return this.list("admin/routes")}putRoute(t,n){return this.call("PUT",`admin/routes/${Po(t)}`,n)}deleteRoute(t){return this.none("DELETE",`admin/routes/${Po(t)}`)}health(){return this.list("admin/health")}credentials(){return this.list("admin/credentials")}putCredential(t,n){return this.call("PUT",`admin/credentials/${mt(t)}`,n)}deleteCredential(t){return this.none("DELETE",`admin/credentials/${mt(t)}`)}keys(){return this.list("admin/keys")}createKey(t){return this.call("POST","admin/keys",t)}revokeKey(t){return this.none("DELETE",`admin/keys/${mt(t)}`)}budgets(){return this.list("admin/budgets")}createBudget(t){return this.call("POST","admin/budgets",t)}editBudget(t,n){return this.call("PATCH",`admin/budgets/${mt(t)}`,n)}deleteBudget(t){return this.none("DELETE",`admin/budgets/${mt(t)}`)}limits(){return this.list("admin/limits")}createLimit(t){return this.call("POST","admin/limits",t)}deleteLimit(t){return this.none("DELETE",`admin/limits/${mt(t)}`)}groups(){return this.list("admin/groups")}usage(t={}){return this.call("GET",`admin/usage${Ru(t)}`)}requests(t={}){return this.call("GET",`admin/requests${Ru(t)}`)}async list(t){return(await this.send("GET",t))?.data??[]}async call(t,n,r){return await this.send(t,n,r)}async none(t,n){await this.send(t,n)}};function mt(e){return encodeURIComponent(e)}function Po(e){return e.split("/").map(mt).join("/")}function Ru(e){let t=Object.entries(e).filter(([,n])=>n!=null&&n!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`);return t.length?`?${t.join("&")}`:""}function ar(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}async function Ao(e,t){return T("cloud-project-ai",t===void 0?{ref:e}:{ref:e,enable:t})}function wS(e){if(e instanceof xe){let t=e.body?.error;if(t&&typeof t=="object"&&typeof t.message=="string")return new xe(e.status,t.message,typeof t.code=="string"?t.code:null,e.body)}return e}function bS(e){return async(t,n,r)=>{try{return await T("cloud-project-ai",{ref:e,admin:{method:t,path:n,...r===void 0?{}:{body:r}}})}catch(o){throw wS(o)}}}function Te(e){return new xo(bS(e))}function SS(e){return e instanceof xe&&(e.status===502||e.status===404&&e.serverCode!=="ai-off")}function Wa(e){return Number.isInteger(e)?`$${e}`:Math.abs(e*100-Math.round(e*100))<1e-9?`$${e.toFixed(2)}`:`$${e}`}function Ou(e){return e?`${Wa(e.input)} in, ${Wa(e.output)} out`:"no price"}function Nu(e){return e.every_user?"every user":e.user_id?`user ${e.user_id}`:e.key_id?`key ${e.key_id}`:e.group_id?`group ${e.group_id}`:"the project"}function Ja(e){let t=e.period==="rolling"?`per ${e.days??"?"} days`:e.period==="since"?`since ${e.starts_on??"?"}`:`a ${e.period}`,n=ar(e.amount);return`${n===null?`$${e.amount}`:Wa(n)} ${t}, ${e.hard?"hard":"soft"}`}function kS(e){let t=ar(e);return t===null?"-":`$${t.toFixed(t!==0&&t<.01?4:2)}`}function Eo(e){return e===null?"never":new Date(e*1e3).toISOString().slice(0,16).replace("T"," ")}function Iu(e,t=Date.now()){return new Date(t-(e-1)*864e5).toISOString().slice(0,10)}function _S(e,t){return`${e} ${t}${e===1?"":"s"}`}async function Cu(e){let t=await Ao(e);if(!t.ai.enabled){w({ref:e,enabled:!1,endpoint:t.ai.endpoint},()=>{u(`AI is off for ${e}.`),u($(` snoutdata ai enable --ref ${e} ${t.ai.restartsDatabase}`))});return}let n=Te(e),[r,o,s]=await Promise.allSettled([n.models(),n.budgets(),n.usage({by:"day",from:Iu(30)})]),a=[r,o,s].find(g=>g.status==="rejected");if(a&&SS(a.reason)){w({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!1},()=>{u(`AI is on for ${e}, and its gateway is still starting. Try again in a minute.`)});return}if(a)throw a.reason;let l=r.value,d=o.value,c=s.value.data,i=c.reduce((g,E)=>g+(ar(E.cost)??0),0),p=c.reduce((g,E)=>g+E.requests,0);w({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!0,models:l,budgets:d,last30Days:{requests:p,cost:i}},()=>{u(`${N(`AI for ${e}`)}: on, at ${t.ai.endpoint}`),u(""),l.length===0?(u("No models yet. Add one:"),u($(" snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):u(Mu(l)),u(""),u(d.length===0?"No budgets.":d.map(g=>`Budget: ${Nu(g)}, ${Ja(g)}`).join(`
|
|
857
|
+
`)),u(`Last 30 days: ${_S(p,"request")}, $${i.toFixed(2)}.`)})}async function Lu(e,t){let n=await Ao(e,t);w(n,()=>{t?(u(`AI is on for ${e}. ${n.ai.restartsDatabase} The gateway answers at ${n.ai.endpoint} within a minute or two.`),u($(" next: snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):u(`AI is off for ${e}. Its providers, models, keys and log stay in the project's database, for when it is switched on again.`)})}function Mu(e){return V([["MODEL","PROVIDER","UPSTREAM","PRICE PER M TOKENS","SERVED"],...e.map(t=>[t.name,t.provider,t.upstream,Ou(t.price)+(t.price_from==="catalogue"?" (catalogue)":""),t.served?"yes":`no: ${t.problem??(t.enabled?"not served":"disabled")}`])])}async function Du(e){let t=await Te(e).models();w(t,()=>{u(t.length===0?`No models on ${e}'s gateway yet.`:Mu(t))})}async function ju(e){let t=await Te(e).providers();w(t,()=>{if(t.length===0){u(`No providers on ${e}'s gateway yet. \`snoutdata ai models add\` makes one with its first model.`);return}u(V([["PROVIDER","KIND","WHERE","KEY","MODELS"],...t.map(n=>[n.name,n.kind,n.kind==="bedrock"?n.region??"":n.base_url,$S(n),n.models.join(", ")||"-"])]));for(let n of t.filter(r=>r.problem))ce(`${n.name}: ${n.problem}`)})}function $S(e){return e.key==="environment"?"from the environment":e.key==="none"||e.credential===null?"none":e.credential_stored?"stored":"missing"}async function Uu(e,t){if(!t)throw new y("ai providers remove needs the provider's name (see `snoutdata ai providers`)");await Te(e).deleteProvider(t),w({ref:e,removed:t},()=>u(`Removed the provider ${t}.`))}function vS(e){let t=vo.map(r=>r.id).join("|");if(!e)throw new y(`ai models add needs --source ${t}: where the model runs`);let n=vo.find(r=>r.id===e);if(!n)throw new y(`--source is one of ${t}, not "${e}"`);return n}function PS(e){u(N(`Adding a model from ${e.name}`));let t=[["The key",e.connect],["The model's id",e.model],["Its price",e.price]];for(let[n,r]of t){u(""),u(N(n));for(let s of r.steps)u(` - ${s}`);let o=r.console??r.link;o&&u($(` ${o.label}: ${o.href}`))}u("")}function xS(e,t,n){if(n)return{name:n,existing:t.find(o=>o.name===n)??null};let r=t.filter(o=>Pu(e,o));if(r.length===1)return{name:r[0].name,existing:r[0]};if(r.length>1)throw new y(`${e.name} is connected more than once (${r.map(o=>o.name).join(", ")}): say which with --provider`);return{name:e.suggestedName,existing:t.find(o=>o.name===e.suggestedName)??null}}async function Fu(e,t,n){let r=vS(n.source),o=n.upstream?.trim();if(!o)throw PS(r),new y(`Give the model's id as ${r.name} names it, with --model (for example ${r.model.example})`);let s=t?.trim()||xu(o),a=Te(e),[l,d]=await Promise.all([a.providers(),a.models()]);if(d.some(C=>C.name===s))throw new y(`${e} already has a model called ${s}. Name this one differently, or remove that one first.`);let{name:c,existing:i}=xS(r,l,n.provider);if(i&&i.kind!==r.kind)throw new y(`The provider ${c} speaks ${i.kind}, not ${r.name}: choose another --provider name`);if(i?.origin==="file"&&n.stdin)throw new y(`The provider ${c} comes from the gateway's providers file, so its key is set there, not here`);let p=n.stdin?await hn():void 0,g=r.auth==="bedrock"&&n.accessKeyId!==void 0,E=null;if(!i){if(r.auth!=="optional"&&!p)throw new y(g?"Pipe the AWS secret access key in with --stdin; --access-key-id is its id":`${r.name} needs a key: pipe it in with --stdin (snoutdata ai models add ... --stdin < key.txt), so it is in neither the shell history nor ps`);let C=Eu(r,c,{baseUrl:n.baseUrl??r.baseUrl,region:n.region,apiKey:g?void 0:p,aws:g,accessKeyId:n.accessKeyId,secretAccessKey:g?p:void 0,authHeader:n.authHeader});if("problem"in C)throw new y(r.kind==="bedrock"&&!n.region?"Give the region the model runs in, with --region":n.baseUrl===void 0&&r.kind!=="bedrock"?"Give the provider's address, with --base-url":C.problem);E=C}let A=Au({provider:c,upstream:o,input:n.priceIn,output:n.priceOut,caching:r.caching,enabled:!0,access:"everyone"});if("problem"in A)throw new y(A.problem.replace("input and the output rate","--price-in and --price-out"));let te=!1,U=!1,B;try{if(E&&(await a.putProvider(c,E.provider),te=!0),B=await a.putModel(s,A.model),U=!0,E?.credential)await a.putCredential(c,E.credential);else if(i&&p){if(!i.credential)throw new y(`The provider ${c} takes no key`);await a.putCredential(i.credential,g?{access_key_id:n.accessKeyId,secret_access_key:p}:{api_key:p})}}catch(C){throw U&&await a.deleteModel(s).catch(()=>{}),te&&await a.deleteProvider(c).catch(()=>{}),C}B=(await a.models()).find(C=>C.name===s)??B,w(B,()=>{u(`Added ${N(s)} (${o} on ${c}${te?", a new provider":""}), at ${Ou(B.price)}${B.price_from==="catalogue"?" from the shipped catalogue":""}.`),B.price||ce("Nothing prices this model, so signed-in users are refused it. Give it a price with --price-in and --price-out."),!B.served&&B.problem&&ce(`It is not served yet: ${B.problem}`),u($(` snoutdata ai test --model ${s}`))})}async function Bu(e,t){if(!t)throw new y("ai models remove needs the model's name (see `snoutdata ai models`)");let n=await Te(e).deleteModel(t);w(n,()=>u(n.disabled?`${t} comes from the gateway's providers file, so it was disabled rather than removed.`:`Removed ${t}.`))}function ES(e){return(e??"").split(",").map(t=>t.trim()).filter(t=>t!=="")}function AS(e){return V([["ROUTE","TRIES, IN ORDER","SORT","SKIPS"],...e.map(t=>[t.name,t.tried.join(", ")||"-",t.sort,t.skipped.join(", ")||"-"])])}async function Hu(e){let t=await Te(e).routes();w(t,()=>{if(t.length===0){u(`No routes on ${e}'s gateway. A route is one name for several models, each tried when the one before fails:`),u($(" snoutdata ai routes set NAME --models first,second [--sort price]"));return}u(AS(t))})}async function Gu(e,t,n){if(!t)throw new y("ai routes set needs the route's name: snoutdata ai routes set NAME --models first,second");let r=ES(n.models);if(r.length===0)throw new y("ai routes set needs --models, the models to try in order, comma-separated (see `snoutdata ai models`)");let o=n.sort??"order";if(o!=="order"&&o!=="price"&&o!=="latency"&&o!=="throughput")throw new y(`--sort is order (as written), price (the cheapest first), latency or throughput (the fastest first, as measured), not ${o}`);let s=Te(e);await s.putRoute(t,{targets:r,sort:o});let a=(await s.routes()).find(l=>l.name===t);w(a??{name:t,targets:r,sort:o},()=>{let l=a?.tried??r;u(`${N(t)} tries ${l.join(", then ")}${o==="price"?", the cheapest first":o==="latency"||o==="throughput"?`, the fastest first by ${o} once measured`:""}.`),a&&a.skipped.length>0&&ce(`skipped, not served: ${a.skipped.join(", ")}`),u($(` Call it as the model "${t}", or: snoutdata ai test --model ${t}`))})}async function qu(e,t){if(!t)throw new y("ai routes remove needs the route's name (see `snoutdata ai routes`)");await Te(e).deleteRoute(t),w({name:t,removed:!0},()=>u(`Removed the route ${t}. Its models are untouched.`))}function RS(e,t=Date.now()/1e3){return e.revoked_at!==null?"revoked":e.expires_at!==null&&e.expires_at<=t?"expired":e.expires_at!==null?`until ${Eo(e.expires_at).slice(0,10)}`:"active"}async function Ku(e){let t=await Te(e).keys();w(t,()=>{if(t.length===0){u(`No keys on ${e}'s gateway. \`snoutdata ai keys create --name my-server\` makes one for a server.`);return}u(V([["NAME","ID","KEY","MODELS","CREATED","LAST USED","STATE"],...t.map(n=>[n.name,n.id,n.hint,n.models?.join(", ")??"all",Eo(n.created_at),n.last_used_at!==null?Eo(n.last_used_at):n.last_used_on??"never",RS(n)])]))})}async function zu(e,t){if(!t.name)throw new y("ai keys create needs --name: what the key is for, shown in ai keys");if(t.expiresDays!==void 0&&t.expiresDays<=0)throw new y("--expires is a number of days, 1 or more");let n=t.models?.split(",").map(s=>s.trim()).filter(Boolean),r=await Te(e).createKey({name:t.name,...n&&n.length>0?{models:n}:{},...t.expiresDays!==void 0?{expires_in:t.expiresDays*86400}:{}}),o=await Ao(e);w({...r,endpoint:o.ai.endpoint},()=>{process.stdout.write(`${r.key}
|
|
858
|
+
`),u(""),u(`${N(r.name)}: ${r.models?`for ${r.models.join(", ")}`:"for every model"}, ${r.expires_at?`until ${Eo(r.expires_at)}`:"until revoked"}.`),u("This is the only time it is shown: only its hash is kept. It is a server's key; a browser calls with the app key and a signed-in user instead."),u($(` OPENAI_BASE_URL=${o.ai.endpoint} OPENAI_API_KEY=<that key>`))})}async function Wu(e,t){if(!t)throw new y("ai keys revoke needs the key's id (see `snoutdata ai keys`)");await Te(e).revokeKey(t),w({ref:e,revoked:t},()=>u(`Revoked ${t}. A call with it is refused from now on.`))}async function Ju(e){let t=await Te(e).budgets();w(t,()=>{if(t.length===0){u(`No budgets on ${e}'s gateway. A browser call needs two hard ones:`),u($(" snoutdata ai budgets set project --amount 5")),u($(" snoutdata ai budgets set users --amount 0.50"));return}u(V([["ID","FOR","BUDGET"],...t.map(n=>[n.id,Nu(n),Ja(n)])]))})}function TS(e){if(e==="project"||e==="users")return e;throw new y("ai budgets set takes project (the whole project) or users (each signed-in user)")}function OS(e,t,n){return e.find(r=>r.period===n&&!r.key_id&&!r.user_id&&!r.group_id&&(t==="users"?r.every_user:!r.every_user))}async function Vu(e,t,n){let r=TS(t),o=Number(n.amount);if(n.amount===void 0||!Number.isFinite(o)||o<0)throw new y("ai budgets set needs --amount, in dollars, zero or more");let s=n.period??"day";if(s!=="day"&&s!=="month")throw new y("--period is day or month");let a=Te(e),l=OS(await a.budgets(),r,s),d=l?await a.editBudget(l.id,{amount:o,hard:!n.soft}):await a.createBudget({name:r==="users"?"every user":"project",amount:o,period:s,hard:!n.soft,...r==="users"?{every_user:!0}:{}});w(d,()=>u(`${l?"Changed":"Set"}: ${r==="users"?"every user":"the project"}, ${Ja(d)}.`))}async function Yu(e,t){if(!t)throw new y("ai budgets remove needs the budget's id (see `snoutdata ai budgets`)");await Te(e).deleteBudget(t),w({ref:e,removed:t},()=>u(`Removed the budget ${t}.`))}var Tu=["day","model","provider","operation","key","user","group"];async function Xu(e,t){let n=t.by??"model";if(!Tu.includes(n))throw new y(`--by is one of ${Tu.join("|")}`);let r=t.days??30;if(r<1||r>366)throw new y("--days is 1 to 366");let o=await Te(e).usage({by:n,from:Iu(r)});w(o,()=>{if(o.data.length===0){u(`No calls to ${e}'s gateway from ${o.from} to ${o.to}.`);return}let s=o.data.reduce((a,l)=>a+(ar(l.cost)??0),0);u(V([[n.toUpperCase(),"REQUESTS","FAILED","TOKENS IN","TOKENS OUT","COST"],...o.data.map(a=>[String(a[n]??"-"),String(a.requests),String(a.failed),String(a.prompt_tokens),String(a.completion_tokens),kS(a.cost)+(a.unpriced>0?` (+${a.unpriced} unpriced)`:"")])])),u(`${o.from} to ${o.to}: $${s.toFixed(2)}.`)})}async function Zu(e,t){let n=await Ao(e);if(!n.ai.enabled)throw new O("not-found",`AI is off for ${e}. Switch it on first: snoutdata ai enable.`);let r=Te(e),s=(await r.models()).filter(E=>E.served&&E.embeddings===null),a=t.model??s[0]?.name;if(!a)throw new O("not-found",`${e}'s gateway serves no chat model yet. Add one: snoutdata ai models add.`);let l=await r.createKey({name:"snoutdata ai test",models:[a],expires_in:600}),d=Date.now(),c=0,i={};try{let E=await fetch(`${n.ai.endpoint}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${l.key}`,"content-type":"application/json"},body:JSON.stringify({model:a,max_tokens:64,messages:[{role:"user",content:t.prompt??"Say hello in five words."}]})});c=E.status;let A=await E.text();try{i=A?JSON.parse(A):{}}catch{i={error:{message:Jn(E.status,E.statusText,A)}}}}finally{await r.revokeKey(l.id).catch(()=>{})}let p=Date.now()-d;if(c<200||c>=300){let E=i.error?.message??`the gateway answered ${c}`;throw new O(kt(c,i.error?.code??null),`${a} through ${e}'s gateway: ${E}`,{model:a,status:c,gatewayCode:i.error?.code??null})}let g=i.choices?.[0]?.message?.content??"";return w({ref:e,model:a,reply:g,usage:i.usage??null,ms:p},()=>{process.stdout.write(`${g}
|
|
859
|
+
`),u($(`${a}, ${p} ms, ${i.usage?.prompt_tokens??"?"} tokens in, ${i.usage?.completion_tokens??"?"} out, through ${n.ai.endpoint}`))}),0}me();ve();pe();import{readFile as IS}from"node:fs/promises";var CS="api.snoutdata.com";function tp(e,t){return{ref:e,enabled:t.enabled===!0,siteUrl:t.settings?.site_url??null,redirects:t.settings?.uri_allow_list??[],google:{enabled:t.google?.enabled===!0,clientId:t.google?.clientId??null,clientSecretSet:t.google?.clientSecretSet===!0,ready:t.google?.ready===!0},googleCallback:`https://${e}.${CS}/auth/v1/callback`,anonymous:{enabled:t.anonymous?.enabled===!0,ready:t.anonymous?.ready===!0}}}async function LS(e){return tp(e,await T("cloud-project-auth",{ref:e,action:"status"}))}async function Ro(e,t){return tp(e,await T("cloud-project-auth",{ref:e,action:"settings",settings:t}))}function Va(e){let t=e.google,n="off";t.ready?n=N("on"):t.enabled&&(n=`switched on, not offered yet: needs ${[!t.clientId&&"a client id",!t.clientSecretSet&&"a client secret"].filter(Boolean).join(" and ")}`),process.stdout.write(`${V([["auth",e.enabled?N("on"):"off"],["site url",e.siteUrl??$("not set")],["redirects",e.redirects.length?e.redirects.join(", "):$("none")],["google",n],["google client id",t.clientId??$("not set")],["google callback",e.googleCallback],["guests",e.anonymous.ready?N("on"):e.anonymous.enabled?"switched on, not applied yet":"off"]])}
|
|
860
|
+
`),e.enabled||u($(` snoutdata products enable auth --ref ${e.ref}`))}async function MS(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8").replace(/\r?\n$/,"")}async function np(e,t,n,r){if(t===void 0||t==="show"){let o=await LS(e);w(o,()=>Va(o));return}if(t==="google"){if(n[0]==="off"){let a=await Ro(e,{googleEnabled:!1});w(a,()=>u("Google sign-in is off. Your auth service restarts within about a minute."));return}if(n.length>0)throw new y('auth google takes --client-id and --stdin, or "off"');let o={googleEnabled:!0};if(r.clientId&&(o.googleClientId=r.clientId),r.stdin){let a=await MS();if(!a)throw new y("--stdin read nothing. Pipe the Google client secret in.");o.googleClientSecret=a}let s=await Ro(e,o);w(s,()=>{s.google.ready?u("Google sign-in is on. Your auth service restarts within about a minute."):Va(s),u($(` Add ${s.googleCallback} to your Google client's Authorized redirect URIs.`))});return}if(t==="anonymous"||t==="guests"){let o=n[0];if(o!=="on"&&o!=="off")throw new y('auth anonymous takes "on" or "off"');let s=await Ro(e,{anonymousEnabled:o==="on"});w(s,()=>{o==="off"?u("Guest sign-in is off. Guests who already have a session keep it until it ends. Your auth service restarts within about a minute."):s.enabled?u("Guest sign-in is on: guestSignIn() gives a browser a session with no email or password. Your auth service restarts within about a minute."):(u("Guest sign-in is switched on, and takes effect when auth is."),u($(` snoutdata products enable auth --ref ${s.ref}`)))});return}if(t==="redirects"){let o={};if(r.siteUrl!==void 0&&(o.siteUrl=r.siteUrl||null),r.allow!==void 0&&(o.uriAllowList=r.allow.split(",").map(a=>a.trim()).filter(Boolean)),Object.keys(o).length===0)throw new y("auth redirects needs --site-url and/or --allow URL,URL (an empty --allow= clears the list)");let s=await Ro(e,o);w(s,()=>Va(s));return}if(t==="templates"){let o=await T("cloud-project-auth",{ref:e,action:"templates"});w(o,()=>ep(o.templates));return}if(t==="template"){let o=n[0];if(!o||!Qu.includes(o))throw new y(`auth template needs a kind: ${Qu.join(", ")}`);let s;if(n[1]==="reset")s={kind:o,reset:!0};else{if(!r.file)throw new y(`auth template ${o} needs --file body.html (and --subject), or "reset"`);let l=await IS(r.file,"utf8"),d=await T("cloud-project-auth",{ref:e,action:"templates"}),c=r.subject??d.templates.find(i=>i.kind===o)?.subject;s={kind:o,subject:c,body:l}}let a=await T("cloud-project-auth",{ref:e,action:"template",template:s});w(a,()=>{ep(a.templates),u($(" Your auth service restarts with it within about a minute."))});return}throw new y(`unknown command: auth ${t}. auth [google [off] | anonymous on|off | redirects | templates | template KIND]`)}var Qu=["confirmation","recovery","magic_link","invite","email_change"];function ep(e){process.stdout.write(`${V([["KIND","SOURCE","SUBJECT"],...e.map(t=>[t.kind,t.custom?N("yours"):"ours",t.subject])])}
|
|
861
|
+
`)}me();pe();_e();import{createHash as rk}from"node:crypto";import{existsSync as ok,readdirSync as sk,readFileSync as ak,statSync as ik}from"node:fs";import{isAbsolute as lk,join as ti,relative as ck,resolve as dk}from"node:path";function DS(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function To(e,t,n={}){let r=DS(e),o=new Map(r.map(c=>[c.name,c])),s=[];for(let c of t){let i=o.get(c.name);if(!i){s.push({code:"missing",name:c.name,reason:`${c.name} has already run against this database and is no longer in the folder. If it was renamed, the old name is still recorded and the new one looks new, so its statements would run a second time.`});continue}i.checksum!==c.checksum&&s.push({code:"changed",name:c.name,reason:`${c.name} has changed since it ran. The database and this folder no longer agree about what happened to the schema, and running anything cannot fix that. Put the change in a new migration instead.`})}let a=t.map(c=>c.name).sort((c,i)=>c<i?-1:c>i?1:0)[t.length-1],l=new Set(t.map(c=>c.name)),d=[];for(let c of r)if(!l.has(c.name)){if(a!==void 0&&c.name<a&&!n.outOfOrder){s.push({code:"out-of-order",name:c.name,reason:`${c.name} sorts before ${a}, which has already run. Applying it now gives this database a history no fresh database will have. Pass --out-of-order if that is what you mean.`});continue}d.push(c)}return s.length>0?{ok:!1,problems:s}:{ok:!0,pending:d}}function Dt(e){return!/^[\t ]*--[\t ]*snoutdata:no-transaction[\t ]*$/im.test(e)}import{createHash as Xa,createHmac as Oo,pbkdf2Sync as jS,randomBytes as US,timingSafeEqual as FS}from"node:crypto";import{readFileSync as BS}from"node:fs";import{homedir as HS}from"node:os";import{connect as GS,isIP as qS}from"node:net";import{connect as KS}from"node:tls";var nt=class extends Error{severity;code;detail;hint;position;where;constructor(t){super(t.get("M")??"the server reported an error"),this.name="PgServerError",this.severity=t.get("V")??t.get("S")??"ERROR",this.code=t.get("C")??"";let n=t.get("D"),r=t.get("H"),o=Number(t.get("P")),s=t.get("W");n&&(this.detail=n),r&&(this.hint=r),Number.isInteger(o)&&o>0&&(this.position=o),s&&(this.where=s)}},he=class extends Error{constructor(t){super(t),this.name="PgConnectError"}};function zS(e){let t=e.readInt16BE(0),n=[],r=2;for(let o=0;o<t;o++){let s=e.indexOf(0,r);if(s<0)break;n.push(e.toString("utf8",r,s)),r=s+1+18}return n}var WS=196608,JS=80877103;function rp(e,t){let n=Buffer.alloc(5);return n.write(e,0,"latin1"),n.writeInt32BE(t.length+4,1),Buffer.concat([n,t])}function jt(e){return Buffer.concat([Buffer.from(e,"utf8"),Buffer.from([0])])}function VS(e,t=0){let n=[],r=t;for(;r<e.length;){let o=e.indexOf(0,r);if(o<0||o===r)break;n.push(e.toString("utf8",r,o)),r=o+1}return n}function Ya(e){let t=new Map,n=0;for(;n<e.length&&e[n]!==0;){let r=String.fromCharCode(e[n]),o=e.indexOf(0,n+1);if(o<0)break;t.set(r,e.toString("utf8",n+1,o)),n=o+1}return t}var Za=class{constructor(t,n=US(18).toString("base64")){this.password=t;this.nonce=n,this.firstBare=`n=,r=${this.nonce}`}nonce;firstBare;serverSignature=null;first(){return`n,,${this.firstBare}`}final(t){let n=new Map(t.split(",").map(A=>[A.slice(0,1),A.slice(2)])),r=n.get("r"),o=n.get("s"),s=Number(n.get("i"));if(!r||!r.startsWith(this.nonce)||r.length<=this.nonce.length)throw new he("the server answered the password exchange with a nonce that is not ours");if(!o||!Number.isInteger(s)||s<1)throw new he("the server answered the password exchange with no salt or iteration count");let a=jS(this.password.normalize("NFKC"),Buffer.from(o,"base64"),s,32,"sha256"),l=Oo("sha256",a).update("Client Key").digest(),d=Xa("sha256").update(l).digest(),c=`c=biws,r=${r}`,i=`${this.firstBare},${t},${c}`,p=Oo("sha256",d).update(i).digest(),g=Buffer.alloc(l.length);for(let A=0;A<g.length;A++)g[A]=l[A]^p[A];let E=Oo("sha256",a).update("Server Key").digest();return this.serverSignature=Oo("sha256",E).update(i).digest(),`${c},p=${g.toString("base64")}`}verify(t){let n=/(?:^|,)e=([^,]*)/.exec(t);if(n)throw new he(`the server refused the password exchange: ${n[1]}`);let r=/(?:^|,)v=([^,]*)/.exec(t),o=r?Buffer.from(r[1],"base64"):Buffer.alloc(0);if(!this.serverSignature||o.length!==this.serverSignature.length||!FS(o,this.serverSignature))throw new he("the server could not prove it knows the password, so this is not the database it claims to be")}},Qa=class{buffer=Buffer.alloc(0);queue=[];waiting=null;failure=null;constructor(t){t.on("data",n=>this.take(n)),t.on("error",n=>this.fail(new he(n.message))),t.on("close",()=>this.fail(new he("the server closed the connection")))}take(t){for(this.buffer=this.buffer.length===0?t:Buffer.concat([this.buffer,t]);this.buffer.length>=5;){let n=this.buffer.readInt32BE(1);if(n<4){this.fail(new he("the server sent a message this client cannot read"));return}if(this.buffer.length<n+1)break;let r={type:String.fromCharCode(this.buffer[0]),body:this.buffer.subarray(5,n+1)};if(this.buffer=this.buffer.subarray(n+1),this.waiting){let{resolve:o}=this.waiting;this.waiting=null,o(r)}else this.queue.push(r)}}fail(t){if(!this.failure&&(this.failure=t,this.waiting)){let{reject:n}=this.waiting;this.waiting=null,n(t)}}next(){let t=this.queue.shift();return t?Promise.resolve(t):this.failure?Promise.reject(this.failure):new Promise((n,r)=>{this.waiting={resolve:n,reject:r}})}};function YS(e){return new Promise((t,n)=>{let r=l=>{if(a(),l.length!==1){n(new he("the server sent more than its answer to the TLS request, so the connection was closed"));return}t(String.fromCharCode(l[0]))},o=l=>{a(),n(new he(l.message))},s=()=>{a(),n(new he("the server closed the connection before TLS"))},a=()=>{e.off("data",r),e.off("error",o),e.off("close",s)};e.on("data",r),e.on("error",o),e.on("close",s)})}function XS(e,t){return new Promise((n,r)=>{let o=GS({host:e,port:t}),s=a=>r(new he(`could not connect to ${e}:${t}: ${a.message}`));o.once("connect",()=>{o.off("error",s),n(o)}),o.once("error",s)})}async function ZS(e,t,n,r){let o=await XS(e.host,e.port);if(r(o),t==="disable")return o;let s=Buffer.alloc(8);if(s.writeInt32BE(8,0),s.writeInt32BE(JS,4),o.write(s),await YS(o)!=="S"){if(t==="allow"||t==="prefer")return o;throw new he(`${e.host} does not accept TLS, and this connection requires it (sslmode ${t})`)}let l=t==="verify-ca"||t==="verify-full";return new Promise((d,c)=>{let i=KS({socket:o,host:e.host,...qS(e.host)===0?{servername:e.host}:{},rejectUnauthorized:l,...l&&n?{ca:BS(n,"utf8")}:{},...t==="verify-ca"?{checkServerIdentity:()=>{}}:{}});r(i),i.once("secureConnect",()=>{i.off("error",p),d(i)});let p=g=>c(new he(`TLS to ${e.host} failed: ${g.message}`));i.once("error",p)})}var bn=class e{constructor(t,n){this.socket=t;this.reader=n}static async open(t,n={}){let r=n.env??process.env,o=rr(t.ssl,r,n.home??HS()),s=o.rootCert??(r.PGSSLROOTCERT||void 0),a=o.mode==="require"&&s?"verify-ca":o.mode,l=n.connectTimeoutMs??12e4,d=[],c=()=>{for(let g of d)g.destroy()},i,p=new Promise((g,E)=>{i=setTimeout(()=>{c(),E(new he(`${t.host}:${t.port} did not answer within ${Math.round(l/1e3)} seconds`))},l)});try{return await Promise.race([(async()=>{let g=await ZS(t,a,s,A=>d.push(A)),E=new e(g,new Qa(g));return await E.startup(t),E})(),p])}catch(g){throw c(),g}finally{clearTimeout(i)}}send(t,n){this.socket.write(rp(t,n))}async startup(t){let n=Buffer.concat([...[["user",t.user],["database",t.database],["application_name","snoutdata"],["client_encoding","UTF8"]].flatMap(([s,a])=>[jt(s),jt(a)]),Buffer.from([0])]),r=Buffer.alloc(8);r.writeInt32BE(n.length+8,0),r.writeInt32BE(WS,4),this.socket.write(Buffer.concat([r,n]));let o=null;for(;;){let s=await this.reader.next();switch(s.type){case"R":{let a=s.body.readInt32BE(0);if(a===0)break;if(a===3)this.send("p",jt(t.password));else if(a===5){let l=Xa("md5").update(t.password+t.user).digest("hex"),d=Xa("md5").update(Buffer.concat([Buffer.from(l),s.body.subarray(4,8)])).digest("hex");this.send("p",jt(`md5${d}`))}else if(a===10){let l=VS(s.body,4);if(!l.includes("SCRAM-SHA-256"))throw new he(`the server asked for ${l.join(", ")||"a password exchange"}, which this client does not speak`);o=new Za(t.password);let d=Buffer.from(o.first(),"utf8"),c=Buffer.alloc(4);c.writeInt32BE(d.length,0),this.send("p",Buffer.concat([jt("SCRAM-SHA-256"),c,d]))}else if(a===11&&o)this.send("p",Buffer.from(o.final(s.body.toString("utf8",4)),"utf8"));else if(a===12&&o)o.verify(s.body.toString("utf8",4));else throw new he(`the server asked for an authentication method (${a}) this client does not speak`);break}case"E":throw new nt(Ya(s.body));case"Z":return;default:break}}}async query(t,n){this.send("Q",jt(t));let r=[],o,s=[],a=null,l=null;for(;;){let d=await this.reader.next();switch(d.type){case"T":r=[],o=zS(d.body);break;case"N":{let c=Ya(d.body);s.push(`${c.get("V")??c.get("S")??"NOTICE"}: ${c.get("M")??""}`);break}case"D":{let c=d.body.readInt16BE(0),i=[],p=2;for(let g=0;g<c;g++){let E=d.body.readInt32BE(p);p+=4,E<0?i.push(null):(i.push(d.body.toString("utf8",p,p+E)),p+=E)}r.push(i);break}case"C":a=d.body.toString("utf8",0,Math.max(0,d.body.indexOf(0)));break;case"E":l??=new nt(Ya(d.body));break;case"G":n===void 0?this.send("f",jt("there are no rows for this COPY: the lines after it, ending in \\., are what it reads")):(n.length>0&&this.send("d",Buffer.from(n,"utf8")),this.send("c",Buffer.alloc(0)));break;case"W":this.send("f",jt("COPY BOTH is not something a migration can do"));break;case"Z":if(l)throw l;return{rows:r,command:a,...o?{columns:o}:{},...s.length>0?{notices:s}:{}};default:break}}}close(){this.socket.destroyed||this.socket.end(rp("X",Buffer.alloc(0)))}};function ir(e,t,n=1){let r=[`${e.severity}: ${e.message}`];if(e.position!==void 0){let o=[...t].slice(0,e.position-1),s=o.filter(c=>c===`
|
|
582
862
|
`).length,a=t.split(`
|
|
583
|
-
`)[s]??"",
|
|
584
|
-
`)+1),
|
|
585
|
-
`)}var
|
|
586
|
-
`,o),
|
|
587
|
-
`,fe),
|
|
588
|
-
`)}
|
|
589
|
-
`||
|
|
590
|
-
`,o));continue}if(
|
|
591
|
-
`,o);n.push({line:s,text:e.slice(o,
|
|
863
|
+
`)[s]??"",l=o.length-(o.lastIndexOf(`
|
|
864
|
+
`)+1),d=`LINE ${n+s}: `;r.push(`${d}${a.replace(/\r$/,"")}`,`${" ".repeat(d.length+l)}^`)}return e.detail&&r.push(`DETAIL: ${e.detail}`),e.hint&&r.push(`HINT: ${e.hint}`),e.where&&r.push(`CONTEXT: ${e.where}`),r.join(`
|
|
865
|
+
`)}var QS=/[A-Za-z0-9_$\u0080-]/,ek=/[A-Za-z_\u0080-]/,tk=/^\$(?:[A-Za-z_\u0080-][A-Za-z0-9_\u0080-]*)?\$/;function nk(e){let t=ei(e);return/^\s*copy\b/i.test(t)&&/\bfrom\s+stdin\b/i.test(t)}function Jt(e){let t=ei(e).trim();if(/^rollback\s+(?:(?:work|transaction)\s+)?to\b/i.test(t))return null;let n=/^(commit|end|rollback|abort|prepare\s+transaction)\b/i.exec(t);return n?n[1].toUpperCase().replace(/\s+/," "):null}function ei(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," ")}function No(e){let t=[],n=[],r=e.length,o=0,s=1,a=-1,l=1,d=0,c=0,i=[],p=0,g=()=>{a<0&&(a=o,l=s)},E=()=>{a=-1,d=0,c=0,i=[],p=0},A=G=>{let se=Math.min(r,o+G);for(let ee=o;ee<se;ee++)e.charCodeAt(ee)===10&&s++;o=se},te=G=>A(G<0?r-o:G-o),U=null,B=()=>{let G=a>=0?e.slice(a,o).trim():"";if(ei(G).replace(/;/g,"").trim()!=="")if(!nk(G))t.push({sql:G,line:l});else{let se=e.indexOf(`
|
|
866
|
+
`,o),ee=[];if(se>=0){let fe=se+1,it=s+1;for(;fe<r;){let bt=e.indexOf(`
|
|
867
|
+
`,fe),Ye=e.slice(fe,bt<0?r:bt).replace(/\r$/,"");if(fe=bt<0?r:bt+1,it++,Ye==="\\.")break;ee.push(`${Ye}
|
|
868
|
+
`)}U={from:se+1,to:fe,line:it}}t.push({sql:G,line:l,copyData:ee.join("")})}E()};for(;o<r;){if(U&&o>=U.from){o=U.to,s=U.line,U=null;continue}let G=e[o],se=e[o+1];if(G===`
|
|
869
|
+
`||G===" "||G===" "||G==="\r"||G==="\f"||G==="\v"){A(1);continue}if(G==="-"&&se==="-"){te(e.indexOf(`
|
|
870
|
+
`,o));continue}if(G==="/"&&se==="*"){g();let ee=0;for(;o<r;)if(e[o]==="/"&&e[o+1]==="*")ee++,A(2);else if(e[o]==="*"&&e[o+1]==="/"){if(ee--,A(2),ee===0)break}else A(1);continue}if(G==="'"){g(),C(!1);continue}if(G==='"'){for(g(),A(1);;){let ee=e.indexOf('"',o);if(ee<0){te(-1);break}if(te(ee+1),e[o]==='"'){A(1);continue}break}continue}if(G==="$"){g();let ee=tk.exec(e.slice(o,o+64))?.[0];if(ee){A(ee.length);let fe=e.indexOf(ee,o);te(fe<0?-1:fe+ee.length)}else A(1);continue}if(G==="\\"){let ee=e.indexOf(`
|
|
871
|
+
`,o);n.push({line:s,text:e.slice(o,ee<0?r:ee).replace(/\r$/,"").trimEnd()}),te(ee);continue}if(G==="("){g(),d++,A(1);continue}if(G===")"){g(),d>0&&d--,A(1);continue}if(G===";"){g(),A(1),d===0&&c===0&&B();continue}if(ek.test(G)){g();let ee=o+1;for(;ee<r&&QS.test(e[ee]);)ee++;let fe=e.slice(o,ee);if(A(ee-o),e[o]==="'"){C(fe==="e"||fe==="E");continue}ue(fe.toLowerCase());continue}if(G>="0"&&G<="9"){g();let ee=o+1;for(;ee<r&&/[0-9A-Za-z_.]/.test(e[ee]);)ee++;A(ee-o);continue}g(),A(1)}return B(),{statements:t,metaCommands:n};function C(G){for(A(1);o<r;){let se=e[o];if(G&&se==="\\"){A(2);continue}if(se==="'"){if(A(1),e[o]==="'"){A(1);continue}return}A(1)}}function ue(G){p<4&&["create","function","procedure","or","replace"].includes(G)&&(i[p]=G[0]),p++,!(!(i[0]==="c"&&(i[1]==="f"||i[1]==="p"||i[1]==="o"&&i[2]==="r"&&(i[3]==="f"||i[3]==="p")))||d!==0)&&(G==="begin"?c++:G==="case"?c>=1&&c++:G==="end"&&c>0&&c--)}}function sp(e){let t=ck(process.cwd(),e);return t&&!t.startsWith("..")?t:e}var Io="_snoutdata_migrations",uk=`create table if not exists ${Io} (
|
|
592
872
|
name text primary key,
|
|
593
873
|
checksum text not null,
|
|
594
874
|
applied_at timestamptz not null default now()
|
|
595
|
-
);`;function
|
|
596
|
-
`);n.problems.every(o=>o.code==="psql-command"||o.code==="ends-transaction")&&
|
|
597
|
-
${r}`,{ref:e,problems:n.problems}),
|
|
598
|
-
${r}`,{ref:e,problems:n.problems})}
|
|
599
|
-
${n.error??""}`.trimEnd(),{ref:e,failed:n.failed})}return
|
|
600
|
-
`),(!n||!r)&&
|
|
875
|
+
);`;function pk(e){if(!ok(e)||!ik(e).isDirectory())throw new Error(`no migrations folder at ${sp(e)}. Put your .sql files there, or pass --dir.`);return sk(e).filter(t=>t.endsWith(".sql")).map(t=>{let n=ti(e,t),r=ak(n,"utf8");return{name:t,path:n,sql:r,checksum:rk("sha256").update(r,"utf8").digest("hex")}})}var mk={connection:e=>Me(e),open:e=>bn.open(e)};function ap(e,t){throw e instanceof he?new O("network",`Could not reach ${t}'s database: ${e.message}.`):e instanceof nt?new O("failed",`${t}'s database refused the connection: ${e.message}`):e}async function ip(e,t,n){try{return await e.open(t)}catch(r){return ap(r,n)}}async function fk(e,t,n){let r=await ip(e,t,n);try{await r.query(uk);let{rows:o}=await r.query(`select name, checksum from ${Io};`);return o.map(([s,a])=>({name:s??"",checksum:a??""}))}catch(o){if(o instanceof nt)throw new O("failed",`Could not read ${Io} on ${n}: ${o.message}`);return ap(o,n)}finally{r.close()}}async function gk(e,t,n){for(let r of t)try{await e.query(r.sql,r.copyData)}catch(o){if(o instanceof nt)return`${r.line>0?`${n}:${r.line}: `:""}${ir(o,r.sql,r.line>0?r.line:1)}`;if(o instanceof he)return`the connection was lost: ${o.message}`;throw o}return null}function op(e){return`'${e.replace(/'/g,"''")}'`}async function lp(e,t={}){let n=await ni(e,t,r=>u(r));if(!n.ok){if(n.problems){let r=n.problems.map(o=>` ${o.reason}`).join(`
|
|
876
|
+
`);n.problems.every(o=>o.code==="psql-command"||o.code==="ends-transaction")&&Q("failed",`Refused, and nothing ran:
|
|
877
|
+
${r}`,{ref:e,problems:n.problems}),Q("conflict",`Refused. This folder and ${e} do not agree:
|
|
878
|
+
${r}`,{ref:e,problems:n.problems})}Q("failed",`${n.failed} failed, and nothing after it was tried.
|
|
879
|
+
${n.error??""}`.trimEnd(),{ref:e,failed:n.failed})}return w(n,()=>{if(n.wouldApply){u(`Would apply ${n.wouldApply.length} migration${n.wouldApply.length===1?"":"s"} to ${e}:`);for(let r of n.wouldApply)u(` ${r}`);return}if(n.upToDate){u(`${e} is up to date.`);return}u(`Applied ${n.applied.length} migration${n.applied.length===1?"":"s"} to ${e}.`)}),0}async function ni(e,t={},n=()=>{},r=mk){let o=dk(t.dir===void 0?ti(process.cwd(),"migrations"):lk(t.dir)?t.dir:ti(process.cwd(),t.dir)),s=[];function a(C){s.push(C),n(C)}let l=pk(o);if(l.length===0)return a(`No .sql files in ${sp(o)}.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};let d=await r.connection(e),c={host:d.host,port:d.port,database:d.database,user:d.user,password:d.password,ssl:d.ssl};d.wakesInstantly||a("This project is paused; the connection will wake it, which takes a few seconds.");let i=await fk(r,c,e),p=To(l,i,{outOfOrder:t.outOfOrder});if(!p.ok)return{ref:e,directory:o,ok:!1,applied:[],problems:[...p.problems],notes:s};let g=new Map(l.map(C=>[C.name,C])),E=p.pending.map(C=>g.get(C.name)),A=new Map(E.map(C=>[C.name,No(C.sql)])),te=E.flatMap(C=>A.get(C.name).metaCommands.map(ue=>({code:"psql-command",name:C.name,reason:`${C.name} line ${ue.line} is a psql command (${ue.text.length>60?`${ue.text.slice(0,57)}...`:ue.text}), which only psql runs. db push sends SQL to the database itself, so put the SQL it stands for in the file instead.`}))),U=E.filter(C=>Dt(C.sql)).flatMap(C=>A.get(C.name).statements.flatMap(ue=>{let G=Jt(ue.sql);return G?[{code:"ends-transaction",name:C.name,reason:`${C.name} line ${ue.line} ends the transaction itself (${G}). db push already runs each file in one transaction and records it there, so a ${G} would keep what ran before it if a later statement failed. Take it out, or put -- snoutdata:no-transaction at the top of the file to run it exactly as written.`}]:[]}));if(te.length>0||U.length>0)return{ref:e,directory:o,ok:!1,applied:[],problems:[...te,...U],notes:s};if(E.length===0)return a(`${e} is up to date: ${i.length} migration${i.length===1?"":"s"} already applied.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};if(t.dryRun){for(let C of E)Dt(C.sql)||a(`${C.name} would run outside a transaction.`);return{ref:e,directory:o,ok:!0,applied:[],wouldApply:E.map(C=>C.name),notes:s}}let B=[];for(let C of E){let ue=`insert into ${Io} (name, checksum) values (${op(C.name)}, ${op(C.checksum)});`,G=Dt(C.sql);G||a(`${C.name} runs outside a transaction, so an interruption can leave it half applied.`);let se=[...G?[{sql:"begin;",line:0}]:[],...A.get(C.name).statements,{sql:ue,line:0},...G?[{sql:"commit;",line:0}]:[]],ee=await ip(r,c,e),fe;try{fe=await gk(ee,se,C.name)}finally{ee.close()}if(fe!==null)return G&&(a("It ran inside a transaction, so nothing from it is in the database."),/cannot run inside a transaction block/i.test(fe)&&a("Put -- snoutdata:no-transaction at the top of the file to run it outside one.")),{ref:e,directory:o,ok:!1,applied:B,failed:C.name,error:fe,notes:s};B.push(C.name),a(` applied ${C.name}`)}return{ref:e,directory:o,ok:!0,applied:B,notes:s}}me();ve();pe();import{readFile as cp}from"node:fs/promises";function ri(e){if(e==="apns"||e==="fcm")return e;throw new y("say which: apns (an Apple .p8) or fcm (a Firebase service account)")}async function hk(e){let t=await T("cloud-project-push",{ref:e,credentials:{list:!0}});return{ref:e,credentials:t??{}}}async function dp(e){if(!e.p8||!e.keyId||!e.teamId||!e.topic)throw new y("push credentials set apns needs --p8 AuthKey.p8 --key-id ID --team-id ID --topic com.example.app");if(e.environment!==void 0&&e.environment!=="production"&&e.environment!=="sandbox")throw new y("--environment is production or sandbox; leave it out for a key that serves both");return{topic:e.topic,keys:[{p8:await cp(e.p8,"utf8"),key_id:e.keyId,team_id:e.teamId,environment:e.environment??null}]}}async function up(e){if(!e)throw new y("push credentials set fcm needs --file service-account.json");return{service_account:await cp(e,"utf8")}}async function yk(e,t,n){let r=await T("cloud-project-push",{ref:e,credentials:{set:{kind:t,body:n}}});return{ref:e,kind:t,summary:r}}async function wk(e,t){return await T("cloud-project-push",{ref:e,credentials:{remove:t}}),{ref:e,kind:t,removed:!0}}async function pp(e){let t=await hk(e);w(t,()=>{let{apns:n,fcm:r,vapid:o}=t.credentials;process.stdout.write(`${V([["TRANSPORT","SET",""],["web push",o?"yes":"starting",o?.public_key?`public key ${o.public_key.slice(0,16)}\u2026`:""],["apns",n?"yes":"no",n?`${n.topic}, key ${n.keys?.map(s=>s.key_id).join(", ")}`:""],["fcm",r?"yes":"no",r?`${r.project_id} as ${r.client_email}`:""]])}
|
|
880
|
+
`),(!n||!r)&&u($(` snoutdata push credentials set ${n?"fcm --file service-account.json":"apns --p8 AuthKey.p8 --key-id ID --team-id ID --topic com.example.app"} --ref ${e}`))})}async function mp(e,t,n){let r=await yk(e,t,n);w(r,()=>u(`${t==="apns"?"The Apple key signed":"Google accepted the service account"}, and it is stored in the project's own database.`))}async function fp(e,t){let n=await wk(e,t);w(n,()=>u(`${t} credentials removed. Devices on it stop receiving until new ones are set.`))}me();_e();pe();import{spawn as Nk}from"node:child_process";import{writeFileSync as Ik}from"node:fs";import{isAbsolute as Ck,resolve as Lk}from"node:path";var Sk=" ";function re(e){return Sk.repeat(e)}function De(e){return JSON.stringify(e)}function ft(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:De(e)}function Vt(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function kk(e){let t=(e??"").trim(),n=!1;for(;t.endsWith("[]");)n=!0,t=t.slice(0,-2).trim();t.startsWith("_")&&t.length>1&&(n=!0,t=t.slice(1));let r=t.indexOf("(");return r>0&&(t=t.slice(0,r)),{base:t.trim().toLowerCase(),array:n}}var _k={smallint:"number",int2:"number",integer:"number",int:"number",int4:"number",bigint:"number",int8:"number",decimal:"number",numeric:"number",number:"number",real:"number",float:"number",float4:"number",float8:"number","double precision":"number",double:"number",binary_float:"number",binary_double:"number",smallserial:"number",serial:"number",bigserial:"number",oid:"number",smallmoney:"number",money:"number",bool:"boolean",boolean:"boolean",json:"json",jsonb:"json",variant:"json",object:"json",char:"string",character:"string","character varying":"string",varchar:"string",varchar2:"string",nvarchar:"string",nvarchar2:"string",nchar:"string",text:"string",ntext:"string",citext:"string",clob:"string",nclob:"string",longtext:"string",mediumtext:"string",tinytext:"string",uuid:"string",uniqueidentifier:"string",date:"string",time:"string","time without time zone":"string","time with time zone":"string",timetz:"string",timestamp:"string","timestamp without time zone":"string","timestamp with time zone":"string",timestamptz:"string",datetime:"string",datetime2:"string",datetimeoffset:"string",smalldatetime:"string",timestamp_ntz:"string",timestamp_ltz:"string",timestamp_tz:"string",interval:"string",year:"string",bytea:"string",blob:"string",longblob:"string",mediumblob:"string",tinyblob:"string",binary:"string",varbinary:"string",raw:"string",xml:"string",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",tsvector:"string",tsquery:"string",name:"string",bit:"string",varbit:"string",tinyint:"number",enum:"string",set:"string"},$k={sqlserver:{bit:"boolean"},"mysql-aurora":{bit:"number"},mariadb:{bit:"number"},sqlite:{bit:"number"},snowflake:{array:"json"}};function vk(e,t){let n=$k[e]?.[t];return n||(_k[t]??"unknown")}function Co(e,t){let{base:n,array:r}=kk(t),o=e.enumRefs.get(n);if(o)return r?`${o}[]`:o;if(n==="array")return"unknown[]";let s=vk(e.driverId,n),a=s==="json"?"Json":s;return r?`${a}[]`:a}function Pk(e){return e.nullable||e.autoIncrement===!0||e.default!==null&&e.default!==void 0}function oi(e,t,n,r,o=!1){if(o&&t.generatedAlways===!0)return`${re(n)}${ft(t.name)}?: never`;let s=Co(e,t.dataType),a=t.nullable?`${s} | null`:s;return`${re(n)}${ft(t.name)}${r?"?":""}: ${a}`}function xk(e,t){let n=[...t.columns].sort(),r=o=>{let s=[...o].sort();return s.length===n.length&&s.every((a,l)=>a===n[l])};return e.primaryKey.length>0&&r(e.primaryKey)?!0:(e.indexes??[]).some(o=>o.unique&&r(o.columns))}function Ek(e,t){let n=[],r=[...e.foreignKeys].sort((o,s)=>o.constraintName<s.constraintName?-1:o.constraintName>s.constraintName?1:0);if(r.length===0)return n.push(`${re(t)}Relationships: []`),n;n.push(`${re(t)}Relationships: [`);for(let o of r)n.push(`${re(t+1)}{`),n.push(`${re(t+2)}foreignKeyName: ${De(o.constraintName)}`),n.push(`${re(t+2)}columns: [${o.columns.map(De).join(", ")}]`),n.push(`${re(t+2)}isOneToOne: ${xk(e,o)?"true":"false"}`),n.push(`${re(t+2)}referencedRelation: ${De(o.referencedTable)}`),n.push(`${re(t+2)}referencedColumns: [${o.referencedColumns.map(De).join(", ")}]`),n.push(`${re(t+1)}},`);return n.push(`${re(t)}]`),n}function gp(e,t,n){let r=Vt(t.columns),o=[];o.push(`${re(n)}${ft(t.name)}: {`),o.push(`${re(n+1)}Row: {`);for(let s of r)o.push(oi(e,s,n+2,!1));if(o.push(`${re(n+1)}}`),t.kind!=="view"){o.push(`${re(n+1)}Insert: {`);for(let s of r)o.push(oi(e,s,n+2,Pk(s),!0));o.push(`${re(n+1)}}`),o.push(`${re(n+1)}Update: {`);for(let s of r)o.push(oi(e,s,n+2,!0,!0));o.push(`${re(n+1)}}`)}return o.push(...Ek(t,n+1)),o.push(`${re(n)}}`),o}function lr(e,t){return[`${re(t)}${e}: {`,`${re(t+1)}[_ in never]: never`,`${re(t)}}`]}function Ak(e,t){if(t.kind==="procedure"||!t.returnType)return"undefined";let n=t.returnType.trim(),r=n.toLowerCase();if(r==="void"||r==="")return"undefined";if(r.startsWith("table("))return"Record<string, unknown>[]";if(r.startsWith("setof ")){let s=n.slice(6).trim();if(s.toLowerCase()==="record")return"Record<string, unknown>[]";let a=e.rowRefs.get(s.toLowerCase());return a?`${a}[]`:`${Co(e,s)}[]`}return r==="record"||r==="trigger"||r==="event_trigger"?"unknown":e.rowRefs.get(r)??Co(e,n)}function Rk(e,t,n){let r=[],o=Vt((t.parameters??[]).filter(s=>s.name.length>0&&(s.mode??"IN").toUpperCase()!=="OUT").map(s=>({name:s.name,dataType:s.dataType})));if(r.push(`${re(n)}${ft(t.name)}: {`),o.length===0)r.push(`${re(n+1)}Args: never`);else{r.push(`${re(n+1)}Args: {`);for(let s of o)r.push(`${re(n+2)}${ft(s.name)}: ${Co(e,s.dataType)}`);r.push(`${re(n+1)}}`)}return r.push(`${re(n+1)}Returns: ${Ak(e,t)}`),r.push(`${re(n)}}`),r}function Sn(e,t){return e.schema&&e.schema.length>0?e.schema:t}function hp(e,t={}){let n=t.defaultSchema??"public",r=t.driverId??"postgres",o=t.enums??[],s=new Map;for(let p of o){let g=p.schema&&p.schema.length>0?p.schema:n;s.set(p.name.toLowerCase(),`Database[${De(g)}][${De("Enums")}][${De(p.name)}]`)}let a=new Map;for(let p of e.tables){let g=Sn(p,n),E=p.kind==="view"?"Views":"Tables";a.set(p.name.toLowerCase(),`Database[${De(g)}][${De(E)}][${De(p.name)}][${De("Row")}]`)}let l={driverId:r,defaultSchema:n,enumRefs:s,rowRefs:a},d=new Set([n]);for(let p of e.tables)d.add(Sn(p,n));for(let p of e.routines??[])d.add(Sn(p,n));for(let p of o)d.add(p.schema&&p.schema.length>0?p.schema:n);let c=[...d].sort(),i=[];i.push("export type Json ="),i.push(" | string"),i.push(" | number"),i.push(" | boolean"),i.push(" | null"),i.push(" | { [key: string]: Json | undefined }"),i.push(" | Json[]"),i.push(""),i.push("export type Database = {");for(let p of c){let g=Vt(e.tables.filter(U=>Sn(U,n)===p&&U.kind!=="view")),E=Vt(e.tables.filter(U=>Sn(U,n)===p&&U.kind==="view")),A=Vt((e.routines??[]).filter(U=>Sn(U,n)===p)),te=Vt(o.filter(U=>(U.schema&&U.schema.length>0?U.schema:n)===p));if(i.push(`${re(1)}${ft(p)}: {`),g.length===0)i.push(...lr("Tables",2));else{i.push(`${re(2)}Tables: {`);for(let U of g)i.push(...gp(l,U,3));i.push(`${re(2)}}`)}if(E.length===0)i.push(...lr("Views",2));else{i.push(`${re(2)}Views: {`);for(let U of E)i.push(...gp(l,U,3));i.push(`${re(2)}}`)}if(A.length===0)i.push(...lr("Functions",2));else{i.push(`${re(2)}Functions: {`);for(let U of A)i.push(...Rk(l,U,3));i.push(`${re(2)}}`)}if(te.length===0)i.push(...lr("Enums",2));else{i.push(`${re(2)}Enums: {`);for(let U of te)i.push(`${re(3)}${ft(U.name)}: ${U.values.map(De).join(" | ")}`);i.push(`${re(2)}}`)}i.push(...lr("CompositeTypes",2)),i.push(`${re(1)}}`)}return i.push("}"),t.helpers!==!1&&(i.push(""),i.push(Ok(n))),t.constants!==!1&&(i.push(""),i.push(Tk(c,o,n))),`${i.join(`
|
|
601
881
|
`)}
|
|
602
|
-
`}function
|
|
603
|
-
`)}function
|
|
882
|
+
`}function Tk(e,t,n){let r=["export const Constants = {"];for(let o of e){let s=Vt(t.filter(a=>(a.schema&&a.schema.length>0?a.schema:n)===o));if(s.length===0){r.push(`${re(1)}${ft(o)}: {`),r.push(`${re(2)}Enums: {},`),r.push(`${re(1)}},`);continue}r.push(`${re(1)}${ft(o)}: {`),r.push(`${re(2)}Enums: {`);for(let a of s)r.push(`${re(3)}${ft(a.name)}: [${a.values.map(De).join(", ")}],`);r.push(`${re(2)}},`),r.push(`${re(1)}},`)}return r.push("} as const"),r.join(`
|
|
883
|
+
`)}function Ok(e){return`type DefaultSchemaName = Extract<keyof Database, ${De(e)}>
|
|
604
884
|
|
|
605
885
|
type InSchema = { schema: keyof Database }
|
|
606
886
|
|
|
@@ -637,7 +917,7 @@ export type Enums<
|
|
|
637
917
|
export type CompositeTypes<
|
|
638
918
|
Choice extends keyof Database[DefaultSchemaName]["CompositeTypes"] | InSchema,
|
|
639
919
|
Name extends Choice extends InSchema ? keyof Database[Choice["schema"]]["CompositeTypes"] : never = never,
|
|
640
|
-
> = Lookup<Database[SchemaOf<Choice>]["CompositeTypes"], NameOf<Choice, Name>>`}function
|
|
920
|
+
> = Lookup<Database[SchemaOf<Choice>]["CompositeTypes"], NameOf<Choice, Name>>`}function Mk(e){let t=rr(e.ssl);return{host:e.host,port:e.port,database:e.database,user:e.user,password:e.password,sslMode:t.mode,...t.rootCert?{sslRootCert:t.rootCert}:{},label:e.ref}}function Lo(e){let t;try{t=new URL(e)}catch{throw new Error(`--db-url is not a URL: ${e}`)}if(t.protocol!=="postgres:"&&t.protocol!=="postgresql:")throw new Error(`--db-url must be a postgres:// URL, not ${t.protocol}//`);let n=decodeURIComponent(t.pathname.replace(/^\//,""));if(!n)throw new Error("--db-url has no database name in its path");let r=t.searchParams.get("sslmode")??"prefer";return{host:t.hostname||"127.0.0.1",port:t.port?Number(t.port):5432,database:n,user:decodeURIComponent(t.username)||"postgres",password:decodeURIComponent(t.password),sslMode:r,label:`${t.hostname||"127.0.0.1"}/${n}`}}function si(e,t){return new Promise(n=>{let r=Nk("psql",["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database,"--no-psqlrc","-v","ON_ERROR_STOP=1","-tA"],{stdio:["pipe","pipe","pipe"],env:{...process.env,PGPASSWORD:e.password,PGSSLMODE:e.sslMode,...e.sslRootCert?{PGSSLROOTCERT:e.sslRootCert}:{}}}),o="",s="";r.stdout.on("data",a=>o+=String(a)),r.stderr.on("data",a=>s+=String(a)),r.on("error",a=>{n({code:127,out:"",err:a.code==="ENOENT"?"psql is not installed, and gen types needs it to read the schema. `snoutdata db url` prints a connection string for any client.":String(a)})}),r.on("close",a=>n({code:a??0,out:o,err:s})),r.stdin.end(t)})}var Dk=`
|
|
641
921
|
with wanted as (select unnest($SCHEMAS$::text[]) as nspname)
|
|
642
922
|
select json_build_object(
|
|
643
923
|
'tables', coalesce((
|
|
@@ -741,48 +1021,93 @@ select json_build_object(
|
|
|
741
1021
|
where t.typtype = 'e' and n.nspname in (select nspname from wanted)
|
|
742
1022
|
), '[]'::json)
|
|
743
1023
|
)::text
|
|
744
|
-
`;function
|
|
1024
|
+
`;function jk(e){return`'{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",").replace(/'/g,"''")}}'`}function Uk(e,t,n=0){let r=e.tables.map(a=>{let l=a.primaryKey??[],d=new Set(l),c=a.columns.map(i=>({name:i.name,dataType:i.dataType,nullable:i.nullable,isPrimaryKey:d.has(i.name),default:i.default,autoIncrement:i.autoIncrement,...i.generatedAlways===!0?{generatedAlways:!0}:{}}));return{name:a.name,schema:a.schema,kind:a.kind,columns:c,primaryKey:l,foreignKeys:(a.foreignKeys??[]).map(i=>({constraintName:i.constraintName,columns:i.columns??[],referencedTable:i.referencedTable,referencedColumns:i.referencedColumns??[]})),indexes:(a.indexes??[]).filter(i=>Array.isArray(i.columns)&&i.columns.every(p=>typeof p=="string")).map(i=>({name:i.name,unique:i.unique,columns:i.columns??[]}))}}),o=e.routines.map(a=>({name:a.name,schema:a.schema,kind:a.kind,returnType:a.returnType??void 0,parameters:(a.parameters??[]).map(l=>({name:l.name,dataType:l.dataType,mode:l.mode}))})),s=e.enums.map(a=>({name:a.name,schema:a.schema,values:a.values??[]}));return{schema:{database:t,tables:r,routines:o,fetchedAt:n},enums:s}}var Fk=`select exists (
|
|
745
1025
|
select from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
746
1026
|
where n.nspname = 'lepis' and c.relname = 'relation'
|
|
747
|
-
)::text`,
|
|
1027
|
+
)::text`,Bk=`select coalesce(json_agg(json_build_object(
|
|
748
1028
|
'schema', schema_name, 'table', table_name, 'kind', kind, 'keyColumn', key_column
|
|
749
|
-
) order by schema_name, table_name), '[]'::json)::text from lepis.relation`;function
|
|
750
|
-
`,{encoding:"utf8",mode:384}),n}var
|
|
751
|
-
`).map(
|
|
752
|
-
${
|
|
753
|
-
`)}`,{problems:
|
|
754
|
-
${
|
|
755
|
-
${
|
|
1029
|
+
) order by schema_name, table_name), '[]'::json)::text from lepis.relation`;function Hk(e){let t=[];for(let n of e.split(/\r?\n/)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{return null}}return t.length===0?null:Gk(t)}function Gk(e){let t=(n,r)=>{let o=new Set,s=[];for(let a of n)for(let l of a??[]){let d=r(l);o.has(d)||(o.add(d),s.push(l))}return s};return{tables:t(e.map(n=>n.tables),n=>`${n.schema}.${n.name}`),routines:t(e.map(n=>n.routines),n=>`${n.schema}.${n.name}(${(n.parameters??[]).map(r=>`${r.mode} ${r.dataType}`).join(",")})`),enums:t(e.map(n=>n.enums),n=>`${n.schema}.${n.name}`)}}async function qk(e,t){let n=await e(Fk);if(n.code!==0||n.out.trim()!=="true")return[];let r=await e(Bk);if(r.code!==0)return[];try{let o=JSON.parse(r.out.trim()),s=new Set(t);return o.filter(a=>s.has(a.schema)).map(a=>({schema:a.schema,table:a.table,kind:a.kind,keyColumn:a.keyColumn??null}))}catch{return[]}}async function Kk(e){let t=e.schemas&&e.schemas.length>0?[...e.schemas]:["public"],n=e.dbUrl?Lo(e.dbUrl):Mk(await Me(zk(e))),r=!1,o=async A=>{if(e.sql)return e.sql(A);if(r&&e.ref)return yp(e.ref,A);let te=await si(n,A);return te.code===127&&!e.dbUrl&&e.ref?(r=!0,yp(e.ref,A)):te},s=Dk.replace("$SCHEMAS$",jk(t)),a=await o(s);a.code===127&&Q("tool-missing",a.err.trim()),a.code!==0&&Q("failed",a.err.trim()||`could not read the schema of ${n.label}`);let l=a.out.trim();l||Q("failed",`${n.label} returned nothing for the schema query`);let d=Hk(l);d||Q("failed",`could not read the schema of ${n.label}: the answer was not JSON`);let c=await qk(o,t),{schema:i,enums:p}=Uk(d,n.database,Date.now()),g=hp(i,{driverId:"postgres",defaultSchema:e.defaultSchema??t[0]??"public",enums:p}),E=null;return e.out&&(E=Ck(e.out)?e.out:Lk(process.cwd(),e.out),Ik(E,g,"utf8")),{target:n.label,schemas:t,tables:i.tables.filter(A=>A.kind!=="view").length,views:i.tables.filter(A=>A.kind==="view").length,functions:(i.routines??[]).length,enums:p.length,path:E,distribution:c,types:g}}async function yp(e,t,n=T){try{let r=await n("cloud-project-sql",{ref:e,sql:t});if(r.error)return{code:1,out:"",err:r.error};let o=Object.values(r.rows?.[0]??{})[0];return{code:0,out:typeof o=="string"?o:o==null?"":JSON.stringify(o),err:""}}catch(r){return{code:1,out:"",err:r instanceof Error?r.message:String(r)}}}function zk(e){if(!e.ref)throw new Error("no project: pass --ref, --db-url, set SNOUTDATA_PROJECT, or run `snoutdata link --ref <ref>`");return e.ref}async function wp(e,t){let n=(e??"typescript").toLowerCase();n!=="typescript"&&n!=="ts"&&Q("usage",`gen types does not know how to write ${e}. It writes typescript, which is the only language it claims.`);let r=await Kk(t);return r.path&&u(`Wrote ${r.tables} table${r.tables===1?"":"s"}, ${r.views} view${r.views===1?"":"s"}, ${r.functions} function${r.functions===1?"":"s"} and ${r.enums} enum${r.enums===1?"":"s"} to ${r.path}.`),w(r,()=>{r.path||process.stdout.write(r.types)}),0}_e();import{createHash as rv}from"node:crypto";import{existsSync as il,mkdirSync as ov,readFileSync as ll,readdirSync as sv,statSync as av,writeFileSync as iv}from"node:fs";import{dirname as lv,isAbsolute as pg,join as kr,resolve as mg}from"node:path";import{pathToFileURL as cv}from"node:url";pe();function dv(e){return/^[a-z][a-z0-9+.-]+:/i.test(e)?e:pg(e)||e.startsWith("./")||e.startsWith("../")?cv(mg(e)).href:e}function uv(){let e=process.env.SNOUTDATA_LOCAL_RUNTIME;return e?import(dv(e)):Promise.resolve().then(()=>(lg(),ig))}function pv(e){let t=e instanceof Error?e.message:String(e),n=process.env.SNOUTDATA_LOCAL_RUNTIME;return n?`SNOUTDATA_LOCAL_RUNTIME points at ${n}, and it could not be loaded: ${t}`:`this build of the CLI has no local pod runtime in it, so \`snoutdata start\` cannot run. That is a packaging fault rather than anything you did: please report it. (${t})`}var cg="It is fetched from ghcr.io/snoutdata/snoutpod-postgres on the first `snoutdata start`, so this usually means that registry could not be reached from here.";async function dg(e,t){try{return await e.localImageFor(t)}catch(n){return n instanceof Error?n.message:String(n)}}async function _r(){let e;try{e=await uv()}catch(t){Q("tool-missing",pv(t))}return{ready:async t=>{let n=await dg(e,t);return typeof n=="string"?await e.podmanReady(cg)??n:e.podmanReady(cg,n.name)},ensureImage:async(t,n)=>{let r=await dg(e,t);return typeof r=="string"?r:e.ensureImage(n,void 0,r)},prepare:()=>e.ensureNetwork(),start:(t,n)=>e.startLocal(e.localRuntime(),t,{onProgress:n}),stop:t=>e.stopLocal(e.localRuntime(),t),status:t=>e.localStatus(e.localRuntime(),t),remove:(t,n)=>e.removeLocal(e.localRuntime(),t,n),uri:t=>e.localUri(t),psql:async(t,n)=>{let r=await e.localPsql(t,n);return{code:r.code,out:r.stdout,err:r.stderr}},mint:t=>({ref:e.newLocalRef(),port:t,ownerPassword:e.newLocalPassword(),adminPassword:e.newLocalPassword()})}}function fg(e){return kr(e,".snoutdata","local.json")}function hs(e){let t=fg(e);if(!il(t))return null;try{let n=JSON.parse(ll(t,"utf8"));return!n.ref||!n.port||!n.ownerPassword||!n.adminPassword?null:{ref:n.ref,port:n.port,ownerPassword:n.ownerPassword,adminPassword:n.adminPassword}}catch{return null}}function mv(e,t){let n=fg(e);return ov(lv(n),{recursive:!0}),iv(n,`${JSON.stringify(t,null,2)}
|
|
1030
|
+
`,{encoding:"utf8",mode:384}),n}var fv=54322;async function gg(e,t){let n=await e.ensureImage(t,o=>u(o));n&&Q("tool-missing",n);let r=await e.ready(t);r&&Q("tool-missing",r),await e.prepare()}function hg(e,t,n,r=si){let o=!1;return async s=>{if(o)return e.psql(t,s);let a=await r(n,s);return a.code!==127?a:(o=!0,e.psql(t,s))}}async function gv(e,t={}){let n=t.cwd??process.cwd(),r=hs(n);await gg(e,r?.ref??null);let o=r??e.mint(t.port??fv),s=r?null:mv(n,o),a=await e.start(o,p=>u(p)),l=e.uri(o);if(t.noMigrations)return{status:a,uri:l,applied:[],seeded:!1,created:s};let d=hg(e,o,Lo(l)),c=await hv(d,n,t),i=await yv(d,n,c.length>0||!!s);return{status:a,uri:l,applied:c,seeded:i,created:s}}async function hv(e,t,n){let r=mg(n.dir===void 0?kr(t,"migrations"):pg(n.dir)?n.dir:kr(t,n.dir));if(!il(r)||!av(r).isDirectory())return[];let o=sv(r).filter(p=>p.endsWith(".sql")).map(p=>{let g=ll(kr(r,p),"utf8");return{name:p,sql:g,checksum:rv("sha256").update(g,"utf8").digest("hex")}});if(o.length===0)return[];let s=await e(wv);s.code!==0&&Q(s.code===127?"tool-missing":"failed",s.err.trim()||`could not create ${Sr}`);let a=await e(`select name || E'\\t' || checksum from ${Sr};`);a.code!==0&&Q("failed",a.err.trim()||`could not read ${Sr}`);let l=a.out.split(`
|
|
1031
|
+
`).map(p=>p.trim()).filter(p=>p.length>0).map(p=>{let g=p.indexOf(" ");return{name:p.slice(0,g),checksum:p.slice(g+1)}}),d=To(o,l,{outOfOrder:n.outOfOrder});d.ok||Q("conflict",`Refused. This folder and the local database do not agree:
|
|
1032
|
+
${d.problems.map(p=>` ${p.reason}`).join(`
|
|
1033
|
+
`)}`,{problems:d.problems});let c=new Map(o.map(p=>[p.name,p])),i=[];for(let p of d.pending){let g=c.get(p.name),E=`insert into ${Sr} (name, checksum) values (${ug(g.name)}, ${ug(g.checksum)});`,A=Dt(g.sql);A||u(`${g.name} runs outside a transaction, so an interruption can leave it half applied.`);let te=A?`begin;
|
|
1034
|
+
${g.sql}
|
|
1035
|
+
${E}
|
|
756
1036
|
commit;
|
|
757
|
-
`:`${
|
|
758
|
-
${
|
|
759
|
-
`,
|
|
760
|
-
${
|
|
761
|
-
${o.err.trim()}`),
|
|
1037
|
+
`:`${g.sql}
|
|
1038
|
+
${E}
|
|
1039
|
+
`,U=await e(te);U.code!==0&&Q("failed",`${g.name} failed, and nothing after it was tried.
|
|
1040
|
+
${U.err.trim()}`,{failed:g.name,applied:i}),i.push(g.name),u(` applied ${g.name}`)}return i}async function yv(e,t,n){let r=kr(t,"seed.sql");if(!n||!il(r))return!1;let o=await e(ll(r,"utf8"));return o.code!==0&&Q("failed",`seed.sql failed.
|
|
1041
|
+
${o.err.trim()}`),u(" ran seed.sql"),!0}var Sr="_snoutdata_migrations",wv=`create table if not exists ${Sr} (
|
|
762
1042
|
name text primary key,
|
|
763
1043
|
checksum text not null,
|
|
764
1044
|
applied_at timestamptz not null default now()
|
|
765
|
-
);`;function
|
|
766
|
-
`),
|
|
767
|
-
`)}),0}async function
|
|
1045
|
+
);`;function ug(e){return`'${e.replace(/'/g,"''")}'`}function bv(e){if(e===null)return"unknown";let t=["B","kB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10&&r>0?n.toFixed(1):Math.round(n)} ${t[r]}`}async function yg(e,t={}){let n=await gv(e,t);return w(n,()=>{n.created&&(u(""),u(`Wrote ${n.created}. It holds a password, so put .snoutdata/ in your .gitignore.`)),u(""),u(` ${N("Database")} running on port ${n.status.port}`),n.applied.length>0&&u(` ${N("Migrations")} ${n.applied.length} applied`),n.seeded&&u(` ${N("Seed")} seed.sql ran`),u(""),process.stdout.write(`${n.uri}
|
|
1046
|
+
`),u($(" snoutdata gen types typescript --local > database.types.ts")),u($(" snoutdata stop"))}),0}async function wg(e,t={}){let n=t.cwd??process.cwd(),r=hs(n);r||Q("not-found","there is no local database for this folder. `snoutdata start` makes one."),await gg(e,r.ref);let o=await e.stop(r.ref);return w(o,()=>u("Stopped. The data is still there; `snoutdata start` brings it back.")),0}async function bg(e,t={}){let n=t.cwd??process.cwd(),r=hs(n);if(!r)return w({exists:!1,ref:null,status:"absent"},()=>u("No local database for this folder. `snoutdata start` makes one.")),0;let o=await e.ready(r.ref);if(o)return w({exists:!1,ref:r.ref,status:"unknown",reason:o},()=>u(o)),0;let s=await e.status(r);return w({...s,uri:s.uri},()=>{u(` ${N("Project")} ${s.ref}`),u(` ${N("State")} ${s.ready?"running":s.status}`),u(` ${N("Port")} ${s.port}`),u(` ${N("Size")} ${bv(s.databaseBytes)}`),s.services.length>0&&u(` ${N("Services")} ${s.services.join(", ")}`),s.uri&&process.stdout.write(`${s.uri}
|
|
1047
|
+
`)}),0}async function Sg(e,t=process.cwd()){let n=hs(t);n||Q("not-found","there is no local database for this folder. `snoutdata start` makes one.");let r=e.uri(n);return{dbUrl:r,sql:hg(e,n,Lo(r))}}me();pe();Br();jn();Ot();import{resolve as kg}from"node:path";function Sv(){let e=n=>Pt(n),t;return{shards:n=>{if(n!==void 0)return Zn({project:n});if(!process.env.LEPIS_ADMIN_URL)throw new Error("The cluster tools need a cluster: pass project (a SnoutData Cloud project's ref, from list_projects), or start snoutdata mcp with LEPIS_ADMIN_URL (a standalone router's admin API, e.g. http://127.0.0.1:7432) and LEPIS_ADMIN_TOKEN set.");return t??=Zn({}),t},whoami:()=>Kt(),listProjects:async()=>({...await Qe(),local:kv()}),localProject:n=>e(n),createProject:async n=>{let r=await T("cloud-project-create",{name:n.name,...n.region?{region:n.region}:{},...n.teamId?{teamId:n.teamId}:{}});try{return await Wn(r.project.ref)}catch{return{...r.project,ready:!1,note:`${r.project.ref} was created and is still starting. It was not ready within the wait. Call list_projects in a few seconds; do not connect to it yet.`}}},usage:(n,r)=>T("cloud-project-usage",{ref:n,...r?{days:r}:{}}),exportStatus:n=>mn(n),requestExport:n=>Kn(n),resetPassword:(n,r)=>T("cloud-project-reset-password",{ref:n,...r!==void 0?{graceMinutes:r}:{}}),listTeams:()=>T("cloud-team-list",{}),deployFunction:(n,r,o)=>{let s=e(n);return s?la(s,r,o):ga(n,r,o).then(a=>a.answer)},listFunctions:async n=>{let r=e(n);return r?ao(r):ha(n)},deleteFunction:(n,r)=>{let o=e(n);return o?da(o,r):ya(n,r)},sizeFunction:(n,r,o)=>wa(n,r,o),listFunctionSecrets:async n=>{let r=e(n);return r?lo(r):T("cloud-project-secrets",{ref:n})},functionLogs:(n,r)=>T("cloud-project-functions",{ref:n,action:"logs",...r.name?{name:r.name}:{},...r.errorsOnly?{errorsOnly:!0}:{},...r.limit?{limit:r.limit}:{}}),listContainers:n=>gn(n),deployContainer:(n,r,o)=>va(n,r,o),restartContainer:(n,r)=>xa(n,r),deleteContainer:(n,r)=>Pa(n,r),containerLogs:(n,r)=>uo(n,r),containerEgress:async n=>{let r=await gn(n);return{ref:r.ref,allowlist:r.allowlist??null}},setContainerEgress:async(n,r)=>{let o=await po(n,r);return{ref:o.ref,allowlist:o.allowlist??null,note:"Running containers follow it within a minute; nothing restarts."}},listTokens:()=>T("cloud-token-list",{}),createToken:(n,r,o)=>T("cloud-token-create",{name:n,...r?{expiresInDays:r}:{},...o?{project:o}:{}}),revokeToken:n=>T("cloud-token-revoke",{id:n}),getProject:async n=>{let r=e(n);return r?{ref:r.ref,name:r.name,local:r.folder,api:r.apiUrl,database:`127.0.0.1:${r.dbPort}`,functions:ao(r).functions.map(o=>o.name),secretNames:lo(r).secrets.map(o=>o.name)}:Ha(n)},getProducts:n=>yn(n),setProduct:(n,r,o)=>ja(n,r,o),listDomains:n=>bo(n),domainAction:(n,r,o)=>Ua(n,r,o),restoreWindow:n=>Fa(n),restoreTo:(n,r,o)=>Ba(n,r,o),setProjectState:async(n,r)=>{let o=await T(`cloud-project-${n}`,{ref:r});try{let s=await zn(r,n,{timeoutMs:12e4});return{changed:o.changed,state:s?.state??"deleted",...s?{project:s}:{}}}catch{return{...o,settled:!1,note:`${r} has not finished yet. Call list_projects in a few seconds.`}}},scaleProject:(n,r,o)=>T("cloud-project-spread",o?{ref:n,instances:r}:{ref:n,preview:!0,...r===void 0?{}:{instances:r}}),connection:n=>Me(n),pushMigrations:(n,r)=>ni(n,{dir:r.dir,dryRun:r.dryRun})}}function kv(){let e=Cr().filter(n=>n.ref!==null).map(n=>({ref:n.ref,name:n.name,folder:n.folder})),t=qt(process.cwd())?.local;if(t&&!e.some(n=>kg(n.folder)===kg(t)))try{let n=It(t);e.push({ref:n.ref,name:n.name,folder:n.folder})}catch{}return e}var _g="app_";async function _v(){if(process.env.SNOUTDATA_NO_DESKTOP)return{tools:[],config:null};let e=await Ur();if(!e.available)return{tools:[],config:null};let t=e.config;try{return{tools:(await Zl(t)).map(o=>({name:`${_g}${o.name}`,description:`[SnoutData Studio, on this machine] ${o.description??o.name}`,inputSchema:o.inputSchema??{type:"object",properties:{}}})),config:t}}catch{return{tools:[],config:null}}}async function $g(e){Gn(!0);let{tools:t,config:n}=await _v(),r=Sv();n&&(r.callBorrowed=(d,c)=>Ql(n,d.slice(_g.length),c));let o={...e,borrowed:t};ce(t.length>0?`snoutdata mcp: ${nr.length} cloud tools, and ${t.length} borrowed from SnoutData Studio on this machine.`:"snoutdata mcp: cloud tools only. SnoutData Studio is not answering here, so its database tools are not on this endpoint.");let s="";process.stdin.setEncoding("utf8");try{let d=await Kt();ce(`snoutdata mcp: signed in as ${d.email??"this account"}.`)}catch(d){if(ce(`snoutdata mcp: ${d instanceof Error?d.message:String(d)}`),!process.env.LEPIS_ADMIN_URL)return ce("Sign in with `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN."),3;ce(`snoutdata mcp: not signed in, so only the cluster tools will work (router ${process.env.LEPIS_ADMIN_URL}).`)}ce(`snoutdata mcp: ready${e.allowDelete?" (delete_project is ON)":""}. Speaking MCP on stdin/stdout; stop it with Ctrl-C.`);let a=new Set;function l(d){a.add(d),d.finally(()=>a.delete(d))}return new Promise(d=>{process.stdin.on("data",c=>{let i=Qd(s+c);s=i.rest;for(let p of i.messages)l($v(p,r,o))}),process.stdin.on("end",()=>{(async()=>{for(;a.size>0;)await Promise.allSettled([...a]);d(0)})()}),process.stdin.on("error",()=>d(1))})}async function $v(e,t,n){let r;try{r=JSON.parse(e)}catch{ce(`snoutdata mcp: ignoring a line that is not JSON: ${e.slice(0,120)}`);return}try{let o=await Zd(r,t,n);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
768
1048
|
`)}catch(o){let s=r.id??null;process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32603,message:o instanceof Error?o.message:String(o)}})}
|
|
769
|
-
`)}}An();pe();de();function rv(e){return e>=1?"over":e>=.8?"near":"ok"}function Af(e,t){let n=null,r=null,o=0,s=0;for(let c of e)o+=Number.isFinite(c.computeSeconds)?c.computeSeconds:0,s+=Number.isFinite(c.connections)?c.connections:0,!(c.dbBytes===null||!Number.isFinite(c.dbBytes))&&(r=r===null?c.dbBytes:Math.max(r,c.dbBytes),(!n||c.day>=n.day)&&(n={day:c.day,dbBytes:c.dbBytes,repoBytes:c.repoBytes}));let a=n&&t&&t.maxStorageBytes>0?{limitBytes:t.maxStorageBytes,usedBytes:n.dbBytes,fraction:n.dbBytes/t.maxStorageBytes,state:rv(n.dbBytes/t.maxStorageBytes)}:null;return{days:e.length,latest:n,peakDbBytes:r,computeSeconds:o,connections:s,storage:a}}function Oi(e){if(!Number.isFinite(e)||e<=0)return"none";let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?n>0?`${t}d ${n}h`:`${t}d`:n>0?r>0?`${n}h ${r}m`:`${n}h`:r>0?`${r}m`:`${Math.round(e)}s`}async function Rf(e,t={}){let n=await R("cloud-project-usage",{ref:e,...t.days?{days:t.days}:{}}),r=Af(n.days,n.limit);return b({...n,summary:r},()=>{if(d(M(`${n.name} (${n.ref})`)),!r.latest)d("Nothing measured yet. The host samples every fifteen minutes.");else if(r.storage){let o=Math.round(r.storage.fraction*100),s=`${wt(r.storage.usedBytes)} of ${wt(r.storage.limitBytes)} on ${n.limit?.tier}`;d(r.storage.state==="over"?`${s} (${o}%). Over the limit, so writes are refused until it shrinks or the plan changes.`:r.storage.state==="near"?`${s} (${o}%). Close to the limit: at 100% the database goes read-only.`:`${s} (${o}%).`)}else d(`${wt(r.latest.dbBytes)} as of ${r.latest.day}.`);n.readOnly&&r.storage?.state!=="over"&&d("This project is currently read-only."),d(`Over ${r.days} day${r.days===1?"":"s"}: ${Oi(r.computeSeconds)} of compute, ${r.connections} connection${r.connections===1?"":"s"}.`),r.peakDbBytes!==null&&r.latest&&r.peakDbBytes>r.latest.dbBytes&&d(v(`Peak in that window was ${wt(r.peakDbBytes)}.`)),t.history&&n.days.length>0&&(d(""),d(X([["DAY","SIZE","BACKUPS","COMPUTE","CONNS"],...n.days.map(o=>[o.day,o.dbBytes===null?"-":wt(o.dbBytes),o.repoBytes===null?"-":wt(o.repoBytes),Oi(o.computeSeconds),String(o.connections)])])),d(v("A dash is a day nothing measured it, which is what a paused project looks like.")))}),0}Ae();be();Pt();de();import{createInterface as ov}from"node:readline/promises";var sv=new Set(["node.drain","node.remove","table.distribute","table.reference","table.global","table.auto","range.split","range.merge","range.move","tenant.pin","rebalance","scale","cleanup","dissolve"]),Ni={max_write_pause_ms:"max-write-pause-ms",drain_timeout_ms:"drain-timeout-ms",ack_timeout_ms:"ack-timeout-ms",copy_mb_per_s:"copy-mb-per-s"},av="nodes add|drain|remove, keyspace create|drop, table distribute|reference|global|auto, range split|merge|move, tenant pin, rebalance, scale, verify, cleanup, dissolve";function Tf(e,t,n=!1){let[r,o,...s]=e,a=l=>E(t,l),c=(l,m)=>{if(l===void 0||l==="")throw new h(m);return l},i,u=`${r??""}${o!==void 0&&iv(r)?` ${o}`:""}`;if(n&&(u==="nodes add"||u==="node add")){if(s.length>0||a("host")!==void 0)throw new h("in SnoutData Cloud a node is a pod the project makes: cluster nodes add --project <ref>, with no name or --host. It joins the cluster on its own once it is ready.");return{body:K(t,"no-join")?{op:"node.add",join:!1}:{op:"node.add"},destructive:!1}}if(u==="nodes attach"||u==="node attach"){if(!n)throw new h("nodes attach is for a SnoutData Cloud project (--project): a standalone node joins with cluster nodes add <name> --host H");return{body:{op:"node.attach",name:c(s[0]??a("node"),"nodes attach needs the node pod's ref, as cluster status lists it")},destructive:!1}}if(n&&u==="scale"){if(a("add")!==void 0||a("remove")!==void 0)throw new h("in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");let l=ut(t,"nodes","nodes");if(!l.nodes)throw new h("scale needs --nodes N: how many nodes the project should have, the home included");i={op:"scale",...l};for(let[m,y]of Object.entries(Ni))Object.assign(i,ut(t,y,m));return{body:i,destructive:!0}}switch(u){case"nodes add":case"node add":i={op:"node.add",name:c(s[0]??a("name"),"nodes add needs a name: cluster nodes add <name> --host H [--port 5432] [--dbname D] [--sslmode M]"),host:c(a("host"),"nodes add needs --host, the address the router reaches the node at"),...ut(t,"port","port"),...Mt(t,"dbname","dbname"),...Mt(t,"sslmode","sslmode"),...Mt(t,"peer-host","peer_host")};break;case"nodes drain":case"node drain":i={op:"node.drain",node:c(s[0]??a("node"),"nodes drain needs a node: cluster nodes drain <id|name> [--to a,b]"),...a("to")?{to:Zo(a("to"))}:{}};break;case"nodes remove":case"node remove":i={op:"node.remove",node:c(s[0]??a("node"),"nodes remove needs a node: cluster nodes remove <id|name>")};break;case"keyspace create":i={op:"keyspace.create",name:c(s[0]??a("name"),"keyspace create needs a name: cluster keyspace create <name> --key-type bigint [--ranges N] [--nodes a,b]"),key_type:c(a("key-type"),"keyspace create needs --key-type, the distribution key's type (bigint, int, text, uuid, ...)"),...ut(t,"ranges","ranges"),...a("seed")!==void 0?{seed:lv(a("seed"))}:{},...a("nodes")?{nodes:Zo(a("nodes"))}:{}};break;case"keyspace drop":i={op:"keyspace.drop",name:c(s[0]??a("name"),"keyspace drop needs a name: cluster keyspace drop <name> (a keyspace no table is distributed by)")};break;case"dissolve":if(n)throw new h("in SnoutData Cloud, turn the cluster off with cluster disable --project <ref>: it dissolves the cluster and then stops the router");i={op:"dissolve"};break;case"table distribute":i={op:"table.distribute",table:c(s[0],"table distribute needs a table: cluster table distribute <schema.table> --distribution-key C --keyspace K"),column:c(a("distribution-key")??a("column"),"table distribute needs --distribution-key, the column whose value decides which node holds each row"),keyspace:c(a("keyspace"),"table distribute needs --keyspace")};break;case"table auto":{let l=a("schemas");i={op:"table.auto",keyspace:c(a("keyspace"),"table auto needs --keyspace, the keyspace every table it distributes goes in"),...l!==void 0?{schemas:l.split(",").map(m=>m.trim()).filter(m=>m!=="")}:{},...ut(t,"min-bytes","min_bytes")};break}case"table reference":case"table global":i={op:`table.${o}`,table:c(s[0],`table ${o} needs a table: cluster table ${o} <schema.table>`)};break;case"range split":{let l=Yo(s[0],t);i={op:"range.split",keyspace:l.keyspace,range:l.lo,...a("at")!==void 0?{at:Ii(a("at"),"--at")}:{},...a("to")?{to:a("to")}:{}};break}case"range move":{let l=Yo(s[0],t);i={op:"range.move",keyspace:l.keyspace,range:l.lo,to:c(a("to"),"range move needs --to, the node that will own it")};break}case"range merge":{if(s.length!==2)throw new h("range merge needs two adjacent ranges: cluster range merge <keyspace:lo> <keyspace:lo>");let l=Yo(s[0],t),m=Yo(s[1],t);if(l.keyspace!==m.keyspace)throw new h(`range merge: ${l.keyspace} and ${m.keyspace} are different keyspaces`);i={op:"range.merge",keyspace:l.keyspace,a:l.lo,b:m.lo};break}case"tenant pin":{let l=a("keyspace")??s[0],m=a("value")??(a("keyspace")?s[0]:s[1]);i={op:"tenant.pin",keyspace:c(l,"tenant pin needs a keyspace: cluster tenant pin <keyspace> <value> [--node N]"),value:c(m,"tenant pin needs the key value to pin (--value V for one that starts with a dash)"),...a("node")?{node:a("node")}:{}};break}case"rebalance":i={op:"rebalance",...Mt(t,"keyspace","keyspace")};break;case"scale":{let l=a("add")?Zo(a("add")).map(y=>cv(y,t)):[],m=ut(t,"remove","remove");if(l.length===0&&!m.remove)throw new h("scale needs --add name=host[:port],... or --remove N (or both)");i={op:"scale",...l.length>0?{add:l}:{},...m};break}case"verify":i={op:"verify",...Mt(t,"keyspace","keyspace")};break;case"cleanup":i={op:"cleanup",...Mt(t,"node","node")};break;default:throw new h(`unknown operation: cluster ${e.join(" ")}. One of ${av}`)}for(let[l,m]of Object.entries(Ni)){let y=ut(t,m,l);Object.assign(i,y)}return{body:i,destructive:sv.has(i.op)}}function iv(e){return e==="nodes"||e==="node"||e==="keyspace"||e==="table"||e==="range"||e==="tenant"}function Zo(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Mt(e,t,n){let r=E(e,t);return r===void 0?{}:{[n]:r}}function ut(e,t,n){let r=E(e,t);if(r===void 0)return{};let o=Number(r);if(!/^\d+$/.test(r)||!Number.isSafeInteger(o))throw new h(`--${t} must be a whole number, not "${r}"`);return{[n]:o}}function Ii(e,t){let n=e.trim();if(!/^-?\d+$/.test(n)||BigInt(n)<-(2n**63n)||BigInt(n)>=2n**63n)throw new h(`${t} must be a 64-bit whole number, not "${e}"`);return BigInt(n).toString()}function lv(e){let t=e.trim();if(!/^\d+$/.test(t)||BigInt(t)>=2n**64n)throw new h(`--seed must be an unsigned 64-bit whole number, not "${e}"`);return BigInt(t).toString()}function Yo(e,t){let n=E(t,"keyspace"),r=E(t,"range");if(e!==void 0&&e.includes(":")){let s=e.lastIndexOf(":"),a=e.slice(0,s);if(!a)throw new h(`a range is keyspace:lo, as cluster status prints it, not "${e}"`);return{keyspace:a,lo:Ii(e.slice(s+1),`the range's lower bound in "${e}"`)}}let o=r??e;if(!n||o===void 0)throw new h("name the range as keyspace:lo (as cluster status prints it), or with --keyspace K --range LO");return{keyspace:n,lo:Ii(o,"--range")}}function cv(e,t){let n=/^([^=]+)=([^:]+)(?::(\d+))?$/.exec(e);if(!n)throw new h(`scale --add takes name=host[:port], not "${e}"`);return{name:n[1],host:n[2],...n[3]?{port:Number(n[3])}:{},...Mt(t,"dbname","dbname"),...Mt(t,"sslmode","sslmode")}}function Xo(e,t){if(e===void 0||!/^\d+$/.test(e))throw new h(`jobs ${t} needs a job id: cluster jobs ${t} <id>`);return Number(e)}async function Cf(e,t={}){let n=e.command.slice(1),[r,o,s]=n,a=E(e,"project")??E(e,"ref"),c=a!==void 0,i=()=>t.client??Un({project:a,admin:E(e,"admin"),token:E(e,"token")});switch(r){case"enable":{if(!c)throw new h("cluster enable is for a SnoutData Cloud project: cluster enable --project <ref>. A standalone router is a cluster from the moment it runs");let l=i();if(!(l instanceof st))throw new h("cluster enable needs --project <ref>");if(K(e,"plan")){let y=await l.enable(!0);return b(y,()=>Ve(y,process.stdout)),0}if(!K(e,"yes")){if(!t.confirm&&!Se())throw new h("making it a cluster moves the project's services into pods of their own, and nothing was asked: pass --yes, or --plan to see what it does");if(Ve(await l.enable(!0),process.stderr),!await(t.confirm??zt)(`Make a cluster of ${l.target}?`))throw new C("failed","Not turned on. Nothing was changed.")}let m=await l.enable(!1);return b(m,()=>d(At(m))),0}case"disable":{if(!c)throw new h("cluster disable is for a SnoutData Cloud project: cluster disable --project <ref>. A standalone cluster is taken apart with cluster dissolve, and then by stopping the router");let l=i();if(!(l instanceof st))throw new h("cluster disable needs --project <ref>");if(K(e,"plan")){let y=await l.disable(!0);return b(y,()=>Ve(y,process.stdout)),0}if(!K(e,"yes")){if(!t.confirm&&!Se())throw new h("turning the cluster off restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(Ve(await l.disable(!0),process.stderr),!await(t.confirm??zt)(`Turn the cluster of ${l.target} off?`))throw new C("failed","Not turned off. Nothing was changed.")}let m=await l.disable(!1);return b(m,()=>d(At(m))),0}case"spread":{if(!c)throw new h("cluster spread is for a SnoutData Cloud project (--project). On a standalone router: cluster keyspace create, then cluster table distribute and cluster rebalance");let l=i();if(!(l instanceof st))throw new h("cluster spread needs --project <ref>");let m={table:o??$n(E(e,"table"),"cluster spread needs the table: cluster spread <schema.table> --distribution-key C --key-type T"),column:$n(E(e,"distribution-key")??E(e,"column"),"cluster spread needs --distribution-key, the column to spread the rows by"),key_type:$n(E(e,"key-type"),"cluster spread needs --key-type, the column's type (bigint, uuid, text, ...)")};if(K(e,"plan")){let T=await l.spread(m,!0);return b(T,()=>Ve(T,process.stdout)),0}if(!K(e,"yes")){if(!t.confirm&&!Se())throw new h("spreading a table moves its rows, and nothing was asked: pass --yes, or --plan to see what it does");if(Ve(await l.spread(m,!0),process.stderr),!await(t.confirm??zt)(`Spread ${m.table} over ${l.target}?`))throw new C("failed","Not spread. Nothing was changed.")}let y=await l.spread(m,!1);return b(y,()=>d(At(y))),0}case"retry":{if(!c)throw new h("cluster retry is for a SnoutData Cloud project (--project): a stopped job on a standalone router is resumed with cluster jobs resume <id>");let l=i();if(!(l instanceof st))throw new h("cluster retry needs --project <ref>");let m=K(e,"queue")?await l.retry({queue:!0}):await l.retry({node:$n(o??E(e,"node"),"cluster retry needs the node pod whose join stopped, or --queue")});return b(m,()=>d(At(m))),0}case"replica":{if(!c)throw new h("cluster replica is for a SnoutData Cloud project (--project): cluster replica add|remove <node-ref> --project <ref>");if(o!=="add"&&o!=="remove")throw new h("cluster replica add|remove <node-ref> --project <ref>: the node pod, as cluster status lists it");let l=i();if(!(l instanceof st))throw new h("cluster replica needs --project <ref>");let m=o==="remove",y=$n(s??E(e,"node"),`cluster replica ${o} needs the node pod's ref, as cluster status lists it`);if(K(e,"plan")){let A=await l.replica(y,m,!0);return b(A,()=>Ve(A,process.stdout)),0}if(!K(e,"yes")){if(!t.confirm&&!Se())throw new h(m?"removing a replica leaves the node without one, and nothing was asked: pass --yes, or --plan to see what it does":"a replica takes one project slot, and nothing was asked: pass --yes, or --plan to see what it does");if(Ve(await l.replica(y,m,!0),process.stderr),!await(t.confirm??zt)(m?`Remove the replica of node ${y}?`:`Add a replica to node ${y}?`))throw new C("failed","Nothing was changed.")}let T=await l.replica(y,m,!1);return b(T,()=>d(At(T))),0}case"alerts":{if(!c)throw new h("cluster alerts is for a SnoutData Cloud project (--project <ref>)");let l=i();if(!(l instanceof st))throw new h("cluster alerts needs --project <ref>");if(o===void 0||o==="list"){let m=await l.alerts();return b({alerts:m},()=>Lf(m,process.stdout,!0,l.ref)),0}if(o==="seen"||o==="acknowledge"){let m=$n(s,`cluster alerts ${o} needs the alert's id, as cluster alerts lists it`);if(!/^[0-9a-f-]{36}$/i.test(m))throw new h(`not an alert id: ${m} (as cluster alerts lists it)`);let y=await l.acknowledge(m.toLowerCase());return b(y,()=>d(At(y))),0}throw new h(`unknown command: cluster alerts ${o}. alerts [list], or alerts seen <id>`)}case void 0:case"status":{let l=await i().status();return b(l,()=>wv(l)),0}case"ops":{let l=await i().ops();return b(l,()=>{process.stdout.write(`${l.ops.join(`
|
|
1049
|
+
`)}}jn();me();pe();function vv(e){return e>=1?"over":e>=.8?"near":"ok"}function vg(e,t){let n=null,r=null,o=0,s=0;for(let l of e)o+=Number.isFinite(l.computeSeconds)?l.computeSeconds:0,s+=Number.isFinite(l.connections)?l.connections:0,!(l.dbBytes===null||!Number.isFinite(l.dbBytes))&&(r=r===null?l.dbBytes:Math.max(r,l.dbBytes),(!n||l.day>=n.day)&&(n={day:l.day,dbBytes:l.dbBytes,repoBytes:l.repoBytes}));let a=n&&t&&t.maxStorageBytes>0?{limitBytes:t.maxStorageBytes,usedBytes:n.dbBytes,fraction:n.dbBytes/t.maxStorageBytes,state:vv(n.dbBytes/t.maxStorageBytes)}:null;return{days:e.length,latest:n,peakDbBytes:r,computeSeconds:o,connections:s,storage:a}}var cl=864e5;function Pg(e,t,n=new Date){let r=e.filter(i=>i.dbBytes!==null&&Number.isFinite(i.dbBytes)).map(i=>({at:Date.parse(`${i.day.slice(0,10)}T00:00:00Z`),bytes:i.dbBytes})).filter(i=>Number.isFinite(i.at)).sort((i,p)=>i.at-p.at),o=r[r.length-1];if(!o)return{perDay:null,overDays:0,fullOn:null};let s=r.find(i=>i.at>=o.at-7*cl),a=s?Math.round((o.at-s.at)/cl):0,l=s&&a>=1?(o.bytes-s.bytes)/a:null,d=t!==null&&t>0?t:null,c=l!==null&&l>0&&d!==null&&o.bytes<d?new Date(n.getTime()+(d-o.bytes)/l*cl).toISOString().slice(0,10):null;return{perDay:l,overDays:a,fullOn:c}}function $r(e){if(!Number.isFinite(e)||e<=0)return"none";let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?n>0?`${t}d ${n}h`:`${t}d`:n>0?r>0?`${n}h ${r}m`:`${n}h`:r>0?`${r}m`:`${Math.round(e)}s`}me();_e();import{readFileSync as Pv,statSync as xv}from"node:fs";pe();var ys={connection:e=>Me(e),open:e=>bn.open(e)};async function dl(e,t,n){let r=await t.connection(e);r.wakesInstantly||u("This project is paused; the connection will wake it, which takes a few seconds.");let o={host:r.host,port:r.port,database:r.database,user:r.user,password:r.password,ssl:r.ssl},s;try{s=await t.open(o)}catch(a){throw a instanceof he?new O("network",`Could not reach ${e}'s database: ${a.message}.`):a instanceof nt?new O("failed",`${e}'s database refused the connection: ${a.message}`):a}try{return await n(s)}finally{s.close()}}function xg(e){return/^\s*(begin|start\s+transaction)\b/i.test(e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," "))}function Ev(e,t){if(t.length<=1||!Dt(e))return{mode:"none"};let n=t[0],r=t[t.length-1],o=t.slice(1,-1),s=Jt(r.sql);if(xg(n.sql)&&(s==="COMMIT"||s==="END")&&o.every(l=>Jt(l.sql)===null&&!xg(l.sql)))return{mode:"own"};let a=t.find(l=>Jt(l.sql)!==null);if(a){let l=Jt(a.sql);return{refused:`line ${a.line} ends the transaction itself (${l}). Several statements run in one transaction, so a ${l} part way would keep what ran before it if a later statement failed. Take it out, wrap the whole file in BEGIN and COMMIT, or put -- snoutdata:no-transaction on a line of its own to run each statement as written.`}}return{mode:"wrapped"}}async function Av(e,t,n){let r=[];n==="wrapped"&&await e.query("begin;");for(let[o,s]of t.entries())try{let a=await e.query(s.sql,s.copyData);r.push({statement:o+1,line:s.line,command:a.command,...a.columns?{columns:a.columns,rows:a.rows}:{},...a.notices?{notices:a.notices}:{}})}catch(a){if(a instanceof nt){if(n!=="none")try{await e.query("rollback;")}catch{}return{failed:o+1,line:s.line,error:ir(a,s.sql,s.line),ran:o}}if(a instanceof he)return{failed:o+1,line:s.line,error:`the connection was lost: ${a.message}`,ran:o};throw a}if(n==="wrapped")try{await e.query("commit;")}catch(o){if(o instanceof nt)return{failed:t.length+1,line:0,error:ir(o,"commit;"),ran:t.length};throw o}return{results:r}}function Rv(e){return e===null?"":e.replace(/\r?\n/g,"\\n").replace(/\t/g,"\\t")}function Tv(e,t){let n=t.map(o=>e.map((s,a)=>Rv(o[a]??null))),r=e.map((o,s)=>Math.max(o.length,...n.map(a=>a[s].length)));return V([[...e],r.map(o=>"-".repeat(Math.max(o,1))),...n])}function vr(e,t){return`${e} ${t}${e===1?"":"s"}`}async function Rg(e,t,n,r){let o=No(t),s=n??"the SQL";if(o.metaCommands.length>0){let p=o.metaCommands.map(g=>` line ${g.line}: ${g.text.length>60?`${g.text.slice(0,57)}...`:g.text}`).join(`
|
|
1050
|
+
`);Q("usage",`Refused, and nothing ran: ${s} holds psql commands, which only psql runs. Put the SQL each one stands for in their place.
|
|
1051
|
+
${p}`,{ref:e,...n?{file:n}:{},metaCommands:o.metaCommands})}o.statements.length===0&&Q("usage",`${n?`${n} holds`:"That is"} no SQL to run.`,{ref:e,...n?{file:n}:{}});let a=Ev(t,o.statements);"refused"in a&&Q("usage",`Refused, and nothing ran: ${n?`${n} `:""}${a.refused}`,{ref:e,...n?{file:n}:{}});let{mode:l}=a;await $o(e);let d=await dl(e,r,p=>Av(p,o.statements,l)),c=o.statements.length;if("failed"in d){let p=d.failed>c?"The commit":c===1?"The statement":`Statement ${d.failed} of ${c}${d.line>0?` (${n?`${n}:`:"line "}${d.line})`:""}`,g=l==="none"?c===1||d.ran===0?"Nothing was changed.":`The ${vr(d.ran,"statement")} before it ran and stay, since this runs outside a transaction; the ones after it were not tried.`:"It ran in one transaction, which was rolled back, so nothing was changed.";Q("failed",`${p} failed. ${g}
|
|
1052
|
+
${d.error}`,{ref:e,...n?{file:n}:{},statement:d.failed>c?null:d.failed,line:d.line>0?d.line:null,transaction:l!=="none",error:d.error})}let{results:i}=d;return w({ref:e,ok:!0,...n?{file:n}:{},transaction:l!=="none",statements:i},()=>{let p=!1;for(let g of i){for(let E of g.notices??[])u(E);if(g.columns){p&&process.stdout.write(`
|
|
1053
|
+
`);let E=g.rows??[];g.columns.length>0&&process.stdout.write(`${Tv(g.columns,E)}
|
|
1054
|
+
`),u($(`(${vr(E.length,"row")})`)),p=!0}else g.command&&u(g.command)}l!=="none"&&u($(`${vr(c,"statement")} ran in one transaction, committed.`))}),0}async function Tg(e,t,n=ys){return Rg(e,t,void 0,n)}async function Og(e,t,n=ys){let r;try{xv(t).isFile()||Q("usage",`${t} is not a file.`,{file:t}),r=Pv(t,"utf8")}catch(o){if(o instanceof O)throw o;Q("usage",`no file at ${t}`,{file:t})}return Rg(e,r,t,n)}function Eg(e){return`"${e.replace(/"/g,'""')}"`}function Ag(e){return e<10?`${e.toFixed(2)} ms`:e<1e3?`${e.toFixed(1)} ms`:e<6e4?`${(e/1e3).toFixed(1)} s`:e<36e5?`${(e/6e4).toFixed(1)} min`:`${(e/36e5).toFixed(1)} h`}function Ov(e,t=80){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Nv="select n.nspname from pg_extension e join pg_namespace n on n.oid = e.extnamespace where e.extname = 'pg_stat_statements';";async function Ng(e,t={},n=ys){let r=t.limit??10,o=await dl(e,n,async s=>{let l=(await s.query(Nv)).rows[0]?.[0];if(!l)return null;let d=`${Eg(l)}.pg_stat_statements`,{rows:c}=await s.query(`select coalesce(r.rolname, s.userid::text),
|
|
1055
|
+
s.calls,
|
|
1056
|
+
s.mean_exec_time,
|
|
1057
|
+
s.total_exec_time,
|
|
1058
|
+
s.rows,
|
|
1059
|
+
round((100 * s.total_exec_time / nullif(sum(s.total_exec_time) over (), 0))::numeric, 1),
|
|
1060
|
+
s.query
|
|
1061
|
+
from ${d} s
|
|
1062
|
+
left join pg_roles r on r.oid = s.userid
|
|
1063
|
+
where s.dbid = (select oid from pg_database where datname = current_database())
|
|
1064
|
+
order by s.total_exec_time desc, s.queryid
|
|
1065
|
+
limit ${Math.floor(r)};`),i=null;try{i=(await s.query(`select to_char(stats_reset at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') from ${Eg(l)}.pg_stat_statements_info;`)).rows[0]?.[0]??null}catch{}let p=c.map(([g,E,A,te,U,B,C])=>({role:g??"",calls:Number(E),meanMs:Number(A),totalMs:Number(te),rows:Number(U),share:B==null?null:Number(B),query:C==="<insufficient privilege>"?`(hidden: Postgres shows this text only to ${g??"the role that ran it"})`:C??""}));return{schema:l,since:i,statements:p}});return o||Q("not-found",`pg_stat_statements is not switched on in this database, so there is nothing to read. It is loaded on every SnoutData database and starts recording once it is created:
|
|
1066
|
+
snoutdata db query "create extension if not exists pg_stat_statements"`,{ref:e}),w({ref:e,...o},()=>{if(o.statements.length===0){u("No statements recorded yet.");return}process.stdout.write(`${V([["TOTAL","MEAN","CALLS","ROWS","SHARE","ROLE","QUERY"],...o.statements.map(s=>[Ag(s.totalMs),Ag(s.meanMs),s.calls.toLocaleString("en-US"),s.rows.toLocaleString("en-US"),s.share===null?"-":`${s.share}%`,s.role,Ov(s.query)])])}
|
|
1067
|
+
`),u($(`${o.since?`Counted since ${o.since} (${We(o.since)}). `:""}--json has each statement's whole text.`))}),0}function Iv(e){return`with recursive tree(root, rel) as (
|
|
1068
|
+
select c.oid, c.oid
|
|
1069
|
+
from pg_class c
|
|
1070
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
1071
|
+
where c.relkind in ('r', 'p', 'm') and not c.relispartition
|
|
1072
|
+
and n.nspname not in ('pg_catalog', 'information_schema')
|
|
1073
|
+
and n.nspname not like 'pg\\_toast%' and n.nspname not like 'pg\\_temp%'
|
|
1074
|
+
union all
|
|
1075
|
+
select t.root, i.inhrelid
|
|
1076
|
+
from tree t
|
|
1077
|
+
join pg_inherits i on i.inhparent = t.rel
|
|
1078
|
+
join pg_class p on p.oid = i.inhrelid and p.relispartition
|
|
1079
|
+
)
|
|
1080
|
+
select n.nspname, c.relname, c.relkind::text,
|
|
1081
|
+
count(*) - 1,
|
|
1082
|
+
coalesce(sum(pg_total_relation_size(t.rel)), 0)::bigint,
|
|
1083
|
+
coalesce(sum(pg_indexes_size(t.rel)), 0)::bigint,
|
|
1084
|
+
case when bool_or(k.relkind <> 'p' and k.reltuples >= 0)
|
|
1085
|
+
then sum(case when k.relkind <> 'p' and k.reltuples > 0 then k.reltuples else 0 end)::bigint end
|
|
1086
|
+
from tree t
|
|
1087
|
+
join pg_class c on c.oid = t.root
|
|
1088
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
1089
|
+
join pg_class k on k.oid = t.rel
|
|
1090
|
+
group by n.nspname, c.relname, c.relkind
|
|
1091
|
+
order by 5 desc, 1, 2
|
|
1092
|
+
limit ${Math.floor(e)};`}var Cv={r:"table",p:"partitioned table",m:"materialized view"};async function Ig(e,t=20,n=ys){return dl(e,n,async r=>{let{rows:o}=await r.query(Iv(t)),s=await r.query("select pg_database_size(current_database());");return{databaseBytes:Number(s.rows[0]?.[0]??0),tables:o.map(([a,l,d,c,i,p,g])=>({schema:a??"",name:l??"",kind:Cv[d??"r"]??"table",partitions:Number(c),totalBytes:Number(i),indexBytes:Number(p),rowsEstimate:g==null?null:Number(g)}))}})}function Lv(e){if(e<1e3)return String(e);let t=["K","M","B","T"],n=e/1e3,r=0;for(;n>=1e3&&r<t.length-1;)n/=1e3,r+=1;return`${n.toFixed(n>=10?0:1)}${t[r]}`}function Cg(e){if(e.tables.length===0)return["No tables yet."];let t=e.tables.reduce((n,r)=>n+r.totalBytes,0);return[V([["TABLE","TOTAL","INDEXES","ROWS (EST.)"],...e.tables.map(n=>[`${n.schema}.${n.name}${n.partitions>0?` (${vr(n.partitions,"partition")})`:n.kind==="materialized view"?" (materialized view)":""}`,Ee(n.totalBytes),Ee(n.indexBytes),n.rowsEstimate===null?"-":`~${Lv(n.rowsEstimate)}`])]),$(`${vr(e.tables.length,"table")}, ${Ee(t)} of the database's ${Ee(e.databaseBytes)}. Totals include indexes and TOAST; rows are Postgres's estimate from the last ANALYZE.`)]}var Dv="https://docs.snoutdata.com/cloud/limits#storage-over-the-limit-means-read-only";async function Lg(e,t={}){let n=await T("cloud-project-usage",{ref:e,...t.days?{days:t.days}:{}}),r=vg(n.days,n.limit),o=Pg(n.days,n.limit?.maxStorageBytes??null),s=t.tables?await Ig(e,t.limit??20):null;return w({...n,summary:r,...s?{databaseBytes:s.databaseBytes,tables:s.tables}:{}},()=>{if(u(N(`${n.name} (${n.ref})`)),!r.latest)u("Nothing measured yet. The host samples every fifteen minutes.");else if(r.storage){let a=Math.round(r.storage.fraction*100),l=`${Ee(r.storage.usedBytes)} of ${Ee(r.storage.limitBytes)} on ${n.limit?.tier}`;u(r.storage.state==="over"?`${l} (${a}%). Over the limit, so writes are refused until it shrinks or the plan changes.`:r.storage.state==="near"?`${l} (${a}%). Close to the limit: at 100% the database goes read-only.`:`${l} (${a}%).`)}else u(`${Ee(r.latest.dbBytes)} as of ${r.latest.day}.`);if(o.perDay!==null&&r.latest){let a=`over the last ${o.overDays} day${o.overDays===1?"":"s"}`;u(o.perDay<=0?`Not growing ${a}.`:`Growing about ${Ee(o.perDay)} a day ${a}${o.fullOn?`: full around ${o.fullOn} at that rate`:""}.`)}if(r.storage&&r.storage.state!=="ok"&&u($(`What happens at the limit: ${Dv}`)),n.readOnly&&r.storage?.state!=="over"&&u("This project is currently read-only."),u(`Over ${r.days} day${r.days===1?"":"s"}: ${$r(r.computeSeconds)} of compute, ${r.connections} connection${r.connections===1?"":"s"}.`),u($("Compute is the time the database was running (wall clock, not CPU); connections counts every connection opened to the database, not the most at once.")),r.peakDbBytes!==null&&r.latest&&r.peakDbBytes>r.latest.dbBytes&&u($(`Peak in that window was ${Ee(r.peakDbBytes)}.`)),t.history&&n.days.length>0&&(u(""),u(V([["DAY","SIZE","BACKUPS","COMPUTE","CONNS"],...n.days.map(a=>[a.day,a.dbBytes===null?"-":Ee(a.dbBytes),a.repoBytes===null?"-":Ee(a.repoBytes),$r(a.computeSeconds),String(a.connections)])])),u($("A dash is a day nothing measured it, which is what a paused project looks like."))),s){u("");for(let a of Cg(s))u(a)}}),0}me();ve();pe();function Rt(e,t){return e.toLocaleString("en-US",{maximumFractionDigits:t})}var Pr=e=>Ee(Math.round(e)),jv=e=>`${Rt(e,e<10?1:0)}%`,ul=e=>`${Rt(e,e<10?2:e<100?1:0)}/s`,Uv=e=>e>=1e3?`${Rt(e/1e3,2)} s`:`${Rt(e,e<1?3:2)} ms`,Mg=e=>e<1?`${Rt(e*1e3,0)} ms`:`${Rt(e,1)} s`,Fv=[["cpuPercent","CPU",jv],["memoryBytes","Memory",Pr],["diskReadBps","Disk read",e=>`${Pr(e)}/s`],["diskWriteBps","Disk write",e=>`${Pr(e)}/s`],["connections","Connections",e=>Rt(e,0)],["commitsPerSec","Commits",ul],["rollbacksPerSec","Rollbacks",ul],["statementsPerSec","Statements",ul],["meanStatementMs","Mean statement time",Uv],["replicaLagSeconds","Replica lag",Mg],["replicaLagBytes","Replica behind by",Pr],["keeperLagSeconds","Second zone lag",Mg],["keeperLagBytes","Second zone behind by",Pr]],pl={hour:"the last hour",day:"the last day",week:"the last week"};function Bv(e){return e.role==="home"?`Home (${e.ref})`:e.role==="replica"?`Replica ${e.ref}`:`Node ${e.ref}`}function Hv(e){let t=[],n=e.figures.cpuLimitCores?.latest;t.push(n?`CPU limit ${Rt(n,2)} cores`:"no CPU limit");let r=e.figures.memoryLimitBytes?.latest;r&&t.push(`memory limit ${Ee(r)}`);let o=e.figures.maxConnections?.latest;return o&&t.push(`${Rt(o,0)} connections allowed`),t.join(", ")}async function Dg(e,t={}){let n=t.window??"hour";if(!["hour","day","week"].includes(n))throw new y("--window is hour, day or week");let r=await T("cloud-project-metrics",{ref:e,window:n,...t.node?{node:t.node}:{},points:Lt()});return w(r,()=>{if(r.nodes.length===0){u(t.node?`Nothing measured for ${t.node} over ${pl[n]}. Is it one of ${r.ref}'s servers?`:`Nothing measured over ${pl[n]}. The server records these once a minute while the database runs.`);return}u($(`Over ${pl[n]}. NOW is the latest minute; MIN, AVG and MAX are over every minute in the window.`));for(let o of r.nodes){u(""),u(`${N(Bv(o))} ${$(`last reading ${We(o.latestAt)}, ${Hv(o)}`)}`);let s=Fv.filter(([a])=>o.figures[a]!==void 0).map(([a,l,d])=>{let c=o.figures[a],i=p=>p===null?"-":d(p);return[l,i(c.latest),i(c.min),i(c.avg),i(c.max)]});u(V([["FIGURE","NOW","MIN","AVG","MAX"],...s]))}}),0}ve();_e();Ct();pe();import{createInterface as Gv}from"node:readline/promises";var qv=new Set(["node.drain","node.remove","table.distribute","table.reference","table.global","table.auto","range.split","range.merge","range.move","tenant.pin","rebalance","scale","cleanup","dissolve"]),fl={max_write_pause_ms:"max-write-pause-ms",drain_timeout_ms:"drain-timeout-ms",ack_timeout_ms:"ack-timeout-ms",copy_mb_per_s:"copy-mb-per-s"},Kv="nodes add|drain|remove, keyspace create|drop, table distribute|reference|global|auto, range split|merge|move, tenant pin, rebalance, scale, verify, cleanup, dissolve";function jg(e,t,n=!1){let[r,o,...s]=e,a=i=>R(t,i),l=(i,p)=>{if(i===void 0||i==="")throw new y(p);return i},d,c=`${r??""}${o!==void 0&&zv(r)?` ${o}`:""}`;if(n&&(c==="nodes add"||c==="node add")){if(s.length>0||a("host")!==void 0)throw new y("in SnoutData Cloud a node is a pod the project makes: cluster nodes add --project <ref>, with no name or --host. It joins the cluster on its own once it is ready.");return{body:W(t,"no-join")?{op:"node.add",join:!1}:{op:"node.add"},destructive:!1}}if(c==="nodes attach"||c==="node attach"){if(!n)throw new y("nodes attach is for a SnoutData Cloud project (--project): a standalone node joins with cluster nodes add <name> --host H");return{body:{op:"node.attach",name:l(s[0]??a("node"),"nodes attach needs the node pod's ref, as cluster status lists it")},destructive:!1}}if(n&&c==="scale"){if(a("add")!==void 0||a("remove")!==void 0)throw new y("in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");let i=wt(t,"nodes","nodes");if(!i.nodes)throw new y("scale needs --nodes N: how many nodes the project should have, the home included");d={op:"scale",...i};for(let[p,g]of Object.entries(fl))Object.assign(d,wt(t,g,p));return{body:d,destructive:!0}}switch(c){case"nodes add":case"node add":d={op:"node.add",name:l(s[0]??a("name"),"nodes add needs a name: cluster nodes add <name> --host H [--port 5432] [--dbname D] [--sslmode M]"),host:l(a("host"),"nodes add needs --host, the address the router reaches the node at"),...wt(t,"port","port"),...Gt(t,"dbname","dbname"),...Gt(t,"sslmode","sslmode"),...Gt(t,"peer-host","peer_host")};break;case"nodes drain":case"node drain":d={op:"node.drain",node:l(s[0]??a("node"),"nodes drain needs a node: cluster nodes drain <id|name> [--to a,b]"),...a("to")?{to:Ss(a("to"))}:{}};break;case"nodes remove":case"node remove":d={op:"node.remove",node:l(s[0]??a("node"),"nodes remove needs a node: cluster nodes remove <id|name>")};break;case"keyspace create":d={op:"keyspace.create",name:l(s[0]??a("name"),"keyspace create needs a name: cluster keyspace create <name> --key-type bigint [--ranges N] [--nodes a,b]"),key_type:l(a("key-type"),"keyspace create needs --key-type, the distribution key's type (bigint, int, text, uuid, ...)"),...wt(t,"ranges","ranges"),...a("seed")!==void 0?{seed:Wv(a("seed"))}:{},...a("nodes")?{nodes:Ss(a("nodes"))}:{}};break;case"keyspace drop":d={op:"keyspace.drop",name:l(s[0]??a("name"),"keyspace drop needs a name: cluster keyspace drop <name> (a keyspace no table is distributed by)")};break;case"dissolve":if(n)throw new y("in SnoutData Cloud, turn the cluster off with cluster disable --project <ref>: it dissolves the cluster and then stops the router");d={op:"dissolve"};break;case"table distribute":d={op:"table.distribute",table:l(s[0],"table distribute needs a table: cluster table distribute <schema.table> --distribution-key C --keyspace K"),column:l(a("distribution-key")??a("column"),"table distribute needs --distribution-key, the column whose value decides which node holds each row"),keyspace:l(a("keyspace"),"table distribute needs --keyspace")};break;case"table auto":{let i=a("schemas");d={op:"table.auto",keyspace:l(a("keyspace"),"table auto needs --keyspace, the keyspace every table it distributes goes in"),...i!==void 0?{schemas:i.split(",").map(p=>p.trim()).filter(p=>p!=="")}:{},...wt(t,"min-bytes","min_bytes")};break}case"table reference":case"table global":d={op:`table.${o}`,table:l(s[0],`table ${o} needs a table: cluster table ${o} <schema.table>`)};break;case"range split":{let i=ws(s[0],t);d={op:"range.split",keyspace:i.keyspace,range:i.lo,...a("at")!==void 0?{at:gl(a("at"),"--at")}:{},...a("to")?{to:a("to")}:{}};break}case"range move":{let i=ws(s[0],t);d={op:"range.move",keyspace:i.keyspace,range:i.lo,to:l(a("to"),"range move needs --to, the node that will own it")};break}case"range merge":{if(s.length!==2)throw new y("range merge needs two adjacent ranges: cluster range merge <keyspace:lo> <keyspace:lo>");let i=ws(s[0],t),p=ws(s[1],t);if(i.keyspace!==p.keyspace)throw new y(`range merge: ${i.keyspace} and ${p.keyspace} are different keyspaces`);d={op:"range.merge",keyspace:i.keyspace,a:i.lo,b:p.lo};break}case"tenant pin":{let i=a("keyspace")??s[0],p=a("value")??(a("keyspace")?s[0]:s[1]);d={op:"tenant.pin",keyspace:l(i,"tenant pin needs a keyspace: cluster tenant pin <keyspace> <value> [--node N]"),value:l(p,"tenant pin needs the key value to pin (--value V for one that starts with a dash)"),...a("node")?{node:a("node")}:{}};break}case"rebalance":d={op:"rebalance",...Gt(t,"keyspace","keyspace")};break;case"scale":{let i=a("add")?Ss(a("add")).map(g=>Jv(g,t)):[],p=wt(t,"remove","remove");if(i.length===0&&!p.remove)throw new y("scale needs --add name=host[:port],... or --remove N (or both)");d={op:"scale",...i.length>0?{add:i}:{},...p};break}case"verify":d={op:"verify",...Gt(t,"keyspace","keyspace")};break;case"cleanup":d={op:"cleanup",...Gt(t,"node","node")};break;default:throw new y(`unknown operation: cluster ${e.join(" ")}. One of ${Kv}`)}for(let[i,p]of Object.entries(fl)){let g=wt(t,p,i);Object.assign(d,g)}return{body:d,destructive:qv.has(d.op)}}function zv(e){return e==="nodes"||e==="node"||e==="keyspace"||e==="table"||e==="range"||e==="tenant"}function Ss(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Gt(e,t,n){let r=R(e,t);return r===void 0?{}:{[n]:r}}function wt(e,t,n){let r=R(e,t);if(r===void 0)return{};let o=Number(r);if(!/^\d+$/.test(r)||!Number.isSafeInteger(o))throw new y(`--${t} must be a whole number, not "${r}"`);return{[n]:o}}function gl(e,t){let n=e.trim();if(!/^-?\d+$/.test(n)||BigInt(n)<-(2n**63n)||BigInt(n)>=2n**63n)throw new y(`${t} must be a 64-bit whole number, not "${e}"`);return BigInt(n).toString()}function Wv(e){let t=e.trim();if(!/^\d+$/.test(t)||BigInt(t)>=2n**64n)throw new y(`--seed must be an unsigned 64-bit whole number, not "${e}"`);return BigInt(t).toString()}function ws(e,t){let n=R(t,"keyspace"),r=R(t,"range");if(e!==void 0&&e.includes(":")){let s=e.lastIndexOf(":"),a=e.slice(0,s);if(!a)throw new y(`a range is keyspace:lo, as cluster status prints it, not "${e}"`);return{keyspace:a,lo:gl(e.slice(s+1),`the range's lower bound in "${e}"`)}}let o=r??e;if(!n||o===void 0)throw new y("name the range as keyspace:lo (as cluster status prints it), or with --keyspace K --range LO");return{keyspace:n,lo:gl(o,"--range")}}function Jv(e,t){let n=/^([^=]+)=([^:]+)(?::(\d+))?$/.exec(e);if(!n)throw new y(`scale --add takes name=host[:port], not "${e}"`);return{name:n[1],host:n[2],...n[3]?{port:Number(n[3])}:{},...Gt(t,"dbname","dbname"),...Gt(t,"sslmode","sslmode")}}function bs(e,t){if(e===void 0||!/^\d+$/.test(e))throw new y(`jobs ${t} needs a job id: cluster jobs ${t} <id>`);return Number(e)}async function Gg(e,t={}){let n=e.command.slice(1),[r,o,s]=n,a=R(e,"project")??R(e,"ref"),l=a!==void 0,d=()=>t.client??Zn({project:a,admin:R(e,"admin"),token:R(e,"token")});switch(r){case"enable":{if(!l)throw new y("cluster enable is for a SnoutData Cloud project: cluster enable --project <ref>. A standalone router is a cluster from the moment it runs");let i=d();if(!(i instanceof pt))throw new y("cluster enable needs --project <ref>");if(W(e,"plan")){let g=await i.enable(!0);return w(g,()=>rt(g,process.stdout)),0}if(!W(e,"yes")){if(!t.confirm&&!Pe())throw new y("making it a cluster moves the project's services into pods of their own, and nothing was asked: pass --yes, or --plan to see what it does");if(rt(await i.enable(!0),process.stderr),!await(t.confirm??tn)(`Make a cluster of ${i.target}?`))throw new O("failed","Not turned on. Nothing was changed.")}let p=await i.enable(!1);return w(p,()=>u(Mt(p))),0}case"disable":{if(!l)throw new y("cluster disable is for a SnoutData Cloud project: cluster disable --project <ref>. A standalone cluster is taken apart with cluster dissolve, and then by stopping the router");let i=d();if(!(i instanceof pt))throw new y("cluster disable needs --project <ref>");if(W(e,"plan")){let g=await i.disable(!0);return w(g,()=>rt(g,process.stdout)),0}if(!W(e,"yes")){if(!t.confirm&&!Pe())throw new y("turning the cluster off restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(rt(await i.disable(!0),process.stderr),!await(t.confirm??tn)(`Turn the cluster of ${i.target} off?`))throw new O("failed","Not turned off. Nothing was changed.")}let p=await i.disable(!1);return w(p,()=>u(Mt(p))),0}case"spread":{if(!l)throw new y("cluster spread is for a SnoutData Cloud project (--project). On a standalone router: cluster keyspace create, then cluster table distribute and cluster rebalance");let i=d();if(!(i instanceof pt))throw new y("cluster spread needs --project <ref>");let p={table:o??Cn(R(e,"table"),"cluster spread needs the table: cluster spread <schema.table> --distribution-key C --key-type T"),column:Cn(R(e,"distribution-key")??R(e,"column"),"cluster spread needs --distribution-key, the column to spread the rows by"),key_type:Cn(R(e,"key-type"),"cluster spread needs --key-type, the column's type (bigint, uuid, text, ...)")};if(W(e,"plan")){let E=await i.spread(p,!0);return w(E,()=>rt(E,process.stdout)),0}if(!W(e,"yes")){if(!t.confirm&&!Pe())throw new y("spreading a table moves its rows, and nothing was asked: pass --yes, or --plan to see what it does");if(rt(await i.spread(p,!0),process.stderr),!await(t.confirm??tn)(`Spread ${p.table} over ${i.target}?`))throw new O("failed","Not spread. Nothing was changed.")}let g=await i.spread(p,!1);return w(g,()=>u(Mt(g))),0}case"retry":{if(!l)throw new y("cluster retry is for a SnoutData Cloud project (--project): a stopped job on a standalone router is resumed with cluster jobs resume <id>");let i=d();if(!(i instanceof pt))throw new y("cluster retry needs --project <ref>");let p=W(e,"queue")?await i.retry({queue:!0}):await i.retry({node:Cn(o??R(e,"node"),"cluster retry needs the node pod whose join stopped, or --queue")});return w(p,()=>u(Mt(p))),0}case"replica":{if(!l)throw new y("cluster replica is for a SnoutData Cloud project (--project): cluster replica add|remove <node-ref> --project <ref>");if(o!=="add"&&o!=="remove")throw new y("cluster replica add|remove <node-ref> --project <ref>: the node pod, as cluster status lists it");let i=d();if(!(i instanceof pt))throw new y("cluster replica needs --project <ref>");let p=o==="remove",g=Cn(s??R(e,"node"),`cluster replica ${o} needs the node pod's ref, as cluster status lists it`);if(W(e,"plan")){let A=await i.replica(g,p,!0);return w(A,()=>rt(A,process.stdout)),0}if(!W(e,"yes")){if(!t.confirm&&!Pe())throw new y(p?"removing a replica leaves the node without one, and nothing was asked: pass --yes, or --plan to see what it does":"a replica takes one project slot, and nothing was asked: pass --yes, or --plan to see what it does");if(rt(await i.replica(g,p,!0),process.stderr),!await(t.confirm??tn)(p?`Remove the replica of node ${g}?`:`Add a replica to node ${g}?`))throw new O("failed","Nothing was changed.")}let E=await i.replica(g,p,!1);return w(E,()=>u(Mt(E))),0}case"alerts":{if(!l)throw new y("cluster alerts is for a SnoutData Cloud project (--project <ref>)");let i=d();if(!(i instanceof pt))throw new y("cluster alerts needs --project <ref>");if(o===void 0||o==="list"){let p=await i.alerts();return w({alerts:p},()=>zg(p,process.stdout,!0,i.ref)),0}if(o==="seen"||o==="acknowledge"){let p=Cn(s,`cluster alerts ${o} needs the alert's id, as cluster alerts lists it`);if(!/^[0-9a-f-]{36}$/i.test(p))throw new y(`not an alert id: ${p} (as cluster alerts lists it)`);let g=await i.acknowledge(p.toLowerCase());return w(g,()=>u(Mt(g))),0}throw new y(`unknown command: cluster alerts ${o}. alerts [list], or alerts seen <id>`)}case void 0:case"status":{let i=await d().status();return w(i,()=>r0(i)),0}case"ops":{let i=await d().ops();return w(i,()=>{process.stdout.write(`${i.ops.join(`
|
|
770
1093
|
`)}
|
|
771
|
-
`),
|
|
772
|
-
`),
|
|
773
|
-
`)),0}let o=await t().settings(n);return
|
|
774
|
-
`)),0;let t=e.state==="failed"?`failed: ${e.error??"no reason recorded"}. Resume it from the failed step: snoutdata cluster jobs resume ${e.id}`:"was cancelled";throw new
|
|
775
|
-
`)}function
|
|
776
|
-
`))q(t,` sql: ${u}`);c.operation&&q(t,` run: ${Mf(c.operation)??JSON.stringify(c.operation)}`)})}function yv(e,t){q(t,e.summary),e.advice.forEach((n,r)=>{q(t),q(t,`${M(`${r+1}. ${n.op}`)} (${n.metric})`),q(t,` ${n.reason}`);let o=Mf(n.request);if(q(t,` run: ${o??JSON.stringify(n.request)}`),n.plan){let s=n.plan;q(t,` plan: ${s.cutovers} cutover${s.cutovers===1?"":"s"}, ~${s.estimated_rows.toLocaleString("en-US")} rows, ${Di(s.estimated_bytes)}, ~${s.estimated_copy_seconds}s to copy, expected write pause ~${s.expected_pause_ms}ms`);for(let a of s.warnings??[])q(t,` warning: ${a}`)}else n.needs.length>0?q(t,` needs: ${n.needs.join(", ")}, so it has no plan yet`):n.plan_error&&q(t,` no plan: ${n.plan_error.message} (${n.plan_error.kind})`)}),e.assumptions&&(q(t),q(t,v(e.assumptions)))}function Nf(e,t){return e.nodes?.find(n=>n.id===t)?.name??`node ${t}`}function Df(e){let t=e.nodes??[];if(t.length===0){d("No nodes in the catalog.");return}q(process.stdout,X([["ID","NAME","ADDRESS","STATE","HOME","RANGES","POSTGRES"],...t.map(n=>[String(n.id),n.name,`${n.host}:${n.port}/${n.dbname}`,n.state,n.home?"yes":"",String(n.ranges.length),n.server_version_num?String(Math.floor(n.server_version_num/1e4)):"?"])]))}function wv(e){let t=process.stdout;if(e.cloud&&(vv(e.cloud,t),!e.cloud.sharded))return;if(!e.catalog){q(t,"The home node has no Lepis catalog yet (schema lepis).");return}q(t,`${M("Cluster")} at epoch ${e.epoch}`),q(t),Df(e);for(let s of e.keyspaces??[]){q(t),q(t,`${M(`Keyspace ${s.name}`)} (${s.key_type}, ${s.ranges.length} range${s.ranges.length===1?"":"s"})`),q(t,X([[" RANGE","HI","NODE"],...s.ranges.map(a=>[` ${s.name}:${a.lo}`,a.hi,Nf(e,a.node)])]));for(let a of s.pins)q(t,` pinned: ${a.value} on ${Nf(e,a.node)}`)}let n=e.tables??[];n.length>0&&(q(t),q(t,X([["TABLE","KIND","KEYSPACE","COLUMN"],...n.map(s=>[s.table,s.kind,s.keyspace??"",s.column??""])])));let r=e.routers??[];r.length>0&&(q(t),q(t,`Routers: ${r.map(s=>`${s.id} (epoch ${s.epoch}${s.live?"":", not heard from"}${s.current?"":", behind"})`).join("; ")}`));let o=e.jobs??[];o.length>0&&q(t,`Unfinished jobs: ${o.map(s=>`${s.id} ${s.op} ${s.state}`).join("; ")}`),e.settings&&d(v(`Settings: ${Object.entries(e.settings).map(([s,a])=>`${s}=${a}`).join(", ")}`))}function bv(e,t){if(t.joining==="failed"&&t.next!=="delete-pod")return`stopped joining: ${t.joinError??"see the audit log"}. Retry: snoutdata cluster retry ${t.ref} --project ${e.ref}`;if(t.replicaOf)return`replica of node ${t.replicaOf} (${t.state})`;switch(t.next){case"attach":return`ready: snoutdata cluster nodes attach ${t.ref} --project ${e.ref}`;case"delete-pod":return`let go by the cluster: snoutdata cluster nodes remove ${t.ref} --project ${e.ref} deletes its pod`;case"wait":return`starting as a copy of the home node (${t.state})`;case"joining":return t.joining==="spreading"?"joining: taking its share of the data":t.joining==="joining"?"joining the cluster":`joining: starting as a copy of the home node (${t.state})`;default:return t.node?`node ${t.node.id}, ${t.node.state}`:t.state}}function Sv(e){if(e.replicaOf)return`replica of node ${e.replicaOf}`;switch(e.failover){case"fence":return"failing over: stopping the node so its replica can take its place";case"promote":return"failing over: its replica is taking its place";case"failed":return`failover stopped: ${e.failoverError??"see cluster alerts"}`;case"held":return"failover held: its replica was behind and its last writes could not be copied to it, so it was not promoted (see cluster alerts)"}return e.desiredState==="deleted"||e.replicaOf===void 0?"":e.replica?`protected by replica ${e.replica}`:e.wantsReplica?"no replica yet: one is being made":"no replica"}function If(e){return e.severity.toUpperCase()}function Lf(e,t,n,r="<ref>"){let o=e.filter(a=>a.resolvedAt===null),s=e.filter(a=>a.resolvedAt!==null);if(!n){for(let a of o)q(t,`${M(If(a))} ${a.message}${a.acknowledged?v(" (seen)"):""}`);o.length>0&&q(t,v(` See them all, and mark one as seen: snoutdata cluster alerts --project ${r}`));return}if(e.length===0){d("No alerts. Nothing has happened to this cluster that needs you.");return}for(let a of o)q(t,`${M(If(a))} ${a.message}`),q(t,v(` ${a.id}, opened ${a.openedAt.slice(0,16).replace("T"," ")}${a.acknowledged?", seen":""}`));if(s.length>0){o.length>0&&q(t),q(t,"Resolved in the last day:");for(let a of s)q(t,` ${a.message}${a.resolution?` ${v(a.resolution)}`:""}`)}}function kv(e){return e.projectsUsed===null||e.maxProjects===null?0:Math.max(0,e.maxProjects-e.projectsUsed)}function _v(e){return e.projectsUsed===null||e.maxProjects===null?"the plan could not be read":`${e.projectsUsed} of ${e.maxProjects} project slots used on the ${e.tier??"current"} plan; each node uses one`}function vv(e,t){let n=_v(e);if(!e.sharded){q(t,`${M(e.ref)} is not a cluster (${n}).`),kv(e)>0&&q(t,`Make it a cluster: snoutdata cluster enable --project ${e.ref} (the database keeps running).`);return}Lf(e.alerts??[],t,!1,e.ref);let r=e.pods.filter(c=>c.desiredState!=="deleted"),o=1+r.filter(c=>!c.replicaOf).length,s=r.length-(o-1);if(q(t,`${M(e.ref)}: ${o} node${o===1?"":"s"}${s>0?` and ${s} replica${s===1?"":"s"}`:""}, ${n}`),e.pods.length>0){let c=e.pods.some(i=>i.replicaOf!==void 0);q(t,X([[" POD","STATE","NEXT",...c?["REPLICA"]:[]],...e.pods.map(i=>[` ${i.ref}`,i.state,bv(e,i),...c?[Sv(i)]:[]])]))}e.router==="starting"?q(t,"The router is starting beside the database, which takes about twenty seconds."):e.router==="paused"&&q(t,"The project is paused; the router wakes with it on the next connection."),e.routerError&&q(t,`The router is not answering: ${e.routerError}`);let a=e.automation;a&&a.queueError?q(t,`Stopped: ${a.queueError}. Retry: snoutdata cluster retry --queue --project ${e.ref}`):a&&(a.queue.length>0||a.queueJob!==null)&&q(t,`Working through a request${a.queueJob!==null?` (job ${a.queueJob})`:""}${a.queue.length>0?`; then ${a.queue.join(", ")}`:""}.`),q(t)}function $v(e){if(e.length===0){d("No jobs yet.");return}q(process.stdout,X([["ID","OPERATION","STATE","STEPS","BY","CREATED","ERROR"],...e.map(t=>[String(t.id),t.op,t.state,`${t.steps_done}/${t.steps}`,t.actor==="lepis"?"autopilot":"you",t.created_at.slice(0,19).replace("T"," "),t.error??""])]))}function Pv(e){let t=process.stdout;q(t,`${M(`Job ${e.id}`)} ${e.op}: ${e.state}${e.error?` (${e.error})`:""}`),q(t,X([[" STEP","KIND","STATE","PHASE"],...e.steps.map(n=>[` ${n.n+1}`,n.kind,n.state,typeof n.detail?.phase=="string"?n.detail.phase:""])])),e.plan&&Array.isArray(e.plan.steps)&&(q(t),Ve(e.plan,t))}be();de();Tn();import{spawn as xv}from"node:child_process";import{createHash as Ev}from"node:crypto";import{chmodSync as Av,renameSync as es,rmSync as jf,writeFileSync as Rv}from"node:fs";import{dirname as Tv,join as Ov}from"node:path";var ts=process.env.SNOUTDATA_NPM_REGISTRY??"https://registry.npmjs.org",Nv="https://github.com/snoutdata/studio/releases/download";function Iv(e,t){let n=t==="x64"||t==="amd64"?"x64":t==="arm64"?"arm64":null;return n?e==="linux"||e==="darwin"?`snoutdata-${e}-${n}`:e==="win32"&&n==="x64"?"snoutdata-windows-x64.exe":null:null}function Cv(e,t){for(let n of e.split(/\r?\n/)){let r=/^([0-9a-f]{64})\s+\*?(.+)$/i.exec(n.trim());if(r&&r[2]===t)return r[1].toLowerCase()}return null}async function Mv(){let e;try{e=await fetch(`${ts}/snoutdata/latest`,{headers:{accept:"application/json"}})}catch(n){throw new C("network",`could not reach ${ts} to find the newest version: ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw new C("server",`${ts} answered ${e.status} when asked for the newest version`);let t=await e.json();if(typeof t.version!="string")throw new C("server",`${ts} did not say which version is newest`);return t.version}async function Uf(e){let t;try{t=await fetch(e)}catch(n){throw new C("network",`could not download ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t.ok)throw new C("failed",`download failed (${t.status}): ${e}`);return Buffer.from(await t.arrayBuffer())}function Dv(e,t){let n=Ov(Tv(e),`.snoutdata-upgrade-${process.pid}`);Rv(n,t,{mode:493});try{if(process.platform==="win32"){let r=`${e}.old`;jf(r,{force:!0}),es(e,r);try{es(n,e)}catch(o){throw es(r,e),o}}else Av(n,493),es(n,e)}catch(r){jf(n,{force:!0});let o=r.code;throw o==="EACCES"||o==="EPERM"?new C("forbidden",`${e} is not writable by this user. Run the installer instead: ${process.platform==="win32"?mt:Rn}`):r}}function Lv(){return new Promise((e,t)=>{let n=xv(process.platform==="win32"?"npm.cmd":"npm",["install","-g","snoutdata@latest"],{stdio:["ignore","inherit","inherit"],shell:process.platform==="win32"});n.on("error",r=>t(new C("tool-missing",`npm could not be run (${r.message}). Run it yourself: ${mt}`))),n.on("exit",r=>e(r??1))})}async function Ff(e={}){let t=e.kind??Er(),n=await Mv(),r=vl(ke,n),o={installed:ke,latest:n,upToDate:!r,install:t};if(!r||e.check)return b({...o,upgraded:!1},()=>{d(r?`snoutdata ${ke} is installed; ${n} is the newest. \`snoutdata upgrade\` installs it.`:`snoutdata ${ke} is the newest version.`)}),0;switch(t){case"npx":return b({...o,upgraded:!1},()=>{d(`This is a copy npx fetched (${ke}). Run \`npx snoutdata@latest\` to use ${n}; there is nothing installed to upgrade.`)}),0;case"source":throw new C("usage",`this snoutdata (${ke}) is running from source, so there is nothing to replace. Install the published one: ${process.platform==="win32"?mt:Rn}`);case"npm":{d(`Upgrading snoutdata ${ke} to ${n} with npm\u2026`);let s=await Lv();if(s!==0)throw new C("failed",`npm exited ${s}. Run it yourself: ${mt}`);return b({...o,upgraded:!0},()=>d(`Upgraded to ${n}.`)),0}case"binary":{let s=Iv(process.platform,process.arch);if(!s)throw new C("failed",`no snoutdata binary is built for ${process.platform}-${process.arch}. Use npm: ${mt}`);d(`Downloading snoutdata ${n} for ${process.platform}-${process.arch}\u2026`);let a=`${Nv}/cli-v${n}`,[c,i]=await Promise.all([Uf(`${a}/${s}`),Uf(`${a}/SHA256SUMS`)]),u=Cv(i.toString("utf8"),s);if(!u)throw new C("failed",`${s} is not listed in the release's SHA256SUMS. Refusing to install.`);let l=Ev("sha256").update(c).digest("hex");if(l!==u)throw new C("failed",`checksum mismatch for ${s}. Refusing to install.
|
|
777
|
-
expected ${
|
|
778
|
-
actual ${
|
|
1094
|
+
`),u($(`Default settings: ${Object.entries(i.settings).map(([p,g])=>`${p}=${g}`).join(", ")}`)),i.refusals&&i.refusals.length>0&&u($(`Refusal kinds: ${i.refusals.map(p=>`${p.kind} (${p.status})`).join(", ")}`))}),0}case"settings":return Xv(e,d);case"autopilot":return Qv(o,e,d,t);case"advise":case"advice":{let i=wt(e,"sample-ms","sampleMs").sampleMs,p=await d().advice(i);return w(p,()=>n0(p,process.stdout)),0}case"check":{let i=await d().check();return w(i,()=>t0(i,process.stdout)),i.summary.errors>0?1:0}case"jobs":return e0(o,s,e,d(),t);case"nodes":case"node":if(o===void 0||o==="list"){let i=await d().status();return w({nodes:i.nodes??[]},()=>Kg(i)),0}break;case"plan":{let i=jg(n.slice(1),e,l),p=await d().plan(i.body);return w(p,()=>rt(p,process.stdout)),0}}let c=jg(n,e,l);if(W(e,"plan")){let i=await d().plan(c.body);return w(i,()=>rt(i,process.stdout)),0}return Vv(c,e,d,t)}async function Vv(e,t,n,r){let o=W(t,"yes"),s=e.body.op;if(e.destructive&&!o&&!r.confirm&&!Pe())throw new y(`${s} moves or deletes data, and nothing was asked: pass --yes to run it, or --plan to see what it would do`);let a=n();if(e.destructive&&!o){let c=await a.plan(e.body);if(rt(c,process.stderr),!await(r.confirm??tn)(`Run ${s} on ${a.target}?`))throw new O("failed","Not run. Nothing was changed.")}let l=await a.submit(e.body);if(l.job===void 0)return w(l.answer,()=>u(l.done)),0;if(W(t,"no-wait"))return w({job:l.job,state:"pending",plan:l.plan},()=>{process.stdout.write(`${l.job}
|
|
1095
|
+
`),u(`Job ${l.job} (${s}) is queued. Follow it: snoutdata cluster jobs watch ${l.job}`)}),0;u(`Job ${l.job} (${s}) is queued; following it. Ctrl+C stops following, not the job.`);let d=await hl(a,l.job,r);return yl(d)}function Cn(e,t){if(e===void 0||e==="")throw new y(t);return e}async function tn(e){let t=Gv({input:process.stdin,output:process.stderr});try{let n=(await t.question(`${e} [y/N] `)).trim().toLowerCase();return n==="y"||n==="yes"}finally{t.close()}}function Yv(e){let t=[...Oa,...zd],n={};for(let r of Ss(e)){let o=r.indexOf("="),s=o<0?r:r.slice(0,o).trim(),a=o<0?"":r.slice(o+1).trim();if(!t.includes(s))throw new y(`--set: unknown setting "${s}". One of ${t.join(", ")}`);let l=Number(a);if(!/^\d+$/.test(a)||!Number.isSafeInteger(l))throw new y(`--set ${s} must be a whole number, not "${a}"`);n[s]=l}return n}async function Xv(e,t){let n={};for(let s of Oa)Object.assign(n,wt(e,fl[s],s));let r=R(e,"set");if(r!==void 0&&Object.assign(n,Yv(r)),Object.keys(n).length===0){let s=await t().status(),a={...s.settings??{},...s.advice_settings??{}};return w({settings:a},()=>process.stdout.write(`${V(Object.entries(a).map(([l,d])=>[l,String(d)]))}
|
|
1096
|
+
`)),0}let o=await t().settings(n);return w(o,()=>u(`Set ${Object.entries(o.settings).map(([s,a])=>`${s}=${a}`).join(", ")}.`)),0}function ks(e,t){let n=`every ${Math.round(t/1e3)} s`;switch(e){case"advise":return`Autopilot: advise. ${n[0].toUpperCase()}${n.slice(1)} it records what it would run, and runs nothing.`;case"auto":return`Autopilot: auto. ${n[0].toUpperCase()}${n.slice(1)}, when no job is running, it runs the advisor's recommendation as a job of its own, never in a keyspace you placed by hand.`;default:return"Autopilot: off. It runs nothing on its own. Turn it on with cluster autopilot advise, or auto."}}function Ug(e){return e?.op?` ${e.op}${e.keyspace?` in ${String(e.keyspace)}`:""}`:""}function Zv(e){let t=e.cloud;if(t?.mode==="auto"){let o=[`${ks("auto",e.interval_ms)} In SnoutData Cloud each goes through the same checks as a move of yours (the database's size, and room on every node).`];if(t.taken_at){let s=Ug(t.request),a=t.job!==null?`it ran${s} (job ${t.job})`:t.error?`it did not run${s}. ${t.error}`:`it is starting${s}`;o.push(`Last taken ${t.taken_at.slice(0,19).replace("T"," ")}: ${a}`)}return o}if(t?.mode==="off")return[ks("off",e.interval_ms)];let n=[ks(e.mode,e.interval_ms)],r=e.last?.decision;if(e.last&&r&&r.kind!=="off"){let o={propose:"it would run",submit:"it ran",nothing:"nothing to run",busy:"it waited for a job",held:"it is waiting for you"},s=Ug(r.request),a=r.job!==void 0?` (job ${r.job})`:"";n.push(`Last decided ${e.last.at.slice(0,19).replace("T"," ")}: ${o[r.kind]??r.kind}${s}${a}${r.why?`. ${r.why}`:""}${r.error?`. It could not: ${r.error}`:""}`)}return n}async function Qv(e,t,n,r){let o=wt(t,"interval-ms","autopilot_interval_ms");if(e===void 0||e==="status"){if(Object.keys(o).length>0){let d=await n().setAutopilot(o);return w(d,()=>u(`Set autopilot_interval_ms=${o.autopilot_interval_ms}.`)),0}let l=await n().autopilot();return w(l,()=>{for(let d of Zv(l))u(d)}),0}if(!Wd.includes(e))throw new y(`cluster autopilot [off|advise|auto] [--interval-ms N], not "${e}"`);let s=e;if(s==="auto"&&!W(t,"yes")){if(!r.confirm&&!Pe())throw new y("autopilot auto lets the router move data on its own, and nothing was asked: pass --yes to turn it on");if(!await(r.confirm??tn)("Let the router move data on its own (autopilot auto)?"))throw new O("failed","Not changed. The autopilot is as it was.")}let a=await n().setAutopilot({autopilot:s,...o});return w(a,()=>u(ks(s,o.autopilot_interval_ms??6e4))),0}async function e0(e,t,n,r,o){switch(e){case void 0:case"list":{let s=await r.jobs();return w({jobs:s},()=>c0(s)),0}case"show":{let s=await r.job(bs(t,"show"));return w(s,()=>d0(s)),0}case"watch":{let s=await hl(r,bs(t,"watch"),o);return yl(s)}case"cancel":{let s=bs(t,"cancel");if(!W(n,"yes")){if(!o.confirm&&!Pe())throw new y(`cancelling job ${s} stops a running operation, and nothing was asked: pass --yes`);if(!await(o.confirm??tn)(`Cancel job ${s} on ${r.target}?`))throw new O("failed","Not cancelled. Nothing was changed.")}let a=await r.cancel(s);return w(a,()=>u(`Job ${s}: ${a.state}.`)),0}case"resume":{let s=bs(t,"resume"),a=await r.resume(s);return W(n,"no-wait")?(w(a,()=>u(`Job ${s}: ${a.state}. Follow it: snoutdata cluster jobs watch ${s}`)),0):yl(await hl(r,s,o))}default:throw new y(`unknown command: cluster jobs ${e}. jobs [list|show|watch|cancel|resume] <id>`)}}async function hl(e,t,n={}){let r=n.pollMs??1e3,o=n.timeoutMs===void 0?1/0:Date.now()+n.timeoutMs,s=new Map;for(;;){let a=await e.job(t);for(let l of a.steps){let d=typeof l.detail?.phase=="string"?l.detail.phase:"",c=`${l.state}${d?` ${d}`:""}`;s.get(l.n)!==c&&(s.set(l.n,c),l.state!=="pending"&&u($(` step ${l.n+1}/${a.steps.length} ${l.kind}: ${c}`)))}if(Xn(a.state))return a;if(Date.now()>=o)throw new O("timeout",`job ${t} is still ${a.state}; it carries on without this command. Follow it again: snoutdata cluster jobs watch ${t}`,{job:a});await new Promise(l=>setTimeout(l,r))}}function yl(e){if(e.state==="done")return w(e,()=>process.stdout.write(`Job ${e.id} (${e.op}): done, ${e.steps.length} step${e.steps.length===1?"":"s"}.
|
|
1097
|
+
`)),0;let t=e.state==="failed"?`failed: ${e.error??"no reason recorded"}. Resume it from the failed step: snoutdata cluster jobs resume ${e.id}`:"was cancelled";throw new O("failed",`job ${e.id} (${e.op}) ${t}`,{job:e})}function Y(e,t=""){e.write(`${t}
|
|
1098
|
+
`)}function wl(e){let t=["B","kB","MB","GB","TB"],n=e,r=0;for(;n>=1e3&&r<t.length-1;)n/=1e3,r+=1;return`${r===0?n:n.toFixed(1)} ${t[r]}`}function rt(e,t){if(Y(t,`${N(e.op)}: ${e.steps.length} step${e.steps.length===1?"":"s"}, ${e.cutovers} cutover${e.cutovers===1?"":"s"}`),e.moves.length>0&&Y(t,V([[" FROM","TO","TABLES","ROWS","SIZE","COPY","PAUSE"],...e.moves.map(n=>[` node ${n.source}`,n.targets.map(r=>`node ${r}`).join(", ")||"-",n.tables.join(", ")||"-",`~${n.estimated_rows.toLocaleString("en-US")}`,wl(n.estimated_bytes),`~${n.estimated_copy_seconds}s`,`~${n.expected_pause_ms}ms`])])),Y(t,` total: ~${e.estimated_rows.toLocaleString("en-US")} rows, ${wl(e.estimated_bytes)}, ~${e.estimated_copy_seconds}s to copy, expected write pause ~${e.expected_pause_ms}ms (ceiling ${e.max_write_pause_ms}ms)`),e.choices&&e.choices.length>0){let n={shard:"shard by",reference:"copy to every node",leave:"leave on the home node"};Y(t,V([[" TABLE","CHOICE","WHY"],...e.choices.map(r=>[` ${r.table}`,r.choice==="shard"?`${n.shard} ${r.column}`:n[r.choice],r.why])]))}Y(t,` steps: ${e.steps.map(n=>n.kind).join(", ")||"none"}`);for(let n of e.warnings)Y(t,` warning: ${n}`);e.assumptions&&Y(t,$(` ${e.assumptions}`))}function at(e){let t=String(e);return/^[\w.:@+-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function qg(e){let t=e,n="snoutdata cluster";switch(e.op){case"range.split":return`${n} range split ${at(`${t.keyspace}:${t.range}`)}${t.at!==void 0?` --at ${at(t.at)}`:""}${t.to!==void 0?` --to ${at(t.to)}`:""}`;case"range.move":return`${n} range move ${at(`${t.keyspace}:${t.range}`)} --to ${at(t.to)}`;case"tenant.pin":return`${n} tenant pin ${at(t.keyspace)} --value ${at(t.value)}${t.node!==void 0?` --node ${at(t.node)}`:""}`;case"node.add":return`${n} nodes add ${at(t.name)} --host ${t.host?at(t.host):"<its address>"}, then ${n} rebalance`;case"rebalance":return`${n} rebalance${t.keyspace?` --keyspace ${at(t.keyspace)}`:""}`;default:return null}}function t0(e,t){let{errors:n,warnings:r,info:o,tables:s}=e.summary;Y(t,`${s} table${s===1?"":"s"} checked: ${n} to fix, ${r} to look at, ${o} suggestion${o===1?"":"s"}.`);let a={error:"fix",warn:"look at",info:"suggestion"};e.findings.forEach((l,d)=>{if(Y(t),Y(t,`${N(`${d+1}. ${l.table}`)} (${a[l.severity]}, ${l.code})`),Y(t,` ${l.message}`),Y(t,` ${l.fix}`),l.sql)for(let c of l.sql.split(`
|
|
1099
|
+
`))Y(t,` sql: ${c}`);l.operation&&Y(t,` run: ${qg(l.operation)??JSON.stringify(l.operation)}`)})}function n0(e,t){Y(t,e.summary),e.advice.forEach((n,r)=>{Y(t),Y(t,`${N(`${r+1}. ${n.op}`)} (${n.metric})`),Y(t,` ${n.reason}`);let o=qg(n.request);if(Y(t,` run: ${o??JSON.stringify(n.request)}`),n.plan){let s=n.plan;Y(t,` plan: ${s.cutovers} cutover${s.cutovers===1?"":"s"}, ~${s.estimated_rows.toLocaleString("en-US")} rows, ${wl(s.estimated_bytes)}, ~${s.estimated_copy_seconds}s to copy, expected write pause ~${s.expected_pause_ms}ms`);for(let a of s.warnings??[])Y(t,` warning: ${a}`)}else n.needs.length>0?Y(t,` needs: ${n.needs.join(", ")}, so it has no plan yet`):n.plan_error&&Y(t,` no plan: ${n.plan_error.message} (${n.plan_error.kind})`)}),e.assumptions&&(Y(t),Y(t,$(e.assumptions)))}function Fg(e,t){return e.nodes?.find(n=>n.id===t)?.name??`node ${t}`}function Kg(e){let t=e.nodes??[];if(t.length===0){u("No nodes in the catalog.");return}Y(process.stdout,V([["ID","NAME","ADDRESS","STATE","HOME","RANGES","POSTGRES"],...t.map(n=>[String(n.id),n.name,`${n.host}:${n.port}/${n.dbname}`,n.state,n.home?"yes":"",String(n.ranges.length),n.server_version_num?String(Math.floor(n.server_version_num/1e4)):"?"])]))}function r0(e){let t=process.stdout;if(e.cloud&&(l0(e.cloud,t),!e.cloud.sharded))return;if(!e.catalog){Y(t,"The home node has no Lepis catalog yet (schema lepis).");return}Y(t,`${N("Cluster")} at epoch ${e.epoch}`),Y(t),Kg(e);for(let s of e.keyspaces??[]){Y(t),Y(t,`${N(`Keyspace ${s.name}`)} (${s.key_type}, ${s.ranges.length} range${s.ranges.length===1?"":"s"})`),Y(t,V([[" RANGE","HI","NODE"],...s.ranges.map(a=>[` ${s.name}:${a.lo}`,a.hi,Fg(e,a.node)])]));for(let a of s.pins)Y(t,` pinned: ${a.value} on ${Fg(e,a.node)}`)}let n=e.tables??[];n.length>0&&(Y(t),Y(t,V([["TABLE","KIND","KEYSPACE","COLUMN"],...n.map(s=>[s.table,s.kind,s.keyspace??"",s.column??""])])));let r=e.routers??[];r.length>0&&(Y(t),Y(t,`Routers: ${r.map(s=>`${s.id} (epoch ${s.epoch}${s.live?"":", not heard from"}${s.current?"":", behind"})`).join("; ")}`));let o=e.jobs??[];o.length>0&&Y(t,`Unfinished jobs: ${o.map(s=>`${s.id} ${s.op} ${s.state}`).join("; ")}`),e.settings&&u($(`Settings: ${Object.entries(e.settings).map(([s,a])=>`${s}=${a}`).join(", ")}`))}function o0(e,t){if(t.joining==="failed"&&t.next!=="delete-pod")return`stopped joining: ${t.joinError??"see the audit log"}. Retry: snoutdata cluster retry ${t.ref} --project ${e.ref}`;if(t.replicaOf)return`replica of node ${t.replicaOf} (${t.state})`;switch(t.next){case"attach":return`ready: snoutdata cluster nodes attach ${t.ref} --project ${e.ref}`;case"delete-pod":return`let go by the cluster: snoutdata cluster nodes remove ${t.ref} --project ${e.ref} deletes its pod`;case"wait":return`starting as a copy of the home node (${t.state})`;case"joining":return t.joining==="spreading"?"joining: taking its share of the data":t.joining==="joining"?"joining the cluster":`joining: starting as a copy of the home node (${t.state})`;default:return t.node?`node ${t.node.id}, ${t.node.state}`:t.state}}function s0(e){if(e.replicaOf)return`replica of node ${e.replicaOf}`;switch(e.failover){case"fence":return"failing over: stopping the node so its replica can take its place";case"promote":return"failing over: its replica is taking its place";case"failed":return`failover stopped: ${e.failoverError??"see cluster alerts"}`;case"held":return"failover held: its replica was behind and its last writes could not be copied to it, so it was not promoted (see cluster alerts)"}return e.desiredState==="deleted"||e.replicaOf===void 0?"":e.replica?`protected by replica ${e.replica}`:e.wantsReplica?"no replica yet: one is being made":"no replica"}function Bg(e){return e.severity.toUpperCase()}function zg(e,t,n,r="<ref>"){let o=e.filter(a=>a.resolvedAt===null),s=e.filter(a=>a.resolvedAt!==null);if(!n){for(let a of o)Y(t,`${N(Bg(a))} ${a.message}${a.acknowledged?$(" (seen)"):""}`);o.length>0&&Y(t,$(` See them all, and mark one as seen: snoutdata cluster alerts --project ${r}`));return}if(e.length===0){u("No alerts. Nothing has happened to this cluster that needs you.");return}for(let a of o)Y(t,`${N(Bg(a))} ${a.message}`),Y(t,$(` ${a.id}, since ${ml(a.openedAt)} (${Hg(a.openedAt,null)} so far)${a.acknowledged?", seen":""}`));if(s.length>0){o.length>0&&Y(t),Y(t,"Resolved in the last day:");for(let a of s)Y(t,` ${a.message}${a.resolution?` ${$(a.resolution)}`:""}`),Y(t,$(` ${ml(a.openedAt)} to ${ml(a.resolvedAt)}, ${Hg(a.openedAt,a.resolvedAt)}`))}}function ml(e){return e?`${e.slice(0,16).replace("T"," ")} UTC`:"unknown"}function Hg(e,t){let n=t?Date.parse(t):Date.now(),r=Math.max(0,Math.round((n-Date.parse(e))/1e3));return r<60?"under a minute":$r(r)}function a0(e){return e.projectsUsed===null||e.maxProjects===null?0:Math.max(0,e.maxProjects-e.projectsUsed)}function i0(e){return e.projectsUsed===null||e.maxProjects===null?"the plan could not be read":`${e.projectsUsed} of ${e.maxProjects} project slots used on the ${e.tier??"current"} plan; each node uses one`}function l0(e,t){let n=i0(e);if(!e.sharded){Y(t,`${N(e.ref)} is not a cluster (${n}).`),a0(e)>0&&Y(t,`Make it a cluster: snoutdata cluster enable --project ${e.ref} (the database keeps running).`);return}zg(e.alerts??[],t,!1,e.ref);let r=e.pods.filter(l=>l.desiredState!=="deleted"),o=1+r.filter(l=>!l.replicaOf).length,s=r.length-(o-1);if(Y(t,`${N(e.ref)}: ${o} node${o===1?"":"s"}${s>0?` and ${s} replica${s===1?"":"s"}`:""}, ${n}`),e.pods.length>0){let l=e.pods.some(d=>d.replicaOf!==void 0);Y(t,V([[" POD","STATE","NEXT",...l?["REPLICA"]:[]],...e.pods.map(d=>[` ${d.ref}`,d.state,o0(e,d),...l?[s0(d)]:[]])]))}e.router==="starting"?Y(t,"The router is starting beside the database, which takes about twenty seconds."):e.router==="paused"&&Y(t,"The project is paused; the router wakes with it on the next connection."),e.routerError&&Y(t,`The router is not answering: ${e.routerError}`);let a=e.automation;a&&a.queueError?Y(t,`Stopped: ${a.queueError}. Retry: snoutdata cluster retry --queue --project ${e.ref}`):a&&(a.queue.length>0||a.queueJob!==null)&&Y(t,`Working through a request${a.queueJob!==null?` (job ${a.queueJob})`:""}${a.queue.length>0?`; then ${a.queue.join(", ")}`:""}.`),Y(t)}function c0(e){if(e.length===0){u("No jobs yet.");return}Y(process.stdout,V([["ID","OPERATION","STATE","STEPS","BY","CREATED","ERROR"],...e.map(t=>[String(t.id),t.op,t.state,`${t.steps_done}/${t.steps}`,t.actor==="lepis"?"autopilot":"you",t.created_at.slice(0,19).replace("T"," "),t.error??""])]))}function d0(e){let t=process.stdout;Y(t,`${N(`Job ${e.id}`)} ${e.op}: ${e.state}${e.error?` (${e.error})`:""}`),Y(t,V([[" STEP","KIND","STATE","PHASE"],...e.steps.map(n=>[` ${n.n+1}`,n.kind,n.state,typeof n.detail?.phase=="string"?n.detail.phase:""])])),e.plan&&Array.isArray(e.plan.steps)&&(Y(t),rt(e.plan,t))}_e();pe();Bn();import{spawn as u0}from"node:child_process";import{createHash as p0}from"node:crypto";import{chmodSync as m0,renameSync as _s,rmSync as Wg,writeFileSync as f0}from"node:fs";import{dirname as g0,join as h0}from"node:path";var xr=process.env.SNOUTDATA_NPM_REGISTRY??"https://registry.npmjs.org",y0="https://github.com/snoutdata/studio/releases/download";function w0(e,t){let n=t==="x64"||t==="amd64"?"x64":t==="arm64"?"arm64":null;return n?e==="linux"||e==="darwin"?`snoutdata-${e}-${n}`:e==="win32"&&n==="x64"?"snoutdata-windows-x64.exe":null:null}function b0(e,t){for(let n of e.split(/\r?\n/)){let r=/^([0-9a-f]{64})\s+\*?(.+)$/i.exec(n.trim());if(r&&r[2]===t)return r[1].toLowerCase()}return null}async function S0(){let e;try{e=await fetch(`${xr}/snoutdata/latest`,{headers:{accept:"application/json"}})}catch(n){throw new O("network",`could not reach ${xr} to find the newest version: ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw new O("server",`${xr} answered ${e.status} when asked for the newest version`);let t=await e.json();if(typeof t.version!="string")throw new O("server",`${xr} did not say which version is newest`);return t.version}async function Vg(e=1500){try{let t=await fetch(`${xr}/snoutdata/latest`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(e)});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"&&Ws($e,n.version)?n.version:null}catch{return null}}async function Jg(e){let t;try{t=await fetch(e)}catch(n){throw new O("network",`could not download ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t.ok)throw new O("failed",`download failed (${t.status}): ${e}`);return Buffer.from(await t.arrayBuffer())}function k0(e,t){let n=h0(g0(e),`.snoutdata-upgrade-${process.pid}`);f0(n,t,{mode:493});try{if(process.platform==="win32"){let r=`${e}.old`;Wg(r,{force:!0}),_s(e,r);try{_s(n,e)}catch(o){throw _s(r,e),o}}else m0(n,493),_s(n,e)}catch(r){Wg(n,{force:!0});let o=r.code;throw o==="EACCES"||o==="EPERM"?new O("forbidden",`${e} is not writable by this user. Run the installer instead: ${process.platform==="win32"?_t:Fn}`):r}}function _0(){return new Promise((e,t)=>{let n=u0(process.platform==="win32"?"npm.cmd":"npm",["install","-g","snoutdata@latest"],{stdio:["ignore","inherit","inherit"],shell:process.platform==="win32"});n.on("error",r=>t(new O("tool-missing",`npm could not be run (${r.message}). Run it yourself: ${_t}`))),n.on("exit",r=>e(r??1))})}async function Yg(e={}){let t=e.kind??Kr(),n=await S0(),r=Ws($e,n),o={installed:$e,latest:n,upToDate:!r,install:t};if(!r||e.check)return w({...o,upgraded:!1},()=>{u(r?`snoutdata ${$e} is installed; ${n} is the newest. \`snoutdata upgrade\` installs it.`:`snoutdata ${$e} is the newest version.`)}),0;switch(t){case"npx":return w({...o,upgraded:!1},()=>{u(`This is a copy npx fetched (${$e}). Run \`npx snoutdata@latest\` to use ${n}; there is nothing installed to upgrade.`)}),0;case"source":throw new O("usage",`this snoutdata (${$e}) is running from source, so there is nothing to replace. Install the published one: ${process.platform==="win32"?_t:Fn}`);case"npm":{u(`Upgrading snoutdata ${$e} to ${n} with npm\u2026`);let s=await _0();if(s!==0)throw new O("failed",`npm exited ${s}. Run it yourself: ${_t}`);return w({...o,upgraded:!0},()=>u(`Upgraded to ${n}.`)),0}case"binary":{let s=w0(process.platform,process.arch);if(!s)throw new O("failed",`no snoutdata binary is built for ${process.platform}-${process.arch}. Use npm: ${_t}`);u(`Downloading snoutdata ${n} for ${process.platform}-${process.arch}\u2026`);let a=`${y0}/cli-v${n}`,[l,d]=await Promise.all([Jg(`${a}/${s}`),Jg(`${a}/SHA256SUMS`)]),c=b0(d.toString("utf8"),s);if(!c)throw new O("failed",`${s} is not listed in the release's SHA256SUMS. Refusing to install.`);let i=p0("sha256").update(l).digest("hex");if(i!==c)throw new O("failed",`checksum mismatch for ${s}. Refusing to install.
|
|
1100
|
+
expected ${c}
|
|
1101
|
+
actual ${i}`);return k0(process.execPath,l),w({...o,upgraded:!0,path:process.execPath},()=>u(`Upgraded ${process.execPath} to ${n}.`)),0}}}to();Ot();Bn();var Xg=`snoutdata ${$e} \u2014 hosted Postgres, from a terminal or an agent
|
|
779
1102
|
|
|
780
1103
|
snoutdata init [--name X] [--env] a database for this folder, linked, ready to use;
|
|
781
1104
|
--env writes DATABASE_URL into ./.env (and adds
|
|
782
1105
|
.env to .gitignore) instead of printing it
|
|
783
|
-
snoutdata login
|
|
784
|
-
|
|
785
|
-
|
|
1106
|
+
snoutdata login sign in through a browser: a page with Google,
|
|
1107
|
+
GitHub and your work email (SSO, or a code by email)
|
|
1108
|
+
snoutdata login --provider google|github straight to that provider
|
|
1109
|
+
snoutdata login --email you@x.com sign in as that account: the page and Google offer
|
|
1110
|
+
it, and a different account is reported at once
|
|
786
1111
|
snoutdata login --sso [--domain D] sign in with your company's identity provider;
|
|
787
1112
|
D is a work email or a domain, and it is asked
|
|
788
1113
|
for when not given. Only the domain is sent
|
|
@@ -852,6 +1177,10 @@ ${o.err.trim()}`),d(" ran seed.sql"),!0}var or="_snoutdata_migrations",X_=`crea
|
|
|
852
1177
|
snoutdata domains add|verify|remove <hostname> [--ref R]
|
|
853
1178
|
|
|
854
1179
|
snoutdata usage [--ref R] [--days 30] [--history] size, compute, and the plan's limit
|
|
1180
|
+
snoutdata usage --tables [--limit 20] and the largest tables, partitions under their parent
|
|
1181
|
+
snoutdata metrics [--ref R] [--node REF] [--window hour|day|week]
|
|
1182
|
+
CPU, memory, disk, connections, transactions,
|
|
1183
|
+
statement time and replica lag, per server
|
|
855
1184
|
|
|
856
1185
|
snoutdata start [--port 54322] [--dir migrations] a Postgres here, migrated and seeded
|
|
857
1186
|
snoutdata stop stop it; the data stays
|
|
@@ -894,11 +1223,23 @@ ${o.err.trim()}`),d(" ran seed.sql"),!0}var or="_snoutdata_migrations",X_=`crea
|
|
|
894
1223
|
snoutdata teams teams you can share a project with
|
|
895
1224
|
snoutdata db url [--ref R] print a connection string
|
|
896
1225
|
snoutdata db psql [--ref R] [-- ...] open psql, with no password typed
|
|
897
|
-
snoutdata db
|
|
1226
|
+
snoutdata db query "SQL" [--ref R] run SQL with no psql installed; rows as a table
|
|
1227
|
+
snoutdata db run FILE.sql [--ref R] a .sql file in one transaction, no psql: the first
|
|
1228
|
+
statement that fails rolls it all back, and says which
|
|
1229
|
+
snoutdata db slow [--limit 10] [--ref R] the statements that took the most time in all
|
|
1230
|
+
snoutdata db reset-password [--grace MINUTES] [--ref R]
|
|
1231
|
+
a new password, on the other of the project's two
|
|
1232
|
+
owner logins (the user name changes with it); the old
|
|
1233
|
+
one works for --grace minutes (default 60, up to 1440;
|
|
1234
|
+
0 stops it now and ends its connections)
|
|
898
1235
|
snoutdata db access [list] [--ref R] who signs in to the database as themselves
|
|
899
1236
|
(OAuth, Postgres 18), and as which role
|
|
900
1237
|
snoutdata db access grant EMAIL [--level full|read] a teammate, or you; read by default
|
|
901
1238
|
snoutdata db access revoke EMAIL|ROLE take it away
|
|
1239
|
+
snoutdata db token [--ref R] a password for user snout_token: you, for an hour
|
|
1240
|
+
snoutdata db allow [list] [--ref R] the addresses that may connect (empty: every address)
|
|
1241
|
+
snoutdata db allow add CIDR [--note TEXT] an address or a range, such as 203.0.113.0/24
|
|
1242
|
+
snoutdata db allow remove CIDR | clear take one off, or let every address in again
|
|
902
1243
|
snoutdata db export [--ref R] [--out FILE] take a copy, and download it
|
|
903
1244
|
snoutdata db export --status [--ref R] what the last copy is doing
|
|
904
1245
|
snoutdata db push [--dir migrations] [--dry-run] run the .sql files, once each
|
|
@@ -949,23 +1290,25 @@ A project comes from --ref, then SNOUTDATA_PROJECT, then
|
|
|
949
1290
|
.snoutdata/project.json in this folder or a parent. A token comes from
|
|
950
1291
|
SNOUTDATA_ACCESS_TOKEN, then the profile's session: ~/.snoutdata/auth.json, or
|
|
951
1292
|
~/.snoutdata/auth.NAME.json for a profile. The profile comes from --profile, then
|
|
952
|
-
SNOUTDATA_PROFILE, then the folder's link (link and init record it), then the
|
|
1293
|
+
SNOUTDATA_PROFILE, then the folder's link (link and init record it), then the one
|
|
1294
|
+
"profile use" chose, then the default.
|
|
953
1295
|
The session that login writes renews itself as it is used, in its own profile; CI, which
|
|
954
1296
|
has no browser to sign in with, wants "tokens create".
|
|
955
1297
|
|
|
956
|
-
psql, pg_dump and pg_restore run by this CLI
|
|
957
|
-
(sslmode=verify-full). SNOUTDATA_DB_SSLMODE=require
|
|
958
|
-
that re-signs Postgres traffic.
|
|
1298
|
+
psql, pg_dump and pg_restore run by this CLI, and its own client (db push, query, run,
|
|
1299
|
+
slow), verify the database's certificate (sslmode=verify-full). SNOUTDATA_DB_SSLMODE=require
|
|
1300
|
+
turns that check off, for a network that re-signs Postgres traffic.
|
|
959
1301
|
|
|
960
1302
|
Docs: https://docs.snoutdata.com/developers/cli
|
|
961
1303
|
Examples: https://github.com/snoutdata/snoutdata (a star helps other people find it)
|
|
962
1304
|
Source: https://github.com/snoutdata/snout-cli
|
|
963
|
-
|
|
964
|
-
`))
|
|
965
|
-
|
|
966
|
-
|
|
1305
|
+
`,$0=["yes","token"];async function v0(e){let[t,n,...r]=e.command;if(W(e,"version")||t==="version"){if(w({version:$e},()=>process.stdout.write(`${$e}
|
|
1306
|
+
`)),!Lt()&&process.stderr.isTTY){let c=await Vg();c&&process.stderr.write($(`${c} is out. Upgrade with: snoutdata upgrade
|
|
1307
|
+
`))}return 0}if(W(e,"help")&&t&&t!=="help"){let c=Il(t,n);if(c.length>0)return w({commands:c.map(i=>({...i,flagHelp:Object.fromEntries(i.flags.map(p=>[p,Ts(i.name,p)]))}))},()=>{for(let i of c){let p="args"in i&&i.args?` ${i.args}`:"",g=i.flags.length>0?` ${i.flags.join(" ")}`:"";process.stdout.write(` snoutdata ${i.name}${p}${g}
|
|
1308
|
+
${i.summary}
|
|
1309
|
+
`);let E=Math.max(0,...i.flags.map(A=>A.length));for(let A of i.flags)process.stdout.write(` ${A.padEnd(E)} ${Ts(i.name,A)}
|
|
967
1310
|
`)}process.stdout.write(`
|
|
968
1311
|
Every command also takes --json, --quiet, --help and --profile.
|
|
969
|
-
`)}),0}let o=
|
|
970
|
-
`);process.env.SNOUTDATA_ACCESS_TOKEN&&
|
|
971
|
-
`),!m&&De()!==Me&&d(`profile ${De()}.`),i.token&&d(`via access token ${i.token.prefix} (${i.token.name})${i.token.project?`, limited to project ${i.token.project}`:""}.`)}),0}case"tokens":switch(n){case void 0:case"list":return await pc(),0;case"create":{let i=E(e,"name")??r[0];if(!i)throw new h("tokens create needs --name (what is it for, and where does it live)");return await uc({name:i,expiresInDays:Fe(e,"expires"),project:E(e,"project")}),0}case"revoke":{let i=r[0];if(!i)throw new h("tokens revoke needs the token's id or its sdt_ prefix");return await mc(i),0}default:throw new h(`unknown command: tokens ${n}`)}case"projects":switch(n){case void 0:case"list":return await oc(),0;case"create":{let i=E(e,"name")??r[0];if(!i)throw new h("projects create needs --name");let u=E(e,"team");return await Ds({teamId:u?await lc(u):void 0,name:i,region:E(e,"region"),servers:E(e,"servers"),size:E(e,"size"),maxSize:E(e,"max-size"),wait:!K(e,"no-wait"),timeoutMs:s(),link:void 0,showUrl:K(e,"show-url")}),0}case"pause":case"resume":case"delete":return await sc(n,E(e,"ref")??r[0]??a(),{wait:!K(e,"no-wait"),timeoutMs:s()}),0;case"scale":{let i=E(e,"instances");return await dc(E(e,"ref")??r[0]??a(),{instances:i===void 0?void 0:cc(i),yes:K(e,"yes")}),0}case"show":{let i=E(e,"ref")??r[0]??a(),u=ht(i);u?Hl(u):await wd(i)}return 0;default:throw new h(`unknown command: projects ${n}`)}case"functions":{let i=c();if(i){if(n==="deploy"){if(!r[0])throw new h("functions deploy needs a name: snoutdata functions deploy <name>");return await Xl(i,r[0],{dir:E(e,"dir"),verifyJwt:!K(e,"no-verify-jwt")}),0}if(n===void 0||n==="list")return Zl(i),0;if((n==="delete"||n==="remove")&&r[0])return await Ql(i,r[0]),0}switch(n){case"deploy":{let u=r[0];if(!u)throw new h("functions deploy needs a name: snoutdata functions deploy <name>");return await Sc(a(),u,{dir:E(e,"dir"),entrypoint:E(e,"entrypoint"),verifyJwt:!K(e,"no-verify-jwt")}),0}case void 0:case"list":return await vc(a()),0;case"size":{let u=r[0];if(!u)throw new h("functions size needs a name: snoutdata functions size <name> --memory MB --concurrency N");return await _c(a(),u,{memoryMb:Fe(e,"memory"),concurrency:Fe(e,"concurrency"),reset:K(e,"reset")}),0}case"logs":return await $c(a(),r[0],{errorsOnly:K(e,"errors"),limit:Fe(e,"tail"),follow:K(e,"follow")}),0;case"delete":case"remove":{let u=r[0];if(!u)throw new h("functions delete needs a name");return await Pc(a(),u),0}default:throw new h(`unknown command: functions ${n}`)}}case"containers":switch(n){case"deploy":{let i=r[0],u=r[1],l=E(e,"dockerfile");if(i&&l){if(u)throw new h("containers deploy takes an image or --dockerfile, not both");if(E(e,"registry-user")||K(e,"clear-registry"))throw new h("an image built with --dockerfile is uploaded to the project and needs no registry login");return await Bc(a(),i,{path:l,port:Fe(e,"port"),wait:!K(e,"no-wait")}),0}if(!i||!u)throw new h("containers deploy needs a name and an image: snoutdata containers deploy <name> <image>, or <name> --dockerfile <dir>");let m=E(e,"registry-user");if(m&&!K(e,"stdin"))throw new h('a registry login takes its token on stdin: echo "$TOKEN" | snoutdata containers deploy <name> <image> --registry-user U --stdin');return await Lc(a(),i,{image:u,port:Fe(e,"port"),registryUser:m,registryPassword:m?await sn():void 0,clearCredential:K(e,"clear-registry"),wait:!K(e,"no-wait")}),0}case void 0:case"list":return await Hc(a()),0;case"logs":return await qc(a(),r[0],{errorsOnly:K(e,"errors"),limit:Fe(e,"tail"),follow:K(e,"follow")}),0;case"restart":{if(!r[0])throw new h("containers restart needs a name");return await Kc(a(),r[0]),0}case"delete":case"remove":{if(!r[0])throw new h("containers delete needs a name");return await Gc(a(),r[0]),0}case"egress":{let i=r[0];if(i===void 0||i==="list"||i==="show")return await Jr(a(),{}),0;if(i==="clear")return await Jr(a(),{clear:!0}),0;if(i==="set"){let u=r.slice(1);if(u.length===0&&!K(e,"none"))throw new h("containers egress set needs at least one destination (api.example.com:443), or --none for nothing outside the project");if(u.length>0&&K(e,"none"))throw new h("containers egress set takes destinations or --none, not both");return await Jr(a(),{set:u}),0}throw new h(`unknown command: containers egress ${i}; it is egress, egress set or egress clear`)}default:throw new h(`unknown command: containers ${n}`)}case"secrets":{let i=c();if(i){if(n==="set")return await tc(i,await Jc(r,{stdin:K(e,"stdin")})),0;if(n===void 0||n==="list")return nc(i),0;if((n==="unset"||n==="remove")&&r[0])return await rc(i,r[0]),0}switch(n){case"set":return await Vc(a(),r,{stdin:K(e,"stdin")}),0;case void 0:case"list":return await Xc(a()),0;case"unset":case"remove":{let u=r[0];if(!u)throw new h("secrets unset needs a name");return await Yc(a(),u),0}default:throw new h(`unknown command: secrets ${n}`)}}case"keys":switch(n){case void 0:case"show":case"list":return await fc(a()),0;case"rotate":return await gc(a(),{force:K(e,"force")}),0;default:throw new h(`unknown command: keys ${n}`)}case"products":{if(n===void 0||n==="list")return await md(a()),0;if(n==="enable"||n==="disable")return await fd(a(),pd(r[0]),n==="enable"),0;throw new h(`unknown command: products ${n}. products [enable|disable ${Zr.join("|")}]`)}case"push":{if(n!=="credentials")throw new h("push credentials [set apns|fcm | remove apns|fcm]");let i=r[0];if(i===void 0||i==="list")return await Pu(a()),0;if(i==="set"){let u=xa(r[1]),l=u==="apns"?await vu({p8:E(e,"p8"),keyId:E(e,"key-id"),teamId:E(e,"team-id"),topic:E(e,"topic"),environment:E(e,"environment")}):await $u(E(e,"file"));return await xu(a(),u,l),0}if(i==="remove"||i==="unset")return await Eu(a(),xa(r[1])),0;throw new h(`unknown command: push credentials ${i}`)}case"auth":return await uu(a(),n,r,{clientId:E(e,"client-id"),stdin:K(e,"stdin"),siteUrl:E(e,"site-url"),allow:E(e,"allow"),file:E(e,"file"),subject:E(e,"subject")}),0;case"realtime":{if(n===void 0||n==="inspect")return Nd(a(),{channel:E(e,"channel"),watch:K(e,"watch")});if(n==="logs")return Id(a(),{channel:E(e,"channel"),since:E(e,"since")});throw new h(`unknown command: realtime ${n}. realtime inspect|logs`)}case"ai":{let i=r[0];switch(n){case void 0:case"status":return await Kd(a()),0;case"enable":case"disable":return await Gd(a(),n==="enable"),0;case"models":if(i===void 0||i==="list")return await zd(a()),0;if(i==="add")return await Vd(a(),r[1],{source:E(e,"source"),upstream:E(e,"model"),provider:E(e,"provider"),baseUrl:E(e,"base-url"),region:E(e,"region"),priceIn:E(e,"price-in"),priceOut:E(e,"price-out"),accessKeyId:E(e,"access-key-id"),authHeader:E(e,"auth-header"),stdin:K(e,"stdin")}),0;if(i==="remove"||i==="delete")return await Yd(a(),r[1]),0;throw new h(`unknown command: ai models ${i}. ai models [add|remove]`);case"providers":if(i===void 0||i==="list")return await Wd(a()),0;if(i==="remove"||i==="delete")return await Jd(a(),r[1]),0;throw new h(`unknown command: ai providers ${i}. ai providers [remove NAME]`);case"routes":if(i===void 0||i==="list")return await Xd(a()),0;if(i==="set")return await Zd(a(),r[1],{models:E(e,"models"),sort:E(e,"sort")}),0;if(i==="remove"||i==="delete")return await Qd(a(),r[1]),0;throw new h(`unknown command: ai routes ${i}. ai routes [set NAME --models a,b | remove NAME]`);case"keys":if(i===void 0||i==="list")return await eu(a()),0;if(i==="create")return await tu(a(),{name:E(e,"name"),models:E(e,"models"),expiresDays:Fe(e,"expires")}),0;if(i==="revoke")return await nu(a(),r[1]),0;throw new h(`unknown command: ai keys ${i}. ai keys [create|revoke]`);case"budgets":if(i===void 0||i==="list")return await ru(a()),0;if(i==="set")return await ou(a(),r[1],{amount:E(e,"amount"),period:E(e,"period"),soft:K(e,"soft")}),0;if(i==="remove"||i==="delete")return await su(a(),r[1]),0;throw new h(`unknown command: ai budgets ${i}. ai budgets [set|remove]`);case"usage":return await au(a(),{days:Fe(e,"days"),by:E(e,"by")}),0;case"test":return iu(a(),{model:E(e,"model"),prompt:E(e,"prompt")});default:throw new h(`unknown command: ai ${n}. ai [enable|disable|models|providers|keys|budgets|usage|test]`)}}case"domains":return await gd(a(),n,r[0]),0;case"teams":return await ic(),0;case"link":{if(K(e,"local")){let l;try{l=ll(n)}catch(y){throw new C("not-found",y instanceof Error?y.message:String(y))}let m=Xt(process.cwd(),{ref:l.ref,...l.name?{name:l.name}:{},local:l.folder});return b({ref:l.ref,local:l.folder,api:l.apiUrl,path:m},()=>{d(`Linked ${l.name??l.ref}, the local project in ${l.folder} (${m}).`),d(`Its API is ${l.apiUrl}; its database is on 127.0.0.1:${l.dbPort}.`)}),0}let i=E(e,"ref")??n;if(!i)throw new h("link needs --ref");let u=Xt(process.cwd(),{ref:i});return b({ref:i,path:u},()=>d(`Linked ${i} (${u}).`)),0}case"db":switch(n){case"url":return await ga(a()),0;case"psql":return Pd(a(),r);case"reset-password":return await ac(a()),0;case"access":return await Rd(a(),r,{level:E(e,"level")}),0;case"push":return ku(a(),{dir:E(e,"dir"),dryRun:!!e.flags["dry-run"],outOfOrder:!!e.flags["out-of-order"]});case"restore":return K(e,"window")?(await hd(a()),0):E(e,"at")?(await yd(a(),E(e,"at"),E(e,"name")),0):Ad(a(),{file:E(e,"file"),force:!!e.flags.force});case"export":return Ed(a(),{timeoutMs:s(),out:E(e,"out"),statusOnly:!!e.flags.status});default:throw new h(n?`unknown command: db ${n}`:"db needs an action: url, psql, reset-password, access, export, push, restore")}case"gen":{if(n!=="types")throw new h(n?`unknown command: gen ${n}`:"gen needs an action: types");let i=K(e,"local")?await $f(await ar()):null,u=i?i.dbUrl:E(e,"db-url");return Ou(r[0],{ref:u?void 0:a(),dbUrl:u,schemas:(E(e,"schema")??"public").split(",").map(l=>l.trim()).filter(Boolean),out:E(e,"out"),sql:i?.sql})}case"start":{let i=c();if(i)return Fl(i)}return kf(await ar(),{port:Fe(e,"port"),dir:E(e,"dir"),noMigrations:K(e,"no-migrations"),outOfOrder:K(e,"out-of-order")});case"stop":{let i=c();return i?Bl(i):_f(await ar())}case"status":{let i=c();return i?Ul(i):vf(await ar())}case"usage":return Rf(a(),{days:Fe(e,"days"),history:!!e.flags.history});case"mcp":return Ef({version:ke,allowDelete:!!e.flags["allow-delete"]});case"init":return Fv(e);case"upgrade":return Ff({check:K(e,"check")});default:throw new h(`unknown command: ${t}`)}}async function Fv(e){let t=al({flag:E(e,"ref")});if(t.kind!=="create"){let o=t.ref;if(t.kind==="linked"?d(`This folder is already linked to ${o}.`):t.kind==="environment"&&d(`Using ${o}, from SNOUTDATA_PROJECT. This folder is not linked to it.`),K(e,"env")?await Hf(o):await ga(o),t.kind==="link"){let s=ht(o),a=Xt(process.cwd(),s?{ref:o,...s.name?{name:s.name}:{},local:s.folder}:{ref:o});d(`Linked this folder to ${o}${t.replaces?`, in place of ${t.replaces}`:""} (${a}).`)}return 0}let n=E(e,"name")??Bv(process.cwd());d(`Creating a project called "${n}"\u2026`),await Ds({name:n,region:E(e,"region"),wait:!0,link:process.cwd(),showUrl:!K(e,"env")});let r=fr({cwd:process.cwd()});return r&&K(e,"env")&&await Hf(r),0}async function Hf(e){let{connection:t}=await Promise.resolve().then(()=>(pe(),et)),n=await t(e),r=xd(process.cwd(),n.uri);d(`${r.replaced?"Updated":"Wrote"} DATABASE_URL in ${r.path}.`),r.ignored&&d("Added .env to .gitignore, since it holds the password.")}function Bv(e){let t=e.split(/[\\/]/).filter(Boolean);return t[t.length-1]??"project"}function Hv(e){if(e instanceof C)return ft(e.code,e.message,e.details),e.exitCode;if(e instanceof h)return ft("usage",e.message),rt.usage;if(e instanceof Et)return ft("not-signed-in",e.message),rt["not-signed-in"];if(e instanceof Re){let r=pt(e.status,e.serverCode);return ft(r,e.message,{status:e.status,...e.serverCode?{serverCode:e.serverCode}:{}}),rt[r]}let t=ul(e);if(t)return ft("usage",t),rt.usage;let n=yr(e);return ft(n,e instanceof Error?e.message:String(e)),rt[n]}function ns(e){process.exitCode=e,setTimeout(()=>process.exit(e),2e3).unref()}function Kv(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}function Li(){return De()===Me?"":` (profile ${De()})`}async function Gv(){Nn(Kv(process.argv.slice(2)));let e;try{e=Vi(process.argv.slice(2))}catch(t){ft("usage",String(t instanceof Error?t.message:t)),ns(rt.usage);return}Nn(e.json),xl(e.flags.quiet===!0),pl(wr({isTty:!!process.stdin.isTTY,json:e.json,env:process.env}));try{nl(rl({flag:E(e,"profile")}).name)}catch(t){ft("usage",String(t instanceof Error?t.message:t)),ns(rt.usage);return}try{ns(await Uv(e))}catch(t){ns(Hv(t))}}Gv();
|
|
1312
|
+
`)}),0}let o=W(e,"help")||t==="help";if(o||!t)return w({version:$e,usage:Xg.trim(),commands:Rs},()=>process.stdout.write(Xg)),o?0:ct.usage;let s=()=>{let c=Le(e,"timeout");if(c!==void 0){if(!(c>0))throw new y("--timeout is a number of seconds greater than zero");return c*1e3}},a=c=>{let i=Le(e,"limit")??c;if(i<1||i>1e3)throw new y("--limit is a whole number from 1 to 1000");return i},l=()=>{let c=Mn({flag:R(e,"ref")});if(!c)throw new y("no project: pass --ref, set SNOUTDATA_PROJECT, or run `snoutdata link --ref <ref>`");return c},d=()=>{let c=Mn({flag:R(e,"ref")});return c?Pt(c):null};for(let c of $0)if(!(c==="yes"&&t==="projects"&&n==="scale")&&e.flags[c]!==void 0&&t!=="cluster")throw new y(`--${c} is only for snoutdata cluster`);switch(t){case"cluster":return Gg(e,{timeoutMs:s()});case"login":{if(W(e,"device")){let g=await zr({name:Fr(),platform:process.platform});w({verifyUrl:g.verifyUrl,code:g.code,expiresAt:g.expiresAt},()=>{u(""),u(` Open ${g.verifyUrl}`),u(` Type ${g.code}`),u(""),u($("Waiting for that to be approved\u2026"))});let E=await Wr(g.secret,{intervalMs:Math.max(1,g.interval)*1e3,expiresAt:g.expiresAt});lt({accessToken:E.token});let A=R(e,"email"),te=A?(await Kt()).email??void 0:void 0;return A&&ta(A,{accessToken:E.token,email:te}),w({ok:!0,name:E.name??null,email:te??null,profile:ke()},()=>u(`Signed in${te?` as ${te}`:""}${bl()}.`)),0}let c=R(e,"domain"),i=W(e,"sso")||c!==void 0;if(i&&R(e,"provider"))throw new y("--sso and --provider are two different doors: pass one or the other");let p=await eo({provider:R(e,"provider"),sso:i,domain:c,noBrowser:W(e,"no-browser")||!Pe(),timeoutMs:s(),email:R(e,"email")});return w({email:p.email??null,profile:ke()},()=>u(`Signed in${p.email?` as ${p.email}`:""}${bl()}.`)),0}case"logout":{if(W(e,"all")){let i=Nr();for(let p of i)Us(void 0,p);return w({ok:!0,profiles:i},()=>u(i.length>0?`Signed out of ${i.join(", ")}.`:"No profile was signed in.")),0}Us();let c=!!process.env.SNOUTDATA_ACCESS_TOKEN;return w({ok:!0,profile:ke(),environmentTokenStillSet:c},()=>{u(`Signed out${bl()}.`),c&&(u("SNOUTDATA_ACCESS_TOKEN is still set in this shell, so commands will keep working."),u($(" unset SNOUTDATA_ACCESS_TOKEN")))}),0}case"profile":{if(n==="use"){let p=r[0];if(!p)throw new y("profile use needs a profile name, as whoami --all lists them");if(p!==be&&!Nr().includes(p))throw new y(`no profile "${p}" is signed in on this machine. Sign in first: snoutdata login --profile ${p}`);return Dl(p),w({ok:!0,profile:p},()=>u(p===be?"Commands use the default profile again.":`Commands now sign in as profile "${p}" unless --profile, SNOUTDATA_PROFILE or a folder's link says otherwise.`)),0}if(n!==void 0&&n!=="show")throw new y(`unknown command: profile ${n}. profile [show], or profile use <name>`);let c=Ms({flag:R(e,"profile")}),i={flag:"from --profile",environment:"from SNOUTDATA_PROFILE",link:"from this folder's link",chosen:"chosen with profile use",default:"the default"}[c.from];return w({profile:c.name,from:c.from},()=>u(`${c.name} (${i})`)),0}case"whoami":{if(W(e,"all")){let E=Nr().map(A=>{let te=js(void 0,A);return{profile:A,email:te?.email??te?.expectedEmail??null,active:A===ke()}});return w({profiles:E,environmentToken:!!process.env.SNOUTDATA_ACCESS_TOKEN},()=>{E.length===0&&u('No profile is signed in on this machine. Run "snoutdata login [--profile NAME]".');let A=Math.max(0,...E.map(te=>te.profile.length));for(let te of E)process.stdout.write(`${te.active?"*":" "} ${te.profile.padEnd(A)} ${te.email??$("(email not stored)")}
|
|
1313
|
+
`);process.env.SNOUTDATA_ACCESS_TOKEN&&u("SNOUTDATA_ACCESS_TOKEN is set in this shell, so commands use it, not these profiles.")}),0}let c=await Kt(),i=Ir()?.expectedEmail,p=!!(i&&c.email&&!na(i,c.email));p&&ce(`This session is ${c.email}, and login asked for ${i}. Run "snoutdata login --email ${i}" to sign in as that account.`);let g=!!process.env.SNOUTDATA_ACCESS_TOKEN;return w({...c,profile:g?null:ke(),...i?{expectedEmail:i,matchesExpected:!p}:{}},()=>{process.stdout.write(`${c.email??c.id}
|
|
1314
|
+
`),!g&&ke()!==be&&u(`profile ${ke()}.`),c.token&&u(`via access token ${c.token.prefix} (${c.token.name})${c.token.project?`, limited to project ${c.token.project}`:""}.`)}),0}case"tokens":switch(n){case void 0:case"list":return await td(),0;case"create":{let c=R(e,"name")??r[0];if(!c)throw new y("tokens create needs --name (what is it for, and where does it live)");return await ed({name:c,expiresInDays:Le(e,"expires"),project:R(e,"project")}),0}case"revoke":{let c=r[0];if(!c)throw new y("tokens revoke needs the token's id or its sdt_ prefix");return await nd(c),0}default:throw new y(`unknown command: tokens ${n}`)}case"projects":switch(n){case void 0:case"list":return await Wc(),0;case"create":{let c=R(e,"name")??r[0];if(!c)throw new y("projects create needs --name");let i=R(e,"team");return await pa({teamId:i?await Xc(i):void 0,name:c,region:R(e,"region"),servers:R(e,"servers"),size:R(e,"size"),maxSize:R(e,"max-size"),wait:!W(e,"no-wait"),timeoutMs:s(),link:void 0,showUrl:W(e,"show-url")}),0}case"pause":case"resume":case"delete":return await Jc(n,R(e,"ref")??r[0]??l(),{wait:!W(e,"no-wait"),timeoutMs:s()}),0;case"scale":{let c=R(e,"instances");return await Qc(R(e,"ref")??r[0]??l(),{instances:c===void 0?void 0:Zc(c),yes:W(e,"yes")}),0}case"show":{let c=R(e,"ref")??r[0]??l(),i=Pt(c);i?Oc(i):await iu(c)}return 0;default:throw new y(`unknown command: projects ${n}`)}case"functions":{let c=d();if(c){if(n==="deploy"){if(!r[0])throw new y("functions deploy needs a name: snoutdata functions deploy <name>");return await Fc(c,r[0],{dir:R(e,"dir"),verifyJwt:!W(e,"no-verify-jwt")}),0}if(n===void 0||n==="list")return Bc(c),0;if((n==="delete"||n==="remove")&&r[0])return await Hc(c,r[0]),0}switch(n){case"deploy":{let i=r[0];if(!i)throw new y("functions deploy needs a name: snoutdata functions deploy <name>");return await cd(l(),i,{dir:R(e,"dir"),entrypoint:R(e,"entrypoint"),verifyJwt:!W(e,"no-verify-jwt")}),0}case void 0:case"list":return await pd(l()),0;case"size":{let i=r[0];if(!i)throw new y("functions size needs a name: snoutdata functions size <name> --memory MB --concurrency N");return await ud(l(),i,{memoryMb:Le(e,"memory"),concurrency:Le(e,"concurrency"),reset:W(e,"reset")}),0}case"logs":return await md(l(),r[0],{errorsOnly:W(e,"errors"),limit:Le(e,"tail"),follow:W(e,"follow")}),0;case"delete":case"remove":{let i=r[0];if(!i)throw new y("functions delete needs a name");return await fd(l(),i),0}default:throw new y(`unknown command: functions ${n}`)}}case"containers":switch(n){case"deploy":{let c=r[0],i=r[1],p=R(e,"dockerfile");if(c&&p){if(i)throw new y("containers deploy takes an image or --dockerfile, not both");if(R(e,"registry-user")||W(e,"clear-registry"))throw new y("an image built with --dockerfile is uploaded to the project and needs no registry login");return await Td(l(),c,{path:p,port:Le(e,"port"),wait:!W(e,"no-wait")}),0}if(!c||!i)throw new y("containers deploy needs a name and an image: snoutdata containers deploy <name> <image>, or <name> --dockerfile <dir>");let g=R(e,"registry-user");if(g&&!W(e,"stdin"))throw new y('a registry login takes its token on stdin: echo "$TOKEN" | snoutdata containers deploy <name> <image> --registry-user U --stdin');return await xd(l(),c,{image:i,port:Le(e,"port"),registryUser:g,registryPassword:g?await hn():void 0,clearCredential:W(e,"clear-registry"),wait:!W(e,"no-wait")}),0}case void 0:case"list":return await Od(l()),0;case"logs":return await Cd(l(),r[0],{errorsOnly:W(e,"errors"),limit:Le(e,"tail"),follow:W(e,"follow")}),0;case"restart":{if(!r[0])throw new y("containers restart needs a name");return await Nd(l(),r[0]),0}case"delete":case"remove":{if(!r[0])throw new y("containers delete needs a name");return await Id(l(),r[0]),0}case"egress":{let c=r[0];if(c===void 0||c==="list"||c==="show")return await fo(l(),{}),0;if(c==="clear")return await fo(l(),{clear:!0}),0;if(c==="set"){let i=r.slice(1);if(i.length===0&&!W(e,"none"))throw new y("containers egress set needs at least one destination (api.example.com:443), or --none for nothing outside the project");if(i.length>0&&W(e,"none"))throw new y("containers egress set takes destinations or --none, not both");return await fo(l(),{set:i}),0}throw new y(`unknown command: containers egress ${c}; it is egress, egress set or egress clear`)}default:throw new y(`unknown command: containers ${n}`)}case"secrets":{let c=d();if(c){if(n==="set")return await qc(c,await Dd(r,{stdin:W(e,"stdin")})),0;if(n===void 0||n==="list")return Kc(c),0;if((n==="unset"||n==="remove")&&r[0])return await zc(c,r[0]),0}switch(n){case"set":return await jd(l(),r,{stdin:W(e,"stdin")}),0;case void 0:case"list":return await Fd(l()),0;case"unset":case"remove":{let i=r[0];if(!i)throw new y("secrets unset needs a name");return await Ud(l(),i),0}default:throw new y(`unknown command: secrets ${n}`)}}case"keys":switch(n){case void 0:case"show":case"list":return await rd(l()),0;case"rotate":return await od(l(),{force:W(e,"force")}),0;default:throw new y(`unknown command: keys ${n}`)}case"products":{if(n===void 0||n==="list")return await nu(l()),0;if(n==="enable"||n==="disable")return await ru(l(),tu(r[0]),n==="enable"),0;throw new y(`unknown command: products ${n}. products [enable|disable ${wo.join("|")}]`)}case"push":{if(n!=="credentials")throw new y("push credentials [set apns|fcm | remove apns|fcm]");let c=r[0];if(c===void 0||c==="list")return await pp(l()),0;if(c==="set"){let i=ri(r[1]),p=i==="apns"?await dp({p8:R(e,"p8"),keyId:R(e,"key-id"),teamId:R(e,"team-id"),topic:R(e,"topic"),environment:R(e,"environment")}):await up(R(e,"file"));return await mp(l(),i,p),0}if(c==="remove"||c==="unset")return await fp(l(),ri(r[1])),0;throw new y(`unknown command: push credentials ${c}`)}case"auth":return await np(l(),n,r,{clientId:R(e,"client-id"),stdin:W(e,"stdin"),siteUrl:R(e,"site-url"),allow:R(e,"allow"),file:R(e,"file"),subject:R(e,"subject")}),0;case"realtime":{if(n===void 0||n==="inspect")return $u(l(),{channel:R(e,"channel"),watch:W(e,"watch")});if(n==="logs")return vu(l(),{channel:R(e,"channel"),since:R(e,"since")});throw new y(`unknown command: realtime ${n}. realtime inspect|logs`)}case"ai":{let c=r[0];switch(n){case void 0:case"status":return await Cu(l()),0;case"enable":case"disable":return await Lu(l(),n==="enable"),0;case"models":if(c===void 0||c==="list")return await Du(l()),0;if(c==="add")return await Fu(l(),r[1],{source:R(e,"source"),upstream:R(e,"model"),provider:R(e,"provider"),baseUrl:R(e,"base-url"),region:R(e,"region"),priceIn:R(e,"price-in"),priceOut:R(e,"price-out"),accessKeyId:R(e,"access-key-id"),authHeader:R(e,"auth-header"),stdin:W(e,"stdin")}),0;if(c==="remove"||c==="delete")return await Bu(l(),r[1]),0;throw new y(`unknown command: ai models ${c}. ai models [add|remove]`);case"providers":if(c===void 0||c==="list")return await ju(l()),0;if(c==="remove"||c==="delete")return await Uu(l(),r[1]),0;throw new y(`unknown command: ai providers ${c}. ai providers [remove NAME]`);case"routes":if(c===void 0||c==="list")return await Hu(l()),0;if(c==="set")return await Gu(l(),r[1],{models:R(e,"models"),sort:R(e,"sort")}),0;if(c==="remove"||c==="delete")return await qu(l(),r[1]),0;throw new y(`unknown command: ai routes ${c}. ai routes [set NAME --models a,b | remove NAME]`);case"keys":if(c===void 0||c==="list")return await Ku(l()),0;if(c==="create")return await zu(l(),{name:R(e,"name"),models:R(e,"models"),expiresDays:Le(e,"expires")}),0;if(c==="revoke")return await Wu(l(),r[1]),0;throw new y(`unknown command: ai keys ${c}. ai keys [create|revoke]`);case"budgets":if(c===void 0||c==="list")return await Ju(l()),0;if(c==="set")return await Vu(l(),r[1],{amount:R(e,"amount"),period:R(e,"period"),soft:W(e,"soft")}),0;if(c==="remove"||c==="delete")return await Yu(l(),r[1]),0;throw new y(`unknown command: ai budgets ${c}. ai budgets [set|remove]`);case"usage":return await Xu(l(),{days:Le(e,"days"),by:R(e,"by")}),0;case"test":return Zu(l(),{model:R(e,"model"),prompt:R(e,"prompt")});default:throw new y(`unknown command: ai ${n}. ai [enable|disable|models|providers|keys|budgets|usage|test]`)}}case"domains":return await ou(l(),n,r[0]),0;case"alerts":{if(n!=="hooks")throw new y("alerts hooks [list], add <url> [--slack], remove <id> or test <id>; a cluster's alerts are cluster alerts");return await lu(l(),r[0],r[1],W(e,"slack")),0}case"teams":return await Yc(),0;case"link":{if(W(e,"local")){let p;try{p=Hl(n)}catch(E){throw new O("not-found",E instanceof Error?E.message:String(E))}let g=sn(process.cwd(),{ref:p.ref,...p.name?{name:p.name}:{},local:p.folder});return w({ref:p.ref,local:p.folder,api:p.apiUrl,path:g},()=>{u(`Linked ${p.name??p.ref}, the local project in ${p.folder} (${g}).`),u(`Its API is ${p.apiUrl}; its database is on 127.0.0.1:${p.dbPort}.`)}),0}let c=R(e,"ref")??n;if(!c)throw new y("link needs --ref");let i=sn(process.cwd(),{ref:c});return w({ref:c,path:i},()=>u(`Linked ${c} (${i}).`)),0}case"db":switch(n){case"url":return await Ka(l()),0;case"psql":return fu(l(),r);case"query":{let c=r.join(" ").trim();if(!c)throw new y('db query needs SQL: snoutdata db query "select now()"');return Tg(l(),c)}case"run":{if(!r[0]||r.length>1)throw new y("db run needs one file: snoutdata db run schema.sql");return Og(l(),r[0])}case"slow":return Ng(l(),{limit:a(10)});case"reset-password":return await Vc(l(),Le(e,"grace")),0;case"access":return await wu(l(),r,{level:R(e,"level")}),0;case"token":return await bu(l()),0;case"allow":return await Su(l(),r,{note:R(e,"note")}),0;case"push":return lp(l(),{dir:R(e,"dir"),dryRun:!!e.flags["dry-run"],outOfOrder:!!e.flags["out-of-order"]});case"restore":return W(e,"window")?(await su(l()),0):R(e,"at")?(await au(l(),R(e,"at"),R(e,"name")),0):yu(l(),{file:R(e,"file"),force:!!e.flags.force});case"export":return hu(l(),{timeoutMs:s(),out:R(e,"out"),statusOnly:!!e.flags.status});default:throw new y(n?`unknown command: db ${n}`:"db needs an action: url, psql, query, run, slow, reset-password, access, token, allow, export, push, restore")}case"gen":{if(n!=="types")throw new y(n?`unknown command: gen ${n}`:"gen needs an action: types");let c=W(e,"local")?await Sg(await _r()):null,i=c?c.dbUrl:R(e,"db-url");return wp(r[0],{ref:i?void 0:l(),dbUrl:i,schemas:(R(e,"schema")??"public").split(",").map(p=>p.trim()).filter(Boolean),out:R(e,"out"),sql:c?.sql})}case"start":{let c=d();if(c)return Rc(c)}return yg(await _r(),{port:Le(e,"port"),dir:R(e,"dir"),noMigrations:W(e,"no-migrations"),outOfOrder:W(e,"out-of-order")});case"stop":{let c=d();return c?Tc(c):wg(await _r())}case"status":{let c=d();return c?Ac(c):bg(await _r())}case"usage":return Lg(l(),{days:Le(e,"days"),history:!!e.flags.history,tables:W(e,"tables"),limit:a(20)});case"metrics":{let c=R(e,"project"),i=c?Mn({flag:c}):l();if(!i)throw new y("no project: pass --ref or --project");return Dg(i,{node:R(e,"node"),window:R(e,"window")})}case"mcp":return $g({version:$e,allowDelete:!!e.flags["allow-delete"]});case"init":return P0(e);case"upgrade":return Yg({check:W(e,"check")});default:throw new y(`unknown command: ${t}`)}}async function P0(e){let t=Fl({flag:R(e,"ref")});if(t.kind!=="create"){let o=t.ref;if(t.kind==="linked"?u(`This folder is already linked to ${o}.`):t.kind==="environment"&&u(`Using ${o}, from SNOUTDATA_PROJECT. This folder is not linked to it.`),W(e,"env")?await Zg(o):await Ka(o),t.kind==="link"){let s=Pt(o),a=sn(process.cwd(),s?{ref:o,...s.name?{name:s.name}:{},local:s.folder}:{ref:o});u(`Linked this folder to ${o}${t.replaces?`, in place of ${t.replaces}`:""} (${a}).`)}return 0}let n=R(e,"name")??x0(process.cwd());u(`Creating a project called "${n}"\u2026`),await pa({name:n,region:R(e,"region"),wait:!0,link:process.cwd(),showUrl:!W(e,"env")});let r=Mn({cwd:process.cwd()});return r&&W(e,"env")&&await Zg(r),0}async function Zg(e){let{connection:t}=await Promise.resolve().then(()=>(me(),et)),n=await t(e),r=gu(process.cwd(),n.uri);u(`${r.replaced?"Updated":"Wrote"} DATABASE_URL in ${r.path}.`),r.ignored&&u("Added .env to .gitignore, since it holds the password.")}function x0(e){let t=e.split(/[\\/]/).filter(Boolean);return t[t.length-1]??"project"}function E0(e){if(e instanceof O)return $t(e.code,e.message,e.details),e.exitCode;if(e instanceof y)return $t("usage",e.message),ct.usage;if(e instanceof vt)return $t("not-signed-in",e.message),ct["not-signed-in"];if(e instanceof xe){let r=kt(e.status,e.serverCode);return $t(r,e.message,{status:e.status,...e.serverCode?{serverCode:e.serverCode}:{}}),ct[r]}let t=Kl(e);if(t)return $t("usage",t),ct.usage;let n=Mr(e);return $t(n,e instanceof Error?e.message:String(e)),ct[n]}function $s(e){process.exitCode=e,setTimeout(()=>process.exit(e),2e3).unref()}function A0(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}function bl(){return ke()===be?"":` (profile ${ke()})`}async function R0(){Gn(A0(process.argv.slice(2)));let e;try{e=Ol(process.argv.slice(2))}catch(t){$t("usage",String(t instanceof Error?t.message:t)),$s(ct.usage);return}Gn(e.json),dc(e.flags.quiet===!0),zl(Dr({isTty:!!process.stdin.isTTY,json:e.json,env:process.env}));try{Ll(Ms({flag:R(e,"profile")}).name)}catch(t){$t("usage",String(t instanceof Error?t.message:t)),$s(ct.usage);return}try{$s(await v0(e))}catch(t){$s(E0(t))}}R0();
|