snoutdata 0.18.2 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/snoutdata.mjs +149 -145
  2. package/package.json +1 -1
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- var Vu=Object.defineProperty;var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var qs=(e,t)=>{for(var n in t)Vu(e,n,{get:t[n],enumerable:!0})};function Gs(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]=Zu(o);if(Yu.has(s)){let l=a??e[++r];if(l===void 0)throw new m(`--${s} needs a value`);n[s]=l;continue}if(a!==void 0)throw new m(`--${s} does not take a value`);if(!Xu.has(s))throw new m(`unknown option --${s}`);n[s]=!0}return{command:t,flags:n,json:n.json===!0}}function Zu(e){let t=e.replace(/^--?/,""),n=t.indexOf("=");return n===-1?[t,void 0]:[t.slice(0,n),t.slice(n+1)]}function S(e,t){let n=e.flags[t];return typeof n=="string"?n:void 0}function N(e,t){return e.flags[t]===!0}function _e(e,t){let n=S(e,t);if(n===void 0)return;let r=Number(n);if(!Number.isInteger(r))throw new m(`--${t} must be a whole number, not "${n}"`);return r}var m,Yu,Xu,be=C(()=>{"use strict";m=class extends Error{},Yu=new Set(["name","sort","at","region","ref","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","admin","token","host","dbname","sslmode","peer-host","to","key-type","ranges","seed","nodes","column","keyspace","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"]);Xu=new Set(["json","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","show-url","check","watch","soft"])});import{chmodSync as Qu,existsSync as Js,mkdirSync as Vs,readFileSync as Ys,rmSync as ep,writeFileSync as Xs}from"node:fs";import{homedir as fn}from"node:os";import{dirname as Mr,join as Zs,parse as tp,resolve as np}from"node:path";function Lr(e=fn()){return Zs(e,".snoutdata","auth.json")}function gn(e=fn()){let t=process.env.SNOUTDATA_ACCESS_TOKEN;if(t)return{accessToken:t};let n=Lr(e);if(!Js(n))return null;try{let r=JSON.parse(Ys(n,"utf8"));return typeof r.accessToken=="string"?r:null}catch{return null}}function Ne(e,t=fn()){let n=Lr(t);Vs(Mr(n),{recursive:!0}),Xs(n,`${JSON.stringify(e,null,2)}
3
- `,{mode:384}),Qu(n,384)}function Qs(e=fn()){ep(Lr(e),{force:!0})}function ea(e,t=Date.now()){return e.expiresAt?e.expiresAt*1e3-6e4<=t:!1}function ta(e){return Zs(e,".snoutdata","project.json")}function ft(e){let t=np(e),n=tp(t).root;for(;;){let r=ta(t);if(Js(r))try{let o=JSON.parse(Ys(r,"utf8"));if(typeof o.ref=="string"&&o.ref)return typeof o.local=="string"&&o.local?{ref:o.ref,directory:t,local:o.local}:{ref:o.ref,directory:t}}catch{}if(t===n)return null;t=Mr(t)}}function gt(e,t){let n=ta(e);return Vs(Mr(n),{recursive:!0}),Xs(n,`${JSON.stringify(t,null,2)}
4
- `),n}function hn(e){let t=e.environment??process.env;return e.flag?e.flag:t.SNOUTDATA_PROJECT?t.SNOUTDATA_PROJECT:ft(e.cwd??process.cwd())?.ref??null}function na(e){let t=e.environment??process.env,n=ft(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 Ge=C(()=>{"use strict"});import{existsSync as Ur,readFileSync as ra}from"node:fs";import{homedir as rp}from"node:os";import{isAbsolute as op,join as We,resolve as ht}from"node:path";function sp(e=process.env,t=process.platform,n=rp()){let r;return t==="win32"?r=e.APPDATA??We(n,"AppData","Roaming"):t==="darwin"?r=We(n,"Library","Application Support"):r=e.XDG_CONFIG_HOME??We(n,".config"),["snoutdata","snoutdata-dev"].map(o=>We(r,o,"localProjects.json"))}function yn(e=sp()){let t=[];for(let n of e)if(Ur(n))try{let r=JSON.parse(ra(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 wn(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 It(e){return Ur(We(e,"compose.yaml"))&&Ur(We(e,".env"))}function ze(e,t=null){let n=ht(e);if(!It(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=wn(ra(We(n,".env"),"utf8")),o=r.get("SNOUT_REF"),s=r.get("POSTGRES_OWNER_PASSWORD");if(!o||!s)throw new Error(`${We(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 oa(e,t=process.cwd(),n=yn()){if(!e){if(It(t))return ze(t);let[i]=n;if(n.length===1&&i)return ze(i.folder,i.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(u=>u.name??u.folder).join(", ")}`)}let r=op(e)?e:ht(t,e);if(It(r)){let i=n.find(u=>ht(u.folder)===ht(r));return ze(r,i?.name??null)}let o=e.toLowerCase(),s=n.filter(i=>i.name?.toLowerCase()===o||i.ref===e),[a]=s;if(s.length===1&&a)return ze(a.folder,a.name);let l=n.map(i=>i.name??i.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 sa(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 aa(e,t,n=yn()){if(t&&It(t))try{let r=n.find(s=>ht(s.folder)===ht(t)),o=ze(t,r?.name??null);if(o.ref===e)return o}catch{}for(let r of n)if(r.ref===e&&It(r.folder))return ze(r.folder,r.name);return null}var Ct=C(()=>{"use strict"});function H(e,t,n){throw new P(e,t,n)}function Ue(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":e===503?"not-ready":e===504?"timeout":e===410?"outdated":e>=500?"server":"failed"}function ia(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 bn(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(ap.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 Le,P,ap,me=C(()=>{"use strict";Le={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},P=class extends Error{code;details;constructor(t,n,r){super(n),this.name="CliFailure",this.code=t,this.details=r}get exitCode(){return Le[this.code]}};ap=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","CERT_HAS_EXPIRED","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT"])});function _n(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 ip){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 yt(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 ca(e){Br=e}function ye(){return(Br??_n({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).canAsk}function wt(){return(Br??_n({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).reason}var ip,Br,at=C(()=>{"use strict";ip=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD"];Br=null});import{createHmac as cp,randomBytes as lp,timingSafeEqual as dp}from"node:crypto";import{existsSync as up,readFileSync as pp}from"node:fs";import{homedir as Fr,hostname as mp}from"node:os";import{join as bt}from"node:path";function fp(e,t,n){if(t==="win32"){let r=n.APPDATA??bt(Fr(),"AppData","Roaming");return bt(r,e)}return t==="darwin"?bt(Fr(),"Library","Application Support",e):bt(n.XDG_CONFIG_HOME??bt(Fr(),".config"),e)}function da(e=process.platform,t=process.env){return t.SNOUTDATA_DESKTOP_CONFIG?[t.SNOUTDATA_DESKTOP_CONFIG]:["snoutdata","snoutdata-dev"].map(n=>bt(fp(n,e,t),"mcp.json"))}function gp(e=process.platform,t=process.env){return da(e,t)[0]}function hp(e=gp()){if(!up(e))return null;try{let t=JSON.parse(pp(e,"utf8"));return typeof t.port!="number"||typeof t.token!="string"||!t.token?null:t}catch{return null}}function yp(e){return e?e.enabled===!1?"server-disabled":e.signInHandoff===!1?"handoff-disabled":null:"no-config"}function bp(e,t,n){return cp("sha256",e).update(`${wp}
2
+ var rp=Object.defineProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var qs=(e,t)=>{for(var n in t)rp(e,n,{get:t[n],enumerable:!0})};function Gs(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]=ap(o);if(op.has(s)){let l=a??e[++r];if(l===void 0)throw new m(`--${s} needs a value`);n[s]=l;continue}if(a!==void 0)throw new m(`--${s} does not take a value`);if(!sp.has(s))throw new m(`unknown option --${s}`);n[s]=!0}return{command:t,flags:n,json:n.json===!0}}function ap(e){let t=e.replace(/^--?/,""),n=t.indexOf("=");return n===-1?[t,void 0]:[t.slice(0,n),t.slice(n+1)]}function S(e,t){let n=e.flags[t];return typeof n=="string"?n:void 0}function I(e,t){return e.flags[t]===!0}function _e(e,t){let n=S(e,t);if(n===void 0)return;let r=Number(n);if(!Number.isInteger(r))throw new m(`--${t} must be a whole number, not "${n}"`);return r}var m,op,sp,be=j(()=>{"use strict";m=class extends Error{},op=new Set(["name","sort","at","region","ref","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","admin","token","host","dbname","sslmode","peer-host","to","key-type","ranges","seed","nodes","column","keyspace","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"]);sp=new Set(["json","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","show-url","check","watch","soft"])});import{chmodSync as ip,existsSync as Js,mkdirSync as Vs,readFileSync as Ys,rmSync as cp,writeFileSync as Xs}from"node:fs";import{homedir as hn}from"node:os";import{dirname as Ur,join as Zs,parse as lp,resolve as dp}from"node:path";function Br(e=hn()){return Zs(e,".snoutdata","auth.json")}function yn(e=hn()){let t=process.env.SNOUTDATA_ACCESS_TOKEN;if(t)return{accessToken:t};let n=Br(e);if(!Js(n))return null;try{let r=JSON.parse(Ys(n,"utf8"));return typeof r.accessToken=="string"?r:null}catch{return null}}function Ne(e,t=hn()){let n=Br(t);Vs(Ur(n),{recursive:!0}),Xs(n,`${JSON.stringify(e,null,2)}
3
+ `,{mode:384}),ip(n,384)}function Qs(e=hn()){cp(Br(e),{force:!0})}function ea(e,t=Date.now()){return e.expiresAt?e.expiresAt*1e3-6e4<=t:!1}function ta(e){return Zs(e,".snoutdata","project.json")}function ft(e){let t=dp(e),n=lp(t).root;for(;;){let r=ta(t);if(Js(r))try{let o=JSON.parse(Ys(r,"utf8"));if(typeof o.ref=="string"&&o.ref)return typeof o.local=="string"&&o.local?{ref:o.ref,directory:t,local:o.local}:{ref:o.ref,directory:t}}catch{}if(t===n)return null;t=Ur(t)}}function gt(e,t){let n=ta(e);return Vs(Ur(n),{recursive:!0}),Xs(n,`${JSON.stringify(t,null,2)}
4
+ `),n}function wn(e){let t=e.environment??process.env;return e.flag?e.flag:t.SNOUTDATA_PROJECT?t.SNOUTDATA_PROJECT:ft(e.cwd??process.cwd())?.ref??null}function na(e){let t=e.environment??process.env,n=ft(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 Ge=j(()=>{"use strict"});import{existsSync as Fr,readFileSync as ra}from"node:fs";import{homedir as up}from"node:os";import{isAbsolute as pp,join as ze,resolve as ht}from"node:path";function mp(e=process.env,t=process.platform,n=up()){let r;return t==="win32"?r=e.APPDATA??ze(n,"AppData","Roaming"):t==="darwin"?r=ze(n,"Library","Application Support"):r=e.XDG_CONFIG_HOME??ze(n,".config"),["snoutdata","snoutdata-dev"].map(o=>ze(r,o,"localProjects.json"))}function bn(e=mp()){let t=[];for(let n of e)if(Fr(n))try{let r=JSON.parse(ra(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 _n(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 Ct(e){return Fr(ze(e,"compose.yaml"))&&Fr(ze(e,".env"))}function We(e,t=null){let n=ht(e);if(!Ct(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=_n(ra(ze(n,".env"),"utf8")),o=r.get("SNOUT_REF"),s=r.get("POSTGRES_OWNER_PASSWORD");if(!o||!s)throw new Error(`${ze(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 oa(e,t=process.cwd(),n=bn()){if(!e){if(Ct(t))return We(t);let[i]=n;if(n.length===1&&i)return We(i.folder,i.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(u=>u.name??u.folder).join(", ")}`)}let r=pp(e)?e:ht(t,e);if(Ct(r)){let i=n.find(u=>ht(u.folder)===ht(r));return We(r,i?.name??null)}let o=e.toLowerCase(),s=n.filter(i=>i.name?.toLowerCase()===o||i.ref===e),[a]=s;if(s.length===1&&a)return We(a.folder,a.name);let l=n.map(i=>i.name??i.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 sa(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 aa(e,t,n=bn()){if(t&&Ct(t))try{let r=n.find(s=>ht(s.folder)===ht(t)),o=We(t,r?.name??null);if(o.ref===e)return o}catch{}for(let r of n)if(r.ref===e&&Ct(r.folder))return We(r.folder,r.name);return null}var jt=j(()=>{"use strict"});function K(e,t,n){throw new P(e,t,n)}function Ue(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&&fp.has(t)?"server":e===503?"not-ready":e===504?"timeout":e===410?"outdated":e>=500?"server":"failed"}function ia(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 Sn(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(gp.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 Le,P,fp,gp,me=j(()=>{"use strict";Le={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},P=class extends Error{code;details;constructor(t,n,r){super(n),this.name="CliFailure",this.code=t,this.details=r}get exitCode(){return Le[this.code]}};fp=new Set(["provider_auth","upstream_error","transport","egress_refused"]);gp=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","CERT_HAS_EXPIRED","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT"])});function kn(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 hp){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 yt(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 ca(e){Hr=e}function ye(){return(Hr??kn({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).canAsk}function wt(){return(Hr??kn({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).reason}var hp,Hr,it=j(()=>{"use strict";hp=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD"];Hr=null});import{createHmac as yp,randomBytes as wp,timingSafeEqual as bp}from"node:crypto";import{existsSync as _p,readFileSync as Sp}from"node:fs";import{homedir as Kr,hostname as kp}from"node:os";import{join as bt}from"node:path";function vp(e,t,n){if(t==="win32"){let r=n.APPDATA??bt(Kr(),"AppData","Roaming");return bt(r,e)}return t==="darwin"?bt(Kr(),"Library","Application Support",e):bt(n.XDG_CONFIG_HOME??bt(Kr(),".config"),e)}function da(e=process.platform,t=process.env){return t.SNOUTDATA_DESKTOP_CONFIG?[t.SNOUTDATA_DESKTOP_CONFIG]:["snoutdata","snoutdata-dev"].map(n=>bt(vp(n,e,t),"mcp.json"))}function $p(e=process.platform,t=process.env){return da(e,t)[0]}function xp(e=$p()){if(!_p(e))return null;try{let t=JSON.parse(Sp(e,"utf8"));return typeof t.port!="number"||typeof t.token!="string"||!t.token?null:t}catch{return null}}function Pp(e){return e?e.enabled===!1?"server-disabled":e.signInHandoff===!1?"handoff-disabled":null:"no-config"}function Ap(e,t,n){return yp("sha256",e).update(`${Ep}
5
5
  ${t}
6
- ${n}`).digest("base64url")}function _p(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&dp(n,r)}async function pa(e){let t=e.port;if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>65535||!e.token)return!1;let n=lp(32).toString("base64url");try{let r=await fetch(`http://127.0.0.1:${t}/cli/prove?nonce=${n}`,{redirect:"error",signal:AbortSignal.timeout(ua)});if(!r.ok)return!1;let o=await r.json();return typeof o.proof=="string"&&_p(o.proof,bp(e.token,t,n))}catch{return!1}}async function Kr(e,t,n,r=pa){if(!await r(e).catch(()=>!1))throw new Sn(e.port);return fetch(`http://127.0.0.1:${e.port}${t}`,{...n,redirect:"error",headers:{...n.headers,Authorization:`Bearer ${e.token}`}})}async function kn(e,t=pa){if(e!==void 0)return la(e,t);let n="no-config";for(let r of da()){let o=hp(r);if(!o)continue;let s=await la(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 la(e,t){let n=yp(e);if(n)return{available:!1,skip:n};let r=e,o;try{let s=await Kr(r,"/cli/whoami",{signal:AbortSignal.timeout(ua)},t);if(!s.ok)return{available:!1,skip:"not-running"};o=await s.json()}catch(s){return s instanceof Sn?{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 ma(e,t){let n=await Kr(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 vn(){return mp()}async function Hr(e,t,n,r){let o=await Kr(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 fa(e){return await Hr(e,"initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"snoutdata-cli",version:"0"}},3e3),(await Hr(e,"tools/list",{},3e3)).tools??[]}async function ga(e,t,n){return Hr(e,"tools/call",{name:t,arguments:n},12e4)}var ua,wp,Sn,$n=C(()=>{"use strict";ua=1500,wp="snoutdata-studio-proof-v1";Sn=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 qr(e){try{return new URL(e).host}catch{return e}}function Pn(e,t=""){return{path:`/v1/fn/${e}${t}`,oldPath:`/functions/v1/${e}${t}`}}function Je(e,t){return{path:`/v1/identity${e}`,oldPath:`/auth/v1${t}`}}function vp(e){return xn.has(qr(e))}function $p(e,t,n){return t===void 0?e:{...e,[n?kp:Sp]:t}}async function Ie(e,t,n={},r=fetch){let o=qr(e),s=n.headers??{};function a(u){return r(`${e}${u?t.oldPath:t.path}`,{method:n.method??"GET",headers:$p(s,n.key,u),body:n.body})}if(xn.has(o))return a(!0);let l=await a(!1);if(l.status!==404)return l;let i=await a(!0);return i.status===404?l:(xn.add(o),i)}async function ya(e,t,n,r=fetch){if(!xn.has(qr(e)))try{await Ie(e,Je("/health","/health"),{key:n},r)}catch{}return`${e}${vp(e)?t.oldPath:t.path}`}var Sp,kp,xn,En=C(()=>{"use strict";Sp="Snout-Key",kp="apikey",xn=new Set});import{basename as xp}from"node:path";function Rn(e={bun:typeof process.versions.bun=="string",execPath:process.execPath,script:process.argv[1]??""}){let t=xp(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 Pp(e=Rn(),t=process.platform){switch(e){case"binary":case"npm":return"snoutdata upgrade";case"npx":return"npx snoutdata@latest";case"source":return t==="win32"?Be:jt}}function Gr(e={}){let t=e.kind??Rn(),n=e.platform??process.platform,r=e.minimum?`${e.minimum} or later is required`:"a newer version is required",o=n==="win32"?Be:`${jt} (or ${Be})`;return`snoutdata ${ue} is installed and ${r}. Run \`${Pp(t,n)}\`, or install again: ${o}`}function wa(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 ue,An,jt,Be,Dt=C(()=>{"use strict";ue="0.18.2",An=`snoutdata-cli/${ue}`,jt="curl -fsSL https://snoutdata.com/install.sh | sh",Be="npm install -g snoutdata@latest"});async function ba(e,t){let n=await Ie(Ce,Pn(e),{method:"POST",key:je,headers:{"Content-Type":"application/json","x-client-info":An},body:JSON.stringify(t)});Nn(n);let r=await n.json().catch(()=>({}));if(n.status===410){let o=r.error;throw In(n,typeof o=="string"?o:"This version of the snoutdata CLI is no longer supported.")}return{status:n.status,body:r}}async function Tn(e={}){let{status:t,body:n}=await ba("cloud-device-start",{client:e});return t===429&&H("quota",n.error??"too many pairing attempts from here: wait a few minutes"),t===404&&H("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)&&H("server",n.error??`could not start a pairing (${t})`),n}async function On(e,t){let n=t.intervalMs,r=Date.parse(t.expiresAt);for(;;){Date.now()>r&&H("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 ba("cloud-device-poll",{secret:e});switch(o===404&&H("not-found","that pairing is not known to the server. Run the command again for a new code."),o===400&&H("usage",s.error??"that is not a pairing secret"),o!==200&&H("server",s.error??`the pairing could not be checked (${o})`),s.status){case"approved":return{token:s.token,name:s.name};case"denied":H("forbidden",s.error??"that pairing was refused in the browser");case"used":H("conflict",s.error??"that pairing has already been completed");case"expired":H("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 Wr=C(()=>{"use strict";re();En();me();Dt()});function Lt(e){Mt=e}function Sa(e){_a=e}function Cn(){return Mt}function w(e){return ka?`\x1B[2m${e}\x1B[0m`:e}function x(e){return ka?`\x1B[1m${e}\x1B[0m`:e}function h(e,t){if(Mt){process.stdout.write(`${JSON.stringify(e,null,2)}
7
- `);return}t()}function d(e){!Mt&&!_a&&process.stderr.write(`${e}
6
+ ${n}`).digest("base64url")}function Rp(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&bp(n,r)}async function pa(e){let t=e.port;if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>65535||!e.token)return!1;let n=wp(32).toString("base64url");try{let r=await fetch(`http://127.0.0.1:${t}/cli/prove?nonce=${n}`,{redirect:"error",signal:AbortSignal.timeout(ua)});if(!r.ok)return!1;let o=await r.json();return typeof o.proof=="string"&&Rp(o.proof,Ap(e.token,t,n))}catch{return!1}}async function Gr(e,t,n,r=pa){if(!await r(e).catch(()=>!1))throw new vn(e.port);return fetch(`http://127.0.0.1:${e.port}${t}`,{...n,redirect:"error",headers:{...n.headers,Authorization:`Bearer ${e.token}`}})}async function $n(e,t=pa){if(e!==void 0)return la(e,t);let n="no-config";for(let r of da()){let o=xp(r);if(!o)continue;let s=await la(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 la(e,t){let n=Pp(e);if(n)return{available:!1,skip:n};let r=e,o;try{let s=await Gr(r,"/cli/whoami",{signal:AbortSignal.timeout(ua)},t);if(!s.ok)return{available:!1,skip:"not-running"};o=await s.json()}catch(s){return s instanceof vn?{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 ma(e,t){let n=await Gr(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 xn(){return kp()}async function qr(e,t,n,r){let o=await Gr(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 fa(e){return await qr(e,"initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"snoutdata-cli",version:"0"}},3e3),(await qr(e,"tools/list",{},3e3)).tools??[]}async function ga(e,t,n){return qr(e,"tools/call",{name:t,arguments:n},12e4)}var ua,Ep,vn,Pn=j(()=>{"use strict";ua=1500,Ep="snoutdata-studio-proof-v1";vn=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 zr(e){try{return new URL(e).host}catch{return e}}function An(e,t=""){return{path:`/v1/fn/${e}${t}`,oldPath:`/functions/v1/${e}${t}`}}function Je(e,t){return{path:`/v1/identity${e}`,oldPath:`/auth/v1${t}`}}function Np(e){return En.has(zr(e))}function Ip(e,t,n){return t===void 0?e:{...e,[n?Op:Tp]:t}}async function Ie(e,t,n={},r=fetch){let o=zr(e),s=n.headers??{};function a(u){return r(`${e}${u?t.oldPath:t.path}`,{method:n.method??"GET",headers:Ip(s,n.key,u),body:n.body})}if(En.has(o))return a(!0);let l=await a(!1);if(l.status!==404)return l;let i=await a(!0);return i.status===404?l:(En.add(o),i)}async function ya(e,t,n,r=fetch){if(!En.has(zr(e)))try{await Ie(e,Je("/health","/health"),{key:n},r)}catch{}return`${e}${Np(e)?t.oldPath:t.path}`}var Tp,Op,En,Rn=j(()=>{"use strict";Tp="Snout-Key",Op="apikey",En=new Set});import{basename as Cp}from"node:path";function On(e={bun:typeof process.versions.bun=="string",execPath:process.execPath,script:process.argv[1]??""}){let t=Cp(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 jp(e=On(),t=process.platform){switch(e){case"binary":case"npm":return"snoutdata upgrade";case"npx":return"npx snoutdata@latest";case"source":return t==="win32"?Be:Dt}}function Wr(e={}){let t=e.kind??On(),n=e.platform??process.platform,r=e.minimum?`${e.minimum} or later is required`:"a newer version is required",o=n==="win32"?Be:`${Dt} (or ${Be})`;return`snoutdata ${ue} is installed and ${r}. Run \`${jp(t,n)}\`, or install again: ${o}`}function wa(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 ue,Tn,Dt,Be,Mt=j(()=>{"use strict";ue="0.18.3",Tn=`snoutdata-cli/${ue}`,Dt="curl -fsSL https://snoutdata.com/install.sh | sh",Be="npm install -g snoutdata@latest"});async function ba(e,t){let n=await Ie(Ce,An(e),{method:"POST",key:je,headers:{"Content-Type":"application/json","x-client-info":Tn},body:JSON.stringify(t)});Cn(n);let r=await n.json().catch(()=>({}));if(n.status===410){let o=r.error;throw jn(n,typeof o=="string"?o:"This version of the snoutdata CLI is no longer supported.")}return{status:n.status,body:r}}async function Nn(e={}){let{status:t,body:n}=await ba("cloud-device-start",{client:e});return t===429&&K("quota",n.error??"too many pairing attempts from here: wait a few minutes"),t===404&&K("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)&&K("server",n.error??`could not start a pairing (${t})`),n}async function In(e,t){let n=t.intervalMs,r=Date.parse(t.expiresAt);for(;;){Date.now()>r&&K("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 ba("cloud-device-poll",{secret:e});switch(o===404&&K("not-found","that pairing is not known to the server. Run the command again for a new code."),o===400&&K("usage",s.error??"that is not a pairing secret"),o!==200&&K("server",s.error??`the pairing could not be checked (${o})`),s.status){case"approved":return{token:s.token,name:s.name};case"denied":K("forbidden",s.error??"that pairing was refused in the browser");case"used":K("conflict",s.error??"that pairing has already been completed");case"expired":K("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 Jr=j(()=>{"use strict";oe();Rn();me();Mt()});function Ut(e){Lt=e}function Sa(e){_a=e}function Dn(){return Lt}function w(e){return ka?`\x1B[2m${e}\x1B[0m`:e}function x(e){return ka?`\x1B[1m${e}\x1B[0m`:e}function h(e,t){if(Lt){process.stdout.write(`${JSON.stringify(e,null,2)}
7
+ `);return}t()}function d(e){!Lt&&!_a&&process.stderr.write(`${e}
8
8
  `)}function Ve(e,t,n){process.stderr.write(`${t}
9
- `),Mt&&process.stdout.write(`${JSON.stringify({ok:!1,code:e,error:t,...n},null,2)}
10
- `)}function Q(e){process.stderr.write(`${e}
11
- `)}function L(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(`
12
- `)}function Fe(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[i,u]of o){if(s<i)break;s=Math.round(s/i),a=u}let l=`${s} ${a}${s===1?"":"s"}`;return n?`in ${l}`:`${l} ago`}var Mt,_a,ka,te=C(()=>{"use strict";Mt=!1,_a=!1;ka=process.stdout.isTTY&&!process.env.NO_COLOR});import{createHash as xa,randomBytes as zr}from"node:crypto";import{createServer as Ap}from"node:http";import{createInterface as Rp}from"node:readline/promises";import{spawn as Tp}from"node:child_process";function jn(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function va(e,t){let n=e==="ok"?"#e0b256":"#e0765a",r=e==="ok"?"Signed in":"Sign-in failed",o=e==="ok"?"You can close this tab and go back to your terminal.":zp(t??"Something went wrong.");return`<!doctype html><html><head><meta charset="utf-8"><title>SnoutData</title>
9
+ `),Lt&&process.stdout.write(`${JSON.stringify({ok:!1,code:e,error:t,...n},null,2)}
10
+ `)}function ee(e){process.stderr.write(`${e}
11
+ `)}function B(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(`
12
+ `)}function Fe(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[i,u]of o){if(s<i)break;s=Math.round(s/i),a=u}let l=`${s} ${a}${s===1?"":"s"}`;return n?`in ${l}`:`${l} ago`}var Lt,_a,ka,ne=j(()=>{"use strict";Lt=!1,_a=!1;ka=process.stdout.isTTY&&!process.env.NO_COLOR});import{createHash as xa,randomBytes as Vr}from"node:crypto";import{createServer as Mp}from"node:http";import{createInterface as Lp}from"node:readline/promises";import{spawn as Up}from"node:child_process";function Mn(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function va(e,t){let n=e==="ok"?"#e0b256":"#e0765a",r=e==="ok"?"Signed in":"Sign-in failed",o=e==="ok"?"You can close this tab and go back to your terminal.":nm(t??"Something went wrong.");return`<!doctype html><html><head><meta charset="utf-8"><title>SnoutData</title>
13
13
  <meta name="viewport" content="width=device-width,initial-scale=1"></head>
14
14
  <body style="font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;background:#050403;color:#e9e4dc;display:grid;place-items:center;min-height:100vh;margin:0">
15
15
  <div style="text-align:center;max-width:460px;padding:40px 24px">
@@ -21,12 +21,14 @@ ${n}`).digest("base64url")}function _p(e,t){let n=Buffer.from(e),r=Buffer.from(t
21
21
  <p style="color:#8f887e;margin:0;font-size:15px;line-height:1.5">${o}</p>
22
22
  ${e==="ok"?"":'<p style="color:#8f887e;margin:14px 0 0;font-size:14px">Run <code style="background:#1b1917;border:1px solid #262320;border-radius:6px;padding:2px 6px;font-size:13px">snoutdata login</code> to try again.</p>'}
23
23
  </div>
24
- </body></html>`}function Jr(){let e=jn(zr(32)),t=jn(xa("sha256").update(e).digest());return{verifier:e,challenge:t}}function Op(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 Np(e){let{command:t,args:n,verbatim:r}=Op(process.platform,e),o=Tp(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}function Vr(){return"1064562458607-9fqmghjoqjr7d56b98agkvjt9vt26pdc.apps.googleusercontent.com"}function jp(){return"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"}function Dp(e){let t=e??jn(zr(32));return{raw:t,hashed:xa("sha256").update(t).digest("hex")}}function Mp(e){return`${Ip}?${new URLSearchParams({...e.loginHint?{login_hint:e.loginHint}:{},client_id:Vr(),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 Lp(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 Yr(e){return new Promise((t,n)=>{let r="",o=Ap((a,l)=>{let i=Lp(a.url??"/",e.state);if(i.kind==="ignore"){l.writeHead(404).end();return}l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(i.kind==="ok"?va("ok"):va("failed",i.message)),o.close(),i.kind==="ok"?t({code:i.code,redirectUri:r}):n(new Error(i.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(i=>{process.stdout.write(`${i}
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."),Np(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 Pa(e,t){let n=await Ie(Ce,Je("/session?via=pkce","/token?grant_type=pkce"),{method:"POST",key:je,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 Ea(await n.json())}async function Up(e,t,n){let r=await fetch(Cp,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:Vr(),client_secret:jp(),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 Bp(e){if(!Vr())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}=Jr(),{raw:r,hashed:o}=Dp(),s=jn(zr(16)),{code:a,redirectUri:l}=await Yr({state:s,timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:c=>Mp({redirectUri:c,challenge:n,hashedNonce:o,state:s,loginHint:e.email})}),i=await Up(a,t,l),u=await Ie(Ce,Je("/session?via=id_token","/token?grant_type=id_token"),{method:"POST",key:je,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 Ea(await u.json())}function Ea(e){let t=e,n={accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,email:t.user?.email};return Ne(n),n}function $a(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 Fp(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 Hp(e,t,n){let r=Fp(t);return e===404||/no sso provider/i.test(r)?new P("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 P("failed",`Single sign-on is not available for ${n} yet. Ask whoever administers your team to connect your identity provider.`,{domain:n}):new P(Ue(e),r||`Could not start single sign-on for ${n}.`,{domain:n})}async function Kp(e){let t=await Ie(Ce,Je("/sso/start","/sso"),{method:"POST",key:je,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 Hp(t.status,n,e.domain);let r;try{r=JSON.parse(n).url}catch{r=void 0}if(typeof r!="string"||!r)throw new P("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 qp(e){if(e!==void 0){let r=$a(e);if(!r)throw new m(`--domain wants a work email or a company domain, like you@yourcompany.com, not "${e}"`);return r}if(!ye()){let r=wt();throw new m(`login --sso needs --domain <your work email or company domain>${r?`, because ${yt(r)}`:""}`)}let t=Rp({input:process.stdin,output:process.stderr}),n=new Promise((r,o)=>{t.once("close",()=>o(new m("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=$a(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 m("no domain to sign in with: pass --domain <your work email or company domain>")}async function Gp(e){let t=await qp(e.domain),{verifier:n,challenge:r}=Jr();d(`Signing in with the identity provider for ${x(t)}.`);let{code:o}=await Yr({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:s=>Kp({domain:t,redirectTo:s,challenge:r})});return Pa(o,n)}async function Dn(e={}){return Xr(e.email,await Wp(e))}function Xr(e,t){if(!e)return t;let n={...t,expectedEmail:e};return Ne(n),t.email&&!Zr(t.email,e)&&Q(`Signed in as ${t.email}, not ${e}. Run \`snoutdata login --email ${e}\` and pick that account.`),n}function Zr(e,t){return e.trim().toLowerCase()===t.trim().toLowerCase()}async function Wp(e){if(e.sso)return Gp({...e,domain:e.domain??e.email});let t=e.provider??"google";if(t==="google")return Bp(e);let{verifier:n,challenge:r}=Jr(),{code:o}=await Yr({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:async s=>{let a=new URL(await ya(Ce,Je("/provider/start","/authorize"),je));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 Pa(o,n)}function zp(e){return e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t])}var Ip,Cp,Mn=C(()=>{"use strict";re();En();be();Ge();me();at();te();Ip="https://accounts.google.com/o/oauth2/v2/auth",Cp="https://oauth2.googleapis.com/token"});import{createInterface as Jp}from"node:readline/promises";async function Qr(e){let t=Jp({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 Vp(){let e=await kn();if(!e.available)return(e.skip==="handoff-disabled"||e.skip==="server-disabled")&&d(w("SnoutData Studio is running but is not set to hand out sign-ins.")),null;let t=e.who.email??"the signed-in account";if(d(""),d(`SnoutData Studio is open here, signed in as ${x(t)}.`),d(w("It can create an access token for this terminal. Your sign-in itself is not handed over,")),d(w("and you can revoke the token later with `snoutdata tokens revoke`.")),!await Qr("Use it?"))return null;d("Asking SnoutData Studio. Approve it there.");let n=await ma(e.config,process.argv.slice(2).join(" ").slice(0,60)||"snoutdata");if("declined"in n)return d(`The app did not create a token: ${n.reason}`),null;let r={accessToken:n.token};return Ne(r),d(`Signed in with "${n.name}".`),r}async function Yp(){if(!await Qr("Sign in with a browser?"))return null;try{let e=await Dn({});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 Xp(){if(!await Qr("Sign in by typing a code into a browser on another machine?"))return null;let e=await Tn({name:vn(),platform:process.platform});d(""),d(` Open ${x(e.verifyUrl)}`),d(` Type ${x(e.code)}`),d(""),d(w("The code is typed rather than in the link on purpose: it is what proves the person")),d(w("at the browser is the person at this terminal. Waiting\u2026"));let t=await On(e.secret,{intervalMs:Math.max(1,e.interval)*1e3,expiresAt:e.expiresAt}),n={accessToken:t.token};return Ne(n),d(`Signed in${t.name?` with "${t.name}"`:""}.`),n}async function Aa(){if(!ye())return null;let e=await Vp();if(e)return e;let t=await Yp();return t||Xp()}var Ra=C(()=>{"use strict";Ge();$n();Wr();at();Mn();te()});var Ae={};qs(Ae,{ACCOUNTS_URL:()=>Ce,APP_KEY:()=>je,ApiError:()=>ge,NotSignedIn:()=>Ye,call:()=>_,connection:()=>ke,errorSentence:()=>Na,exportStatus:()=>_t,isSettled:()=>Oa,listProjects:()=>xe,listTeams:()=>Un,localStack:()=>He,noticeFrom:()=>Nn,outdated:()=>In,requestExport:()=>Ut,unreadableAnswer:()=>Bn,waitForReady:()=>Ft,waitForSettled:()=>Bt,whoami:()=>it,withKeyNames:()=>Ln});function Zp(){let e=wt();return e?`not signed in, and ${yt(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: run `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN"}async function Qp(){let e=gn();if(e||(e=await Aa()),!e)throw new Ye;if(!ea(e)||!e.refreshToken)return e.accessToken;let t=await Ie(Ce,Je("/session?via=renew","/token?grant_type=refresh_token"),{method:"POST",key:je,headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refreshToken})});if(!t.ok)throw new Ye;let n=await t.json(),r={...e,accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at};return Ne(r),r.accessToken}async function _(e,t={},n="POST"){let r=typeof t=="object"&&t?t.ref:void 0;if(typeof r=="string"){let u=He(r);if(u)throw new P("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 Qp(),s=n==="GET"&&typeof t=="object"&&t?`?${new URLSearchParams(t).toString()}`:"",a=await Ie(Ce,Pn(e,s),{method:n,key:je,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-client-info":An},body:n==="GET"?void 0:JSON.stringify(t)});Nn(a);let l=await a.text(),i;try{i=l?JSON.parse(l):{}}catch{throw new ge(a.status,Bn(a.status,a.statusText,l))}if(!a.ok){let u=Na(i)??`${a.status} ${a.statusText}`;if(a.status===401)throw new Ye(u);if(a.status===410)throw In(a,u);let c=typeof i=="object"&&i&&"code"in i&&typeof i.code=="string"?i.code:null;throw new ge(a.status,u,c,i)}return i}function Nn(e){let t=e.headers.get("x-snoutdata-cli-notice");!t||Ta||(Ta=!0,Q(`${t} ${Gr({minimum:e.headers.get("x-snoutdata-cli-minimum")})}`))}function In(e,t){let n=e.headers.get("x-snoutdata-cli-minimum");return new P("outdated",`${t.replace(/\s+$/,"")} ${Gr({minimum:n})}`,{status:410,installed:ue,minimum:n??null})}async function it(){return _("cloud-whoami")}async function xe(){return _("cloud-project-list")}async function ke(e){let t=He(e);return t?sa(t):Ln(await _("cloud-project-connection",{ref:e}))}function Ln(e){let{anonKey:t,serviceRoleKey:n,...r}=e;return{...r,appKey:e.appKey??t??null,serverKey:e.serverKey??n??null}}function He(e){return aa(e,ft(process.cwd())?.local??null)}async function Un(){return _("cloud-team-list")}async function Ut(e){return _("cloud-project-export",{ref:e})}async function _t(e){return _("cloud-project-export",{ref:e},"GET")}async function Bt(e,t,n={}){let r=Date.now()+(n.timeoutMs??3e5);for(;;){let{projects:o}=await xe(),s=o.find(l=>l.ref===e)??null,a=s?.state??"deleted";if(n.onTick?.(a),Oa(t,a))return s;if(Date.now()>=r)throw new ge(504,`${e} is still ${a} after waiting`);await new Promise(l=>setTimeout(l,2e3))}}function Oa(e,t){let n={pause:"paused",resume:"ready",delete:"deleted"}[e];return t===n||t==="error"}async function Ft(e,t={}){let n=Date.now()+(t.timeoutMs??3e5);for(;;){let{projects:r}=await xe(),o=r.find(s=>s.ref===e);if(!o)throw new ge(404,`no project ${e}`);if(t.onTick?.(o.state),o.state==="ready")return o;if(Date.now()>=n)throw new ge(504,`${e} is still ${o.state} after waiting`);await new Promise(s=>setTimeout(s,2e3))}}function Na(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 Bn(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 Ce,je,ge,Ye,Ta,re=C(()=>{"use strict";Ge();Ct();me();at();Ra();te();Dt();En();Ce=process.env.SNOUTDATA_ACCOUNTS_URL??"https://accounts.snoutdata.com",je=process.env.SNOUTDATA_APP_KEY??process.env.SNOUTDATA_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzbm91dGRhdGEiLCJyb2xlIjoic25vdXRfYXBwIiwiaWF0IjoxNzkyMDc2NTQyLCJleHAiOjIxMDQ4NzU1MjR9.hWSbcDfbGuyDHHSFLoZzD8KVSg9bWVZzzQ_eftW6TPM",ge=class extends Error{status;serverCode;body;constructor(t,n,r=null,o){super(n),this.status=t,this.serverCode=r,this.body=o}},Ye=class extends Error{constructor(t){super(t??Zp())}};Ta=!1});function es(e,t){let n=256-256%t.length;for(;;){let r=e(1)[0];if(r<n)return t[r%t.length]}}function $l(e,t,n){let r="";for(;r.length<n;)r+=es(e,t);return r}var Qo,vl,xl=C(()=>{"use strict";Qo="0123456789abcdefghjkmnpqrstvwxyz",vl="abcdefghjkmnpqrstvwxyz"});function Al(e){return es(e,Pl)+$l(e,Qo,El-1)}function ny(e){return ty.test(e)}function le(e){if(!ny(e))throw new Error(`not a project ref: ${JSON.stringify(e)}`);return e}function G(e,t=ry){return le(e),{ref:e,database:e,ownerRole:`${e}_owner`,pod:`snoutpod-${e}`,host:`${e}.${t}`}}var Pl,El,ty,ry,Re=C(()=>{"use strict";xl();Pl=vl,El=13,ty=new RegExp(`^[${Pl}][${Qo}]{${El-1}}$`);ry="db.snoutdata.com"});var Rl=C(()=>{"use strict";Re()});function Ol(e,t){let n=Tl(e,7),r=Tl(t,24);return Math.max(2,Math.ceil(n*24/r))}function Tl(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var ts=C(()=>{"use strict"});function ns(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)?n:null}var rs=C(()=>{"use strict"});var Nl=C(()=>{"use strict"});function jl(e){let n=(e.trim().split(`
26
- `)[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 Ml(e){if(e!==""&&!sy.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()"]}var oy,tt,Il,Cl,Dl,sy,os=C(()=>{"use strict";Re();oy=20,tt="snoutpod_keeper",Il=/^SCRAM-SHA-256\$[0-9]{4,6}:[A-Za-z0-9+/]+=*\$[A-Za-z0-9+/]+=*:[A-Za-z0-9+/]+=*$/,Cl=`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 '${oy} seconds')), ''), coalesce((select last_archived_wal from pg_stat_archiver), ''), exists (select 1 from pg_roles where rolname = '${tt}' and rolreplication) and exists (select 1 from pg_hba_file_rules where database = '{replication}' and '${tt}' = 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`;Dl=/^-----BEGIN CERTIFICATE-----\n[A-Za-z0-9+/=\n]{64,12000}-----END CERTIFICATE-----\n$/,sy=/^(?:"[a-z0-9-]+"|(?:ANY|FIRST) [1-9] \("[a-z0-9-]+"(?:, "[a-z0-9-]+")+\))$/});function Ul(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(`
27
- `)){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 Ll,ss=C(()=>{"use strict";Ll='for h in "$@"; do ( pg_isready -q -h "$h" -p 5432 -U snoutpod_admin -d postgres -t 3; echo "$h $?" ) & done; wait'});function iy(e){return/^[0-9A-F]{1,8}\/[0-9A-F]{1,8}$/i.test(e)}function Fl(e){let[t,n]=(e.trim().split(`
28
- `)[0]??"").split("|");return t==="t"&&n!==void 0&&iy(n)?n:null}var ay,gv,Bl,as=C(()=>{"use strict";ay="/var/lib/postgresql/data",gv=`set -u
29
- D=${ay}
24
+ </body></html>`}function Yr(){let e=Mn(Vr(32)),t=Mn(xa("sha256").update(e).digest());return{verifier:e,challenge:t}}function Bp(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 Fp(e){let{command:t,args:n,verbatim:r}=Bp(process.platform,e),o=Up(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}function Xr(){return"1064562458607-9fqmghjoqjr7d56b98agkvjt9vt26pdc.apps.googleusercontent.com"}function qp(){return"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"}function Gp(e){let t=e??Mn(Vr(32));return{raw:t,hashed:xa("sha256").update(t).digest("hex")}}function zp(e){return`${Hp}?${new URLSearchParams({...e.loginHint?{login_hint:e.loginHint}:{},client_id:Xr(),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 Wp(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 Zr(e){return new Promise((t,n)=>{let r="",o=Mp((a,l)=>{let i=Wp(a.url??"/",e.state);if(i.kind==="ignore"){l.writeHead(404).end();return}l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(i.kind==="ok"?va("ok"):va("failed",i.message)),o.close(),i.kind==="ok"?t({code:i.code,redirectUri:r}):n(new Error(i.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(i=>{process.stdout.write(`${i}
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."),Fp(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 Pa(e,t){let n=await Ie(Ce,Je("/session?via=pkce","/token?grant_type=pkce"),{method:"POST",key:je,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 Ea(await n.json())}async function Jp(e,t,n){let r=await fetch(Kp,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:Xr(),client_secret:qp(),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 Vp(e){if(!Xr())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}=Yr(),{raw:r,hashed:o}=Gp(),s=Mn(Vr(16)),{code:a,redirectUri:l}=await Zr({state:s,timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:c=>zp({redirectUri:c,challenge:n,hashedNonce:o,state:s,loginHint:e.email})}),i=await Jp(a,t,l),u=await Ie(Ce,Je("/session?via=id_token","/token?grant_type=id_token"),{method:"POST",key:je,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 Ea(await u.json())}function Ea(e){let t=e,n={accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,email:t.user?.email};return Ne(n),n}function $a(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 Yp(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 Xp(e,t,n){let r=Yp(t);return e===404||/no sso provider/i.test(r)?new P("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 P("failed",`Single sign-on is not available for ${n} yet. Ask whoever administers your team to connect your identity provider.`,{domain:n}):new P(Ue(e),r||`Could not start single sign-on for ${n}.`,{domain:n})}async function Zp(e){let t=await Ie(Ce,Je("/sso/start","/sso"),{method:"POST",key:je,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 Xp(t.status,n,e.domain);let r;try{r=JSON.parse(n).url}catch{r=void 0}if(typeof r!="string"||!r)throw new P("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 Qp(e){if(e!==void 0){let r=$a(e);if(!r)throw new m(`--domain wants a work email or a company domain, like you@yourcompany.com, not "${e}"`);return r}if(!ye()){let r=wt();throw new m(`login --sso needs --domain <your work email or company domain>${r?`, because ${yt(r)}`:""}`)}let t=Lp({input:process.stdin,output:process.stderr}),n=new Promise((r,o)=>{t.once("close",()=>o(new m("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=$a(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 m("no domain to sign in with: pass --domain <your work email or company domain>")}async function em(e){let t=await Qp(e.domain),{verifier:n,challenge:r}=Yr();d(`Signing in with the identity provider for ${x(t)}.`);let{code:o}=await Zr({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:s=>Zp({domain:t,redirectTo:s,challenge:r})});return Pa(o,n)}async function Ln(e={}){return Qr(e.email,await tm(e))}function Qr(e,t){if(!e)return t;let n={...t,expectedEmail:e};return Ne(n),t.email&&!eo(t.email,e)&&ee(`Signed in as ${t.email}, not ${e}. Run \`snoutdata login --email ${e}\` and pick that account.`),n}function eo(e,t){return e.trim().toLowerCase()===t.trim().toLowerCase()}async function tm(e){if(e.sso)return em({...e,domain:e.domain??e.email});let t=e.provider??"google";if(t==="google")return Vp(e);let{verifier:n,challenge:r}=Yr(),{code:o}=await Zr({callbackPath:"/callback",timeoutMs:e.timeoutMs,noBrowser:e.noBrowser,authorizeUrl:async s=>{let a=new URL(await ya(Ce,Je("/provider/start","/authorize"),je));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 Pa(o,n)}function nm(e){return e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t])}var Hp,Kp,Un=j(()=>{"use strict";oe();Rn();be();Ge();me();it();ne();Hp="https://accounts.google.com/o/oauth2/v2/auth",Kp="https://oauth2.googleapis.com/token"});import{createInterface as rm}from"node:readline/promises";async function to(e){let t=rm({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 om(){let e=await $n();if(!e.available)return(e.skip==="handoff-disabled"||e.skip==="server-disabled")&&d(w("SnoutData Studio is running but is not set to hand out sign-ins.")),null;let t=e.who.email??"the signed-in account";if(d(""),d(`SnoutData Studio is open here, signed in as ${x(t)}.`),d(w("It can create an access token for this terminal. Your sign-in itself is not handed over,")),d(w("and you can revoke the token later with `snoutdata tokens revoke`.")),!await to("Use it?"))return null;d("Asking SnoutData Studio. Approve it there.");let n=await ma(e.config,process.argv.slice(2).join(" ").slice(0,60)||"snoutdata");if("declined"in n)return d(`The app did not create a token: ${n.reason}`),null;let r={accessToken:n.token};return Ne(r),d(`Signed in with "${n.name}".`),r}async function sm(){if(!await to("Sign in with a browser?"))return null;try{let e=await Ln({});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 am(){if(!await to("Sign in by typing a code into a browser on another machine?"))return null;let e=await Nn({name:xn(),platform:process.platform});d(""),d(` Open ${x(e.verifyUrl)}`),d(` Type ${x(e.code)}`),d(""),d(w("The code is typed rather than in the link on purpose: it is what proves the person")),d(w("at the browser is the person at this terminal. Waiting\u2026"));let t=await In(e.secret,{intervalMs:Math.max(1,e.interval)*1e3,expiresAt:e.expiresAt}),n={accessToken:t.token};return Ne(n),d(`Signed in${t.name?` with "${t.name}"`:""}.`),n}async function Aa(){if(!ye())return null;let e=await om();if(e)return e;let t=await sm();return t||am()}var Ra=j(()=>{"use strict";Ge();Pn();Jr();it();Un();ne()});var Re={};qs(Re,{ACCOUNTS_URL:()=>Ce,APP_KEY:()=>je,ApiError:()=>ge,NotSignedIn:()=>Ye,call:()=>_,connection:()=>ke,errorSentence:()=>Ia,exportStatus:()=>_t,isSettled:()=>Na,listProjects:()=>xe,listTeams:()=>Fn,localStack:()=>He,noticeFrom:()=>Cn,outdated:()=>jn,requestExport:()=>Bt,serverCodeOf:()=>Oa,unreadableAnswer:()=>Hn,waitForReady:()=>Ht,waitForSettled:()=>Ft,whoami:()=>ct,withKeyNames:()=>Bn});function im(){let e=wt();return e?`not signed in, and ${yt(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: run `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN"}async function cm(){let e=yn();if(e||(e=await Aa()),!e)throw new Ye;if(!ea(e)||!e.refreshToken)return e.accessToken;let t=await Ie(Ce,Je("/session?via=renew","/token?grant_type=refresh_token"),{method:"POST",key:je,headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refreshToken})});if(!t.ok)throw new Ye;let n=await t.json(),r={...e,accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at};return Ne(r),r.accessToken}async function _(e,t={},n="POST"){let r=typeof t=="object"&&t?t.ref:void 0;if(typeof r=="string"){let u=He(r);if(u)throw new P("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 cm(),s=n==="GET"&&typeof t=="object"&&t?`?${new URLSearchParams(t).toString()}`:"",a=await Ie(Ce,An(e,s),{method:n,key:je,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-client-info":Tn},body:n==="GET"?void 0:JSON.stringify(t)});Cn(a);let l=await a.text(),i;try{i=l?JSON.parse(l):{}}catch{throw new ge(a.status,Hn(a.status,a.statusText,l))}if(!a.ok){let u=Ia(i)??`${a.status} ${a.statusText}`;throw a.status===401?new Ye(u):a.status===410?jn(a,u):new ge(a.status,u,Oa(i),i)}return i}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 Cn(e){let t=e.headers.get("x-snoutdata-cli-notice");!t||Ta||(Ta=!0,ee(`${t} ${Wr({minimum:e.headers.get("x-snoutdata-cli-minimum")})}`))}function jn(e,t){let n=e.headers.get("x-snoutdata-cli-minimum");return new P("outdated",`${t.replace(/\s+$/,"")} ${Wr({minimum:n})}`,{status:410,installed:ue,minimum:n??null})}async function ct(){return _("cloud-whoami")}async function xe(){return _("cloud-project-list")}async function ke(e){let t=He(e);return t?sa(t):Bn(await _("cloud-project-connection",{ref:e}))}function Bn(e){let{anonKey:t,serviceRoleKey:n,...r}=e;return{...r,appKey:e.appKey??t??null,serverKey:e.serverKey??n??null}}function He(e){return aa(e,ft(process.cwd())?.local??null)}async function Fn(){return _("cloud-team-list")}async function Bt(e){return _("cloud-project-export",{ref:e})}async function _t(e){return _("cloud-project-export",{ref:e},"GET")}async function Ft(e,t,n={}){let r=Date.now()+(n.timeoutMs??3e5);for(;;){let{projects:o}=await xe(),s=o.find(l=>l.ref===e)??null,a=s?.state??"deleted";if(n.onTick?.(a),Na(t,a))return s;if(Date.now()>=r)throw new ge(504,`${e} is still ${a} after waiting`);await new Promise(l=>setTimeout(l,2e3))}}function Na(e,t){let n={pause:"paused",resume:"ready",delete:"deleted"}[e];return t===n||t==="error"}async function Ht(e,t={}){let n=Date.now()+(t.timeoutMs??3e5);for(;;){let{projects:r}=await xe(),o=r.find(s=>s.ref===e);if(!o)throw new ge(404,`no project ${e}`);if(t.onTick?.(o.state),o.state==="ready")return o;if(Date.now()>=n)throw new ge(504,`${e} is still ${o.state} after waiting`);await new Promise(s=>setTimeout(s,2e3))}}function Ia(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 Hn(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 Ce,je,ge,Ye,Ta,oe=j(()=>{"use strict";Ge();jt();me();it();Ra();ne();Mt();Rn();Ce=process.env.SNOUTDATA_ACCOUNTS_URL??"https://accounts.snoutdata.com",je=process.env.SNOUTDATA_APP_KEY??process.env.SNOUTDATA_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzbm91dGRhdGEiLCJyb2xlIjoic25vdXRfYXBwIiwiaWF0IjoxNzkyMDc2NTQyLCJleHAiOjIxMDQ4NzU1MjR9.hWSbcDfbGuyDHHSFLoZzD8KVSg9bWVZzzQ_eftW6TPM",ge=class extends Error{status;serverCode;body;constructor(t,n,r=null,o){super(n),this.status=t,this.serverCode=r,this.body=o}},Ye=class extends Error{constructor(t){super(t??im())}};Ta=!1});var $l,dy,xl=j(()=>{"use strict";$l="snoutpod_isolation",dy=`table bridge ${$l}
26
+ delete table bridge ${$l}
27
+ `});function ns(e,t){let n=256-256%t.length;for(;;){let r=e(1)[0];if(r<n)return t[r%t.length]}}function El(e,t,n){let r="";for(;r.length<n;)r+=ns(e,t);return r}var ts,Pl,Al=j(()=>{"use strict";ts="0123456789abcdefghjkmnpqrstvwxyz",Pl="abcdefghjkmnpqrstvwxyz"});function Ol(e){return ns(e,Rl)+El(e,ts,Tl-1)}function py(e){return uy.test(e)}function de(e){if(!py(e))throw new Error(`not a project ref: ${JSON.stringify(e)}`);return e}function G(e,t=my){return de(e),{ref:e,database:e,ownerRole:`${e}_owner`,pod:`snoutpod-${e}`,host:`${e}.${t}`}}var Rl,Tl,uy,my,Te=j(()=>{"use strict";Al();Rl=Pl,Tl=13,uy=new RegExp(`^[${Rl}][${ts}]{${Tl-1}}$`);my="db.snoutdata.com"});var Nl=j(()=>{"use strict";Te()});function Cl(e,t){let n=Il(e,7),r=Il(t,24);return Math.max(2,Math.ceil(n*24/r))}function Il(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var rs=j(()=>{"use strict"});function os(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)?n:null}var ss=j(()=>{"use strict"});var jl=j(()=>{"use strict"});function Ll(e){let n=(e.trim().split(`
28
+ `)[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 yy(e){if(!fy.test(e))throw new Error(`not a keeper name: ${e}`);return`keeper_${e.replace(/-/g,"_")}`}function Bl(e){let t=e.map(r=>`'${yy(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 Fl(e){if(e!==""&&!hy.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()"]}var fy,gy,tt,Dl,Ml,Ul,hy,as=j(()=>{"use strict";Te();fy=/^[a-z0-9][a-z0-9-]*$/,gy=20,tt="snoutpod_keeper",Dl=/^SCRAM-SHA-256\$[0-9]{4,6}:[A-Za-z0-9+/]+=*\$[A-Za-z0-9+/]+=*:[A-Za-z0-9+/]+=*$/,Ml=`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 '${gy} seconds')), ''), coalesce((select last_archived_wal from pg_stat_archiver), ''), exists (select 1 from pg_roles where rolname = '${tt}' and rolreplication) and exists (select 1 from pg_hba_file_rules where database = '{replication}' and '${tt}' = 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`;Ul=/^-----BEGIN CERTIFICATE-----\n[A-Za-z0-9+/=\n]{64,12000}-----END CERTIFICATE-----\n$/,hy=/^(?:"[a-z0-9-]+"|(?:ANY|FIRST) [1-9] \("[a-z0-9-]+"(?:, "[a-z0-9-]+")+\))$/});function Kl(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(`
29
+ `)){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 Hl,is=j(()=>{"use strict";Hl='for h in "$@"; do ( pg_isready -q -h "$h" -p 5432 -U snoutpod_admin -d postgres -t 3; echo "$h $?" ) & done; wait'});function by(e){return/^[0-9A-F]{1,8}\/[0-9A-F]{1,8}$/i.test(e)}function Gl(e){let[t,n]=(e.trim().split(`
30
+ `)[0]??"").split("|");return t==="t"&&n!==void 0&&by(n)?n:null}var wy,Nv,ql,cs=j(()=>{"use strict";wy="/var/lib/postgresql/data",Nv=`set -u
31
+ D=${wy}
30
32
  W="$D/pg_wal"
31
33
  fail() { echo "salvage-error $*"; exit 3; }
32
34
  [ -d "$W" ] || fail "the volume has no pg_wal"
@@ -65,22 +67,22 @@ for s in $segs; do
65
67
  echo "salvage-pushed $s"
66
68
  done
67
69
  echo "salvage-done"
68
- `;Bl="select pg_is_in_recovery(), coalesce(pg_last_wal_replay_lsn()::text, '')"});var wv,Hl=C(()=>{"use strict";Re();wv=7*24});var _v,Kl=C(()=>{"use strict";_v=7*24*60*60*1e3});var cy,ql=C(()=>{"use strict";Kl();cy=60*60*1e3});var Gl=C(()=>{"use strict"});var is,Ev,Wl=C(()=>{"use strict";is="snoutdata_realtime",Ev=`do $snoutpod$
70
+ `;ql="select pg_is_in_recovery(), coalesce(pg_last_wal_replay_lsn()::text, '')"});var jv,zl=j(()=>{"use strict";Te();jv=7*24});var Mv,Wl=j(()=>{"use strict";Mv=7*24*60*60*1e3});var _y,Jl=j(()=>{"use strict";Wl();_y=60*60*1e3});var Vl=j(()=>{"use strict"});var ls,qv,Yl=j(()=>{"use strict";ls="snoutdata_realtime",qv=`do $snoutpod$
69
71
  begin
70
- if exists (select 1 from pg_publication where pubname = '${is}') then
72
+ if exists (select 1 from pg_publication where pubname = '${ls}') then
71
73
  return;
72
74
  end if;
73
- create publication ${is};
74
- execute format('alter publication ${is} owner to %I',
75
+ create publication ${ls};
76
+ execute format('alter publication ${ls} owner to %I',
75
77
  (select pg_get_userbyid(datdba) from pg_database where datname = current_database()));
76
78
  end
77
79
  $snoutpod$;
78
- `});var Rv,Tv,zl=C(()=>{"use strict";Rv=2*1024*1024,Tv=64*1024});var Jl=C(()=>{"use strict"});function cs(e,t,n){if(!n.test(t))throw new Error(`${e} is not a value this can route: ${JSON.stringify(t)}`);return t}function yr(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(r!=null)return dy(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 dy(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(cs("the subnet",n,Vl),cs("the sink",r,ly),!Xl(r,n))throw new Error(`the sink ${r} is not inside ${n}, so denied traffic would be routed at the host`);if(e.gateway&&!Xl(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",`${cs("a denied prefix",s,Vl)},${r}`);return o.push(e.name),o}function Yl(e){return e.split(".").reduce((t,n)=>t*256+Number(n),0)}function Xl(e,t){let[n,r]=t.split("/"),o=Number(r),s=o===0?0:4294967295<<32-o>>>0;return(Yl(e)&s)>>>0===(Yl(n??"")&s)>>>0}function Ql(e){return e?.internal===!0}var Zl,Vl,ly,ls=C(()=>{"use strict";Zl=["169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"],Vl=/^((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])$/,ly=/^((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 uy,wr=C(()=>{"use strict";uy=7*24*60*60});function gy(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 i=2**(32-l);a.push(`${o}${(s^i)&~(i-1)&255}/${l}`)}return a}var my,fy,zv,ed=C(()=>{"use strict";Re();zl();Jl();ls();wr();my="10.93.0.0/24",fy="10.93.0.1",zv=[...Zl,"100.64.0.0/10",...gy(my,fy)]});var td=C(()=>{"use strict"});import{createHash as hy}from"node:crypto";function br(e){return`${G(e).pod}-lepis-tls`}function wy(e){return hy("sha256").update(`snout-lepis-admin:${e}`).digest("hex")}function sd(e,t){let n={...e},r=n[ds],o=n[us];delete n[ds],delete n[us];for(let[s,a,l]of[[ds,r,t],[us,o,wy(t)]])if(a!==void 0){if(!yy.test(a))throw new Error(`${s} names ${JSON.stringify(a)}, which is not a variable name`);n[a]=l}return n}var tn,ds,us,nd,rd,ps,od,yy,ms=C(()=>{"use strict";Re();td();tn="lepis",ds="SNOUTPOD_ADMIN_PASSWORD_ENV",us="SNOUTPOD_ADMIN_TOKEN_ENV",nd=7433,rd=1e3;ps="/tls",od=["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(`
79
- `),yy=/^[A-Z][A-Z0-9_]{0,63}$/});var s$,a$,ad=C(()=>{"use strict";Re();wr();s$=6*60*60,a$=5*60});var id=C(()=>{"use strict"});var cd=C(()=>{"use strict"});var d$,ld=C(()=>{"use strict";d$=15*6e4});var g$,dd=C(()=>{"use strict";ld();g$=2*1024**3});var ud=C(()=>{"use strict";cd();dd()});function md(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"||!_y.test(o))throw new Error(`not a database access role: ${JSON.stringify(o)}`);if(typeof s!="string"||!by.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 fd(e,t){return`${e}.nspname !~ '^pg_'
80
- and ${e}.nspname <> all (array[${pd.map(n=>`'${n}'`).join(", ")}]::text[])
80
+ `});var zv,Wv,Xl=j(()=>{"use strict";zv=2*1024*1024,Wv=64*1024});var Zl=j(()=>{"use strict"});function ds(e,t,n){if(!n.test(t))throw new Error(`${e} is not a value this can route: ${JSON.stringify(t)}`);return t}function br(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(r!=null)return ky(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 ky(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(ds("the subnet",n,Ql),ds("the sink",r,Sy),!td(r,n))throw new Error(`the sink ${r} is not inside ${n}, so denied traffic would be routed at the host`);if(e.gateway&&!td(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",`${ds("a denied prefix",s,Ql)},${r}`);return o.push(e.name),o}function ed(e){return e.split(".").reduce((t,n)=>t*256+Number(n),0)}function td(e,t){let[n,r]=t.split("/"),o=Number(r),s=o===0?0:4294967295<<32-o>>>0;return(ed(e)&s)>>>0===(ed(n??"")&s)>>>0}function rd(e){return e?.internal===!0}var nd,Ql,Sy,us=j(()=>{"use strict";nd=["169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"],Ql=/^((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])$/,Sy=/^((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 vy,_r=j(()=>{"use strict";vy=7*24*60*60});function Ey(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 i=2**(32-l);a.push(`${o}${(s^i)&~(i-1)&255}/${l}`)}return a}var xy,Py,d$,od=j(()=>{"use strict";Te();Xl();Zl();us();_r();xy="10.93.0.0/24",Py="10.93.0.1",d$=[...nd,"100.64.0.0/10",...Ey(xy,Py)]});var sd=j(()=>{"use strict"});import{createHash as Ay}from"node:crypto";function Sr(e){return`${G(e).pod}-lepis-tls`}function Ty(e){return Ay("sha256").update(`snout-lepis-admin:${e}`).digest("hex")}function ld(e,t){let n={...e},r=n[ps],o=n[ms];delete n[ps],delete n[ms];for(let[s,a,l]of[[ps,r,t],[ms,o,Ty(t)]])if(a!==void 0){if(!Ry.test(a))throw new Error(`${s} names ${JSON.stringify(a)}, which is not a variable name`);n[a]=l}return n}var nn,ps,ms,ad,id,fs,cd,Ry,gs=j(()=>{"use strict";Te();sd();nn="lepis",ps="SNOUTPOD_ADMIN_PASSWORD_ENV",ms="SNOUTPOD_ADMIN_TOKEN_ENV",ad=7433,id=1e3;fs="/tls",cd=["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(`
81
+ `),Ry=/^[A-Z][A-Z0-9_]{0,63}$/});var k$,v$,dd=j(()=>{"use strict";Te();_r();k$=6*60*60,v$=5*60});var ud=j(()=>{"use strict"});var pd=j(()=>{"use strict"});var E$,md=j(()=>{"use strict";E$=15*6e4});var N$,fd=j(()=>{"use strict";md();N$=2*1024**3});var gd=j(()=>{"use strict";pd();fd()});function yd(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"||!Ny.test(o))throw new Error(`not a database access role: ${JSON.stringify(o)}`);if(typeof s!="string"||!Oy.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 wd(e,t){return`${e}.nspname !~ '^pg_'
82
+ and ${e}.nspname <> all (array[${hd.map(n=>`'${n}'`).join(", ")}]::text[])
81
83
  and not ${t}.rolsuper
82
- and ${t}.rolname !~ '${Sy.source}'`}function hd(e){let t=[];for(let n of e.split(`
83
- `)){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 yd(e,t){return le(e),JSON.stringify(md(t).map(n=>({role:n.role,level:n.level})))}var by,At,_y,X,pd,Sy,Sr,ky,_r,vy,gd,fs=C(()=>{"use strict";Re();by=["full","read"],At="snout_oauth",_y=/^oauth_[0-9a-f]{32}$/,X="snout_oauth_read",pd=["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"],Sy=/^(snout_[a-z]+_admin|snout_gate|authenticator|pgbouncer)$/;Sr="SNOUTPOD_DB_ACCESS",ky=/^[a-z_][a-z0-9_]*$/;for(let e of pd)if(!ky.test(e))throw new Error(`not a schema name: ${JSON.stringify(e)}`);_r="snoutpod_oauth_read_new_schema",vy=`do $home$
84
+ and ${t}.rolname !~ '${Iy.source}'`}function _d(e){let t=[];for(let n of e.split(`
85
+ `)){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 Sd(e,t){return de(e),JSON.stringify(yd(t).map(n=>({role:n.role,level:n.level})))}var Oy,At,Ny,X,hd,Iy,vr,Cy,kr,jy,bd,hs=j(()=>{"use strict";Te();Oy=["full","read"],At="snout_oauth",Ny=/^oauth_[0-9a-f]{32}$/,X="snout_oauth_read",hd=["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"],Iy=/^(snout_[a-z]+_admin|snout_gate|authenticator|pgbouncer)$/;vr="SNOUTPOD_DB_ACCESS",Cy=/^[a-z_][a-z0-9_]*$/;for(let e of hd)if(!Cy.test(e))throw new Error(`not a schema name: ${JSON.stringify(e)}`);kr="snoutpod_oauth_read_new_schema",jy=`do $home$
84
86
  declare
85
87
  -- snout_ext in the own layout, extensions in a database not yet renamed (docs/cloud/OWN-LAYOUT.md).
86
88
  home text := case
@@ -89,7 +91,7 @@ declare
89
91
  end;
90
92
  begin
91
93
  execute pg_catalog.format('create schema if not exists %I', home);
92
- execute pg_catalog.replace($fn$create or replace function @home@.${_r}() returns event_trigger
94
+ execute pg_catalog.replace($fn$create or replace function @home@.${kr}() returns event_trigger
93
95
  language plpgsql
94
96
  security invoker
95
97
  set search_path = pg_catalog, pg_temp
@@ -109,7 +111,7 @@ begin
109
111
  where c.command_tag = 'CREATE SCHEMA'
110
112
  and c.classid = 'pg_catalog.pg_namespace'::pg_catalog.regclass
111
113
  and not c.in_extension
112
- and ${fd("n","r")}
114
+ and ${wd("n","r")}
113
115
  loop
114
116
  begin
115
117
  execute pg_catalog.format('grant usage on schema %I to ${X}', created.nspname);
@@ -123,15 +125,15 @@ begin
123
125
  end loop;
124
126
  end
125
127
  $snoutpod$$fn$, '@home@', pg_catalog.quote_ident(home));
126
- if not exists (select from pg_catalog.pg_event_trigger where evtname = '${_r}') then
127
- execute pg_catalog.format('create event trigger ${_r} on ddl_command_end
128
+ if not exists (select from pg_catalog.pg_event_trigger where evtname = '${kr}') then
129
+ execute pg_catalog.format('create event trigger ${kr} on ddl_command_end
128
130
  when tag in (''CREATE SCHEMA'')
129
- execute function %I.${_r}()', home);
131
+ execute function %I.${kr}()', home);
130
132
  end if;
131
133
  end
132
134
  $home$;
133
- `,gd=`\\getenv db_access ${Sr}
134
- ${vy}create function pg_temp.snoutpod_member(member_name text, group_name text)
135
+ `,bd=`\\getenv db_access ${vr}
136
+ ${jy}create function pg_temp.snoutpod_member(member_name text, group_name text)
135
137
  returns boolean
136
138
  language sql
137
139
  stable
@@ -152,7 +154,7 @@ create function pg_temp.snoutpod_customer_schema(schema_oid oid)
152
154
  set search_path = pg_catalog, pg_temp
153
155
  as $snoutpod$
154
156
  -- isCustomerSchema in dbAccess.ts, from the same SYSTEM_SCHEMAS and PLATFORM_OWNER.
155
- select ${fd("n","r")}
157
+ select ${wd("n","r")}
156
158
  from pg_namespace n
157
159
  join pg_roles r on r.oid = n.nspowner
158
160
  where n.oid = schema_oid
@@ -341,8 +343,8 @@ begin
341
343
  end
342
344
  $snoutpod$;
343
345
  select change || ' ' || role_name from pg_temp.snoutpod_db_access(:'db_access'::jsonb);
344
- `});var wd,yx,wx,bx,_x,Sx,bd=C(()=>{"use strict";Rl();ts();rs();Nl();os();ss();as();Hl();ql();Gl();Wl();ed();ms();ad();id();ud();wr();fs();wd=120,yx=2*6e4,wx=15*60*1e3,bx=60*60*1e3,_x=5*60*1e3,Sx=10*60*1e3});import{execFile as $y}from"node:child_process";function _d(){return(e,t,n={})=>new Promise((r,o)=>{let s=$y(e,[...t],{timeout:n.timeoutMs??0,maxBuffer:8388608,env:n.env?{...process.env,...n.env}:process.env},(a,l,i)=>{if(a&&typeof a.code=="string"){o(a);return}let u=a&&typeof a.code=="number"?a.code:0;r({code:u,stdout:String(l),stderr:String(i)})});n.stdin!==void 0&&s.stdin?.end(n.stdin)})}async function z(e,t,n,r){let o=await e(t,n,r);if(o.code!==0){let s=(o.stderr||o.stdout).trim().split(`
345
- `).slice(-3).join("; ");throw new Error(`${t} ${n[0]??""} failed (${o.code}): ${s}`)}return o.stdout}var nn=C(()=>{"use strict"});import{readdir as xy,readFile as Px}from"node:fs/promises";async function Sd(e,t,n={}){let r=n.binary??"podman",o=G(t).pod,s=await e(r,["volume","inspect",o,"--format","json"]);if(s.code!==0)return!1;let a=JSON.parse(s.stdout||"[]"),i=(Array.isArray(a)?a[0]:a)?.Mountpoint;return i?await(n.look??Py)(i)!=="empty":!1}async function Py(e){try{return(await xy(e)).length>0?"data":"empty"}catch(t){return t.code==="ENOENT"?"empty":"hidden"}}var kd=C(()=>{"use strict";Re();nn()});import{createHash as Ey,createHmac as vd,pbkdf2Sync as Ay}from"node:crypto";function $d(e,t){let n=Ry.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 i=Ay(t.normalize("NFKC"),Buffer.from(o,"base64"),l,32,"sha256"),u=vd("sha256",i).update("Client Key").digest(),c=Ey("sha256").update(u).digest(),p=vd("sha256",i).update("Server Key").digest();return c.equals(Buffer.from(s,"base64"))&&p.equals(Buffer.from(a,"base64"))}var Ry,xd=C(()=>{"use strict";Ry=/^SCRAM-SHA-256\$(\d+):([^$]+)\$([^:]+):(.+)$/});function Pd(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 Rd(e,t){if(!t)return e??null;let n=await t();return{...e??{},key:n.accessKeyId,secret:n.secretAccessKey,token:n.sessionToken}}function Td(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=${Pd("the access key",e.key,Oy)}`),n.push("--env",Ed),e.token&&n.push("--env",Ad)),e.endpoint&&n.push("--env",`SNOUTPOD_S3_ENDPOINT=${Pd("the endpoint",e.endpoint,Ty)}`),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 Od(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{[Ed]:e.secret,...e.token?{[Ad]:e.token}:{}}}var Ed,Ad,Ty,Oy,Nd=C(()=>{"use strict";Ed="SNOUTPOD_S3_SECRET",Ad="SNOUTPOD_S3_TOKEN",Ty=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/i,Oy=/^[A-Za-z0-9/+=_.-]{1,256}$/});function jd(e){if(!gs.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 Id,Cd,gs,Dd=C(()=>{"use strict";Id=["snout_gate","authenticator"],Cd=`do $snoutpod$
346
+ `});var kd,Dx,Mx,Lx,Ux,Bx,vd=j(()=>{"use strict";xl();Nl();rs();ss();jl();as();is();cs();zl();Jl();Vl();Yl();od();gs();dd();ud();gd();_r();hs();kd=120,Dx=2*6e4,Mx=15*60*1e3,Lx=60*60*1e3,Ux=5*60*1e3,Bx=10*60*1e3});import{execFile as Dy}from"node:child_process";function $d(){return(e,t,n={})=>new Promise((r,o)=>{let s=Dy(e,[...t],{timeout:n.timeoutMs??0,maxBuffer:8388608,env:n.env?{...process.env,...n.env}:process.env},(a,l,i)=>{if(a&&typeof a.code=="string"){o(a);return}let u=a&&typeof a.code=="number"?a.code:0;r({code:u,stdout:String(l),stderr:String(i)})});n.stdin!==void 0&&s.stdin?.end(n.stdin)})}async function z(e,t,n,r){let o=await e(t,n,r);if(o.code!==0){let s=(o.stderr||o.stdout).trim().split(`
347
+ `).slice(-3).join("; ");throw new Error(`${t} ${n[0]??""} failed (${o.code}): ${s}`)}return o.stdout}var rn=j(()=>{"use strict"});import{readdir as My,readFile as Gx}from"node:fs/promises";async function xd(e,t,n={}){let r=n.binary??"podman",o=G(t).pod,s=await e(r,["volume","inspect",o,"--format","json"]);if(s.code!==0)return!1;let a=JSON.parse(s.stdout||"[]"),i=(Array.isArray(a)?a[0]:a)?.Mountpoint;return i?await(n.look??Ly)(i)!=="empty":!1}async function Ly(e){try{return(await My(e)).length>0?"data":"empty"}catch(t){return t.code==="ENOENT"?"empty":"hidden"}}var Pd=j(()=>{"use strict";Te();rn()});import{createHash as Uy,createHmac as Ed,pbkdf2Sync as By}from"node:crypto";function Ad(e,t){let n=Fy.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 i=By(t.normalize("NFKC"),Buffer.from(o,"base64"),l,32,"sha256"),u=Ed("sha256",i).update("Client Key").digest(),c=Uy("sha256").update(u).digest(),p=Ed("sha256",i).update("Server Key").digest();return c.equals(Buffer.from(s,"base64"))&&p.equals(Buffer.from(a,"base64"))}var Fy,Rd=j(()=>{"use strict";Fy=/^SCRAM-SHA-256\$(\d+):([^$]+)\$([^:]+):(.+)$/});function Td(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 Id(e,t){if(!t)return e??null;let n=await t();return{...e??{},key:n.accessKeyId,secret:n.secretAccessKey,token:n.sessionToken}}function Cd(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=${Td("the access key",e.key,Ky)}`),n.push("--env",Od),e.token&&n.push("--env",Nd)),e.endpoint&&n.push("--env",`SNOUTPOD_S3_ENDPOINT=${Td("the endpoint",e.endpoint,Hy)}`),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 jd(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{[Od]:e.secret,...e.token?{[Nd]:e.token}:{}}}var Od,Nd,Hy,Ky,Dd=j(()=>{"use strict";Od="SNOUTPOD_S3_SECRET",Nd="SNOUTPOD_S3_TOKEN",Hy=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/i,Ky=/^[A-Za-z0-9/+=_.-]{1,256}$/});function Ud(e){if(!ys.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 Md,Ld,ys,Bd=j(()=>{"use strict";Md=["snout_gate","authenticator"],Ld=`do $snoutpod$
346
348
  declare
347
349
  wanted text[];
348
350
  begin
@@ -360,8 +362,8 @@ begin
360
362
  end loop;
361
363
  end
362
364
  $snoutpod$;
363
- `,gs=["snout_psyche_admin"]});function Ld(e){let t=[];for(let n of e.split(`
364
- `)){let r=n.split(ys);if(r.length!==4||!hs.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 hs,ys,Md,Ud=C(()=>{"use strict";hs=["snouttime"];for(let e of hs)if(!/^[a-z][a-z0-9_]{0,62}$/.test(e))throw new Error(`not an extension name: ${JSON.stringify(e)}`);ys="",Md=`
365
+ `,ys=["snout_psyche_admin"]});function Hd(e){let t=[];for(let n of e.split(`
366
+ `)){let r=n.split(bs);if(r.length!==4||!ws.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 ws,bs,Fd,Kd=j(()=>{"use strict";ws=["snouttime"];for(let e of ws)if(!/^[a-z][a-z0-9_]{0,62}$/.test(e))throw new Error(`not an extension name: ${JSON.stringify(e)}`);bs="",Fd=`
365
367
  SET search_path = pg_catalog, pg_temp;
366
368
  CREATE TEMP TABLE snoutpod_extension_updates (name text, from_version text, to_version text, error text);
367
369
  DO $snoutpod$
@@ -375,7 +377,7 @@ BEGIN
375
377
  SELECT e.extname, e.extversion
376
378
  FROM pg_extension e
377
379
  JOIN pg_available_extensions a ON a.name = e.extname
378
- WHERE e.extname = ANY (ARRAY[${hs.map(e=>`'${e}'`).join(", ")}])
380
+ WHERE e.extname = ANY (ARRAY[${ws.map(e=>`'${e}'`).join(", ")}])
379
381
  AND a.default_version IS DISTINCT FROM e.extversion
380
382
  LOOP
381
383
  BEGIN
@@ -406,8 +408,8 @@ BEGIN
406
408
  END
407
409
  $snoutpod$;
408
410
  SELECT name, from_version, coalesce(to_version, ''), coalesce(error, '') FROM snoutpod_extension_updates ORDER BY name;
409
- `});function Fd(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 Bd,Mx,Lx,Hd=C(()=>{"use strict";nn();ws();Bd="SNOUTPOD_OAUTH_ISSUER",Mx=256*1024,Lx=5*6e4});function Kd(e,t){let n=null,r=!1;for(let o of e.split(`
410
- `)){let s=o.trim();s.startsWith("swap-error")?n=s.slice(10).trim()||"the swap failed":s==="swap-done"&&(r=!0)}return n||(r&&t===0?null:`the swap ended without finishing (exit ${t})`)}var Ny,bs,qd,Gd=C(()=>{"use strict";Ny='snoutpod-pgbackrest archive-get %f "%p"',bs=String.raw`set -u
411
+ `});function Gd(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 qd,n0,r0,zd=j(()=>{"use strict";rn();_s();qd="SNOUTPOD_OAUTH_ISSUER",n0=256*1024,r0=5*6e4});function Wd(e,t){let n=null,r=!1;for(let o of e.split(`
412
+ `)){let s=o.trim();s.startsWith("swap-error")?n=s.slice(10).trim()||"the swap failed":s==="swap-done"&&(r=!0)}return n||(r&&t===0?null:`the swap ended without finishing (exit ${t})`)}var qy,Ss,Jd,Vd=j(()=>{"use strict";qy='snoutpod-pgbackrest archive-get %f "%p"',Ss=String.raw`set -u
411
413
  A=$1
412
414
  B=$2
413
415
  fail() { echo "swap-error $*"; exit 3; }
@@ -426,112 +428,114 @@ kept=""
426
428
  if [ -f "$C" ]; then
427
429
  kept=$(grep -v -E '^[[:space:]]*(primary_conninfo|primary_slot_name|restore_command|synchronous_standby_names)[[:space:]]*=' "$C")
428
430
  fi
429
- { [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+Ny.replace(/"/g,'\\"')+String.raw`'"; } > "$C" || fail "postgresql.auto.conf could not be written"
431
+ { [ -n "$kept" ] && printf '%s\n' "$kept"; printf '%s\n' "restore_command = '`+qy.replace(/"/g,'\\"')+String.raw`'"; } > "$C" || fail "postgresql.auto.conf could not be written"
430
432
  echo "swap-done"
431
- `;qd=["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()"]});import{createHash as vs,randomBytes as Cy}from"node:crypto";import{access as jy,constants as Dy}from"node:fs/promises";import{delimiter as My,join as Ly}from"node:path";function Uy(e,t){return vs("sha256").update($s(e)).update(e.smtpSecretEnv&&t?vs("sha256").update(t).digest("hex"):"").digest("hex").slice(0,32)}function $s(e){if(Array.isArray(e))return`[${e.map($s).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)}:${$s(t[r])}`).join(",")}}`}return JSON.stringify(e??null)}function Ps(e){if(!Fy.test(e))throw new Error(`not a service name: ${JSON.stringify(e)}`);return e}function on(e){if(!Hy.test(e))throw new Error(`not a database role: ${JSON.stringify(e)}`);return e}function Ky(e,t,n){return`postgres://${on(t)}:${n}@127.0.0.1:5432/${le(e)}`}function Jd(e,t,n,r){let o=sd(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]=Ky(e.ref,s,a)}return t.smtpSecretEnv&&r&&(o[t.smtpSecretEnv]=r),o}function Vd(e,t){return`${G(e).pod}-${Ps(t)}`}function kr(e){return`snoutpod-host-${Ps(e)}`}function qy(e){let t=Object.keys(e.env).sort().map(n=>[n,e.env[n]]);return vs("sha256").update(JSON.stringify([e.image,e.port,e.hostPort,e.healthPath??null,e.memoryMb,t,e.adminPort??null,e.adminHostPort??null,e.command??null,e.volumes??null,e.network??null])).digest("hex").slice(0,32)}function Gy(e,t){let n=[],r=xs(t);for(let o of e??[])if(Ps(o.name),vr(o.port,`${o.name}: port`),!(o.hostPort===null||o.hostPort===void 0)){vr(o.hostPort,`${o.name}: hostPort`);for(let s of r)n.push("--publish",`${s}:${o.hostPort}:${o.port}`);if(o.name===tn){let s=o.hostPort+rd;vr(s,`${o.name}: admin hostPort`);for(let a of r)n.push("--publish",`${a}:${s}:${nd}`)}}return n}function xs(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 vr(e,t){if(!Number.isInteger(e)||e<1||e>65535)throw new Error(`${t} is not a port: ${JSON.stringify(e)}`);return e}function Xd(e){let t=[];for(let n of Object.keys(e)){if(!Wy.test(n))throw new Error(`not an environment variable name: ${JSON.stringify(n)}`);t.push("--env",n)}return t}function zy(e){let t=e.healthPath;if(t==null||t==="")return[];if(!tu.test(t))throw new Error(`${e.name}: not a health path: ${JSON.stringify(t)}`);return e.hostPort===null||e.hostPort===void 0?[]:(vr(e.hostPort,`${e.name}: hostPort`),["--label",`${Es}=${e.hostPort}:${t}`])}function Jy(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||!tu.test(r)?null:{port:n,path:r}}async function Yy(e,t={}){let n=t.path??process.env.PATH??"",r=t.look??(o=>jy(o,Dy.X_OK));for(let o of n.split(My))if(o)try{let s=Ly(o,e);return await r(s),s}catch{}return null}function Xy(){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(`
432
- `)}function Qy(e){return/^(\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com)\//.exec(e)?.[1]??null}function ew(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 As(e){let t=(e??"").trim();return/^\d+(?:\.\d+)?$/.test(t)?t:null}function tw(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 nw(e,t,n,r){return{image:await rw(e,t,r),data:await ow(e,t,n)}}async function rw(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 ew(r,n)}async function ow(e,t,n){try{let r=await e(t,["volume","inspect","--format","{{.Mountpoint}}",G(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?As(s.stdout):null}catch{return null}}function sw(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:Zd;return t.push(`SNOUTPOD_MAX_CONNECTIONS=${Math.max(r,Zd)}`),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 aw(e){let t=null;return()=>(t===null&&(t=n()),t);async function n(){if(e.runtime===null)return[];let r=e.runtime??Vy;return e.runtime!==void 0&&e.runtime!==""?["--runtime",r]:await Yy(r,{look:e.lookExecutable})===null?[]:["--runtime",r]}}function ru(e){let t=e.binary??"podman",n=e.exec,r=aw(e),o=e.probe??nu;async function s(g){try{await n(t,["exec",...he,"--interactive",G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"--quiet","--file","-"],{timeoutMs:Zy,stdin:Xy()})}catch{}}async function a(){let g=await z(n,t,["ps","--all","--filter",`label=${Te}`,"--format","json"]),y=g.trim()?JSON.parse(g):[],b=new Map,T=new Map,A=new Map;for(let E of y){let ne=E.Labels?.[Te],oe=E.Labels?.[ut];if(!ne||!oe)continue;let de=b.get(ne)??[];de.push(oe),b.set(ne,de),eu(E.State)==="stopped"&&T.set(ne,[...T.get(ne)??[],oe]);let M=Number(E.Labels?.[Ss]??0),ae=Number.isInteger(M)?M:0;A.set(ne,Math.max(A.get(ne)??ae,ae))}let q=y.filter(E=>E.Labels?.[Te]&&!E.Labels?.[ut]),F=q.map(E=>eu(E.State)),B=await cw(q,iw,(E,ne)=>F[ne]==="running"?Promise.resolve(!0):e.hasData(E.Labels?.[Te]??""));return q.map((E,ne)=>{let oe=E.Labels?.[Te]??"",de=Number(E.Labels?.[_s]);return{ref:oe,status:F[ne]??"unknown",generation:Number.isInteger(de)?de:null,hasData:B[ne]??!1,services:b.get(oe)??[],servicesStopped:T.get(oe)??[],...A.has(oe)?{servicesGeneration:A.get(oe)}:{}}})}async function l(){let g=await z(n,t,["ps","--all","--filter",`label=${Te}`,"--format","json"]);return(g.trim()?JSON.parse(g):[]).filter(b=>b.Labels?.[Te]&&!b.Labels?.[ut]).length}async function i(g){let y=await(e.majors??((b,T)=>nw(n,t,b,T)))(g.ref,g.image);return tw(g.ref,y)}async function u(g){let y=G(g.ref),b=await i(g);if(b)throw new Error(b);let T=e.credentials,A=await Rd(e.repository,T?()=>T.forProject(g.ref,g.bucket):null),q={SNOUTPOD_OWNER_PASSWORD:g.ownerPassword,POSTGRES_PASSWORD:g.adminPassword,...Od(A)},F=[...await r(),"run","--detach","--name",y.pod,"--label",`${Te}=${g.ref}`,"--label",`${_s}=${g.generation}`,"--userns=auto","--memory",`${g.memoryMb}m`,...uw(g.cpus),"--restart","no",...e.network?["--network",e.network]:[],...g.port?xs(e.podBind).flatMap(B=>["--publish",`${B}:${g.port}:5432`]):[],...Gy(g.services,e.podBind),"--volume",`${y.pod}:/var/lib/postgresql/data:U`,"--env","SNOUTPOD_OWNER_PASSWORD","--env","POSTGRES_PASSWORD","--env",`SNOUTPOD_REF=${g.ref}`,"--env","POSTGRES_USER=snoutpod_admin","--env","POSTGRES_DB=postgres","--env",`SNOUTPOD_S3_BUCKET=${g.bucket}`,"--env",`SNOUTPOD_S3_REGION=${g.region}`,...e.egressDenied?["--env","SNOUTPOD_EGRESS=denied"]:[],...dw(g.oauth),...sw(g.tuning).flatMap(B=>["--env",B]),"--env",`SNOUTPOD_RETENTION_FULL=${Ol(g.backup?.retentionDays,g.backup?.fullIntervalHours)}`,...Td(A),g.image,"snoutpod-postgres"];await z(n,t,F,{env:q})}async function c(g){let y=await z(n,t,["ps","--all","--filter",`label=${Te}=${le(g)}`,"--filter",`label=${ut}`,"--format","json"]),b=y.trim()?JSON.parse(y):[],T=[];for(let A of b){let q=A.Labels?.[ut];if(!q)continue;let F=Number(A.Labels?.[Ss]??0);T.push({name:q,container:Vd(g,q),spec:A.Labels?.[Wd]??"",pod:A.Labels?.[zd]??"",running:A.State==="running",generation:Number.isInteger(F)?F:0})}return T}async function p(g){let y=await n(t,["container","inspect","--format","{{.Id}}",G(g).pod]);return y.code===0?y.stdout.trim():""}async function f(g,y){let b=[];for(let B of y){let E=B.dbUriRole??null;B.dbUriEnv&&E&&!b.includes(E)&&b.push(on(E))}let T=new Map;if(b.length===0)return T;let A={},q=[],F=[];b.some(B=>Id.includes(B))&&F.push(Cd);for(let B of b.filter(E=>gs.includes(E)))F.push(jd(B));return b.forEach((B,E)=>{let ne=Cy(24).toString("base64url"),oe=`SNOUTPOD_SERVICE_PASSWORD_${E}`;T.set(B,ne),A[oe]=ne,q.push("--env",oe),F.push(`\\getenv service_password_${E} ${oe}`),F.push(`\\set service_role_${E} ${B}`),F.push(`alter role :"service_role_${E}" with password :'service_password_${E}';`)}),F.push(""),await z(n,t,["exec",...he,"--interactive",...q,G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname",G(g.ref).database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:A,stdin:F.join(`
433
- `)}),T}async function k(g){let y=br(g.ref);await z(n,t,["volume","create","--ignore",y]),await z(n,t,[...await r(),"run","--rm","--network","none","--volume",`${y}:${ps}`,"--entrypoint","bash",g.image,"-c",od])}async function v(g){let y=await r();if((await n(t,[...y,"image","exists",g])).code===0)return;let b=await n(t,[...y,"pull","--quiet",g]);if(b.code===0)return;let T=Qy(g);if(!T||!e.registryLogin)throw new Error(`${g} could not be pulled: ${(b.stderr||b.stdout).trim()}`);await e.registryLogin(T),await z(n,t,[...y,"pull","--quiet",g])}async function V(g){let y=g.services??[],b=await c(g.ref),T;y.some(M=>M.smtpSecretEnv)&&(T=await e.smtpSecret?.().catch(()=>{}));let A=y.length>0?await p(g.ref):"",q=new Map(b.map(M=>[M.name,M])),F=new Map(y.map(M=>[M.name,Uy(M,T)])),B=new Set(y.filter(M=>{let ae=q.get(M.name);return!ae||!ae.running||ae.spec!==F.get(M.name)||A===""||ae.pod!==A}).map(M=>M.name)),E=g.servicesGeneration??0;if(B.size===0&&y.length>0&&!b.some(M=>M.generation>=E))for(let M of y)B.add(M.name);let ne=M=>M.dbUriEnv&&M.dbUriRole?M.dbUriRole:null;for(let M=!0;M;){M=!1;let ae=new Set(y.filter(st=>B.has(st.name)).map(ne));for(let st of y){let Ks=ne(st);!B.has(st.name)&&Ks!==null&&ae.has(Ks)&&(B.add(st.name),M=!0)}}for(let M of new Set(y.filter(ae=>B.has(ae.name)).map(ae=>ae.image)))await v(M);for(let M of b)(B.has(M.name)||!F.has(M.name))&&await z(n,t,["rm","--force","--ignore",M.container]);let oe=y.filter(M=>B.has(M.name)),de=await f(g,oe);oe.some(M=>M.name===tn)&&await k(g);for(let M of oe){let ae=Vd(g.ref,M.name),st=[...await r(),"run","--detach","--name",ae,"--label",`${Te}=${g.ref}`,"--label",`${_s}=${g.generation}`,"--label",`${ut}=${M.name}`,"--label",`${Ss}=${g.servicesGeneration??0}`,"--label",`${Wd}=${F.get(M.name)??""}`,"--label",`${zd}=${A}`,"--network",`container:${G(g.ref).pod}`,"--userns",`container:${G(g.ref).pod}`,"--memory",`${M.memoryMb}m`,"--restart","no",...zy(M),...M.name===tn?["--volume",`${br(g.ref)}:${ps}:ro`]:[],...Xd(Jd(g,M,de,T)),M.image];await z(n,t,st,{env:Jd(g,M,de,T)})}}async function j(g,y){if(y%6!==0)return!1;let b=await n(t,["container","inspect","--format","{{.State.Status}}",G(g).pod]);return b.code===0&&/^(exited|stopped|dead)$/.test(b.stdout.trim())}function Y(g){return["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres"]}async function R(g){let y=await n(t,[...Y(g),"-tAc",Bl]);return y.code===0?Fl(y.stdout):null}async function ee(g){let y=await n(t,[...Y(g),"-tAc","select pg_is_in_recovery()"]);if(y.code!==0)return null;let b=y.stdout.trim();return b==="t"?!0:b==="f"?!1:null}async function O(g,y){let b=A=>n(t,[...Y(g),"-tAc",A]),T=Date.now()+y;do{if((await b("checkpoint")).code!==0)return!1;let q=await b("select (select timeline_id from pg_control_checkpoint()) = ('x' || substr(pg_walfile_name(pg_current_wal_lsn()), 1, 8))::bit(32)::int");if(q.code===0&&q.stdout.trim()==="t")return!0;await new Promise(F=>setTimeout(F,1e3))}while(Date.now()<T);return!1}async function pe(g){let y=await n(t,[...Y(g),"-tAc",Cl],{timeoutMs:ks});return y.code===0?jl(y.stdout):null}async function W(g,y){let b=new Map;for(let A of y)le(A),b.set(A,G(A).pod);if(b.size===0)return new Map;let T=await n(t,["exec",G(g).pod,"timeout",String(10),"sh","-c",Ll,"sh",...b.values()]);return T.code===0?Ul(T.stdout,b):null}async function ce(g,y){le(y);let b=[];for(let F of[g,y]){let B=G(F).pod,E=await n(t,["container","inspect","--format","{{.State.Status}}",B]);if(E.code===0&&E.stdout.trim()==="running")throw new Error(`${B} is still running, so its data was not moved`);let ne=await n(t,["volume","inspect","--format","{{.Mountpoint}}",B]),oe=ne.code===0?ne.stdout.trim().replace(/\/+$/,""):"";if(!oe)throw new Error(`the volume ${B} could not be found, so nothing was moved`);b.push(oe)}let A=typeof process.getuid!="function"||process.getuid()!==0?await n(t,["unshare","sh","-c",bs,"sh",b[0],b[1]]):await n("sh",["-c",bs,"sh",b[0],b[1]]),q=Kd(A.stdout,A.code);if(q)throw new Error(q)}async function pn(g){return(await n(t,[...Y(g),"-v","ON_ERROR_STOP=1",...qd.flatMap(b=>["-c",b])])).code===0}async function pt(g,y){return(await n(t,[...Y(g),"-v","ON_ERROR_STOP=1",...Ml(y).flatMap(T=>["-c",T])],{timeoutMs:ks})).code===0}async function mn(g){let y=await n(t,[...Y(g),"-tAc","select pg_read_file(current_setting('ssl_cert_file')) where current_setting('ssl') = 'on'"]),b=`${y.stdout.trim()}
434
- `;return y.code===0&&Dl.test(b)?b:null}async function Ju(g,y){if(!Il.test(y))throw new Error("not a SCRAM-SHA-256 verifier");let b=G(g).pod,T=[...Y(g),"-v","ON_ERROR_STOP=1"];if((await n(t,[...T,"-c",`do $$ begin if not exists (select 1 from pg_roles where rolname = '${tt}') then create role ${tt} with login replication; end if; end $$`,"-c",`alter role ${tt} with login replication noinherit password '${y}'`],{timeoutMs:ks})).code!==0)return!1;let q=await n(t,[...T,"-tAc","show hba_file"]),F=q.stdout.trim();if(q.code!==0||!/^\/[A-Za-z0-9/_.-]+$/.test(F))return!1;let B=`hostssl replication ${tt} all scram-sha-256`;if((await n(t,["exec",b,"sh","-c",'grep -Eq "^host(ssl)?[[:space:]]+replication[[:space:]]+$2[[:space:]]" "$1" || printf "%s\\n" "$3" >> "$1"',"sh",F,tt,B])).code!==0)return!1;if((await n(t,[...T,"-tAc","show ssl"])).stdout.trim()!=="on"){let de=F.replace(/\/[^/]+$/,"");if((await n(t,["exec","--user","root",b,"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",de,b])).code!==0||(await n(t,[...T,"-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)return!1}return(await n(t,[...T,"-tAc","select pg_reload_conf()"])).code===0}return{list:a,inRecovery:ee,replayLsn:R,settleTimeline:O,podHealth:pe,setSyncNames:pt,ensureKeeperRole:Ju,podCertificate:mn,swapHomeData:ce,promoteStandby:pn,nodesAnswer:W,preflight:i,create:u,createServices:V,async start(g){let y=(await c(g).catch(()=>[])).filter(b=>b.running).map(b=>b.container);y.length>0&&await z(n,t,["stop","--time","5",...y]),await z(n,t,["start",G(g).pod])},async startServices(g){let y=(await c(g)).map(b=>b.container);y.length>0&&await z(n,t,["start",...y])},async applyHostServices(g){let y=[],b=await z(n,t,["ps","--all","--filter",`label=${rn}`,"--format","json"]),T=b.trim()?JSON.parse(b):[],A=new Map;for(let F of T){let B=F.Labels?.[rn];B&&A.set(B,{spec:F.Labels?.[Yd]??"",state:F.State??""})}for(let F of g)try{await q(F)}catch(B){y.push({name:F.name,action:"failed",reason:B instanceof Error?B.message:String(B)})}async function q(F){let B=e.hostServiceLocal?.(F,g),E=B?{...F,...B.env&&Object.keys(B.env).length>0?{env:{...F.env,...B.env}}:{},...B.volumes?{volumes:B.volumes}:{},...B.network?{network:B.network}:{}}:F,ne=kr(E.name),oe=qy(E),de=A.get(E.name);if(A.delete(E.name),de&&de.spec===oe){de.state!=="running"&&(await z(n,t,["start",ne]),y.push({name:E.name,action:"started",reason:de.state}));return}let M=de?"the spec changed":"it was not here";await v(E.image),de&&await z(n,t,["rm","--force","--ignore",ne]),await z(n,t,[...await r(),"run","--detach","--name",ne,"--label",`${rn}=${E.name}`,"--label",`${Yd}=${oe}`,...E.healthPath?["--label",`${Es}=${E.hostPort}:${E.healthPath}`]:[],"--memory",`${E.memoryMb}m`,"--restart","no",...E.network?["--network",E.network]:e.network?["--network",e.network]:[],...(E.volumes??[]).flatMap(ae=>["--volume",ae]),...xs(e.podBind).flatMap(ae=>["--publish",`${ae}:${E.hostPort}:${E.port}`]),...E.adminPort&&E.adminHostPort?["--publish",`127.0.0.1:${E.adminHostPort}:${E.adminPort}`]:[],...Xd(E.env),E.image,...E.command??[]],{env:{...E.env}}),y.push({name:E.name,action:de?"recreated":"created",reason:M})}for(let F of A.keys())await z(n,t,["rm","--force","--ignore",kr(F)]),y.push({name:F,action:"removed",reason:"it is no longer on the list"});return y},async hostServiceHealth(g){let y=await z(n,t,["ps","--all","--filter",`label=${rn}`,"--format","json"]),b=(y.trim()?JSON.parse(y):[]).map(A=>A.Labels?.[rn]??"").filter(A=>A!=="");if(b.length===0)return[];let T=Date.now()+g;for(;;){let A=[];for(let q of b)A.push(await Qd(n,t,q,kr(q),o));if(A.every(q=>q.ok)||Date.now()>=T)return A;await new Promise(q=>setTimeout(q,500))}},async serviceHealth(g,y){let b=await c(g);if(b.length===0)return[];let T=Date.now()+y;for(;;){let A=await Promise.all(b.map(q=>Qd(n,t,q.name,q.container,o)));if(A.every(q=>q.ok)||Date.now()>=T)return A;await new Promise(q=>setTimeout(q,500))}},async stop(g,y){for(let b of await c(g))await z(n,t,["stop","--time",String(By),b.container]);await z(n,t,["stop","--time",String(y),G(g).pod])},async remove(g){for(let y of await c(g))await z(n,t,["rm","--force","--ignore",y.container]);await z(n,t,["rm","--force","--ignore","--volumes",G(g).pod])},async removeData(g){await z(n,t,["volume","rm","--force",G(g).pod]);let y=br(g);(await n(t,["volume","exists",y])).code===0&&await z(n,t,["volume","rm","--force",y])},async applyOwnerPassword(g){let y=await n(t,["exec",...he,G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select rolpassword from pg_authid where rolname = '${le(g.ref)}_owner'`]);if(y.code===0&&$d(y.stdout,g.ownerPassword))return;let b=["\\getenv owner_password SNOUTPOD_OWNER_PASSWORD",`\\set owner_role ${g.ref}_owner`,`alter role :"owner_role" with password :'owner_password';`,""].join(`
435
- `);await z(n,t,["exec",...he,"--interactive","--env","SNOUTPOD_OWNER_PASSWORD",G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_OWNER_PASSWORD:g.ownerPassword},stdin:b})},async applyRolePassword(g,y,b){let T=["\\getenv role_password SNOUTPOD_ROLE_PASSWORD",`\\set target_role ${on(y)}`,`alter role :"target_role" with password :'role_password';`,""].join(`
436
- `);await z(n,t,["exec",...he,"--interactive","--env","SNOUTPOD_ROLE_PASSWORD",G(g).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_ROLE_PASSWORD:b},stdin:T})},async updateExtensions(g){let y=G(g),b=await n(t,["exec",...he,y.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select datname from pg_database where datname = '${y.database}' or (not datistemplate and datname <> 'postgres') order by datname = '${y.database}' desc, datname limit 1`]),T=b.code===0&&/^[a-z][a-z0-9_]{0,62}$/.test(b.stdout.trim())?b.stdout.trim():y.database,A=await z(n,t,["exec",...he,"--interactive",y.pod,"psql","--username","snoutpod_admin","--dbname",T,"--quiet","-tA","-F",ys,"-v","ON_ERROR_STOP=1","--file","-"],{stdin:Md});return Ld(A)},async applyDbAccess(g,y){let b=G(g),T=await z(n,t,["exec",...he,"--interactive","--env",Sr,b.pod,"psql","--username","snoutpod_admin","--dbname",b.database,"--quiet","-tA","-v","ON_ERROR_STOP=1","--file","-"],{env:{[Sr]:yd(g,y)},stdin:gd,timeoutMs:6e4});return hd(T)},async runProjectSql(g,y){let b=G(g);await z(n,t,["exec",...he,"--interactive",b.pod,"psql","--username","snoutpod_admin","--dbname",b.database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:y})},async ensureHostServiceDatabase(g,y,b){let T=kr(g),A=on(y),q=on(b),F=E=>["exec",T,"psql","--username",A,"--dbname","postgres","--quiet","-tA","-v","ON_ERROR_STOP=1","-c",E];(await z(n,t,F(`select 1 from pg_database where datname = '${q}'`))).trim()!=="1"&&await z(n,t,F(`create database "${q}"`))},async renameProject(g,y){y!==g.ref&&await z(n,t,["exec",...he,"--interactive",G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:lw(y,g.ref)})},async waitReady(g,y){let b=G(g).pod,T=Date.now()+y,A=0;for(;;){let q=await n(t,["exec",...he,b,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres","-tAc","select not pg_is_in_recovery()"]);if(q.code===0&&q.stdout.trim()==="t")return s(g),!0;if(Date.now()>=T||await j(g,++A))return!1;await new Promise(F=>setTimeout(F,500))}},async waitStandby(g,y){let b=Date.now()+y,T=0;for(;;){if(await ee(g)===!0)return!0;if(Date.now()>=b||await j(g,++T))return!1;await new Promise(A=>setTimeout(A,500))}},async capacity(){let[g,y]=await Promise.all([l(),e.capacity()]);return{pods:g,...y}},async databaseBytes(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-tAc","select pg_database_size(current_database())"]);return y.code===0?ns(y.stdout):null},async storageBytes(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-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 y.code===0?ns(y.stdout):null},async setReadOnly(g,y){let b=G(g);await z(n,t,["exec",...he,b.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`alter database ${b.database} set default_transaction_read_only = ${y?"on":"off"}`])},async archiveState(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-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(y.code!==0)return null;let[b="",T=""]=y.stdout.trim().split(`
437
- `)[0]?.split("|")??[],A=Number(T);return{lastArchivedAt:b.trim()||null,failures:Number.isInteger(A)&&A>=0?A:0}}}}async function Qd(e,t,n,r,o=nu){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 i=a?.Status??"unknown";if(i!=="running")return{name:n,ok:!1,detail:i};let u=Jy(l?.[Es]);if(!u)return{name:n,ok:!0,detail:"running"};let c=await o(u.port,u.path);return c===null?{name:n,ok:!1,detail:"not answering yet"}:{name:n,ok:!0,detail:`answered ${c}`}}async function cw(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 eu(e){switch((e??"").toLowerCase()){case"running":return"running";case"created":case"configured":return"starting";case"exited":case"stopped":return"stopped";default:return"unknown"}}function lw(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" rename to :"to_db";','alter role :"from_role" rename to :"to_role";',"alter system reset restore_command;","alter system reset recovery_target_time;","alter system reset recovery_target_action;",""].join(`
438
- `)}function dw(e){if(!e?.issuer)return[];try{return["--env",`${Bd}=${Fd(e.issuer)}`]}catch{return[]}}function uw(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?[]:["--cpus",e.toFixed(2)]}var Te,_s,ut,Ss,Wd,zd,By,Fy,Hy,rn,Yd,Wy,tu,Es,nu,Vy,he,ks,Zy,Zd,iw,ws=C(()=>{"use strict";Re();ts();os();ss();xd();nn();Nd();rs();Dd();Ud();fs();Hd();as();Gd();ms();Te="snoutpod.ref",_s="snoutpod.generation",ut="snoutpod.service",Ss="snoutpod.services-generation",Wd="snoutpod.service-spec",zd="snoutpod.service-pod";By=10,Fy=/^[a-z][a-z0-9-]{0,30}$/;Hy=/^[a-z][a-z0-9_]{0,62}$/;rn="snoutpod.host-service",Yd="snoutpod.host-service-spec";Wy=/^[A-Za-z_][A-Za-z0-9_]*$/;tu=/^\/[A-Za-z0-9\/_\-.~%?=&]*$/,Es="snoutpod.health";nu=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()})},Vy="crun";he=["--env","PGOPTIONS=-c search_path=pg_catalog,pg_temp -c synchronous_commit=local"],ks=3e4,Zy=3e4;Zd=200;iw=8});var wu={};qs(wu,{DEFAULT_LOCAL_MEMORY_MB:()=>cu,DEFAULT_LOCAL_PORT:()=>hw,ENGINE:()=>Z,ENGINE_NAME:()=>Rs,IMAGE:()=>Ns,NETWORK:()=>nt,NEW_PROJECT_MAJOR:()=>Os,NO_BLACKHOLE_ROUTES:()=>pu,PUBLIC_IMAGE:()=>_w,PUBLISHED_MAJORS:()=>Rt,capacity:()=>uu,chooseLocalImage:()=>cn,dropIfUnused:()=>hu,ensureImage:()=>Sw,ensureNetwork:()=>Pw,exec:()=>ie,hasData:()=>Er,localImageFor:()=>du,localPsql:()=>Rw,localRuntime:()=>xw,localSpec:()=>gu,localStatus:()=>Is,localUri:()=>fu,networkPolicyInPlace:()=>mu,newLocalPassword:()=>ww,newLocalRef:()=>yw,podLog:()=>yu,podName:()=>Tt,podmanReady:()=>vw,removeLocal:()=>Nw,staleImage:()=>Ts,startLocal:()=>Aw,stopLocal:()=>Ow,volumePgVersion:()=>$r});import{randomBytes as au}from"node:crypto";import{existsSync as ou}from"node:fs";import{platform as Pr}from"node:os";import{delimiter as pw,join as mw}from"node:path";function fw(){if(process.env.SNOUTPOD_ENGINE)return process.env.SNOUTPOD_ENGINE;let e=Pr()==="win32"?["podman.exe","podman"]:["podman"];for(let t of(process.env.PATH??"").split(pw))if(t&&e.some(n=>ou(mw(t,n))))return"podman";return ou("/opt/podman/bin/podman")?"/opt/podman/bin/podman":"podman"}function cn(e,t=process.env.SNOUTPOD_IMAGE){if(t)return{name:t,published:null,major:null};if(e===null)return an(Os);let n=Number(As(e));if(!Rt.includes(n)){let r=e.trim()||"(empty)",o=Rt.map(s=>an(s).published).join(" or ");throw new Error(`its data directory's PG_VERSION says ${r}, and there is an image only for Postgres ${Rt.join(" and ")}. Set SNOUTPOD_IMAGE to an image of that major (${o} for those).`)}return an(n)}function an(e){return{name:`${gw}:${e}`,published:`${iu}:${e}`,major:e}}function yw(){return Al(e=>au(e))}function ww(){return au(18).toString("base64url")}async function Sw(e,t=ie,n=cn(null)){let r=n.published;if(!r)return null;if((await t(Z,["image","exists",n.name])).code===0)return await kw(e,t,n.name,r),null;e?.(`Fetching the database image (${r}). This happens once.`);let o=await t(Z,["pull",r],{timeoutMs:lu}).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(Z,["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 kw(e,t,n,r){let o=await t(Z,["image","inspect","--format","{{.Id}}",n,r]).catch(()=>null),[s,a]=o?.code===0?o.stdout.trim().split(`
439
- `):[];if(!s||s!==a)return;let l=setTimeout(()=>e?.(`Fetching a newer database image (${r}).`),3e3),i=await t(Z,["pull",r],{timeoutMs:lu}).catch(f=>({code:1,stdout:"",stderr:f instanceof Error?f.message:String(f)})).finally(()=>clearTimeout(l));if(i.code!==0){let f=(i.stderr.trim()||i.stdout.trim()||"the pull failed").split(`
440
- `).at(-1);e?.(`Could not check for a newer database image (${f}); using the one on this machine.`);return}let u=await t(Z,["image","inspect","--format","{{.Id}}",r]).catch(()=>null),c=u?.code===0?u.stdout.trim():"";if(!c||c===s)return;let p=await t(Z,["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 vw(e=bw,t=Ns){if(Rs!=="podman")return`SNOUTPOD_ENGINE=${Rs}: 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 ie(Z,["--version"])}catch{return`${Z} 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`${Z} --version failed: ${n.stderr.trim()||n.stdout.trim()}`;if((await ie(Z,["image","exists",t])).code!==0)return`the pod image ${t} is not on this machine. ${e}`;let o=await ie(Z,["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 $w(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 ie(Z,["machine","ssh",t]).then(n=>{let r=n.stdout.trim().split(`
441
- `).at(-1);return r==="DATA"?"data":r==="EMPTY"?"empty":"hidden"},()=>"hidden")}function Er(e){let t=Pr()==="darwin"||Pr()==="win32";return Sd(ie,e,{binary:Z,look:t?$w:void 0})}async function $r(e,t=ie,n=Pr()){let r=G(e).pod;if((await t(Z,["volume","exists",r])).code!==0)return null;let o;if(n==="darwin"||n==="win32"){let s=null;for(let a of Rt){let l=an(a).name;if((await t(Z,["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 (${Rt.map(a=>an(a).published).join(" or ")}).`);o=await t(Z,["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(Z,["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(Z,["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 du(e,t=$r){if(!e||process.env.SNOUTPOD_IMAGE)return Promise.resolve(cn(null));le(e);let n=t===$r?xr.get(e):void 0;if(n)return n;let r=t(e).then(o=>{try{return cn(o)}catch(s){throw new Error(`${Tt(e)}: ${s instanceof Error?s.message:String(s)}`)}});return t===$r&&(xr.set(e,r),r.catch(()=>xr.delete(e))),r}async function uu(){return{ramFreeMb:4096,ramTotalMb:8192,diskFreeMb:32768,diskTotalMb:65536}}function xw(e){return ru({exec:ie,binary:Z,network:nt,hasData:Er,capacity:uu,repository:e})}function Tt(e){return G(e).pod}async function Pw(e){if(process.env.SNOUTPOD_LOCAL_ALLOW_EGRESS==="1"){await Ew()||await ie(Z,yr({name:nt}));return}let t=yr({name:nt,allow:[]}),n="";for(let r=0;r<10;r+=1){if(await mu())return;await e?.(),await ie(Z,["network","rm","--force",nt]).catch(()=>{});let o=await ie(Z,t);if(o.code===0)return;if(n=`${o.stderr}${o.stdout}`.trim(),/invalid route gateway/i.test(n))throw new Error(`${pu}: ${n}`);await new Promise(s=>setTimeout(s,500))}throw new Error(`could not create ${nt} with egress blocked${n?`: ${n}`:""}`)}async function Ew(){return(await ie(Z,["network","inspect",nt,"--format","json"])).code===0}async function mu(){let e=await ie(Z,["network","inspect",nt,"--format","json"]);if(e.code!==0)return!1;try{return Ql(JSON.parse(e.stdout)?.[0])}catch{return!1}}function fu(e){let t=G(e.ref);return`postgres://${t.ownerRole}:${encodeURIComponent(e.ownerPassword)}@127.0.0.1:${e.port}/${t.database}?sslmode=disable`}function gu(e,t={}){return le(e.ref),{ref:e.ref,generation:1,image:t.image??Ns,memoryMb:t.memoryMb??cu,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 sn(e,t){e.onProgress?.(t)}async function Aw(e,t,n={}){let r=n.image??(await du(t.ref,n.pgVersion)).name,o=gu(t,{...n,image:r}),s=n.timeoutMs??12e4,a=n.hasData??Er,l=(await e.list()).find(u=>u.ref===t.ref),i=null;if(l?l.status==="stopped"&&(i=await(n.staleImage??Ts)(t.ref,r))?(sn(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??hu)(i)):l.status==="stopped"?(sn(n,"Starting the database."),await e.start(t.ref),await e.startServices(t.ref)):(sn(n,"The database is already running."),l.status==="running"&&await(n.staleImage??Ts)(t.ref,r)&&sn(n,"A newer database image is on this machine. To move onto it: snoutdata stop, then snoutdata start.")):(sn(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 Tw(t.ref,s,n.podLog??yu));return await e.applyOwnerPassword(o),await e.createServices(o),Is(e,t,n)}function su(e){return e.trim().replace(/^sha256:/,"")}async function Ts(e,t){let[n,r]=await Promise.all([ie(Z,["container","inspect","--format","{{.Image}}",Tt(e)]).catch(()=>null),ie(Z,["image","inspect","--format","{{.Id}}",t]).catch(()=>null)]);if(n?.code!==0||r?.code!==0)return null;let o=su(n.stdout),s=su(r.stdout);return o&&s&&o!==s?o:null}async function hu(e){let t=await ie(Z,["image","inspect","--format","{{len .RepoTags}}",e]).catch(()=>null);t?.code===0&&t.stdout.trim()==="0"&&await ie(Z,["rmi",e]).catch(()=>{})}async function Rw(e,t){let n=G(e.ref);return ie(Z,["exec","--interactive","-e","PGPASSWORD",Tt(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 yu(e){let t=await ie(Z,["logs","--tail","20",Tt(e)]).catch(()=>null);return t?`${t.stdout}${t.stderr}`:"(no log: the container is not there)"}async function Tw(e,t,n){let r=await n(e).catch(()=>"(no log)");return`${Tt(e)} never became ready in ${t}ms
433
+ `;Jd=["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()"]});import{createHash as $s,randomBytes as zy}from"node:crypto";import{access as Wy,constants as Jy}from"node:fs/promises";import{delimiter as Vy,join as Yy}from"node:path";function Xy(e,t){return $s("sha256").update(xs(e)).update(e.smtpSecretEnv&&t?$s("sha256").update(t).digest("hex"):"").digest("hex").slice(0,32)}function xs(e){if(Array.isArray(e))return`[${e.map(xs).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)}:${xs(t[r])}`).join(",")}}`}return JSON.stringify(e??null)}function Ps(e){if(!Qy.test(e))throw new Error(`not a service name: ${JSON.stringify(e)}`);return e}function an(e){if(!ew.test(e))throw new Error(`not a database role: ${JSON.stringify(e)}`);return e}function tw(e,t,n){return`postgres://${an(t)}:${n}@127.0.0.1:5432/${de(e)}`}function Zd(e,t,n,r){let o=ld(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]=tw(e.ref,s,a)}return t.smtpSecretEnv&&r&&(o[t.smtpSecretEnv]=r),o}function Qd(e,t){return`${G(e).pod}-${Ps(t)}`}function on(e){return`snoutpod-host-${Ps(e)}`}function nw(e){let t=Object.keys(e.env).sort().map(n=>[n,e.env[n]]);return $s("sha256").update(JSON.stringify([e.image,e.port,e.hostPort,e.healthPath??null,e.memoryMb,t,e.adminPort??null,e.adminHostPort??null,e.command??null,e.volumes??null,e.network??null])).digest("hex").slice(0,32)}function rw(e,t){let n=[],r=xr(t);for(let o of e??[])if(Ps(o.name),$r(o.port,`${o.name}: port`),!(o.hostPort===null||o.hostPort===void 0)){$r(o.hostPort,`${o.name}: hostPort`);for(let s of r)n.push("--publish",`${s}:${o.hostPort}:${o.port}`);if(o.name===nn){let s=o.hostPort+id;$r(s,`${o.name}: admin hostPort`);for(let a of r)n.push("--publish",`${a}:${s}:${ad}`)}}return n}function xr(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 $r(e,t){if(!Number.isInteger(e)||e<1||e>65535)throw new Error(`${t} is not a port: ${JSON.stringify(e)}`);return e}function tu(e){let t=[];for(let n of Object.keys(e)){if(!ow.test(n))throw new Error(`not an environment variable name: ${JSON.stringify(n)}`);t.push("--env",n)}return t}function sw(e){let t=e.healthPath;if(t==null||t==="")return[];if(!au.test(t))throw new Error(`${e.name}: not a health path: ${JSON.stringify(t)}`);return e.hostPort===null||e.hostPort===void 0?[]:($r(e.hostPort,`${e.name}: hostPort`),["--label",`${Es}=${e.hostPort}:${t}`])}function aw(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||!au.test(r)?null:{port:n,path:r}}async function cw(e,t={}){let n=t.path??process.env.PATH??"",r=t.look??(o=>Wy(o,Jy.X_OK));for(let o of n.split(Vy))if(o)try{let s=Yy(o,e);return await r(s),s}catch{}return null}function lw(){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(`
434
+ `)}function pw(e){return/^(\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com)\//.exec(e)?.[1]??null}function mw(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 As(e){let t=(e??"").trim();return/^\d+(?:\.\d+)?$/.test(t)?t:null}function fw(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 gw(e,t,n,r){return{image:await hw(e,t,r),data:await yw(e,t,n)}}async function hw(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 mw(r,n)}async function yw(e,t,n){try{let r=await e(t,["volume","inspect","--format","{{.Mountpoint}}",G(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?As(s.stdout):null}catch{return null}}function nu(e,t){let n=xr(t);return(e.Ports??[]).some(r=>{let o=r.host_ip??"";return o!==""&&o!=="0.0.0.0"&&o!=="::"&&!n.includes(o)})}function Sw(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:ru;return t.push(`SNOUTPOD_MAX_CONNECTIONS=${Math.max(r,ru)}`),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 kw(e){let t=null;return()=>(t===null&&(t=n()),t);async function n(){if(e.runtime===null)return[];let r=e.runtime??iw;return e.runtime!==void 0&&e.runtime!==""?["--runtime",r]:await cw(r,{look:e.lookExecutable})===null?[]:["--runtime",r]}}function cu(e){let t=e.binary??"podman",n=e.exec,r=kw(e),o=e.probe??iu;async function s(g){try{await n(t,["exec",...he,"--interactive",G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"--quiet","--file","-"],{timeoutMs:uw,stdin:lw()})}catch{}}async function a(){let g=await z(n,t,["ps","--all","--filter",`label=${Ee}`,"--format","json"]),y=g.trim()?JSON.parse(g):[],b=new Map,T=new Map,R=new Map;for(let A of y){let Q=A.Labels?.[Ee],re=A.Labels?.[nt];if(!Q||!re)continue;let se=b.get(Q)??[];se.push(re),b.set(Q,se),su(A.State)==="stopped"&&T.set(Q,[...T.get(Q)??[],re]);let U=Number(A.Labels?.[vs]??0),ie=Number.isInteger(U)?U:0;R.set(Q,Math.max(R.get(Q)??ie,ie))}let H=y.filter(A=>A.Labels?.[Ee]&&!A.Labels?.[nt]),M=H.map(A=>su(A.State)),E=await $w(H,vw,(A,Q)=>M[Q]==="running"?Promise.resolve(!0):e.hasData(A.Labels?.[Ee]??""));return H.map((A,Q)=>{let re=A.Labels?.[Ee]??"",se=Number(A.Labels?.[ks]);return{ref:re,status:M[Q]??"unknown",generation:Number.isInteger(se)?se:null,hasData:E[Q]??!1,services:b.get(re)??[],servicesStopped:T.get(re)??[],...nu(A,e.podBind)?{boundElsewhere:!0}:{},...R.has(re)?{servicesGeneration:R.get(re)}:{}}})}async function l(){let g=await z(n,t,["ps","--all","--filter",`label=${Ee}`,"--format","json"]);return(g.trim()?JSON.parse(g):[]).filter(b=>b.Labels?.[Ee]&&!b.Labels?.[nt]).length}async function i(g){let y=await(e.majors??((b,T)=>gw(n,t,b,T)))(g.ref,g.image);return fw(g.ref,y)}async function u(g){let y=G(g.ref),b=await i(g);if(b)throw new Error(b);let T=e.credentials,R=await Id(e.repository,T?()=>T.forProject(g.ref,g.bucket):null),H={SNOUTPOD_OWNER_PASSWORD:g.ownerPassword,POSTGRES_PASSWORD:g.adminPassword,...jd(R)},M=[...await r(),"run","--detach","--name",y.pod,"--label",`${Ee}=${g.ref}`,"--label",`${ks}=${g.generation}`,"--userns=auto","--memory",`${g.memoryMb}m`,"--pids-limit",String(ww),...Ew(g.cpus),"--restart","no",...e.network?["--network",e.network]:[],...g.port?xr(e.podBind).flatMap(E=>["--publish",`${E}:${g.port}:5432`]):[],...rw(g.services,e.podBind),"--volume",`${y.pod}:/var/lib/postgresql/data:U`,"--env","SNOUTPOD_OWNER_PASSWORD","--env","POSTGRES_PASSWORD","--env",`SNOUTPOD_REF=${g.ref}`,"--env","POSTGRES_USER=snoutpod_admin","--env","POSTGRES_DB=postgres","--env",`SNOUTPOD_S3_BUCKET=${g.bucket}`,"--env",`SNOUTPOD_S3_REGION=${g.region}`,...e.egressDenied?["--env","SNOUTPOD_EGRESS=denied"]:[],...Pw(g.oauth),...Sw(g.tuning).flatMap(E=>["--env",E]),"--env",`SNOUTPOD_RETENTION_FULL=${Cl(g.backup?.retentionDays,g.backup?.fullIntervalHours)}`,...Cd(R),g.image,"snoutpod-postgres"];await z(n,t,M,{env:H})}async function c(g){let y=await z(n,t,["ps","--all","--filter",`label=${Ee}=${de(g)}`,"--filter",`label=${nt}`,"--format","json"]),b=y.trim()?JSON.parse(y):[],T=[];for(let R of b){let H=R.Labels?.[nt];if(!H)continue;let M=Number(R.Labels?.[vs]??0);T.push({name:H,container:Qd(g,H),spec:R.Labels?.[Yd]??"",pod:R.Labels?.[Xd]??"",running:R.State==="running",generation:Number.isInteger(M)?M:0})}return T}async function p(g){let y=await n(t,["container","inspect","--format","{{.Id}}",G(g).pod]);return y.code===0?y.stdout.trim():""}async function f(g,y){let b=[];for(let E of y){let A=E.dbUriRole??null;E.dbUriEnv&&A&&!b.includes(A)&&b.push(an(A))}let T=new Map;if(b.length===0)return T;let R={},H=[],M=[];b.some(E=>Md.includes(E))&&M.push(Ld);for(let E of b.filter(A=>ys.includes(A)))M.push(Ud(E));return b.forEach((E,A)=>{let Q=zy(24).toString("base64url"),re=`SNOUTPOD_SERVICE_PASSWORD_${A}`;T.set(E,Q),R[re]=Q,H.push("--env",re),M.push(`\\getenv service_password_${A} ${re}`),M.push(`\\set service_role_${A} ${E}`),M.push(`alter role :"service_role_${A}" with password :'service_password_${A}';`)}),M.push(""),await z(n,t,["exec",...he,"--interactive",...H,G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname",G(g.ref).database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:R,stdin:M.join(`
435
+ `)}),T}async function k(g){let y=Sr(g.ref);await z(n,t,["volume","create","--ignore",y]),await z(n,t,[...await r(),"run","--rm","--network","none","--volume",`${y}:${fs}`,"--entrypoint","bash",g.image,"-c",cd])}async function v(g){let y=await r();if((await n(t,[...y,"image","exists",g])).code===0)return;let b=await n(t,[...y,"pull","--quiet",g]);if(b.code===0)return;let T=pw(g);if(!T||!e.registryLogin)throw new Error(`${g} could not be pulled: ${(b.stderr||b.stdout).trim()}`);await e.registryLogin(T),await z(n,t,[...y,"pull","--quiet",g])}async function Y(g){let y=g.services??[],b=await c(g.ref),T;y.some(U=>U.smtpSecretEnv)&&(T=await e.smtpSecret?.().catch(()=>{}));let R=y.length>0?await p(g.ref):"",H=new Map(b.map(U=>[U.name,U])),M=new Map(y.map(U=>[U.name,Xy(U,T)])),E=new Set(y.filter(U=>{let ie=H.get(U.name);return!ie||!ie.running||ie.spec!==M.get(U.name)||R===""||ie.pod!==R}).map(U=>U.name)),A=g.servicesGeneration??0;if(E.size===0&&y.length>0&&!b.some(U=>U.generation>=A))for(let U of y)E.add(U.name);let Q=U=>U.dbUriEnv&&U.dbUriRole?U.dbUriRole:null;for(let U=!0;U;){U=!1;let ie=new Set(y.filter(at=>E.has(at.name)).map(Q));for(let at of y){let Ks=Q(at);!E.has(at.name)&&Ks!==null&&ie.has(Ks)&&(E.add(at.name),U=!0)}}for(let U of new Set(y.filter(ie=>E.has(ie.name)).map(ie=>ie.image)))await v(U);for(let U of b)(E.has(U.name)||!M.has(U.name))&&await z(n,t,["rm","--force","--ignore",U.container]);let re=y.filter(U=>E.has(U.name)),se=await f(g,re);re.some(U=>U.name===nn)&&await k(g);for(let U of re){let ie=Qd(g.ref,U.name),at=[...await r(),"run","--detach","--name",ie,"--label",`${Ee}=${g.ref}`,"--label",`${ks}=${g.generation}`,"--label",`${nt}=${U.name}`,"--label",`${vs}=${g.servicesGeneration??0}`,"--label",`${Yd}=${M.get(U.name)??""}`,"--label",`${Xd}=${R}`,"--network",`container:${G(g.ref).pod}`,"--userns",`container:${G(g.ref).pod}`,"--memory",`${U.memoryMb}m`,"--pids-limit",String(bw),"--restart","no",...sw(U),...U.name===nn?["--volume",`${Sr(g.ref)}:${fs}:ro`]:[],...tu(Zd(g,U,se,T)),U.image];await z(n,t,at,{env:Zd(g,U,se,T)})}}async function D(g,y){if(y%6!==0)return!1;let b=await n(t,["container","inspect","--format","{{.State.Status}}",G(g).pod]);return b.code===0&&/^(exited|stopped|dead)$/.test(b.stdout.trim())}function J(g){return["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres"]}async function O(g){let y=await n(t,[...J(g),"-tAc",ql]);return y.code===0?Gl(y.stdout):null}async function te(g){let y=await n(t,[...J(g),"-tAc","select pg_is_in_recovery()"]);if(y.code!==0)return null;let b=y.stdout.trim();return b==="t"?!0:b==="f"?!1:null}async function N(g,y){let b=R=>n(t,[...J(g),"-tAc",R]),T=Date.now()+y;do{if((await b("checkpoint")).code!==0)return!1;let H=await b("select (select timeline_id from pg_control_checkpoint()) = ('x' || substr(pg_walfile_name(pg_current_wal_lsn()), 1, 8))::bit(32)::int");if(H.code===0&&H.stdout.trim()==="t")return!0;await new Promise(M=>setTimeout(M,1e3))}while(Date.now()<T);return!1}async function pe(g){let y=await n(t,[...J(g),"-tAc",Ml],{timeoutMs:sn});return y.code===0?Ll(y.stdout):null}async function W(g,y){let b=new Map;for(let R of y)de(R),b.set(R,G(R).pod);if(b.size===0)return new Map;let T=await n(t,["exec",G(g).pod,"timeout",String(10),"sh","-c",Hl,"sh",...b.values()]);return T.code===0?Kl(T.stdout,b):null}async function le(g,y){de(y);let b=[];for(let M of[g,y]){let E=G(M).pod,A=await n(t,["container","inspect","--format","{{.State.Status}}",E]);if(A.code===0&&A.stdout.trim()==="running")throw new Error(`${E} is still running, so its data was not moved`);let Q=await n(t,["volume","inspect","--format","{{.Mountpoint}}",E]),re=Q.code===0?Q.stdout.trim().replace(/\/+$/,""):"";if(!re)throw new Error(`the volume ${E} could not be found, so nothing was moved`);b.push(re)}let R=typeof process.getuid!="function"||process.getuid()!==0?await n(t,["unshare","sh","-c",Ss,"sh",b[0],b[1]]):await n("sh",["-c",Ss,"sh",b[0],b[1]]),H=Wd(R.stdout,R.code);if(H)throw new Error(H)}async function fn(g){return(await n(t,[...J(g),"-v","ON_ERROR_STOP=1",...Jd.flatMap(b=>["-c",b])])).code===0}async function pt(g,y){return(await n(t,[...J(g),"-v","ON_ERROR_STOP=1",...Fl(y).flatMap(T=>["-c",T])],{timeoutMs:sn})).code===0}async function gn(){let g=e.network;if(!g)return null;let y=(await z(n,t,["network","inspect",g,"--format","{{range .Subnets}}{{.Subnet}} {{end}}"])).trim().split(" ")[0]??"";if(y==="")return null;let b=await z(n,t,["ps","--format","json"]),R=(b.trim()?JSON.parse(b):[]).map(E=>{let A=E.Labels?.[Ee],Q=E.Labels?.[Rt];return A&&!E.Labels?.[nt]?{name:G(A).pod,ref:A,service:!1}:Q?{name:on(Q),ref:Q,service:!0}:null}).filter(E=>E!==null);if(R.length===0)return{subnet:y,containers:[]};let H=await z(n,t,["inspect","--format",`{{.Name}} {{with index .NetworkSettings.Networks "${g}"}}{{.IPAddress}}{{end}}`,...R.map(E=>E.name)]),M=new Map(H.split(`
436
+ `).map(E=>E.trim().split(" ")).filter(E=>E.length===2&&E[1]!=="").map(([E,A])=>[E,A]));return{subnet:y,containers:R.flatMap(E=>M.has(E.name)?[{ref:E.ref,ip:M.get(E.name),service:E.service}]:[])}}async function Qu(g){return(await n(t,["unshare","--rootless-netns",dw,"-f","-"],{stdin:g,timeoutMs:sn})).code===0}async function ep(g,y){let b=await n(t,[...J(g),"-tA","-v","ON_ERROR_STOP=1",...Bl(y).flatMap(R=>["-c",R])],{timeoutMs:sn}),T=Number(b.stdout.trim().split(`
437
+ `).pop());return b.code===0&&Number.isInteger(T)?T:null}async function tp(g){let y=await n(t,[...J(g),"-tAc","select pg_read_file(current_setting('ssl_cert_file')) where current_setting('ssl') = 'on'"]),b=`${y.stdout.trim()}
438
+ `;return y.code===0&&Ul.test(b)?b:null}async function np(g,y){if(!Dl.test(y))throw new Error("not a SCRAM-SHA-256 verifier");let b=G(g).pod,T=[...J(g),"-v","ON_ERROR_STOP=1"];if((await n(t,[...T,"-c",`do $$ begin if not exists (select 1 from pg_roles where rolname = '${tt}') then create role ${tt} with login replication; end if; end $$`,"-c",`alter role ${tt} with login replication noinherit password '${y}'`],{timeoutMs:sn})).code!==0)return!1;let H=await n(t,[...T,"-tAc","show hba_file"]),M=H.stdout.trim();if(H.code!==0||!/^\/[A-Za-z0-9/_.-]+$/.test(M))return!1;let E=`hostssl replication ${tt} all scram-sha-256`;if((await n(t,["exec",b,"sh","-c",'grep -Eq "^host(ssl)?[[:space:]]+replication[[:space:]]+$2[[:space:]]" "$1" || printf "%s\\n" "$3" >> "$1"',"sh",M,tt,E])).code!==0)return!1;if((await n(t,[...T,"-tAc","show ssl"])).stdout.trim()!=="on"){let se=M.replace(/\/[^/]+$/,"");if((await n(t,["exec","--user","root",b,"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",se,b])).code!==0||(await n(t,[...T,"-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)return!1}return(await n(t,[...T,"-tAc","select pg_reload_conf()"])).code===0}return{list:a,inRecovery:te,replayLsn:O,settleTimeline:N,podHealth:pe,setSyncNames:pt,dropKeeperSlots:ep,bridgeContainers:gn,applyPodIsolation:Qu,ensureKeeperRole:np,podCertificate:tp,swapHomeData:le,promoteStandby:fn,nodesAnswer:W,preflight:i,create:u,createServices:Y,async start(g){let y=(await c(g).catch(()=>[])).filter(b=>b.running).map(b=>b.container);y.length>0&&await z(n,t,["stop","--time","5",...y]),await z(n,t,["start",G(g).pod])},async startServices(g){let y=(await c(g)).map(b=>b.container);y.length>0&&await z(n,t,["start",...y])},async applyHostServices(g){let y=[],b=await z(n,t,["ps","--all","--filter",`label=${Rt}`,"--format","json"]),T=b.trim()?JSON.parse(b):[],R=new Map;for(let M of T){let E=M.Labels?.[Rt];E&&R.set(E,{spec:M.Labels?.[eu]??"",state:M.State??"",elsewhere:nu(M,e.podBind)})}for(let M of g)try{await H(M)}catch(E){y.push({name:M.name,action:"failed",reason:E instanceof Error?E.message:String(E)})}async function H(M){let E=e.hostServiceLocal?.(M,g),A=E?{...M,...E.env&&Object.keys(E.env).length>0?{env:{...M.env,...E.env}}:{},...E.volumes?{volumes:E.volumes}:{},...E.network?{network:E.network}:{}}:M,Q=on(A.name),re=nw(A),se=R.get(A.name);if(R.delete(A.name),se&&se.spec===re&&!(se.state!=="running"&&se.elsewhere)){se.state!=="running"&&(await z(n,t,["start",Q]),y.push({name:A.name,action:"started",reason:se.state}));return}let U=se?se.spec===re?"published on another instance's address":"the spec changed":"it was not here";await v(A.image),se&&await z(n,t,["rm","--force","--ignore",Q]),await z(n,t,[...await r(),"run","--detach","--name",Q,"--label",`${Rt}=${A.name}`,"--label",`${eu}=${re}`,...A.healthPath?["--label",`${Es}=${A.hostPort}:${A.healthPath}`]:[],"--memory",`${A.memoryMb}m`,"--pids-limit",String(_w),"--restart","no",...A.network?["--network",A.network]:e.network?["--network",e.network]:[],...(A.volumes??[]).flatMap(ie=>["--volume",ie]),...xr(e.podBind).flatMap(ie=>["--publish",`${ie}:${A.hostPort}:${A.port}`]),...A.adminPort&&A.adminHostPort?["--publish",`127.0.0.1:${A.adminHostPort}:${A.adminPort}`]:[],...tu(A.env),A.image,...A.command??[]],{env:{...A.env}}),y.push({name:A.name,action:se?"recreated":"created",reason:U})}for(let M of R.keys())await z(n,t,["rm","--force","--ignore",on(M)]),y.push({name:M,action:"removed",reason:"it is no longer on the list"});return y},async hostServiceHealth(g){let y=await z(n,t,["ps","--all","--filter",`label=${Rt}`,"--format","json"]),b=(y.trim()?JSON.parse(y):[]).map(R=>R.Labels?.[Rt]??"").filter(R=>R!=="");if(b.length===0)return[];let T=Date.now()+g;for(;;){let R=[];for(let H of b)R.push(await ou(n,t,H,on(H),o));if(R.every(H=>H.ok)||Date.now()>=T)return R;await new Promise(H=>setTimeout(H,500))}},async serviceHealth(g,y){let b=await c(g);if(b.length===0)return[];let T=Date.now()+y;for(;;){let R=await Promise.all(b.map(H=>ou(n,t,H.name,H.container,o)));if(R.every(H=>H.ok)||Date.now()>=T)return R;await new Promise(H=>setTimeout(H,500))}},async stop(g,y){for(let b of await c(g))await z(n,t,["stop","--time",String(Zy),b.container]);await z(n,t,["stop","--time",String(y),G(g).pod])},async remove(g){for(let y of await c(g))await z(n,t,["rm","--force","--ignore",y.container]);await z(n,t,["rm","--force","--ignore","--volumes",G(g).pod])},async removeData(g){await z(n,t,["volume","rm","--force",G(g).pod]);let y=Sr(g);(await n(t,["volume","exists",y])).code===0&&await z(n,t,["volume","rm","--force",y])},async applyOwnerPassword(g){let y=await n(t,["exec",...he,G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select rolpassword from pg_authid where rolname = '${de(g.ref)}_owner'`]);if(y.code===0&&Ad(y.stdout,g.ownerPassword))return;let b=["\\getenv owner_password SNOUTPOD_OWNER_PASSWORD",`\\set owner_role ${g.ref}_owner`,`alter role :"owner_role" with password :'owner_password';`,""].join(`
439
+ `);await z(n,t,["exec",...he,"--interactive","--env","SNOUTPOD_OWNER_PASSWORD",G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_OWNER_PASSWORD:g.ownerPassword},stdin:b})},async applyRolePassword(g,y,b){let T=["\\getenv role_password SNOUTPOD_ROLE_PASSWORD",`\\set target_role ${an(y)}`,`alter role :"target_role" with password :'role_password';`,""].join(`
440
+ `);await z(n,t,["exec",...he,"--interactive","--env","SNOUTPOD_ROLE_PASSWORD",G(g).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{env:{SNOUTPOD_ROLE_PASSWORD:b},stdin:T})},async updateExtensions(g){let y=G(g),b=await n(t,["exec",...he,y.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`select datname from pg_database where datname = '${y.database}' or (not datistemplate and datname <> 'postgres') order by datname = '${y.database}' desc, datname limit 1`]),T=b.code===0&&/^[a-z][a-z0-9_]{0,62}$/.test(b.stdout.trim())?b.stdout.trim():y.database,R=await z(n,t,["exec",...he,"--interactive",y.pod,"psql","--username","snoutpod_admin","--dbname",T,"--quiet","-tA","-F",bs,"-v","ON_ERROR_STOP=1","--file","-"],{stdin:Fd});return Hd(R)},async applyDbAccess(g,y){let b=G(g),T=await z(n,t,["exec",...he,"--interactive","--env",vr,b.pod,"psql","--username","snoutpod_admin","--dbname",b.database,"--quiet","-tA","-v","ON_ERROR_STOP=1","--file","-"],{env:{[vr]:Sd(g,y)},stdin:bd,timeoutMs:6e4});return _d(T)},async runProjectSql(g,y){let b=G(g);await z(n,t,["exec",...he,"--interactive",b.pod,"psql","--username","snoutpod_admin","--dbname",b.database,"--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:y})},async ensureHostServiceDatabase(g,y,b){let T=on(g),R=an(y),H=an(b),M=A=>["exec",T,"psql","--username",R,"--dbname","postgres","--quiet","-tA","-v","ON_ERROR_STOP=1","-c",A];(await z(n,t,M(`select 1 from pg_database where datname = '${H}'`))).trim()!=="1"&&await z(n,t,M(`create database "${H}"`))},async renameProject(g,y){y!==g.ref&&await z(n,t,["exec",...he,"--interactive",G(g.ref).pod,"psql","--username","snoutpod_admin","--dbname","postgres","--quiet","-v","ON_ERROR_STOP=1","--file","-"],{stdin:xw(y,g.ref)})},async waitReady(g,y){let b=G(g).pod,T=Date.now()+y,R=0;for(;;){let H=await n(t,["exec",...he,b,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname","postgres","-tAc","select not pg_is_in_recovery()"]);if(H.code===0&&H.stdout.trim()==="t")return s(g),!0;if(Date.now()>=T||await D(g,++R))return!1;await new Promise(M=>setTimeout(M,500))}},async waitStandby(g,y){let b=Date.now()+y,T=0;for(;;){if(await te(g)===!0)return!0;if(Date.now()>=b||await D(g,++T))return!1;await new Promise(R=>setTimeout(R,500))}},async capacity(){let[g,y]=await Promise.all([l(),e.capacity()]);return{pods:g,...y}},async databaseBytes(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-tAc","select pg_database_size(current_database())"]);return y.code===0?os(y.stdout):null},async storageBytes(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-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 y.code===0?os(y.stdout):null},async setReadOnly(g,y){let b=G(g);await z(n,t,["exec",...he,b.pod,"psql","--username","snoutpod_admin","--dbname","postgres","-tAc",`alter database ${b.database} set default_transaction_read_only = ${y?"on":"off"}`])},async archiveState(g){let y=await n(t,["exec",...he,G(g).pod,"psql","--host","127.0.0.1","--username","snoutpod_admin","--dbname",g,"-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(y.code!==0)return null;let[b="",T=""]=y.stdout.trim().split(`
441
+ `)[0]?.split("|")??[],R=Number(T);return{lastArchivedAt:b.trim()||null,failures:Number.isInteger(R)&&R>=0?R:0}}}}async function ou(e,t,n,r,o=iu){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 i=a?.Status??"unknown";if(i!=="running")return{name:n,ok:!1,detail:i};let u=aw(l?.[Es]);if(!u)return{name:n,ok:!0,detail:"running"};let c=await o(u.port,u.path);return c===null?{name:n,ok:!1,detail:"not answering yet"}:{name:n,ok:!0,detail:`answered ${c}`}}async function $w(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 su(e){switch((e??"").toLowerCase()){case"running":return"running";case"created":case"configured":return"starting";case"exited":case"stopped":return"stopped";default:return"unknown"}}function xw(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" rename to :"to_db";','alter role :"from_role" rename to :"to_role";',"alter system reset restore_command;","alter system reset recovery_target_time;","alter system reset recovery_target_action;",""].join(`
442
+ `)}function Pw(e){if(!e?.issuer)return[];try{return["--env",`${qd}=${Gd(e.issuer)}`]}catch{return[]}}function Ew(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?[]:["--cpus",e.toFixed(2)]}var Ee,ks,nt,vs,Yd,Xd,Zy,Qy,ew,Rt,eu,ow,au,Es,iu,iw,dw,he,sn,uw,ru,ww,bw,_w,vw,_s=j(()=>{"use strict";Te();rs();as();is();Rd();rn();Dd();ss();Bd();Kd();hs();zd();cs();Vd();gs();Ee="snoutpod.ref",ks="snoutpod.generation",nt="snoutpod.service",vs="snoutpod.services-generation",Yd="snoutpod.service-spec",Xd="snoutpod.service-pod";Zy=10,Qy=/^[a-z][a-z0-9-]{0,30}$/;ew=/^[a-z][a-z0-9_]{0,62}$/;Rt="snoutpod.host-service",eu="snoutpod.host-service-spec";ow=/^[A-Za-z_][A-Za-z0-9_]*$/;au=/^\/[A-Za-z0-9\/_\-.~%?=&]*$/,Es="snoutpod.health";iu=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()})},iw="crun";dw="/usr/sbin/nft",he=["--env","PGOPTIONS=-c search_path=pg_catalog,pg_temp -c synchronous_commit=local"],sn=3e4,uw=3e4;ru=200,ww=1024,bw=512,_w=4096;vw=8});var vu={};qs(vu,{DEFAULT_LOCAL_MEMORY_MB:()=>mu,DEFAULT_LOCAL_PORT:()=>Nw,ENGINE:()=>Z,ENGINE_NAME:()=>Rs,IMAGE:()=>Ns,NETWORK:()=>rt,NEW_PROJECT_MAJOR:()=>Os,NO_BLACKHOLE_ROUTES:()=>yu,PUBLIC_IMAGE:()=>Dw,PUBLISHED_MAJORS:()=>Tt,capacity:()=>hu,chooseLocalImage:()=>dn,dropIfUnused:()=>Su,ensureImage:()=>Mw,ensureNetwork:()=>Hw,exec:()=>ce,hasData:()=>Rr,localImageFor:()=>gu,localPsql:()=>Gw,localRuntime:()=>Fw,localSpec:()=>_u,localStatus:()=>Is,localUri:()=>bu,networkPolicyInPlace:()=>wu,newLocalPassword:()=>Cw,newLocalRef:()=>Iw,podLog:()=>ku,podName:()=>Ot,podmanReady:()=>Uw,removeLocal:()=>Jw,staleImage:()=>Ts,startLocal:()=>qw,stopLocal:()=>Ww,volumePgVersion:()=>Pr});import{randomBytes as uu}from"node:crypto";import{existsSync as lu}from"node:fs";import{platform as Ar}from"node:os";import{delimiter as Aw,join as Rw}from"node:path";function Tw(){if(process.env.SNOUTPOD_ENGINE)return process.env.SNOUTPOD_ENGINE;let e=Ar()==="win32"?["podman.exe","podman"]:["podman"];for(let t of(process.env.PATH??"").split(Aw))if(t&&e.some(n=>lu(Rw(t,n))))return"podman";return lu("/opt/podman/bin/podman")?"/opt/podman/bin/podman":"podman"}function dn(e,t=process.env.SNOUTPOD_IMAGE){if(t)return{name:t,published:null,major:null};if(e===null)return ln(Os);let n=Number(As(e));if(!Tt.includes(n)){let r=e.trim()||"(empty)",o=Tt.map(s=>ln(s).published).join(" or ");throw new Error(`its data directory's PG_VERSION says ${r}, and there is an image only for Postgres ${Tt.join(" and ")}. Set SNOUTPOD_IMAGE to an image of that major (${o} for those).`)}return ln(n)}function ln(e){return{name:`${Ow}:${e}`,published:`${pu}:${e}`,major:e}}function Iw(){return Ol(e=>uu(e))}function Cw(){return uu(18).toString("base64url")}async function Mw(e,t=ce,n=dn(null)){let r=n.published;if(!r)return null;if((await t(Z,["image","exists",n.name])).code===0)return await Lw(e,t,n.name,r),null;e?.(`Fetching the database image (${r}). This happens once.`);let o=await t(Z,["pull",r],{timeoutMs:fu}).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(Z,["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 Lw(e,t,n,r){let o=await t(Z,["image","inspect","--format","{{.Id}}",n,r]).catch(()=>null),[s,a]=o?.code===0?o.stdout.trim().split(`
443
+ `):[];if(!s||s!==a)return;let l=setTimeout(()=>e?.(`Fetching a newer database image (${r}).`),3e3),i=await t(Z,["pull",r],{timeoutMs:fu}).catch(f=>({code:1,stdout:"",stderr:f instanceof Error?f.message:String(f)})).finally(()=>clearTimeout(l));if(i.code!==0){let f=(i.stderr.trim()||i.stdout.trim()||"the pull failed").split(`
444
+ `).at(-1);e?.(`Could not check for a newer database image (${f}); using the one on this machine.`);return}let u=await t(Z,["image","inspect","--format","{{.Id}}",r]).catch(()=>null),c=u?.code===0?u.stdout.trim():"";if(!c||c===s)return;let p=await t(Z,["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 Uw(e=jw,t=Ns){if(Rs!=="podman")return`SNOUTPOD_ENGINE=${Rs}: 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 ce(Z,["--version"])}catch{return`${Z} 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`${Z} --version failed: ${n.stderr.trim()||n.stdout.trim()}`;if((await ce(Z,["image","exists",t])).code!==0)return`the pod image ${t} is not on this machine. ${e}`;let o=await ce(Z,["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 Bw(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 ce(Z,["machine","ssh",t]).then(n=>{let r=n.stdout.trim().split(`
445
+ `).at(-1);return r==="DATA"?"data":r==="EMPTY"?"empty":"hidden"},()=>"hidden")}function Rr(e){let t=Ar()==="darwin"||Ar()==="win32";return xd(ce,e,{binary:Z,look:t?Bw:void 0})}async function Pr(e,t=ce,n=Ar()){let r=G(e).pod;if((await t(Z,["volume","exists",r])).code!==0)return null;let o;if(n==="darwin"||n==="win32"){let s=null;for(let a of Tt){let l=ln(a).name;if((await t(Z,["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 (${Tt.map(a=>ln(a).published).join(" or ")}).`);o=await t(Z,["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(Z,["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(Z,["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 gu(e,t=Pr){if(!e||process.env.SNOUTPOD_IMAGE)return Promise.resolve(dn(null));de(e);let n=t===Pr?Er.get(e):void 0;if(n)return n;let r=t(e).then(o=>{try{return dn(o)}catch(s){throw new Error(`${Ot(e)}: ${s instanceof Error?s.message:String(s)}`)}});return t===Pr&&(Er.set(e,r),r.catch(()=>Er.delete(e))),r}async function hu(){return{ramFreeMb:4096,ramTotalMb:8192,diskFreeMb:32768,diskTotalMb:65536}}function Fw(e){return cu({exec:ce,binary:Z,network:rt,hasData:Rr,capacity:hu,repository:e})}function Ot(e){return G(e).pod}async function Hw(e){if(process.env.SNOUTPOD_LOCAL_ALLOW_EGRESS==="1"){await Kw()||await ce(Z,br({name:rt}));return}let t=br({name:rt,allow:[]}),n="";for(let r=0;r<10;r+=1){if(await wu())return;await e?.(),await ce(Z,["network","rm","--force",rt]).catch(()=>{});let o=await ce(Z,t);if(o.code===0)return;if(n=`${o.stderr}${o.stdout}`.trim(),/invalid route gateway/i.test(n))throw new Error(`${yu}: ${n}`);await new Promise(s=>setTimeout(s,500))}throw new Error(`could not create ${rt} with egress blocked${n?`: ${n}`:""}`)}async function Kw(){return(await ce(Z,["network","inspect",rt,"--format","json"])).code===0}async function wu(){let e=await ce(Z,["network","inspect",rt,"--format","json"]);if(e.code!==0)return!1;try{return rd(JSON.parse(e.stdout)?.[0])}catch{return!1}}function bu(e){let t=G(e.ref);return`postgres://${t.ownerRole}:${encodeURIComponent(e.ownerPassword)}@127.0.0.1:${e.port}/${t.database}?sslmode=disable`}function _u(e,t={}){return de(e.ref),{ref:e.ref,generation:1,image:t.image??Ns,memoryMb:t.memoryMb??mu,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 cn(e,t){e.onProgress?.(t)}async function qw(e,t,n={}){let r=n.image??(await gu(t.ref,n.pgVersion)).name,o=_u(t,{...n,image:r}),s=n.timeoutMs??12e4,a=n.hasData??Rr,l=(await e.list()).find(u=>u.ref===t.ref),i=null;if(l?l.status==="stopped"&&(i=await(n.staleImage??Ts)(t.ref,r))?(cn(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??Su)(i)):l.status==="stopped"?(cn(n,"Starting the database."),await e.start(t.ref),await e.startServices(t.ref)):(cn(n,"The database is already running."),l.status==="running"&&await(n.staleImage??Ts)(t.ref,r)&&cn(n,"A newer database image is on this machine. To move onto it: snoutdata stop, then snoutdata start.")):(cn(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 zw(t.ref,s,n.podLog??ku));return await e.applyOwnerPassword(o),await e.createServices(o),Is(e,t,n)}function du(e){return e.trim().replace(/^sha256:/,"")}async function Ts(e,t){let[n,r]=await Promise.all([ce(Z,["container","inspect","--format","{{.Image}}",Ot(e)]).catch(()=>null),ce(Z,["image","inspect","--format","{{.Id}}",t]).catch(()=>null)]);if(n?.code!==0||r?.code!==0)return null;let o=du(n.stdout),s=du(r.stdout);return o&&s&&o!==s?o:null}async function Su(e){let t=await ce(Z,["image","inspect","--format","{{len .RepoTags}}",e]).catch(()=>null);t?.code===0&&t.stdout.trim()==="0"&&await ce(Z,["rmi",e]).catch(()=>{})}async function Gw(e,t){let n=G(e.ref);return ce(Z,["exec","--interactive","-e","PGPASSWORD",Ot(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 ku(e){let t=await ce(Z,["logs","--tail","20",Ot(e)]).catch(()=>null);return t?`${t.stdout}${t.stderr}`:"(no log: the container is not there)"}async function zw(e,t,n){let r=await n(e).catch(()=>"(no log)");return`${Ot(e)} never became ready in ${t}ms
442
446
  --- pod log ---
443
- ${r}`}async function Ow(e,t,n={}){le(t);let r=(await e.list()).find(o=>o.ref===t);return r&&r.status!=="stopped"&&await e.stop(t,wd),Is(e,{ref:t,port:0,ownerPassword:"",adminPassword:""},n)}async function Nw(e,t,n){le(t),await e.remove(t),n&&(await e.removeData(t),xr.delete(t))}async function Is(e,t,n={}){le(t.ref);let r=(await e.list()).find(a=>a.ref===t.ref),o=r?.status==="running",s=n.hasData??Er;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?fu(t):null}}var Rs,Z,Os,Rt,gw,iu,Ns,nt,hw,cu,ie,bw,_w,lu,xr,pu,bu=C(()=>{"use strict";bd();nn();kd();ls();ws();Re();Rs=process.env.SNOUTPOD_ENGINE??"podman";Z=fw(),Os=18,Rt=[17,18],gw="snoutpod/postgres",iu="ghcr.io/snoutdata/snoutpod-postgres";Ns=cn(null).name,nt=process.env.SNOUTPOD_LOCAL_NETWORK??"snoutpod-local",hw=54322,cu=512,ie=_d();bw="cd packages/snoutpod && npm run image:build",_w=`${iu}:${Os}`;lu=20*60*1e3;xr=new Map;pu="this podman cannot blackhole a route, so the local tier cannot isolate its containers"});be();var $e=["--admin","--token","--project"],Cr=["--max-write-pause-ms","--drain-timeout-ms","--ack-timeout-ms","--copy-mb-per-s"],mt=[...$e,"--plan","--no-wait","--timeout",...Cr],Se=[...mt,"--yes"],jr=[{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","--timeout"]},{name:"logout",summary:"Forget the stored session",flags:[]},{name:"whoami",summary:"Who this credential belongs to, and whether it is the account login --email asked for",flags:[]},{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","--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 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",flags:["--ref"]},{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:[...$e]},{name:"cluster ops",summary:"The operations the router offers, and its default settings",flags:[...$e]},{name:"cluster nodes",summary:"The nodes, their state and how many ranges each owns",flags:[...$e]},{name:"cluster enable",summary:"SnoutData Cloud: make a project a cluster. The router joins its pod, which restarts the database once. 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 and the router leaves its 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:[...mt]},{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:[...mt,"--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","--column","--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:[...Se,"--to"]},{name:"cluster nodes remove",summary:"Detach a drained node",flags:[...Se]},{name:"cluster keyspace create",summary:"A keyspace: the shard key type and its initial ranges",flags:[...mt,"--key-type","--ranges","--seed","--nodes"]},{name:"cluster keyspace drop",summary:"Forget a keyspace no table is distributed by",flags:[...mt]},{name:"cluster table distribute",summary:"Shard a table by a column, moving its rows out from the home node",flags:[...Se,"--column","--keyspace"]},{name:"cluster table reference",summary:"Copy a table to every node",flags:[...Se]},{name:"cluster table global",summary:"Bring a table back to the home node alone",flags:[...Se]},{name:"cluster range split",summary:"One range becomes two, and one half moves",flags:[...Se,"--keyspace","--range","--at","--to"]},{name:"cluster range merge",summary:"Two adjacent ranges become one",flags:[...Se]},{name:"cluster range move",summary:"Give a range to another node",flags:[...Se,"--keyspace","--range","--to"]},{name:"cluster tenant pin",summary:"One key value gets its own range, and optionally its own node",flags:[...Se,"--keyspace","--value","--node"]},{name:"cluster rebalance",summary:"Even out the ranges across the nodes",flags:[...Se,"--keyspace"]},{name:"cluster scale",summary:"Add nodes and rebalance, or drain and remove the emptiest",flags:[...Se,"--add","--remove","--nodes","--dbname","--sslmode"]},{name:"cluster verify",summary:"Row counts and a checksum per range, source against target",flags:[...mt,"--keyspace"]},{name:"cluster cleanup",summary:"Delete the rows a node no longer owns, then VACUUM",flags:[...Se,"--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:[...Se]},{name:"cluster plan",summary:"The dry run of any operation above: steps, what moves, rows, size, copy time, expected pause",flags:[...$e,...Cr]},{name:"cluster jobs",summary:"The latest jobs",flags:[...$e]},{name:"cluster jobs show",summary:"One job, its plan and its steps",flags:[...$e]},{name:"cluster jobs watch",summary:"Follow a job until it finishes: exit 0 done, 1 failed or cancelled, 10 timed out",flags:[...$e,"--timeout"]},{name:"cluster jobs cancel",summary:"Stop a job: a move before its cutover rolls back, after it finishes its cleanup",flags:[...$e,"--yes"]},{name:"cluster jobs resume",summary:"Run a failed job again from the step that failed, and follow it",flags:[...$e,"--no-wait","--timeout"]},{name:"cluster settings",summary:"The cluster's cutover and advisor settings, or set them",flags:[...$e,...Cr,"--set"]},{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:[...$e,"--sample-ms"]},{name:"mcp",summary:"Serve these operations as tools over stdio",flags:["--allow-delete"]}],Ws={"--ref":"The project. Defaults to SNOUTDATA_PROJECT, then .snoutdata/project.json here or in a parent","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","--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","--column":"The distribution key column","--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","--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 Dr(e,t){return Ws[`${e} ${t}`]??Ws[t]??""}function zs(e,t){let n=jr.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}re();me();te();import{spawn as em}from"node:child_process";function tm(e){return`snout-${e}`}function St(e,t,n){return new Promise((r,o)=>{let s=em("docker",["compose","-p",tm(e.ref),"--project-directory",e.folder,...t],{cwd:e.folder,stdio:["ignore","pipe","pipe"]}),a="",l="";s.stdout.on("data",i=>{a+=String(i)}),s.stderr.on("data",i=>{if(l+=String(i),n)for(let u of String(i).split(/\r?\n/).filter(Boolean))d(w(` ${u.trim()}`))}),s.on("error",i=>{if(i.code==="ENOENT"){o(new P("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 P("failed",String(i)))}),s.on("close",i=>r({code:i??0,out:a,err:l}))})}async function nm(e){let t=await St(e,["ps","-a","--format","json"],!1);if(t.code!==0)throw new P("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 Ia(e){let t=await nm(e),n=t.filter(o=>o.state==="running").length,r=t.filter(o=>o.state!=="done").length;return h({ref:e.ref,local:e.folder,api:e.apiUrl,dbPort:e.dbPort,running:n,services:t},()=>{if(d(`${x(e.name??e.ref)} (local, ${e.folder})`),t.length===0){d("Not started. `snoutdata start` brings it up.");return}process.stdout.write(`${L([["SERVICE","STATE","HEALTH"],...t.map(o=>[o.service,o.state,o.health])])}
444
- `),d(`${n} of ${r} services running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}.`)}),0}async function Ca(e){d(`Starting ${e.name??e.ref} (local)\u2026`);let t=await St(e,["up","-d","--wait","--wait-timeout","600"],!0);if(t.code!==0)throw new P("failed",`docker compose up failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return h({ref:e.ref,api:e.apiUrl,dbPort:e.dbPort,started:!0},()=>{d(`Running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}. \`snoutdata db url\` prints the connection string.`)}),0}async function ja(e){let t=await St(e,["stop"],!0);if(t.code!==0)throw new P("failed",`docker compose stop failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return h({ref:e.ref,stopped:!0},()=>d(`Stopped ${e.name??e.ref}. Its data is kept; \`snoutdata start\` brings it back.`)),0}function Da(e){h({ref:e.ref,name:e.name,local:e.folder,api:e.apiUrl,dbPort:e.dbPort},()=>{process.stdout.write(`${L([["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}`]])}
445
- `)})}Ct();import{cpSync as Ua,existsSync as Kt,readdirSync as dm,readFileSync as Ba,rmSync as Fa,statSync as um,writeFileSync as Ha}from"node:fs";import{join as Pe,resolve as Fn}from"node:path";var rm=/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;function om(e){return rm.test(e)}function ct(e){if(!om(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 sm=/^[A-Za-z0-9_][A-Za-z0-9._-]*$/;function am(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!==".."&&sm.test(n))}var eo=2*1024*1024,Ma=200;function La(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>Ma)throw new Error(`a function may hold ${Ma} files and this one has ${e.files.length}`);let n=new Set;for(let a of e.files){if(!am(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=im(o);if(s.length>eo)throw new Error(`this function is ${Math.round(s.length/1024)} KB and the limit is ${eo/1024} KB. A function is source code; put large files in Storage.`);return o}function im(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 cm=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/;var lm=["SNOUTDATA_","SNOUT_"];function Ht(e){if(!cm.test(e))return`${JSON.stringify(e)} is not an environment variable name: letters, digits and underscores, not starting with a digit.`;let t=lm.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 F_=64*1024;me();be();te();function Ka(e){let t=Pe(e.folder,"functions");return Kt(t)?dm(t).filter(n=>!n.startsWith(".")&&!n.startsWith("_")&&um(Pe(t,n)).isDirectory()).sort():[]}async function Hn(e){d(w(" docker compose run --rm functions-deploy"));let t=await St(e,["run","--rm","functions-deploy"],!0);if(t.code!==0)throw new P("failed",`functions-deploy failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`)}function qa(e,t,n){let r=Pe(e.folder,".env"),o=Ba(r,"utf8"),s=(wn(o).get("FUNCTIONS_NO_VERIFY_JWT")??"").split(",").map(u=>u.trim()).filter(Boolean),a=n?[...new Set([...s,t])]:s.filter(u=>u!==t);if(a.join(",")===s.join(","))return!1;let l=`FUNCTIONS_NO_VERIFY_JWT=${a.join(",")}`,i=/^FUNCTIONS_NO_VERIFY_JWT=.*$/m;return Ha(r,i.test(o)?o.replace(i,l):`${o.replace(/\n?$/,`
447
+ ${r}`}async function Ww(e,t,n={}){de(t);let r=(await e.list()).find(o=>o.ref===t);return r&&r.status!=="stopped"&&await e.stop(t,kd),Is(e,{ref:t,port:0,ownerPassword:"",adminPassword:""},n)}async function Jw(e,t,n){de(t),await e.remove(t),n&&(await e.removeData(t),Er.delete(t))}async function Is(e,t,n={}){de(t.ref);let r=(await e.list()).find(a=>a.ref===t.ref),o=r?.status==="running",s=n.hasData??Rr;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?bu(t):null}}var Rs,Z,Os,Tt,Ow,pu,Ns,rt,Nw,mu,ce,jw,Dw,fu,Er,yu,$u=j(()=>{"use strict";vd();rn();Pd();us();_s();Te();Rs=process.env.SNOUTPOD_ENGINE??"podman";Z=Tw(),Os=18,Tt=[17,18],Ow="snoutpod/postgres",pu="ghcr.io/snoutdata/snoutpod-postgres";Ns=dn(null).name,rt=process.env.SNOUTPOD_LOCAL_NETWORK??"snoutpod-local",Nw=54322,mu=512,ce=$d();jw="cd packages/snoutpod && npm run image:build",Dw=`${pu}:${Os}`;fu=20*60*1e3;Er=new Map;yu="this podman cannot blackhole a route, so the local tier cannot isolate its containers"});be();var $e=["--admin","--token","--project"],Dr=["--max-write-pause-ms","--drain-timeout-ms","--ack-timeout-ms","--copy-mb-per-s"],mt=[...$e,"--plan","--no-wait","--timeout",...Dr],Se=[...mt,"--yes"],Mr=[{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","--timeout"]},{name:"logout",summary:"Forget the stored session",flags:[]},{name:"whoami",summary:"Who this credential belongs to, and whether it is the account login --email asked for",flags:[]},{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","--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 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",flags:["--ref"]},{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:[...$e]},{name:"cluster ops",summary:"The operations the router offers, and its default settings",flags:[...$e]},{name:"cluster nodes",summary:"The nodes, their state and how many ranges each owns",flags:[...$e]},{name:"cluster enable",summary:"SnoutData Cloud: make a project a cluster. The router joins its pod, which restarts the database once. 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 and the router leaves its 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:[...mt]},{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:[...mt,"--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","--column","--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:[...Se,"--to"]},{name:"cluster nodes remove",summary:"Detach a drained node",flags:[...Se]},{name:"cluster keyspace create",summary:"A keyspace: the shard key type and its initial ranges",flags:[...mt,"--key-type","--ranges","--seed","--nodes"]},{name:"cluster keyspace drop",summary:"Forget a keyspace no table is distributed by",flags:[...mt]},{name:"cluster table distribute",summary:"Shard a table by a column, moving its rows out from the home node",flags:[...Se,"--column","--keyspace"]},{name:"cluster table reference",summary:"Copy a table to every node",flags:[...Se]},{name:"cluster table global",summary:"Bring a table back to the home node alone",flags:[...Se]},{name:"cluster range split",summary:"One range becomes two, and one half moves",flags:[...Se,"--keyspace","--range","--at","--to"]},{name:"cluster range merge",summary:"Two adjacent ranges become one",flags:[...Se]},{name:"cluster range move",summary:"Give a range to another node",flags:[...Se,"--keyspace","--range","--to"]},{name:"cluster tenant pin",summary:"One key value gets its own range, and optionally its own node",flags:[...Se,"--keyspace","--value","--node"]},{name:"cluster rebalance",summary:"Even out the ranges across the nodes",flags:[...Se,"--keyspace"]},{name:"cluster scale",summary:"Add nodes and rebalance, or drain and remove the emptiest",flags:[...Se,"--add","--remove","--nodes","--dbname","--sslmode"]},{name:"cluster verify",summary:"Row counts and a checksum per range, source against target",flags:[...mt,"--keyspace"]},{name:"cluster cleanup",summary:"Delete the rows a node no longer owns, then VACUUM",flags:[...Se,"--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:[...Se]},{name:"cluster plan",summary:"The dry run of any operation above: steps, what moves, rows, size, copy time, expected pause",flags:[...$e,...Dr]},{name:"cluster jobs",summary:"The latest jobs",flags:[...$e]},{name:"cluster jobs show",summary:"One job, its plan and its steps",flags:[...$e]},{name:"cluster jobs watch",summary:"Follow a job until it finishes: exit 0 done, 1 failed or cancelled, 10 timed out",flags:[...$e,"--timeout"]},{name:"cluster jobs cancel",summary:"Stop a job: a move before its cutover rolls back, after it finishes its cleanup",flags:[...$e,"--yes"]},{name:"cluster jobs resume",summary:"Run a failed job again from the step that failed, and follow it",flags:[...$e,"--no-wait","--timeout"]},{name:"cluster settings",summary:"The cluster's cutover and advisor settings, or set them",flags:[...$e,...Dr,"--set"]},{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:[...$e,"--sample-ms"]},{name:"mcp",summary:"Serve these operations as tools over stdio",flags:["--allow-delete"]}],zs={"--ref":"The project. Defaults to SNOUTDATA_PROJECT, then .snoutdata/project.json here or in a parent","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","--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","--column":"The distribution key column","--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","--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 Lr(e,t){return zs[`${e} ${t}`]??zs[t]??""}function Ws(e,t){let n=Mr.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}oe();me();ne();import{spawn as lm}from"node:child_process";function dm(e){return`snout-${e}`}function St(e,t,n){return new Promise((r,o)=>{let s=lm("docker",["compose","-p",dm(e.ref),"--project-directory",e.folder,...t],{cwd:e.folder,stdio:["ignore","pipe","pipe"]}),a="",l="";s.stdout.on("data",i=>{a+=String(i)}),s.stderr.on("data",i=>{if(l+=String(i),n)for(let u of String(i).split(/\r?\n/).filter(Boolean))d(w(` ${u.trim()}`))}),s.on("error",i=>{if(i.code==="ENOENT"){o(new P("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 P("failed",String(i)))}),s.on("close",i=>r({code:i??0,out:a,err:l}))})}async function um(e){let t=await St(e,["ps","-a","--format","json"],!1);if(t.code!==0)throw new P("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 Ca(e){let t=await um(e),n=t.filter(o=>o.state==="running").length,r=t.filter(o=>o.state!=="done").length;return h({ref:e.ref,local:e.folder,api:e.apiUrl,dbPort:e.dbPort,running:n,services:t},()=>{if(d(`${x(e.name??e.ref)} (local, ${e.folder})`),t.length===0){d("Not started. `snoutdata start` brings it up.");return}process.stdout.write(`${B([["SERVICE","STATE","HEALTH"],...t.map(o=>[o.service,o.state,o.health])])}
448
+ `),d(`${n} of ${r} services running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}.`)}),0}async function ja(e){d(`Starting ${e.name??e.ref} (local)\u2026`);let t=await St(e,["up","-d","--wait","--wait-timeout","600"],!0);if(t.code!==0)throw new P("failed",`docker compose up failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return h({ref:e.ref,api:e.apiUrl,dbPort:e.dbPort,started:!0},()=>{d(`Running. API ${e.apiUrl}, database 127.0.0.1:${e.dbPort}. \`snoutdata db url\` prints the connection string.`)}),0}async function Da(e){let t=await St(e,["stop"],!0);if(t.code!==0)throw new P("failed",`docker compose stop failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`);return h({ref:e.ref,stopped:!0},()=>d(`Stopped ${e.name??e.ref}. Its data is kept; \`snoutdata start\` brings it back.`)),0}function Ma(e){h({ref:e.ref,name:e.name,local:e.folder,api:e.apiUrl,dbPort:e.dbPort},()=>{process.stdout.write(`${B([["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}`]])}
449
+ `)})}jt();import{cpSync as Ba,existsSync as qt,readdirSync as bm,readFileSync as Fa,rmSync as Ha,statSync as _m,writeFileSync as Ka}from"node:fs";import{join as Pe,resolve as Kn}from"node:path";var pm=/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;function mm(e){return pm.test(e)}function lt(e){if(!mm(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 fm=/^[A-Za-z0-9_][A-Za-z0-9._-]*$/;function gm(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!==".."&&fm.test(n))}var no=2*1024*1024,La=200;function Ua(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>La)throw new Error(`a function may hold ${La} files and this one has ${e.files.length}`);let n=new Set;for(let a of e.files){if(!gm(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=hm(o);if(s.length>no)throw new Error(`this function is ${Math.round(s.length/1024)} KB and the limit is ${no/1024} KB. A function is source code; put large files in Storage.`);return o}function hm(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 ym=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/;var wm=["SNOUTDATA_","SNOUT_"];function Kt(e){if(!ym.test(e))return`${JSON.stringify(e)} is not an environment variable name: letters, digits and underscores, not starting with a digit.`;let t=wm.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 rS=64*1024;me();be();ne();function qa(e){let t=Pe(e.folder,"functions");return qt(t)?bm(t).filter(n=>!n.startsWith(".")&&!n.startsWith("_")&&_m(Pe(t,n)).isDirectory()).sort():[]}async function qn(e){d(w(" docker compose run --rm functions-deploy"));let t=await St(e,["run","--rm","functions-deploy"],!0);if(t.code!==0)throw new P("failed",`functions-deploy failed: ${t.err.trim().split(/\r?\n/).slice(-3).join(" ")}`)}function Ga(e,t,n){let r=Pe(e.folder,".env"),o=Fa(r,"utf8"),s=(_n(o).get("FUNCTIONS_NO_VERIFY_JWT")??"").split(",").map(u=>u.trim()).filter(Boolean),a=n?[...new Set([...s,t])]:s.filter(u=>u!==t);if(a.join(",")===s.join(","))return!1;let l=`FUNCTIONS_NO_VERIFY_JWT=${a.join(",")}`,i=/^FUNCTIONS_NO_VERIFY_JWT=.*$/m;return Ka(r,i.test(o)?o.replace(i,l):`${o.replace(/\n?$/,`
446
450
  `)}${l}
447
- `),!0}async function to(e,t,n){ct(t);let r=Fn(n.dir??Pe(process.cwd(),"functions",t));if(!Kt(Pe(r,"index.ts")))throw new m(`${r} has no index.ts. A local function is a folder with an index.ts in it.`);let o=Pe(e.folder,"functions",t);if(Fn(o)!==r){Fa(o,{recursive:!0,force:!0}),Ua(r,o,{recursive:!0});let a=Pe(r,"..","_shared");Kt(a)&&Fn(a)!==Fn(Pe(e.folder,"functions","_shared"))&&Ua(a,Pe(e.folder,"functions","_shared"),{recursive:!0})}let s=qa(e,t,!n.verifyJwt);if(await Hn(e),s){let a=await St(e,["up","-d","--wait","--wait-timeout","600"],!1);if(a.code!==0)throw new P("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:no(e,t),verifyJwt:n.verifyJwt,local:e.folder}}async function Ga(e,t,n){let r=await to(e,t,n);h(r,()=>{d(`${x(t)} deployed locally: ${r.url}`),n.verifyJwt||d(w(" Callable with no key (FUNCTIONS_NO_VERIFY_JWT), so it must check what calls it itself."))})}function no(e,t){return`${e.apiUrl}/functions/v1/${t}`}function Kn(e){return{ref:e.ref,local:e.folder,functions:Ka(e).map(t=>({name:t,url:no(e,t)}))}}function Wa(e){let t=Ka(e);h(Kn(e),()=>{if(t.length===0){d(`No functions in ${Pe(e.folder,"functions")}.`);return}process.stdout.write(`${L([["NAME","URL"],...t.map(n=>[n,no(e,n)])])}
448
- `)})}async function ro(e,t){ct(t);let n=Pe(e.folder,"functions",t);if(!Kt(n))throw new P("not-found",`this local project has no function called ${t}`);return Fa(n,{recursive:!0,force:!0}),qa(e,t,!1),await Hn(e),{ref:e.ref,name:t,removed:!0}}async function za(e,t){h(await ro(e,t),()=>d(`${t} is gone.`))}function qn(e){return Pe(e.folder,"functions",".env")}function oo(e){let t=qn(e);return Kt(t)?wn(Ba(t,"utf8")):new Map}function Ja(e,t){let n=r=>r.includes("'")?JSON.stringify(r):`'${r}'`;Ha(qn(e),[...t].map(([r,o])=>`${r}=${n(o)}`).join(`
451
+ `),!0}async function ro(e,t,n){lt(t);let r=Kn(n.dir??Pe(process.cwd(),"functions",t));if(!qt(Pe(r,"index.ts")))throw new m(`${r} has no index.ts. A local function is a folder with an index.ts in it.`);let o=Pe(e.folder,"functions",t);if(Kn(o)!==r){Ha(o,{recursive:!0,force:!0}),Ba(r,o,{recursive:!0});let a=Pe(r,"..","_shared");qt(a)&&Kn(a)!==Kn(Pe(e.folder,"functions","_shared"))&&Ba(a,Pe(e.folder,"functions","_shared"),{recursive:!0})}let s=Ga(e,t,!n.verifyJwt);if(await qn(e),s){let a=await St(e,["up","-d","--wait","--wait-timeout","600"],!1);if(a.code!==0)throw new P("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:oo(e,t),verifyJwt:n.verifyJwt,local:e.folder}}async function za(e,t,n){let r=await ro(e,t,n);h(r,()=>{d(`${x(t)} deployed locally: ${r.url}`),n.verifyJwt||d(w(" Callable with no key (FUNCTIONS_NO_VERIFY_JWT), so it must check what calls it itself."))})}function oo(e,t){return`${e.apiUrl}/functions/v1/${t}`}function Gn(e){return{ref:e.ref,local:e.folder,functions:qa(e).map(t=>({name:t,url:oo(e,t)}))}}function Wa(e){let t=qa(e);h(Gn(e),()=>{if(t.length===0){d(`No functions in ${Pe(e.folder,"functions")}.`);return}process.stdout.write(`${B([["NAME","URL"],...t.map(n=>[n,oo(e,n)])])}
452
+ `)})}async function so(e,t){lt(t);let n=Pe(e.folder,"functions",t);if(!qt(n))throw new P("not-found",`this local project has no function called ${t}`);return Ha(n,{recursive:!0,force:!0}),Ga(e,t,!1),await qn(e),{ref:e.ref,name:t,removed:!0}}async function Ja(e,t){h(await so(e,t),()=>d(`${t} is gone.`))}function zn(e){return Pe(e.folder,"functions",".env")}function ao(e){let t=zn(e);return qt(t)?_n(Fa(t,"utf8")):new Map}function Va(e,t){let n=r=>r.includes("'")?JSON.stringify(r):`'${r}'`;Ka(zn(e),[...t].map(([r,o])=>`${r}=${n(o)}`).join(`
449
453
  `)+(t.size?`
450
- `:""))}async function Va(e,t){for(let r of t){let o=Ht(r.name);if(o)throw new m(o)}let n=oo(e);for(let r of t)n.set(r.name,r.value);Ja(e,n),await Hn(e),h({ref:e.ref,set:t.map(r=>r.name)},()=>{for(let r of t)d(`${x(r.name)} set in ${qn(e)}`)})}function Gn(e){return{ref:e.ref,local:e.folder,secrets:[...oo(e).keys()].sort().map(t=>({name:t}))}}function Ya(e){let t=Gn(e),n=t.secrets.map(r=>r.name);h(t,()=>{d(n.length?n.join(`
451
- `):`No function secrets in ${qn(e)}.`)})}async function Xa(e,t){let n=oo(e);if(!n.delete(t))throw new P("not-found",`${t} is not set for this local project`);Ja(e,n),await Hn(e),h({ref:e.ref,unset:t},()=>d(`${t} unset.`))}me();at();Ge();Wr();$n();te();Mn();re();re();me();Ge();te();async function Za(){let{projects:e,allowance:t}=await xe();h({projects:e,allowance:t},()=>{if(e.length===0){d('No projects yet. `snoutdata projects create --name "my project"`.');return}process.stdout.write(`${L(pm(e))}
452
- `)})}function pm(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?x("read-only"):n.state==="ready"?n.state:x(n.state),n.region,...t?[typeof n.postgresVersion=="number"?String(n.postgresVersion):"-"]:[],Fe(n.lastConnectionAt)])]}async function so(e){let t=await _("cloud-project-create",{name:e.name,region:e.region,teamId:e.teamId}),n=t.project.ref;d(`Created ${n}.`);let r=t.project;if(e.wait){d("Waiting for it to start\u2026");let s="";r=await Ft(n,{timeoutMs:e.timeoutMs,onTick:a=>{a!==s&&(s=a,d(w(` ${a}`)))}})}e.link&&gt(e.link,{ref:n,name:r.name});let o=`postgres://${r.user}:${encodeURIComponent(t.password)}@${r.host}:5432/${r.database}?sslmode=require`;h({project:r,ref:n,host:r.host,database:r.database,user:r.user,...e.showUrl?{password:t.password,uri:o}:{connectionString:"snoutdata db url"}},()=>{process.stdout.write(`${e.showUrl?o:n}
453
- `),d(""),d(`Ready. ${x(n)} in ${r.region}, at ${r.host}.`),d(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 Qa(e,t,n={}){let r=`cloud-project-${e}`,o=await _(r,{ref:t}),s=e==="delete"?"deleted":`${e}d`;if(n.wait===!1){h({...o,settled:!1},()=>d(`${t}: asked to be ${s}. \`snoutdata projects list\` shows when it is.`));return}let a=o.project?.state??"",l=await Bt(t,e,{timeoutMs:n.timeoutMs,onTick:u=>{u!==a&&(a=u,d(w(` ${u}`)))}}),i=l?.state??"deleted";if(i==="error")throw new P("failed",`${t} went to error instead of ${s}${l?.stateDetail?`: ${l.stateDetail}`:""}.`,{ref:t,state:i});h({...o,...l?{project:l}:{},settled:!0},()=>{d(o.changed?`${t}: ${s}.`:`${t} was already ${s}.`)})}async function ei(e){let t=await _("cloud-project-reset-password",{ref:e});h(t,()=>{process.stdout.write(`${t.password}
454
- `),d(`New password for ${t.user}. It applies ${t.appliesIn}.`)})}async function ti(){let{teams:e}=await Un();h({teams:e},()=>{if(e.length===0){d("You are not on any teams.");return}process.stdout.write(`${L([["NAME","ID","SHARE"],...e.map(t=>[t.name,t.id,t.mayShare?"yes":t.why??"no"])])}
455
- `)})}async function ni(e){let{teams:t}=await Un(),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}re();te();async function ri(e){let t=await _("cloud-token-create",{name:e.name,expiresInDays:e.expiresInDays,...e.project?{project:e.project}:{}});h(t,()=>{process.stdout.write(`${t.token}
456
- `),d(""),d(`${x(t.name)} \u2014 ${t.expiresAt?`expires ${t.expiresAt.slice(0,10)}`:"does not expire"}.`),d(t.project?`Reaches project ${t.project} only.`:"Reaches every project on this account."),d("This is the only time it is shown: only its hash is stored."),d(w(" export SNOUTDATA_ACCESS_TOKEN=<that token>"))})}async function oi(){let{tokens:e}=await _("cloud-token-list");h({tokens:e},()=>{if(e.length===0){d("No access tokens. `snoutdata tokens create --name ci`.");return}process.stdout.write(`${L([["PREFIX","NAME","PROJECT","STATE","LAST USED","EXPIRES"],...e.map(t=>[t.current?x(t.prefix):t.prefix,t.name,t.project??"all",t.revokedAt?"revoked":t.live?"live":"expired",Fe(t.lastUsedAt),t.expiresAt?t.expiresAt.slice(0,10):"never"])])}
457
- `)})}async function si(e){let t=e.startsWith("sdt_")?{prefix:e}:{id:e},n=await _("cloud-token-revoke",t);h(n,()=>{d(n.changed?`Revoked ${n.token.prefix} (${n.token.name}).`:`${n.token.prefix} was already revoked.`)})}re();be();te();async function ai(e){let t=await ke(e);h({ref:t.ref,appKey:t.appKey,serverKey:t.serverKey,issuedAt:t.keysIssuedAt,expiresAt:t.keysExpireAt},()=>{if(!t.appKey||!t.serverKey){d(`${e} has no API keys yet. Ask again in a moment.`);return}process.stdout.write(`${ci(t.appKey,t.serverKey)}
458
- `),gm(t.keysIssuedAt)})}async function ii(e,t){if(!t.force)throw d(`Rotating the keys for ${e} stops every app key and server key already pasted anywhere.`),d("Anything holding one (a deployed app, a CI secret, a teammate) breaks until it is updated."),new m("keys rotate needs --force, because this cannot be undone");let n=Ln(await _("cloud-project-rotate-jwt",{ref:e}));h(n,()=>{process.stdout.write(`${ci(n.appKey,n.serverKey)}
459
- `),d(""),d(n.breaks),d(w(" snoutdata keys --json to read them again later"))})}function ci(e,t){return L([["KEY","VALUE"],["app key",e],["server key",t]])}function gm(e){d(""),d(`The ${x("app key")} is the public one: it goes in a browser, and row-level security decides what it reads.`),d(`The ${x("server key")} bypasses row-level security. Server side only, never in a client bundle.`),e&&d(w(` issued ${e.slice(0,10)}`))}re();be();te();import{readdir as ym,readFile as wm,stat as bm}from"node:fs/promises";import{join as io,relative as _m,sep as Sm}from"node:path";var li=["functions"];async function ao(e){try{return(await bm(e)).isDirectory()}catch{return!1}}async function km(e,t){if(t){if(!await ao(t))throw new m(`${t} is not a directory`);return t}for(let n of li){let r=io(n,e);if(await ao(r))return r}throw new m(`no folder found for ${e} at ${li[0]}/${e}; use --dir to say where it is.`)}async function di(e){let t=[];async function n(r){for(let o of await ym(r,{withFileTypes:!0})){if(o.name.startsWith(".")||o.name==="node_modules")continue;let s=io(r,o.name);if(o.isDirectory()){await n(s);continue}if(!o.isFile())continue;let a=await wm(s),l=a.toString("utf8");if(Buffer.compare(Buffer.from(l,"utf8"),a)!==0)throw new m(`${s} is not text, and a function bundle is source code. Put binary assets in Storage.`);t.push({path:_m(e,s).split(Sm).join("/"),text:l})}}return await n(e),t}async function vm(e,t,n){let r=await di(t);if(r.length===0)throw new m(`${t} has no files in it`);let o=n??(r.some(l=>l.path==="index.ts")?"index.ts":"");if(!o)throw new m(`${t} has no index.ts, so there is nothing to start. Name the file with --entrypoint.`);let s=io(t,"..","_shared");if(!await ao(s))return{entrypoint:o,files:r};let a=(await di(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 co(e,t,n){ct(t);let r=await km(t,n.dir),{entrypoint:o,files:s}=await vm(t,r,n.entrypoint),a=La({entrypoint:o,files:s});return{answer:await _("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 pi(e,t,n){let{answer:r,directory:o,files:s,bytes:a}=await co(e,t,n),l=r.functions.find(i=>i.name===t);h(r,()=>{let i=Math.max(1,Math.round(a/1024));d(`${x(t)} deployed from ${o} (${s} file${s===1?"":"s"}, ${i} KB)`),l&&d(` ${l.url}`),n.verifyJwt||(d(""),d(x(" Anybody who knows this URL can run it. No API key is required.")),d(w(" That is what a webhook receiver needs. Check the sender signature inside the function."))),r.limit.maxFunctions!==null&&d(w(` ${r.limit.deployed} of ${r.limit.maxFunctions} functions on this plan`))})}function lo(e){return _("cloud-project-functions",{ref:e})}function uo(e,t){return ct(t),_("cloud-project-functions",{ref:e,action:"delete",name:t})}function po(e,t,n){if(ct(t),!n.reset&&n.memoryMb===void 0&&n.concurrency===void 0)throw new m("functions size needs --memory MB, --concurrency N, or --reset");return _("cloud-project-functions",{ref:e,action:"size",name:t,...n.reset?{reset:!0}:{memoryMb:n.memoryMb??null,concurrency:n.concurrency??null}})}function $m(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 mi(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 fi(e,t,n){let r=await po(e,t,n),o=r.functions.find(s=>s.name===t);h(r,()=>{let s=o?$m(o,r.limit):null;d(`${x(t)} ${n.reset?"is back to the plan default":"is resized"}${s?`: ${s}`:""}`),d(w(" The next request runs at it; workers already running finish what they hold."));let a=mi(r.limit);a&&d(w(` ${a}`))})}async function gi(e){let t=await lo(e);h(t,()=>{if(t.functions.length===0){d(`${e} has no functions.`),d(w(" snoutdata functions deploy <name> from functions/<name>"));return}process.stdout.write(`${L([["NAME","KEY","SIZE","MEMORY","WORKERS","URL"],...t.functions.map(r=>[r.name,r.verifyJwt?"required":x("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])])}
460
- `),t.limit.maxFunctions!==null&&d(w(`${t.limit.deployed} of ${t.limit.maxFunctions} on this plan`));let n=mi(t.limit);n&&d(w(`${n}. Change one with: snoutdata functions size <name> --memory MB --concurrency N`))})}function ui(e){let t=e.dropped_before>0?w(`(${e.dropped_before} earlier line(s) were printed too fast to keep) `):"",n=e.cut_bytes?w(` (cut from ${e.cut_bytes} bytes)`):"",r=e.level==="error"?x("error "):"";return`${w(e.at)} ${e.name} ${r}${t}${e.message}${n}`}async function hi(e,t,n){let r=a=>_("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(h({ref:e,lines:o},()=>{if(o.length===0&&!n.follow){d(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),d(w(" Lines show up about a minute after a function prints them."));return}for(let a of o)process.stdout.write(`${ui(a)}
461
- `)}),!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(`${ui(l)}
462
- `),s=l.at}}async function yi(e,t){let n=await uo(e,t);h(n,()=>{d(n.live?`${t} is gone.`:`${t} is gone. It stops answering within a few seconds.`)})}re();import{spawn as Jm}from"node:child_process";import{createHash as Vm}from"node:crypto";import{createReadStream as Ei}from"node:fs";import{mkdtemp as Ym,rm as Xm,stat as Wn}from"node:fs/promises";import{request as Zm}from"node:http";import{request as Qm}from"node:https";import{tmpdir as ef}from"node:os";import{basename as tf,dirname as nf,join as yo}from"node:path";var Pm="x-snoutdata-upload-bytes",Em="x-snoutdata-upload-sha256",Am="/done",Rm=/^[0-9a-f]{64}$/,Tm=/^sha256:[0-9a-f]{64}$/;function Om(e){return Rm.test(e)}var ve=class extends Error{constructor(n,r){super(`the upload failed (${n})`);this.status=n;this.body=r}};function mo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function wi(e){let t=String(mo(e).digest??"");if(!Tm.test(t))throw new ve(502,JSON.stringify({error:"The upload finished without saying what it stored, so there is nothing to deploy. Build again."}));return t}var Nm=15*6e4,Im=2e3;async function bi(e){let{ticketUrl:t,file:n,transport:r}=e;if(!Om(e.sha256))throw new Error("an upload is declared with its SHA-256, in hex");let o=await r.call("POST",t,{[Pm]:String(e.bytes),[Em]:e.sha256});if(o.status===405){e.step?.("uploading");let c=await r.put(t,n,{});if(c.status!==200)throw new ve(c.status,c.body);return wi(c.body)}if(o.status!==200)throw new ve(o.status,o.body);let s=mo(o.body);if(typeof s.url!="string"||!s.url.startsWith("https://")||!s.headers||typeof s.headers!="object")throw new ve(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 c=/<Code>([^<]+)<\/Code>/.exec(a.body)?.[1],p=c==="BadDigest"||c==="XAmzContentSHA256Mismatch"?"The image changed or was damaged while it was uploading. Build again.":c==="AccessDenied"||c==="SignatureDoesNotMatch"||c==="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 ve(a.status===403?401:502,JSON.stringify({error:p}))}e.step?.("storing");let l=r.now()+(e.waitMs??Nm),i=e.pollMs??Im,u=!1;for(;!u;){let c=await r.call("POST",`${t}${Am}`,{});if(c.status===200||c.status===202)u=!0;else if(c.status===429&&r.now()<l)await r.sleep(i*5);else throw new ve(c.status,c.body)}for(;;){let c=await r.call("GET",t,{});if(c.status!==200)throw new ve(c.status,c.body);let p=mo(c.body);if(p.state==="stored")return wi(c.body);if(p.state==="failed")throw new ve(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 ve(504,JSON.stringify({error:"The project's host took too long to store the image. Build again in a moment."}));await r.sleep(i)}}te();var Cm=/^[a-z0-9][a-z0-9_-]{0,31}$/;function jm(e){return Cm.test(e)}function Si(e){return jm(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 Dm=/^sha256:[0-9a-f]{64}$/,Mm=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,Lm=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/,Um=/^(?:[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 Bm(e){return Dm.test(e)}function ki(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),!Bm(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),!Mm.test(s)))return{error:`${JSON.stringify(s)} is not an image tag.`};let i=n.split("/"),u="docker.io",c=i[0]??"";return i.length>1&&(c.includes(".")||c.includes(":")||c==="localhost")&&(u=c.toLowerCase(),i.shift()),Um.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(p=>!Lm.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:u,repository:i.join("/"),tag:s,digest:r})):{error:`${JSON.stringify(c)} is not a registry address.`}}var fS=["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 fo(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 Fm(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 c=fo(t.slice(r+1));if(!c)return null;t=`${t.slice(0,r+1)}${(c[0]<<8|c[1]).toString(16)}:${(c[2]<<8|c[3]).toString(16)}`}let o=t.split("::");if(o.length>2)return null;let s=c=>c===""?[]:c.split(":"),a=s(o[0]??""),l=o.length===2?s(o[1]??""):[];if([...a,...l].some(c=>!/^[0-9a-fA-F]{1,4}$/.test(c)))return null;let i=a.length+l.length;if(o.length===1?i!==8:i>7)return null;let u=new Array(8-i).fill(0);return[...a.map(c=>parseInt(c,16)),...u,...l.map(c=>parseInt(c,16))]}function Hm(e,t,n){let r=fo(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 Km=[["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 gS=1024**3;var _i=16,qm=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/,Gm=/^(\d{1,3}(?:\.\d{1,3}){3})(?:\/(\d{1,2}))?$/;function Wm(e,t){let n=e??[],r={error:`${t}: ports are up to ${_i} whole numbers, 1 to 65535.`};if(!Array.isArray(n)||n.length>_i)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 zm(e){let t=e.trim().toLowerCase(),n=Gm.exec(t);if(n){let r=fo(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,i=[24,16,8,0].map(u=>l>>>u&255);return Km.some(([u,c])=>o>=c&&Hm(i,u,c))?{error:`${e} is not on the public internet, and a container reaches nothing else.`}:o===32?i.join("."):`${i.join(".")}/${o}`}return Fm(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.`}:qm.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 vi(e){let t=e.trim(),n=t.lastIndexOf(":"),r=n!==-1&&t.indexOf(":")===n,o=r?t.slice(0,n):t,s=Wm(r?t.slice(n+1).split(",").map(l=>l.trim()):[],o.trim());if("error"in s)return s;let a=zm(o);return typeof a!="string"?a:{destination:a,ports:s}}function go(e){return e.ports.length===0?e.destination:`${e.destination}:${e.ports.join(",")}`}var rf=new Set(["pending","pulling","starting","restarting"]),of=5*6e4;function Vn(e){let t=Si(e);if(t)throw new Error(t)}function wo(e,t,n){Vn(t);let r=ki(n.image);if("error"in r)throw new Error(r.error);return _("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 kt(e){return _("cloud-project-containers",{ref:e})}function bo(e,t){return Vn(t),_("cloud-project-containers",{ref:e,action:"delete",name:t})}function _o(e,t){return Vn(t),_("cloud-project-containers",{ref:e,action:"restart",name:t})}function zn(e,t){return _("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 Ai(e,t){let n=Date.now()+of,r=null;for(;Date.now()<n;)if(await new Promise(o=>setTimeout(o,3e3)),r=(await kt(e)).containers.find(o=>o.name===t)??null,!r||!rf.has(r.status))return r;return r}function So(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 Ri(e,t,n){await Ti(e,t,await wo(e,t,n),n.wait!==!1)}async function Ti(e,t,n,r){let o=n.containers.find(s=>s.name===t)??null;r&&o&&(d(w(`${t}: ${o.image} pinned to ${o.digest.slice(0,19)}\u2026, waiting for the host`)),o=await Ai(e,t)??o),h({...n,containers:o?[o]:n.containers},()=>{if(!o){d(`${x(t)} deployed.`);return}d(`${x(t)} ${So(o)}`),d(` ${o.url}`),o.statusDetail&&d(` ${o.statusDetail}`),d(""),d(w(" Listens on PORT ("+o.port+"). DATABASE_URL and your secrets are in its environment.")),d(x(" Anything written inside the container is lost when it restarts or is redeployed.")),d(w(" Keep what matters in your database.")),n.allowance&&d(w(` ${n.allowance.deployed} of ${n.allowance.maxContainers} containers on this plan, ${n.allowance.memoryMb} MB and ${n.allowance.cpuPercent}% of a core each`))})}var sf=2*1024**3,af=3*6e4;async function cf(e){let t;try{t=await Wn(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 Wn(yo(e,"Dockerfile"))}catch{throw new Error(`${e} has no Dockerfile in it.`)}return{context:e,file:null}}return{context:nf(e),file:e}}function lf(e){return["buildx","build","--platform","linux/arm64","--provenance=false","--output",`type=oci,dest=${e.archive}`,...e.file?["--file",e.file]:[],e.context]}function ko(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 df(e,t){let n="";try{let r=JSON.parse(t);n=String(r.error??r.message??"")}catch{}return n?ko(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 uf(e){return new Promise((t,n)=>{let r=Jm("docker",e,{stdio:["ignore",2,2]});r.on("error",o=>n(o)),r.on("close",o=>t(o??1))})}function Oi(e,t,n,r){return new Promise((o,s)=>{let a=new URL(e),l=(a.protocol==="http:"?Zm:Qm)(a,{method:t,headers:n});l.on("response",i=>{let u=[];i.on("data",c=>u.push(c)),i.on("end",()=>o({status:i.statusCode??0,body:Buffer.concat(u).toString("utf8")})),i.on("error",s)}),l.on("error",i=>{s(i)}),r(l)})}async function pf(e,t,n){let r=Object.keys(n).length>0?n:{"content-type":"application/octet-stream","content-length":String((await Wn(t)).size)};return Oi(e,"PUT",r,o=>{let s=Ei(t);s.on("error",a=>o.destroy(a)),s.pipe(o)})}function mf(e){return new Promise((t,n)=>{let r=Vm("sha256");Ei(e).on("error",n).on("data",o=>r.update(o)).on("end",()=>t(r.digest("hex")))})}var ff={call:(e,t,n)=>Oi(t,e,{"content-length":"0",...n},r=>r.end()),put:pf,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now()},Ni={docker:uf,scratch:()=>Ym(yo(ef(),"snoutdata-build-")),remove:e=>Xm(e,{recursive:!0,force:!0}),size:async e=>(await Wn(e)).size,hash:mf,transport:ff,ask:e=>_("cloud-project-containers",e),say:e=>d(w(e)),now:()=>Date.now()};function $i(e){return`${Math.max(1,Math.round(e/1024**2))} MB`}async function xi(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 gf(e,t,n,r=Ni){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 xi(r,e,t),s=await r.scratch();try{let a=yo(s,"image.tar");if(r.say(`${t}: building ${n.file?tf(n.file):n.context} for linux/arm64`),await r.docker(lf({...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>sf)throw new Error(`the image is ${$i(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()>af||(o=await xi(r,e,t));let i=await r.hash(a);r.say(`${t}: uploading the image (${$i(l)})`);try{return await bi({ticketUrl:o.url,file:a,bytes:l,sha256:i,transport:r.transport,step:u=>{u==="storing"&&r.say(`${t}: storing the image in the project`)}})}catch(u){throw u instanceof ve?new Error(df(u.status,u.body)):u}}finally{await r.remove(s).catch(()=>{})}}catch(o){throw new Error(ko(o instanceof Error?o.message:String(o)))}}async function Ii(e,t,n,r=Ni){Vn(t);let o=await cf(n.path),s=await gf(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(ko(l instanceof Error?l.message:String(l)))}await Ti(e,t,a,n.wait!==!1)}async function Ci(e){let t=await kt(e);h(t,()=>{if(t.containers.length===0){d(`No containers on ${e}.`),t.allowance&&t.allowance.maxContainers===0?d(w(" Containers run on the Plus and Pro plans.")):d(w(" snoutdata containers deploy <name> <image>"));return}d(L([["name","status","image","url"],...t.containers.map(r=>[r.name,So(r),r.image,r.url])]));for(let r of t.containers)r.statusDetail&&r.status!=="running"&&d(w(` ${r.name}: ${r.statusDetail}`));let n=t.allowance?.egress;n&&n.allowanceBytes>0&&d(w(` Sent this month: ${ho(n.usedBytes)} of ${ho(n.allowanceBytes)}. At ${ho(n.allowanceBytes)} the project's containers stop until the 1st.`))})}async function Jn(e,t){if(t===null)return _("cloud-project-containers",{ref:e,action:"egress",clear:!0});let n=[];for(let r of t){let o=vi(r);if("error"in o)throw new Error(o.error);n.push(o)}return _("cloud-project-containers",{ref:e,action:"egress",allow:n})}function hf(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).`,w(" 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(` ${go(n)}${n.ports.length===0?w(" (any port)"):""}`);return t.push(w(` and always: ${e.allowlist.alwaysAllowed.map(go).join(", ")}, and each other`)),t.push(w(" snoutdata containers egress clear to allow the public internet again")),t}async function Yn(e,t){let n=t.clear?await Jn(e,null):t.set?await Jn(e,t.set):await kt(e);h({ref:n.ref,allowlist:n.allowlist??null},()=>{for(let r of hf(n))d(r);(t.set||t.clear)&&d(w(" Running containers follow it within a minute; nothing restarts."))})}function ho(e){return`${Math.round(e/1024**3*10)/10} GB`}async function ji(e,t){await _o(e,t);let n=await Ai(e,t);h({ref:e,containers:n?[n]:[]},()=>{d(n?`${x(t)} ${So(n)}`:`${t} is restarting.`),n?.statusDetail&&d(` ${n.statusDetail}`)})}async function Di(e,t){let n=await bo(e,t);h(n,()=>d(`${t} is gone. It stops within a few seconds.`))}function Pi(e){return`${w(e.at.replace("T"," ").slice(0,19))} ${e.name} ${e.stream==="stderr"?x(e.message):e.message}`}async function Mi(e,t,n){let r=((await zn(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit})).lines??[]).slice().reverse();if(h({ref:e,lines:r},()=>{if(r.length===0&&!n.follow){d(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),d(w(" Lines show up about a minute after a container prints them."));return}for(let s of r)process.stdout.write(`${Pi(s)}
463
- `)}),!n.follow)return;let o=r.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(a=>setTimeout(a,5e3));let s=((await zn(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit,since:o})).lines??[]).slice().reverse();for(let a of s)process.stdout.write(`${Pi(a)}
464
- `),o=a.at}}re();be();te();function Ui(e){let t=e.indexOf("=");return t<=0?null:{name:e.slice(0,t),value:e.slice(t+1)}}async function vt(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8").replace(/\n$/,"")}async function Bi(e,t){if(e.length===0)throw new m("secrets set needs NAME=value, or NAME with --stdin");if(t.stdin){if(e.length!==1)throw new m("--stdin sets one secret, so it takes one NAME");return[{name:e[0],value:await vt()}]}return e.map(n=>{let r=Ui(n);if(!r)throw new m(`${n} is not NAME=value. Use --stdin to set a value from a pipe.`);return r})}async function Fi(e,t,n){if(t.length===0)throw new m("secrets set needs NAME=value, or NAME with --stdin");let r=[];if(n.stdin){if(t.length!==1)throw new m("--stdin sets one secret, so it takes one NAME");r.push({name:t[0],value:await vt()})}else for(let s of t){let a=Ui(s);if(!a)throw new m(`${s} is not NAME=value. Use --stdin to set a value from a pipe.`);r.push(a)}for(let s of r){let a=Ht(s.name);if(a)throw new m(a)}let o=null;for(let s of r)o=await _("cloud-project-secrets",{ref:e,action:"set",name:s.name,value:s.value});h(o,()=>{for(let s of r)d(`${x(s.name)} set`);d(w(" Functions pick it up within a few seconds. Redeploying is not needed.")),n.stdin||d(w(" A value typed here is in your shell history. In CI, use: \u2026 | snoutdata secrets set NAME --stdin"))})}async function Hi(e,t){let n=Ht(t);if(n)throw new m(n);let r=await _("cloud-project-secrets",{ref:e,action:"unset",name:t});h(r,()=>{d(`${t} is gone.`)})}async function Ki(e){let t=await _("cloud-project-secrets",{ref:e});h(t,()=>{if(t.secrets.length===0){d(`${e} has no function secrets.`),d(w(" snoutdata secrets set STRIPE_KEY=sk_..."));return}process.stdout.write(`${L([["NAME","SIZE","SET"],...t.secrets.map(n=>[n.name,n.bytes===null?"-":`${n.bytes} B`,Fe(n.updatedAt)])])}
465
- `),d(w("Values are not readable, here or anywhere. Set one again to change it."))})}import{spawn as Zt}from"node:child_process";import{appendFileSync as pc,existsSync as rr,readFileSync as mc,statSync as ng,unlinkSync as rg,writeFileSync as xt}from"node:fs";import{dirname as og,join as or}from"node:path";import{tmpdir as sg}from"node:os";import{open as fc}from"node:fs/promises";function qi(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 Gi(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 Wi(e){let t=e.split(`
466
- `).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 vo={auth:"snout_auth_admin",storage:"snout_storage_admin",push:"snout_push_admin"},wf=/^(snoutpod_admin|snout_[a-z]+_admin)$/,Xn=new Set(["snout_identity","snout_files","push","snout_live","snout_realtime","_realtime","graphql","snout_graph","snout_ext","net","cron","pgbouncer","vault","pgsodium","auth","storage","realtime","graphql_public","extensions"]),bf=/^(pgrst_ddl_watch|pgrst_drop_watch|snoutpod_[a-z_]+|snoutdata_realtime|snout_realtime_messages)(\(|$)/,_f={snout_identity:"auth",snout_files:"storage",auth:"auth",storage:"storage",push:"push"},Sf=new Set(["push.settings"]),kf=["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 vf(e){let t=/^\d+; \d+ \d+ (.+)$/.exec(e.trim());if(!t)return null;let n=t[1],r=kf.find(i=>n.startsWith(`${i} `))??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 $f(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 zi(e,t){let n=new Map,r=[],o=new Set,s=0;for(let i of e.split(`
467
- `)){let u=vf(i);if(!u)continue;let{type:c,schema:p,name:f,owner:k}=u;if(c==="TABLE DATA"||c==="SEQUENCE SET"){let V=/^(schema_migrations|migrations)$/.test(f)&&Xn.has(p);if(/realtime/.test(p)||p==="snout_live"||V||p==="public"&&f==="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"&&f==="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 j=_f[p];if(j){j==="storage"&&(f==="objects"||f==="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(j,[...n.get(j)??[],u]);continue}if(Xn.has(p)){s++;continue}r.push(u.line);continue}if(c==="COMMENT"&&p==="-"&&/^EXTENSION( |$)/.test(f)||(c==="SCHEMA"?Xn.has(f):Xn.has(p))||bf.test(f)||wf.test(k)&&c!=="SCHEMA"){s++;continue}r.push(u.line)}let a=$f(t),l=["auth","storage","push"];return{platformData:l.filter(i=>n.has(i)).map(i=>{let u=n.get(i),c=u.filter(f=>f.type==="TABLE DATA"&&Sf.has(`${f.schema}.${f.name}`)).map(f=>`${f.schema}.${f.name}`),p=u.filter(f=>f.type==="TABLE DATA").map(f=>`${f.schema}.${f.name}`);return{product:i,clear:c,tables:p,lines:xf(u,a)}}),rest:r,products:l.filter(i=>n.has(i)),skipped:s,notes:[...o]}}function xf(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 i=a.find(u=>[...t.get(n(u))??[]].every(c=>!r.has(c)||o.has(c)||c===n(u)))??a[0];o.add(n(i)),s.push(i.line),a=a.filter(u=>u!==i)}return s}re();be();me();te();re();me();var xo=["max_write_pause_ms","drain_timeout_ms","ack_timeout_ms","copy_mb_per_s"],Vi=["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"];function qt(e){return e==="done"||e==="failed"||e==="cancelled"}function Gt(e,t=process.env){if(e.project!==void 0){if(e.admin!==void 0)throw new P("usage","cluster takes --project (a SnoutData Cloud project) or --admin (a standalone router), not both");return new De(Tf(e.project))}let n=e.admin??Ji(t.LEPIS_ADMIN_URL);if(!n)throw new P("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??Ji(t.LEPIS_ADMIN_TOKEN);if(!r)throw new P("not-signed-in","no admin token: set LEPIS_ADMIN_TOKEN to the router's token, or pass --token");return new $o(Pf(n),r)}function Ji(e){return e===void 0||e===""?void 0:e}function Pf(e){let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`,n;try{n=new URL(t)}catch{throw new P("usage",`--admin: not a URL: ${e}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new P("usage",`--admin: http or https, not ${n.protocol.replace(":","")}`);if(n.username||n.password)throw new P("usage","--admin: the URL carries no credentials; the token comes from LEPIS_ADMIN_TOKEN or --token");if(n.protocol==="http:"&&!Ef(n.hostname))throw new P("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 Ef(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)}var Af=6e4,$o=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))}`)}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(Af)})}catch(i){let u=bn(i),c=i instanceof Error?i.cause instanceof Error?i.cause.message:i.message:String(i);throw new P(u==="failed"?"network":u,`could not reach the Lepis admin API at ${this.target}: ${c}`)}let a=await s.text(),l;try{l=a===""?{}:JSON.parse(a)}catch{throw new P("server",`the admin API at ${this.target} answered ${s.status} with something that is not JSON`,{status:s.status})}if(!s.ok)throw Yi(s.status,l);return l}},Rf={bad_request:"usage",unauthorized:"not-signed-in",not_found:"not-found",conflict:"conflict",failed:"failed",timeout:"timeout"};function Yi(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?Rf[n.code]:void 0)??(e===401?"not-signed-in":e===400?"usage":Ue(e));return s==="not-signed-in"?new P(s,"the router refused the admin token (LEPIS_ADMIN_TOKEN or --token)",o):new P(s,r,o)}function Tf(e){let t=e.trim();if(!/^[a-z][0-9a-z]{12}$/.test(t))throw new P("usage",`--project: not a project ref: ${e} (13 characters, as projects list prints it)`);return t}var Of={"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","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"},Nf="cloud-project-shards",De=class{target;ref;#t;constructor(t,n=_){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:Xe(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))}})}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=Of[t.op];if(!n)throw new P("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 P("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 P("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(Nf,{ref:this.ref,...t})}catch(n){throw If(n)}}};function Xe(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 If(e){if(!(e instanceof ge))return e;let t=e.body??{};if(typeof t.apiCode=="string"||typeof t.kind=="string")return Yi(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":Ue(e.status);return new P(n,e.message,{status:e.status,...typeof t.code=="string"?{kind:t.code}:{}})}function zt(e){if(Array.isArray(e))return`[${e.map(zt).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)}:${zt(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}var Ao=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}
468
- ${zt(t)}`,this.#e())}shown(t,n=""){let r=this.#t.get(`${n}
469
- ${zt(t)}`);return r!==void 0&&this.#e()-r<=this.#n}forget(t,n=""){this.#t.delete(`${n}
470
- ${zt(t)}`)}},Cf=new Ao,Ro=["node.add","node.drain","node.remove","keyspace.create","table.distribute","table.reference","table.global","range.split","range.merge","range.move","tenant.pin","rebalance","scale","verify","cleanup","node.attach","keyspace.drop","dissolve"],jf="2024-11-05";function K(e,t=[]){return{type:"object",properties:e,additionalProperties:!1,...t.length?{required:t}:{}}}var I={type:"string"},Xi={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:[...Ro]}},required:["op"],additionalProperties:!0},Zn={type:"integer",description:"The job id cluster_run returned, or one from cluster_jobs."},Ze={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)."},Vt=[{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:K({})},{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:K({})},{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:K({name:I,region:I,teamId:I},["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:K({ref:I},["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:K({ref:I},["ref"])},{name:"resume_project",description:"Start a paused project without waiting for a connection to wake it, and wait until it is ready.",inputSchema:K({ref:I},["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:K({ref:I,dir:I,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:K({ref:I,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:K({ref:I},["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:K({ref:I},["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:K({ref:I},["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:K({})},{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:K({})},{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:K({name:I,expires:I,project:I},["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:K({id:I},["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:K({ref:I,name:I,dir:I,entrypoint:I,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:K({ref:I},["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:K({ref:I,name:I,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:K({ref:I,name:I},["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:K({ref:I},["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:K({ref:I,name:I,image:I,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:K({ref:I,name:I},["ref","name"])},{name:"delete_container",description:"Stop one container and remove it from the project. It does not touch the database.",inputSchema:K({ref:I,name:I},["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:K({ref:I,name:I,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:K({ref:I},["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:K({ref:I,allow:{type:"array",items:I},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:K({ref:I},["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:K({ref:I,name:I,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:K({ref:I},["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:K({ref:I},["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:K({ref:I,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:K({ref:I},["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:K({ref:I,hostname:I},["ref","hostname"])},{name:"verify_domain",description:"Check a custom domain's DNS records and verify it once they are published.",inputSchema:K({ref:I,hostname:I},["ref","hostname"])},{name:"remove_domain",description:"Stop serving a project at a custom domain.",inputSchema:K({ref:I,hostname:I},["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:K({ref:I},["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:K({ref:I,at:I,name:I},["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:K({project:Ze})},{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:K({project:Ze,sampleMs:{type:"integer"}})},{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:K({project:Ze,operation:Xi},["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:K({project:Ze,operation:Xi,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:K({project:Ze,id:Zn})},{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:K({project:Ze,id:Zn,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:K({project:Ze,id:Zn},["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:K({project:Ze,id:Zn},["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:K({ref:I},["ref"])}],Df=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_plan","cluster_jobs","cluster_watch_job"]),Mf=new Set(["delete_project","delete_function","reset_password","revoke_token","remove_domain","cluster_run"]),Zi=["get_connection_url","push_migrations","get_project","list_functions","deploy_function","delete_function","list_function_secrets"];function To(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.projects))return{...t,projects:t.projects.map(To)};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 Oo(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 Lf(e){return{...e,annotations:Df.has(e.name)?{readOnlyHint:!0}:{readOnlyHint:!1,destructiveHint:Mf.has(e.name)}}}function Uf(e){let t=new Set;return e.filter(n=>!t.has(n.name)&&t.add(n.name))}function Jt(e,t){return{jsonrpc:"2.0",id:e,result:t}}function Qn(e,t,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:n}}}function $(e,t,n=!1){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return Jt(e,{content:[{type:"text",text:r}],...n?{isError:!0}:{}})}function Bf(e,t=new Date){let n=Date.parse(e);return!Number.isFinite(n)||n<=t.getTime()?null:Math.ceil((n-t.getTime())/864e5)}function Wt(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 Po(e){return{id:e.id,op:e.op,state:e.state,finished:qt(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 Qi(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"||!Ro.includes(r.op))return`${t}: operation.op must be one of ${Ro.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 Eo(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 Ff(e){let t=e instanceof Error?e.message:String(e),n=e?.details?.kind;return typeof n=="string"?{error:t,kind:n}:t}var Hf="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 Kf(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 $(e,Hf,!0);s=r.shards(a)}catch(u){return $(e,u instanceof Error?u.message:String(u),!0)}let l=o.shardsPlans??Cf,i=a??"";try{switch(t){case"cluster_status":return $(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,c=await s.advice(u);for(let p of c.advice)p.plan&&l.remember(p.request,i);return $(e,{summary:c.summary,advice:c.advice.map(p=>({op:p.op,reason:p.reason,metric:p.metric,operation:p.request,...p.plan?{plan:Wt(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:c.facts,assumptions:c.assumptions,...c.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_plan":{let u=Qi(n,t);if(typeof u=="string")return $(e,u,!0);let c=await s.plan(u);return l.remember(u,i),$(e,{plan:Wt(c),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=Qi(n,t);if(typeof u=="string")return $(e,u,!0);if(n.confirm!==!0||!l.shown(u,i)){let p=await s.plan(u);l.remember(u,i);let f=n.confirm===!0;return $(e,{ran:!1,plan:Wt(p),next:f?"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."},f)}let c=await s.submit(u);return l.forget(u,i),c.job===void 0?$(e,{ran:!0,done:c.done,answer:c.answer}):$(e,{ran:!0,job:c.job,plan:Wt(c.plan),next:`Follow it with cluster_watch_job {"id": ${c.job}}.`})}case"cluster_jobs":{if(n.id===void 0)return $(e,{jobs:await s.jobs()});let u=Eo(n);if(u===null)return $(e,"cluster_jobs: id is a job number. Call it without id to list them.",!0);let c=await s.job(u);return $(e,{...Po(c),plan:c.plan&&Array.isArray(c.plan.steps)?Wt(c.plan):null})}case"cluster_watch_job":{let u=Eo(n);if(u===null)return $(e,"cluster_watch_job needs id, the job number cluster_run returned.",!0);let c=typeof n.timeoutSeconds=="number"&&n.timeoutSeconds>0?Math.min(n.timeoutSeconds,120):30,p=Date.now()+c*1e3;for(;;){let f=await s.job(u);if(qt(f.state))return $(e,Po(f),f.state!=="done");if(Date.now()>=p)return $(e,{...Po(f),note:`Still ${f.state} after ${c}s. It carries on; call cluster_watch_job again to keep waiting.`});await new Promise(k=>setTimeout(k,o.shardsPollMs??1e3))}}case"cluster_cancel_job":case"cluster_resume_job":{let u=Eo(n);if(u===null)return $(e,`${t} needs id, a job number.`,!0);let c=t==="cluster_cancel_job"?await s.cancel(u):await s.resume(u);return $(e,{...c,next:`Follow it with cluster_watch_job {"id": ${u}}.`})}default:return Qn(e,-32602,`unknown tool: ${t}`)}}catch(u){return $(e,Ff(u),!0)}}function J(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}async function ec(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 Jt(r,{protocolVersion:jf,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"snoutdata",version:n.version}});case"ping":return Jt(r,{});case"tools/list":return Jt(r,{tools:Uf([...Vt.map(Lf),...n.borrowed??[]])});case"tools/call":return qf(r,s,t,n);default:return Qn(r,-32601,`unknown method: ${o}`)}}async function qf(e,t,n,r){let o=typeof t.name=="string"?t.name:"",s=t.arguments??{};if(!(Vt.some(c=>c.name===o)||(r.borrowed?.some(c=>c.name===o)??!1)))return Qn(e,-32602,`unknown tool: ${o}`);let l=["get_connection_url","pause_project","resume_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_")&&Vt.some(c=>c.name===o))return Kf(e,o,s,n,r);let i=J(s,"ref");if(l.includes(o)&&!i)return $(e,`${o} needs a project ref. Call list_projects to see them.`,!0);let u=i&&n.localProject?n.localProject(i):null;if(u&&!Zi.includes(o))return $(e,`${i} is the self-hosted project in ${u.folder}, and ${o} is about SnoutData Cloud. On a local project these tools work: ${Zi.join(", ")}.`,!0);try{switch(o){case"whoami":return $(e,await n.whoami());case"list_projects":return $(e,To(await n.listProjects()));case"create_project":{let c=J(s,"name");return c?$(e,await n.createProject({name:c,region:J(s,"region")??void 0,teamId:J(s,"teamId")??void 0})):$(e,"create_project needs a name.",!0)}case"get_connection_url":{let c=await n.connection(i);return $(e,{url:c.uri,state:c.state,wakesInstantly:c.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 $(e,await n.setProjectState("pause",i));case"resume_project":return $(e,await n.setProjectState("resume",i));case"usage":{let c=typeof s.days=="number"?s.days:void 0;return $(e,await n.usage(i,c))}case"export_status":return $(e,await n.exportStatus(i));case"start_export":return $(e,await n.requestExport(i));case"reset_password":{let c=await n.resetPassword(i),p=await n.connection(i);return $(e,{url:p.uri,appliesIn:c.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 $(e,await n.listTeams());case"get_project":return $(e,To(await n.getProject(i)));case"list_products":return $(e,await n.getProducts(i));case"set_product":{let c=J(s,"product");return c!=="auth"&&c!=="storage"&&c!=="data-api"?$(e,"set_product needs product: auth, storage or data-api.",!0):typeof s.enabled!="boolean"?$(e,"set_product needs enabled: true or false.",!0):$(e,await n.setProduct(i,c,s.enabled))}case"list_domains":return $(e,await n.listDomains(i));case"add_domain":case"verify_domain":case"remove_domain":{let c=J(s,"hostname");return c?$(e,await n.domainAction(i,o.split("_")[0],c)):$(e,`${o} needs a hostname, e.g. api.example.com.`,!0)}case"restore_window":{let c=await n.restoreWindow(i),p=c&&c.restore?Oo(i,c.restore):null;return $(e,p?{...c,reason:p}:c)}case"restore_to_point":{let c=J(s,"at");return c?$(e,await n.restoreTo(i,c,J(s,"name")??void 0)):$(e,"restore_to_point needs at: an ISO 8601 moment inside restore_window.",!0)}case"deploy_function":{let c=J(s,"ref"),p=J(s,"name");return!c||!p?$(e,"deploy_function needs a project ref and a function name.",!0):$(e,await n.deployFunction(c,p,{dir:J(s,"dir")??void 0,entrypoint:J(s,"entrypoint")??void 0,verifyJwt:s&&typeof s=="object"&&"openToAnyone"in s?s.openToAnyone!==!0:!0}))}case"list_functions":{let c=J(s,"ref");return c?$(e,await n.listFunctions(c)):$(e,"list_functions needs a project ref.",!0)}case"size_function":{let c=J(s,"ref"),p=J(s,"name");if(!c||!p)return $(e,"size_function needs a project ref and a function name.",!0);let f=typeof s.memoryMb=="number"?s.memoryMb:void 0,k=typeof s.concurrency=="number"?s.concurrency:void 0,v=s.reset===!0;return!v&&f===void 0&&k===void 0?$(e,"size_function needs memoryMb, concurrency, or reset: true.",!0):$(e,await n.sizeFunction(c,p,{memoryMb:f,concurrency:k,reset:v}))}case"delete_function":{let c=J(s,"ref"),p=J(s,"name");return!c||!p?$(e,"delete_function needs a project ref and a function name.",!0):$(e,await n.deleteFunction(c,p))}case"list_containers":{let c=J(s,"ref");return c?$(e,await n.listContainers(c)):$(e,"list_containers needs a project ref.",!0)}case"deploy_container":{let c=J(s,"ref"),p=J(s,"name"),f=J(s,"image");if(!c||!p||!f)return $(e,"deploy_container needs a project ref, a container name and an image.",!0);let k=typeof s.port=="number"?s.port:void 0;return $(e,await n.deployContainer(c,p,{image:f,...k===void 0?{}:{port:k}}))}case"restart_container":case"delete_container":{let c=J(s,"ref"),p=J(s,"name");return!c||!p?$(e,`${o} needs a project ref and a container name.`,!0):$(e,o==="restart_container"?await n.restartContainer(c,p):await n.deleteContainer(c,p))}case"container_logs":{let c=J(s,"ref");if(!c)return $(e,"container_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return $(e,await n.containerLogs(c,{name:J(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"container_egress":{let c=J(s,"ref");return c?$(e,await n.containerEgress(c)):$(e,"container_egress needs a project ref.",!0)}case"set_container_egress":{let c=J(s,"ref");if(!c)return $(e,"set_container_egress needs a project ref.",!0);let p=s.clear===!0,f=s.allow;return f!==void 0&&(!Array.isArray(f)||!f.every(k=>typeof k=="string"))?$(e,'set_container_egress takes allow as a list of destinations, such as ["api.example.com:443"].',!0):p===(f!==void 0)?$(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):$(e,await n.setContainerEgress(c,p?null:f))}case"list_function_secrets":{let c=J(s,"ref");return c?$(e,await n.listFunctionSecrets(c)):$(e,"list_function_secrets needs a project ref.",!0)}case"function_logs":{let c=J(s,"ref");if(!c)return $(e,"function_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return $(e,await n.functionLogs(c,{name:J(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"list_tokens":return $(e,await n.listTokens());case"create_token":{let c=J(s,"name");if(!c)return $(e,"create_token needs a name, so somebody can tell later what it was for.",!0);let p=J(s,"expires"),f=p?Bf(p):void 0;return f===null?$(e,`create_token: \`expires\` must be a date in the future, like 2026-12-31. Got "${p}".`,!0):$(e,await n.createToken(c,f,J(s,"project")??void 0))}case"revoke_token":{let c=J(s,"id");return c?$(e,await n.revokeToken(c)):$(e,"revoke_token needs the id of a token. list_tokens has them.",!0)}case"push_migrations":return $(e,await n.pushMigrations(i,{dir:J(s,"dir")??void 0,dryRun:s.dryRun===!0}));case"delete_project":return r.allowDelete?$(e,await n.setProjectState("delete",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(c=>c.name===o)?n.callBorrowed?Jt(e,await n.callBorrowed(o,s)):$(e,`${o} needs SnoutData Studio, which is no longer answering.`,!0):Qn(e,-32602,`unknown tool: ${o}`)}}catch(c){return $(e,c instanceof Error?c.message:String(c),!0)}}function tc(e){let t=e.split(`
471
- `),n=t.pop()??"";return{messages:t.map(r=>r.trim()).filter(r=>r.length>0),rest:n}}var er=["auth","storage","data-api","push"];function lt(e){return{error:e instanceof Error?e.message:String(e)}}async function $t(e){let[t,n,r,o]=await Promise.all([_("cloud-project-auth",{ref:e,action:"status"}).then(s=>({enabled:s.enabled===!0,google:s.google?.enabled===!0,saml:s.saml?.enabled===!0}),lt),_("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}),lt),_("cloud-project-data-api",{ref:e}).then(s=>({enabled:s.dataApi?.enabled===!0,allowedOnPlan:s.dataApi?.allowed===!0}),lt),_("cloud-project-push",{ref:e}).then(s=>({enabled:s.push?.enabled===!0,scheduling:s.push?.scheduling===!0}),lt)]);return{ref:e,auth:t,storage:n,dataApi:r,push:o,realtime:Gf}}var Gf={enabled:!0,broadcast:!0,presence:!0,tableChanges:"Plus and Pro plans"};function rc(e){let t=(e??"").toLowerCase().replace("_","-").replace(/^dataapi$/,"data-api");if(!er.includes(t))throw new m(`say which product: ${er.join(", ")}`);return t}async function No(e,t,n){if(t==="auth"){let r=await _("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 _("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==="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 oc(e){let t=await $t(e);h(t,()=>{let n=(l,i,u="")=>[l,i&&typeof i=="object"&&"error"in i?`could not read: ${i.error}`:i.enabled?x("on"):"off",u],r=t.storage,o=t.dataApi;process.stdout.write(`${L([["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 and Pro")])}
472
- `);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&&d(w(` snoutdata products enable ${a} --ref ${e}`))})}async function sc(e,t,n){let r=await No(e,t,n);h(r,()=>d(r.note))}async function tr(e){let t=await _("cloud-project-domain",{ref:e,action:"list"});return{ref:e,domains:t.domains??[]}}async function Io(e,t,n){if(!n)throw new m(`domains ${t} needs a hostname, e.g. api.example.com`);let r=await _("cloud-project-domain",{ref:e,action:t,hostname:n});return{ref:e,domain:r.domain??null,next:r.next??null}}function nc(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(`${L(n)}
473
- `)}async function ac(e,t,n){if(t===void 0||t==="list"){let o=await tr(e);h(o,()=>{if(o.domains.length===0){d(`No domains on ${e}. \`snoutdata domains add api.example.com\`.`);return}process.stdout.write(`${L([["HOSTNAME","VERIFIED","CERTIFICATE"],...o.domains.map(s=>[s.hostname,s.verified?"yes":x("no"),s.certificate?.state??""])])}
474
- `)});return}if(t!=="add"&&t!=="verify"&&t!=="remove")throw new m(`unknown command: domains ${t}`);let r=await Io(e,t,n??"");t==="verify"&&r.domain&&!r.domain.verified&&(Cn()||nc(r.domain,e),H("not-ready",r.domain.verificationError??`${n} is not verified yet. Publish the records above, then run this again.`,{ref:e,domain:r.domain})),h(r,()=>{if(t==="remove"){d(`${n} removed.`);return}r.domain&&(d(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||nc(r.domain,e)),r.next&&d(r.next)})}async function Co(e){return _("cloud-project-restore",{ref:e},"GET")}async function jo(e,t,n){if(Number.isNaN(Date.parse(t)))throw new m(`--at needs a moment, e.g. 2026-09-20T14:30:00Z (got "${t}")`);return _("cloud-project-restore",{ref:e,at:new Date(t).toISOString(),...n?{name:n}:{}})}async function ic(e){let t=await Co(e);h(t,()=>{let n=t.restore,r=Oo(e,n);if(r){d(r);return}d(`${e} can be restored to any moment from ${n.earliest} to ${n.latest}.`),d(w(` snoutdata db restore --at ${n.latest} --ref ${e}`))})}async function cc(e,t,n){let r=await jo(e,t,n);h(r,()=>{d(`Restoring ${e} as it was at ${r.targetAt} into a new project, ${x(r.project.name)} (${r.project.ref}).`),d(w(" snoutdata projects list to see when it is ready"))})}async function Do(e){let{projects:t}=await xe(),n=t.find(l=>l.ref===e);if(!n)throw new m(`no project ${e} on this account. \`snoutdata projects list\`.`);let[r,o,s,a]=await Promise.all([$t(e),_("cloud-project-functions",{ref:e}).then(l=>(l.functions??[]).map(i=>i.name),lt),_("cloud-project-secrets",{ref:e}).then(l=>(l.secrets??[]).map(i=>i.name),lt),tr(e).then(l=>l.domains.map(i=>({hostname:i.hostname,verified:i.verified})),lt)]);return{...n,products:r,functions:o,secretNames:s,domains:a}}async function lc(e){let t=await Do(e);h(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(`${L([["name",n.name],["ref",n.ref],["state",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; table changes on Plus and Pro)"],["functions",o(n.functions)],["secrets",o(n.secretNames)],["domains",o(n.domains)]])}
475
- `)})}re();me();at();re();te();import{existsSync as Wf,mkdirSync as zf,readFileSync as Jf,renameSync as Vf,writeFileSync as Yf}from"node:fs";import{homedir as Mo}from"node:os";import{dirname as Xf,join as Zf}from"node:path";import{rootCertificates as Qf}from"node:tls";var eg="SNOUTDATA_DB_SSLMODE";function tg(e=Mo()){let t=Zf(e,".snoutdata","ca-roots.pem"),n=`${Qf.join(`
454
+ `:""))}async function Ya(e,t){for(let r of t){let o=Kt(r.name);if(o)throw new m(o)}let n=ao(e);for(let r of t)n.set(r.name,r.value);Va(e,n),await qn(e),h({ref:e.ref,set:t.map(r=>r.name)},()=>{for(let r of t)d(`${x(r.name)} set in ${zn(e)}`)})}function Wn(e){return{ref:e.ref,local:e.folder,secrets:[...ao(e).keys()].sort().map(t=>({name:t}))}}function Xa(e){let t=Wn(e),n=t.secrets.map(r=>r.name);h(t,()=>{d(n.length?n.join(`
455
+ `):`No function secrets in ${zn(e)}.`)})}async function Za(e,t){let n=ao(e);if(!n.delete(t))throw new P("not-found",`${t} is not set for this local project`);Va(e,n),await qn(e),h({ref:e.ref,unset:t},()=>d(`${t} unset.`))}me();it();Ge();Jr();Pn();ne();Un();oe();oe();me();Ge();ne();async function Qa(){let{projects:e,allowance:t}=await xe();h({projects:e,allowance:t},()=>{if(e.length===0){d('No projects yet. `snoutdata projects create --name "my project"`.');return}process.stdout.write(`${B(Sm(e))}
456
+ `)})}function Sm(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?x("read-only"):n.state==="ready"?n.state:x(n.state),n.region,...t?[typeof n.postgresVersion=="number"?String(n.postgresVersion):"-"]:[],Fe(n.lastConnectionAt)])]}async function io(e){let t=await _("cloud-project-create",{name:e.name,region:e.region,teamId:e.teamId}),n=t.project.ref;d(`Created ${n}.`);let r=t.project;if(e.wait){d("Waiting for it to start\u2026");let s="";r=await Ht(n,{timeoutMs:e.timeoutMs,onTick:a=>{a!==s&&(s=a,d(w(` ${a}`)))}})}e.link&&gt(e.link,{ref:n,name:r.name});let o=`postgres://${r.user}:${encodeURIComponent(t.password)}@${r.host}:5432/${r.database}?sslmode=require`;h({project:r,ref:n,host:r.host,database:r.database,user:r.user,...e.showUrl?{password:t.password,uri:o}:{connectionString:"snoutdata db url"}},()=>{process.stdout.write(`${e.showUrl?o:n}
457
+ `),d(""),d(`Ready. ${x(n)} in ${r.region}, at ${r.host}.`),d(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 ei(e,t,n={}){let r=`cloud-project-${e}`,o=await _(r,{ref:t}),s=e==="delete"?"deleted":`${e}d`;if(n.wait===!1){h({...o,settled:!1},()=>d(`${t}: asked to be ${s}. \`snoutdata projects list\` shows when it is.`));return}let a=o.project?.state??"",l=await Ft(t,e,{timeoutMs:n.timeoutMs,onTick:u=>{u!==a&&(a=u,d(w(` ${u}`)))}}),i=l?.state??"deleted";if(i==="error")throw new P("failed",`${t} went to error instead of ${s}${l?.stateDetail?`: ${l.stateDetail}`:""}.`,{ref:t,state:i});h({...o,...l?{project:l}:{},settled:!0},()=>{d(o.changed?`${t}: ${s}.`:`${t} was already ${s}.`)})}async function ti(e){let t=await _("cloud-project-reset-password",{ref:e});h(t,()=>{process.stdout.write(`${t.password}
458
+ `),d(`New password for ${t.user}. It applies ${t.appliesIn}.`)})}async function ni(){let{teams:e}=await Fn();h({teams:e},()=>{if(e.length===0){d("You are not on any teams.");return}process.stdout.write(`${B([["NAME","ID","SHARE"],...e.map(t=>[t.name,t.id,t.mayShare?"yes":t.why??"no"])])}
459
+ `)})}async function ri(e){let{teams:t}=await Fn(),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}oe();ne();async function oi(e){let t=await _("cloud-token-create",{name:e.name,expiresInDays:e.expiresInDays,...e.project?{project:e.project}:{}});h(t,()=>{process.stdout.write(`${t.token}
460
+ `),d(""),d(`${x(t.name)} \u2014 ${t.expiresAt?`expires ${t.expiresAt.slice(0,10)}`:"does not expire"}.`),d(t.project?`Reaches project ${t.project} only.`:"Reaches every project on this account."),d("This is the only time it is shown: only its hash is stored."),d(w(" export SNOUTDATA_ACCESS_TOKEN=<that token>"))})}async function si(){let{tokens:e}=await _("cloud-token-list");h({tokens:e},()=>{if(e.length===0){d("No access tokens. `snoutdata tokens create --name ci`.");return}process.stdout.write(`${B([["PREFIX","NAME","PROJECT","STATE","LAST USED","EXPIRES"],...e.map(t=>[t.current?x(t.prefix):t.prefix,t.name,t.project??"all",t.revokedAt?"revoked":t.live?"live":"expired",Fe(t.lastUsedAt),t.expiresAt?t.expiresAt.slice(0,10):"never"])])}
461
+ `)})}async function ai(e){let t=e.startsWith("sdt_")?{prefix:e}:{id:e},n=await _("cloud-token-revoke",t);h(n,()=>{d(n.changed?`Revoked ${n.token.prefix} (${n.token.name}).`:`${n.token.prefix} was already revoked.`)})}oe();be();ne();async function ii(e){let t=await ke(e);h({ref:t.ref,appKey:t.appKey,serverKey:t.serverKey,issuedAt:t.keysIssuedAt,expiresAt:t.keysExpireAt},()=>{if(!t.appKey||!t.serverKey){d(`${e} has no API keys yet. Ask again in a moment.`);return}process.stdout.write(`${li(t.appKey,t.serverKey)}
462
+ `),$m(t.keysIssuedAt)})}async function ci(e,t){if(!t.force)throw d(`Rotating the keys for ${e} stops every app key and server key already pasted anywhere.`),d("Anything holding one (a deployed app, a CI secret, a teammate) breaks until it is updated."),new m("keys rotate needs --force, because this cannot be undone");let n=Bn(await _("cloud-project-rotate-jwt",{ref:e}));h(n,()=>{process.stdout.write(`${li(n.appKey,n.serverKey)}
463
+ `),d(""),d(n.breaks),d(w(" snoutdata keys --json to read them again later"))})}function li(e,t){return B([["KEY","VALUE"],["app key",e],["server key",t]])}function $m(e){d(""),d(`The ${x("app key")} is the public one: it goes in a browser, and row-level security decides what it reads.`),d(`The ${x("server key")} bypasses row-level security. Server side only, never in a client bundle.`),e&&d(w(` issued ${e.slice(0,10)}`))}oe();be();ne();import{readdir as Pm,readFile as Em,stat as Am}from"node:fs/promises";import{join as lo,relative as Rm,sep as Tm}from"node:path";var di=["functions"];async function co(e){try{return(await Am(e)).isDirectory()}catch{return!1}}async function Om(e,t){if(t){if(!await co(t))throw new m(`${t} is not a directory`);return t}for(let n of di){let r=lo(n,e);if(await co(r))return r}throw new m(`no folder found for ${e} at ${di[0]}/${e}; use --dir to say where it is.`)}async function ui(e){let t=[];async function n(r){for(let o of await Pm(r,{withFileTypes:!0})){if(o.name.startsWith(".")||o.name==="node_modules")continue;let s=lo(r,o.name);if(o.isDirectory()){await n(s);continue}if(!o.isFile())continue;let a=await Em(s),l=a.toString("utf8");if(Buffer.compare(Buffer.from(l,"utf8"),a)!==0)throw new m(`${s} is not text, and a function bundle is source code. Put binary assets in Storage.`);t.push({path:Rm(e,s).split(Tm).join("/"),text:l})}}return await n(e),t}async function Nm(e,t,n){let r=await ui(t);if(r.length===0)throw new m(`${t} has no files in it`);let o=n??(r.some(l=>l.path==="index.ts")?"index.ts":"");if(!o)throw new m(`${t} has no index.ts, so there is nothing to start. Name the file with --entrypoint.`);let s=lo(t,"..","_shared");if(!await co(s))return{entrypoint:o,files:r};let a=(await ui(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 uo(e,t,n){lt(t);let r=await Om(t,n.dir),{entrypoint:o,files:s}=await Nm(t,r,n.entrypoint),a=Ua({entrypoint:o,files:s});return{answer:await _("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 mi(e,t,n){let{answer:r,directory:o,files:s,bytes:a}=await uo(e,t,n),l=r.functions.find(i=>i.name===t);h(r,()=>{let i=Math.max(1,Math.round(a/1024));d(`${x(t)} deployed from ${o} (${s} file${s===1?"":"s"}, ${i} KB)`),l&&d(` ${l.url}`),n.verifyJwt||(d(""),d(x(" Anybody who knows this URL can run it. No API key is required.")),d(w(" That is what a webhook receiver needs. Check the sender signature inside the function."))),r.limit.maxFunctions!==null&&d(w(` ${r.limit.deployed} of ${r.limit.maxFunctions} functions on this plan`))})}function po(e){return _("cloud-project-functions",{ref:e})}function mo(e,t){return lt(t),_("cloud-project-functions",{ref:e,action:"delete",name:t})}function fo(e,t,n){if(lt(t),!n.reset&&n.memoryMb===void 0&&n.concurrency===void 0)throw new m("functions size needs --memory MB, --concurrency N, or --reset");return _("cloud-project-functions",{ref:e,action:"size",name:t,...n.reset?{reset:!0}:{memoryMb:n.memoryMb??null,concurrency:n.concurrency??null}})}function Im(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 fi(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 gi(e,t,n){let r=await fo(e,t,n),o=r.functions.find(s=>s.name===t);h(r,()=>{let s=o?Im(o,r.limit):null;d(`${x(t)} ${n.reset?"is back to the plan default":"is resized"}${s?`: ${s}`:""}`),d(w(" The next request runs at it; workers already running finish what they hold."));let a=fi(r.limit);a&&d(w(` ${a}`))})}async function hi(e){let t=await po(e);h(t,()=>{if(t.functions.length===0){d(`${e} has no functions.`),d(w(" snoutdata functions deploy <name> from functions/<name>"));return}process.stdout.write(`${B([["NAME","KEY","SIZE","MEMORY","WORKERS","URL"],...t.functions.map(r=>[r.name,r.verifyJwt?"required":x("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])])}
464
+ `),t.limit.maxFunctions!==null&&d(w(`${t.limit.deployed} of ${t.limit.maxFunctions} on this plan`));let n=fi(t.limit);n&&d(w(`${n}. Change one with: snoutdata functions size <name> --memory MB --concurrency N`))})}function pi(e){let t=e.dropped_before>0?w(`(${e.dropped_before} earlier line(s) were printed too fast to keep) `):"",n=e.cut_bytes?w(` (cut from ${e.cut_bytes} bytes)`):"",r=e.level==="error"?x("error "):"";return`${w(e.at)} ${e.name} ${r}${t}${e.message}${n}`}async function yi(e,t,n){let r=a=>_("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(h({ref:e,lines:o},()=>{if(o.length===0&&!n.follow){d(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),d(w(" Lines show up about a minute after a function prints them."));return}for(let a of o)process.stdout.write(`${pi(a)}
465
+ `)}),!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(`${pi(l)}
466
+ `),s=l.at}}async function wi(e,t){let n=await mo(e,t);h(n,()=>{d(n.live?`${t} is gone.`:`${t} is gone. It stops answering within a few seconds.`)})}oe();import{spawn as rf}from"node:child_process";import{createHash as of}from"node:crypto";import{createReadStream as Ai}from"node:fs";import{mkdtemp as sf,rm as af,stat as Jn}from"node:fs/promises";import{request as cf}from"node:http";import{request as lf}from"node:https";import{tmpdir as df}from"node:os";import{basename as uf,dirname as pf,join as bo}from"node:path";var jm="x-snoutdata-upload-bytes",Dm="x-snoutdata-upload-sha256",Mm="/done",Lm=/^[0-9a-f]{64}$/,Um=/^sha256:[0-9a-f]{64}$/;function Bm(e){return Lm.test(e)}var ve=class extends Error{constructor(n,r){super(`the upload failed (${n})`);this.status=n;this.body=r}};function go(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function bi(e){let t=String(go(e).digest??"");if(!Um.test(t))throw new ve(502,JSON.stringify({error:"The upload finished without saying what it stored, so there is nothing to deploy. Build again."}));return t}var Fm=15*6e4,Hm=2e3;async function _i(e){let{ticketUrl:t,file:n,transport:r}=e;if(!Bm(e.sha256))throw new Error("an upload is declared with its SHA-256, in hex");let o=await r.call("POST",t,{[jm]:String(e.bytes),[Dm]:e.sha256});if(o.status===405){e.step?.("uploading");let c=await r.put(t,n,{});if(c.status!==200)throw new ve(c.status,c.body);return bi(c.body)}if(o.status!==200)throw new ve(o.status,o.body);let s=go(o.body);if(typeof s.url!="string"||!s.url.startsWith("https://")||!s.headers||typeof s.headers!="object")throw new ve(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 c=/<Code>([^<]+)<\/Code>/.exec(a.body)?.[1],p=c==="BadDigest"||c==="XAmzContentSHA256Mismatch"?"The image changed or was damaged while it was uploading. Build again.":c==="AccessDenied"||c==="SignatureDoesNotMatch"||c==="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 ve(a.status===403?401:502,JSON.stringify({error:p}))}e.step?.("storing");let l=r.now()+(e.waitMs??Fm),i=e.pollMs??Hm,u=!1;for(;!u;){let c=await r.call("POST",`${t}${Mm}`,{});if(c.status===200||c.status===202)u=!0;else if(c.status===429&&r.now()<l)await r.sleep(i*5);else throw new ve(c.status,c.body)}for(;;){let c=await r.call("GET",t,{});if(c.status!==200)throw new ve(c.status,c.body);let p=go(c.body);if(p.state==="stored")return bi(c.body);if(p.state==="failed")throw new ve(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 ve(504,JSON.stringify({error:"The project's host took too long to store the image. Build again in a moment."}));await r.sleep(i)}}ne();var Km=/^[a-z0-9][a-z0-9_-]{0,31}$/;function qm(e){return Km.test(e)}function ki(e){return qm(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 Gm=/^sha256:[0-9a-f]{64}$/,zm=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,Wm=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/,Jm=/^(?:[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 Vm(e){return Gm.test(e)}function vi(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),!Vm(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),!zm.test(s)))return{error:`${JSON.stringify(s)} is not an image tag.`};let i=n.split("/"),u="docker.io",c=i[0]??"";return i.length>1&&(c.includes(".")||c.includes(":")||c==="localhost")&&(u=c.toLowerCase(),i.shift()),Jm.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(p=>!Wm.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:u,repository:i.join("/"),tag:s,digest:r})):{error:`${JSON.stringify(c)} is not a registry address.`}}var TS=["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 ho(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 Ym(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 c=ho(t.slice(r+1));if(!c)return null;t=`${t.slice(0,r+1)}${(c[0]<<8|c[1]).toString(16)}:${(c[2]<<8|c[3]).toString(16)}`}let o=t.split("::");if(o.length>2)return null;let s=c=>c===""?[]:c.split(":"),a=s(o[0]??""),l=o.length===2?s(o[1]??""):[];if([...a,...l].some(c=>!/^[0-9a-fA-F]{1,4}$/.test(c)))return null;let i=a.length+l.length;if(o.length===1?i!==8:i>7)return null;let u=new Array(8-i).fill(0);return[...a.map(c=>parseInt(c,16)),...u,...l.map(c=>parseInt(c,16))]}function Xm(e,t,n){let r=ho(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 Zm=[["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 OS=1024**3;var Si=16,Qm=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/,ef=/^(\d{1,3}(?:\.\d{1,3}){3})(?:\/(\d{1,2}))?$/;function tf(e,t){let n=e??[],r={error:`${t}: ports are up to ${Si} whole numbers, 1 to 65535.`};if(!Array.isArray(n)||n.length>Si)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 nf(e){let t=e.trim().toLowerCase(),n=ef.exec(t);if(n){let r=ho(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,i=[24,16,8,0].map(u=>l>>>u&255);return Zm.some(([u,c])=>o>=c&&Xm(i,u,c))?{error:`${e} is not on the public internet, and a container reaches nothing else.`}:o===32?i.join("."):`${i.join(".")}/${o}`}return Ym(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.`}:Qm.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 $i(e){let t=e.trim(),n=t.lastIndexOf(":"),r=n!==-1&&t.indexOf(":")===n,o=r?t.slice(0,n):t,s=tf(r?t.slice(n+1).split(",").map(l=>l.trim()):[],o.trim());if("error"in s)return s;let a=nf(o);return typeof a!="string"?a:{destination:a,ports:s}}function yo(e){return e.ports.length===0?e.destination:`${e.destination}:${e.ports.join(",")}`}var mf=new Set(["pending","pulling","starting","restarting"]),ff=5*6e4;function Xn(e){let t=ki(e);if(t)throw new Error(t)}function _o(e,t,n){Xn(t);let r=vi(n.image);if("error"in r)throw new Error(r.error);return _("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 kt(e){return _("cloud-project-containers",{ref:e})}function So(e,t){return Xn(t),_("cloud-project-containers",{ref:e,action:"delete",name:t})}function ko(e,t){return Xn(t),_("cloud-project-containers",{ref:e,action:"restart",name:t})}function Vn(e,t){return _("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 Ri(e,t){let n=Date.now()+ff,r=null;for(;Date.now()<n;)if(await new Promise(o=>setTimeout(o,3e3)),r=(await kt(e)).containers.find(o=>o.name===t)??null,!r||!mf.has(r.status))return r;return r}function vo(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 Ti(e,t,n){await Oi(e,t,await _o(e,t,n),n.wait!==!1)}async function Oi(e,t,n,r){let o=n.containers.find(s=>s.name===t)??null;r&&o&&(d(w(`${t}: ${o.image} pinned to ${o.digest.slice(0,19)}\u2026, waiting for the host`)),o=await Ri(e,t)??o),h({...n,containers:o?[o]:n.containers},()=>{if(!o){d(`${x(t)} deployed.`);return}d(`${x(t)} ${vo(o)}`),d(` ${o.url}`),o.statusDetail&&d(` ${o.statusDetail}`),d(""),d(w(" Listens on PORT ("+o.port+"). DATABASE_URL and your secrets are in its environment.")),d(x(" Anything written inside the container is lost when it restarts or is redeployed.")),d(w(" Keep what matters in your database.")),n.allowance&&d(w(` ${n.allowance.deployed} of ${n.allowance.maxContainers} containers on this plan, ${n.allowance.memoryMb} MB and ${n.allowance.cpuPercent}% of a core each`))})}var gf=2*1024**3,hf=3*6e4;async function yf(e){let t;try{t=await Jn(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 Jn(bo(e,"Dockerfile"))}catch{throw new Error(`${e} has no Dockerfile in it.`)}return{context:e,file:null}}return{context:pf(e),file:e}}function wf(e){return["buildx","build","--platform","linux/arm64","--provenance=false","--output",`type=oci,dest=${e.archive}`,...e.file?["--file",e.file]:[],e.context]}function $o(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 bf(e,t){let n="";try{let r=JSON.parse(t);n=String(r.error??r.message??"")}catch{}return n?$o(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 _f(e){return new Promise((t,n)=>{let r=rf("docker",e,{stdio:["ignore",2,2]});r.on("error",o=>n(o)),r.on("close",o=>t(o??1))})}function Ni(e,t,n,r){return new Promise((o,s)=>{let a=new URL(e),l=(a.protocol==="http:"?cf:lf)(a,{method:t,headers:n});l.on("response",i=>{let u=[];i.on("data",c=>u.push(c)),i.on("end",()=>o({status:i.statusCode??0,body:Buffer.concat(u).toString("utf8")})),i.on("error",s)}),l.on("error",i=>{s(i)}),r(l)})}async function Sf(e,t,n){let r=Object.keys(n).length>0?n:{"content-type":"application/octet-stream","content-length":String((await Jn(t)).size)};return Ni(e,"PUT",r,o=>{let s=Ai(t);s.on("error",a=>o.destroy(a)),s.pipe(o)})}function kf(e){return new Promise((t,n)=>{let r=of("sha256");Ai(e).on("error",n).on("data",o=>r.update(o)).on("end",()=>t(r.digest("hex")))})}var vf={call:(e,t,n)=>Ni(t,e,{"content-length":"0",...n},r=>r.end()),put:Sf,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now()},Ii={docker:_f,scratch:()=>sf(bo(df(),"snoutdata-build-")),remove:e=>af(e,{recursive:!0,force:!0}),size:async e=>(await Jn(e)).size,hash:kf,transport:vf,ask:e=>_("cloud-project-containers",e),say:e=>d(w(e)),now:()=>Date.now()};function xi(e){return`${Math.max(1,Math.round(e/1024**2))} MB`}async function Pi(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 $f(e,t,n,r=Ii){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 Pi(r,e,t),s=await r.scratch();try{let a=bo(s,"image.tar");if(r.say(`${t}: building ${n.file?uf(n.file):n.context} for linux/arm64`),await r.docker(wf({...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>gf)throw new Error(`the image is ${xi(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()>hf||(o=await Pi(r,e,t));let i=await r.hash(a);r.say(`${t}: uploading the image (${xi(l)})`);try{return await _i({ticketUrl:o.url,file:a,bytes:l,sha256:i,transport:r.transport,step:u=>{u==="storing"&&r.say(`${t}: storing the image in the project`)}})}catch(u){throw u instanceof ve?new Error(bf(u.status,u.body)):u}}finally{await r.remove(s).catch(()=>{})}}catch(o){throw new Error($o(o instanceof Error?o.message:String(o)))}}async function Ci(e,t,n,r=Ii){Xn(t);let o=await yf(n.path),s=await $f(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($o(l instanceof Error?l.message:String(l)))}await Oi(e,t,a,n.wait!==!1)}async function ji(e){let t=await kt(e);h(t,()=>{if(t.containers.length===0){d(`No containers on ${e}.`),t.allowance&&t.allowance.maxContainers===0?d(w(" Containers run on the Plus and Pro plans.")):d(w(" snoutdata containers deploy <name> <image>"));return}d(B([["name","status","image","url"],...t.containers.map(r=>[r.name,vo(r),r.image,r.url])]));for(let r of t.containers)r.statusDetail&&r.status!=="running"&&d(w(` ${r.name}: ${r.statusDetail}`));let n=t.allowance?.egress;n&&n.allowanceBytes>0&&d(w(` Sent this month: ${wo(n.usedBytes)} of ${wo(n.allowanceBytes)}. At ${wo(n.allowanceBytes)} the project's containers stop until the 1st.`))})}async function Yn(e,t){if(t===null)return _("cloud-project-containers",{ref:e,action:"egress",clear:!0});let n=[];for(let r of t){let o=$i(r);if("error"in o)throw new Error(o.error);n.push(o)}return _("cloud-project-containers",{ref:e,action:"egress",allow:n})}function xf(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).`,w(" 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(` ${yo(n)}${n.ports.length===0?w(" (any port)"):""}`);return t.push(w(` and always: ${e.allowlist.alwaysAllowed.map(yo).join(", ")}, and each other`)),t.push(w(" snoutdata containers egress clear to allow the public internet again")),t}async function Zn(e,t){let n=t.clear?await Yn(e,null):t.set?await Yn(e,t.set):await kt(e);h({ref:n.ref,allowlist:n.allowlist??null},()=>{for(let r of xf(n))d(r);(t.set||t.clear)&&d(w(" Running containers follow it within a minute; nothing restarts."))})}function wo(e){return`${Math.round(e/1024**3*10)/10} GB`}async function Di(e,t){await ko(e,t);let n=await Ri(e,t);h({ref:e,containers:n?[n]:[]},()=>{d(n?`${x(t)} ${vo(n)}`:`${t} is restarting.`),n?.statusDetail&&d(` ${n.statusDetail}`)})}async function Mi(e,t){let n=await So(e,t);h(n,()=>d(`${t} is gone. It stops within a few seconds.`))}function Ei(e){return`${w(e.at.replace("T"," ").slice(0,19))} ${e.name} ${e.stream==="stderr"?x(e.message):e.message}`}async function Li(e,t,n){let r=((await Vn(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit})).lines??[]).slice().reverse();if(h({ref:e,lines:r},()=>{if(r.length===0&&!n.follow){d(`Nothing printed${t?` by ${t}`:""} on ${e} in the last seven days.`),d(w(" Lines show up about a minute after a container prints them."));return}for(let s of r)process.stdout.write(`${Ei(s)}
467
+ `)}),!n.follow)return;let o=r.at(-1)?.at??new Date().toISOString();for(;;){await new Promise(a=>setTimeout(a,5e3));let s=((await Vn(e,{name:t,errorsOnly:n.errorsOnly,limit:n.limit,since:o})).lines??[]).slice().reverse();for(let a of s)process.stdout.write(`${Ei(a)}
468
+ `),o=a.at}}oe();be();ne();function Bi(e){let t=e.indexOf("=");return t<=0?null:{name:e.slice(0,t),value:e.slice(t+1)}}async function vt(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8").replace(/\n$/,"")}async function Fi(e,t){if(e.length===0)throw new m("secrets set needs NAME=value, or NAME with --stdin");if(t.stdin){if(e.length!==1)throw new m("--stdin sets one secret, so it takes one NAME");return[{name:e[0],value:await vt()}]}return e.map(n=>{let r=Bi(n);if(!r)throw new m(`${n} is not NAME=value. Use --stdin to set a value from a pipe.`);return r})}async function Hi(e,t,n){if(t.length===0)throw new m("secrets set needs NAME=value, or NAME with --stdin");let r=[];if(n.stdin){if(t.length!==1)throw new m("--stdin sets one secret, so it takes one NAME");r.push({name:t[0],value:await vt()})}else for(let s of t){let a=Bi(s);if(!a)throw new m(`${s} is not NAME=value. Use --stdin to set a value from a pipe.`);r.push(a)}for(let s of r){let a=Kt(s.name);if(a)throw new m(a)}let o=null;for(let s of r)o=await _("cloud-project-secrets",{ref:e,action:"set",name:s.name,value:s.value});h(o,()=>{for(let s of r)d(`${x(s.name)} set`);d(w(" Functions pick it up within a few seconds. Redeploying is not needed.")),n.stdin||d(w(" A value typed here is in your shell history. In CI, use: \u2026 | snoutdata secrets set NAME --stdin"))})}async function Ki(e,t){let n=Kt(t);if(n)throw new m(n);let r=await _("cloud-project-secrets",{ref:e,action:"unset",name:t});h(r,()=>{d(`${t} is gone.`)})}async function qi(e){let t=await _("cloud-project-secrets",{ref:e});h(t,()=>{if(t.secrets.length===0){d(`${e} has no function secrets.`),d(w(" snoutdata secrets set STRIPE_KEY=sk_..."));return}process.stdout.write(`${B([["NAME","SIZE","SET"],...t.secrets.map(n=>[n.name,n.bytes===null?"-":`${n.bytes} B`,Fe(n.updatedAt)])])}
469
+ `),d(w("Values are not readable, here or anywhere. Set one again to change it."))})}import{spawn as Qt}from"node:child_process";import{appendFileSync as mc,existsSync as sr,readFileSync as fc,statSync as ug,unlinkSync as pg,writeFileSync as xt}from"node:fs";import{dirname as mg,join as ar}from"node:path";import{tmpdir as fg}from"node:os";import{open as gc}from"node:fs/promises";function Gi(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 zi(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 Wi(e){let t=e.split(`
470
+ `).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 xo={auth:"snout_auth_admin",storage:"snout_storage_admin",push:"snout_push_admin"},Ef=/^(snoutpod_admin|snout_[a-z]+_admin)$/,Qn=new Set(["snout_identity","snout_files","push","snout_live","snout_realtime","_realtime","graphql","snout_graph","snout_ext","net","cron","pgbouncer","vault","pgsodium","auth","storage","realtime","graphql_public","extensions"]),Af=/^(pgrst_ddl_watch|pgrst_drop_watch|snoutpod_[a-z_]+|snoutdata_realtime|snout_realtime_messages)(\(|$)/,Rf={snout_identity:"auth",snout_files:"storage",auth:"auth",storage:"storage",push:"push"},Tf=new Set(["push.settings"]),Of=["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 Nf(e){let t=/^\d+; \d+ \d+ (.+)$/.exec(e.trim());if(!t)return null;let n=t[1],r=Of.find(i=>n.startsWith(`${i} `))??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 If(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 Ji(e,t){let n=new Map,r=[],o=new Set,s=0;for(let i of e.split(`
471
+ `)){let u=Nf(i);if(!u)continue;let{type:c,schema:p,name:f,owner:k}=u;if(c==="TABLE DATA"||c==="SEQUENCE SET"){let Y=/^(schema_migrations|migrations)$/.test(f)&&Qn.has(p);if(/realtime/.test(p)||p==="snout_live"||Y||p==="public"&&f==="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"&&f==="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 D=Rf[p];if(D){D==="storage"&&(f==="objects"||f==="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(D,[...n.get(D)??[],u]);continue}if(Qn.has(p)){s++;continue}r.push(u.line);continue}if(c==="COMMENT"&&p==="-"&&/^EXTENSION( |$)/.test(f)||(c==="SCHEMA"?Qn.has(f):Qn.has(p))||Af.test(f)||Ef.test(k)&&c!=="SCHEMA"){s++;continue}r.push(u.line)}let a=If(t),l=["auth","storage","push"];return{platformData:l.filter(i=>n.has(i)).map(i=>{let u=n.get(i),c=u.filter(f=>f.type==="TABLE DATA"&&Tf.has(`${f.schema}.${f.name}`)).map(f=>`${f.schema}.${f.name}`),p=u.filter(f=>f.type==="TABLE DATA").map(f=>`${f.schema}.${f.name}`);return{product:i,clear:c,tables:p,lines:Cf(u,a)}}),rest:r,products:l.filter(i=>n.has(i)),skipped:s,notes:[...o]}}function Cf(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 i=a.find(u=>[...t.get(n(u))??[]].every(c=>!r.has(c)||o.has(c)||c===n(u)))??a[0];o.add(n(i)),s.push(i.line),a=a.filter(u=>u!==i)}return s}oe();be();me();ne();oe();me();var Eo=["max_write_pause_ms","drain_timeout_ms","ack_timeout_ms","copy_mb_per_s"],Yi=["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"];function Gt(e){return e==="done"||e==="failed"||e==="cancelled"}function zt(e,t=process.env){if(e.project!==void 0){if(e.admin!==void 0)throw new P("usage","cluster takes --project (a SnoutData Cloud project) or --admin (a standalone router), not both");return new De(Uf(e.project))}let n=e.admin??Vi(t.LEPIS_ADMIN_URL);if(!n)throw new P("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??Vi(t.LEPIS_ADMIN_TOKEN);if(!r)throw new P("not-signed-in","no admin token: set LEPIS_ADMIN_TOKEN to the router's token, or pass --token");return new Po(jf(n),r)}function Vi(e){return e===void 0||e===""?void 0:e}function jf(e){let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`,n;try{n=new URL(t)}catch{throw new P("usage",`--admin: not a URL: ${e}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new P("usage",`--admin: http or https, not ${n.protocol.replace(":","")}`);if(n.username||n.password)throw new P("usage","--admin: the URL carries no credentials; the token comes from LEPIS_ADMIN_TOKEN or --token");if(n.protocol==="http:"&&!Df(n.hostname))throw new P("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 Df(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)}var Mf=6e4,Po=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))}`)}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(Mf)})}catch(i){let u=Sn(i),c=i instanceof Error?i.cause instanceof Error?i.cause.message:i.message:String(i);throw new P(u==="failed"?"network":u,`could not reach the Lepis admin API at ${this.target}: ${c}`)}let a=await s.text(),l;try{l=a===""?{}:JSON.parse(a)}catch{throw new P("server",`the admin API at ${this.target} answered ${s.status} with something that is not JSON`,{status:s.status})}if(!s.ok)throw Xi(s.status,l);return l}},Lf={bad_request:"usage",unauthorized:"not-signed-in",not_found:"not-found",conflict:"conflict",failed:"failed",timeout:"timeout"};function Xi(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?Lf[n.code]:void 0)??(e===401?"not-signed-in":e===400?"usage":Ue(e));return s==="not-signed-in"?new P(s,"the router refused the admin token (LEPIS_ADMIN_TOKEN or --token)",o):new P(s,r,o)}function Uf(e){let t=e.trim();if(!/^[a-z][0-9a-z]{12}$/.test(t))throw new P("usage",`--project: not a project ref: ${e} (13 characters, as projects list prints it)`);return t}var Bf={"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","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"},Ff="cloud-project-shards",De=class{target;ref;#t;constructor(t,n=_){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:Xe(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))}})}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=Bf[t.op];if(!n)throw new P("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 P("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 P("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(Ff,{ref:this.ref,...t})}catch(n){throw Hf(n)}}};function Xe(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 Hf(e){if(!(e instanceof ge))return e;let t=e.body??{};if(typeof t.apiCode=="string"||typeof t.kind=="string")return Xi(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":Ue(e.status);return new P(n,e.message,{status:e.status,...typeof t.code=="string"?{kind:t.code}:{}})}function Jt(e){if(Array.isArray(e))return`[${e.map(Jt).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)}:${Jt(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}var To=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}
472
+ ${Jt(t)}`,this.#e())}shown(t,n=""){let r=this.#t.get(`${n}
473
+ ${Jt(t)}`);return r!==void 0&&this.#e()-r<=this.#n}forget(t,n=""){this.#t.delete(`${n}
474
+ ${Jt(t)}`)}},Kf=new To,Oo=["node.add","node.drain","node.remove","keyspace.create","table.distribute","table.reference","table.global","range.split","range.merge","range.move","tenant.pin","rebalance","scale","verify","cleanup","node.attach","keyspace.drop","dissolve"],qf="2024-11-05";function q(e,t=[]){return{type:"object",properties:e,additionalProperties:!1,...t.length?{required:t}:{}}}var C={type:"string"},Zi={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:[...Oo]}},required:["op"],additionalProperties:!0},er={type:"integer",description:"The job id cluster_run returned, or one from cluster_jobs."},Ze={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)."},Yt=[{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:q({})},{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:q({})},{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:q({name:C,region:C,teamId:C},["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:q({ref:C},["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:q({ref:C},["ref"])},{name:"resume_project",description:"Start a paused project without waiting for a connection to wake it, and wait until it is ready.",inputSchema:q({ref:C},["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:q({ref:C,dir:C,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:q({ref:C,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:q({ref:C},["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:q({ref:C},["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:q({ref:C},["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:q({})},{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:q({})},{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:q({name:C,expires:C,project:C},["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:q({id:C},["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:q({ref:C,name:C,dir:C,entrypoint:C,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:q({ref:C},["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:q({ref:C,name:C,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:q({ref:C,name:C},["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:q({ref:C},["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:q({ref:C,name:C,image:C,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:q({ref:C,name:C},["ref","name"])},{name:"delete_container",description:"Stop one container and remove it from the project. It does not touch the database.",inputSchema:q({ref:C,name:C},["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:q({ref:C,name:C,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:q({ref:C},["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:q({ref:C,allow:{type:"array",items:C},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:q({ref:C},["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:q({ref:C,name:C,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:q({ref:C},["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:q({ref:C},["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:q({ref:C,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:q({ref:C},["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:q({ref:C,hostname:C},["ref","hostname"])},{name:"verify_domain",description:"Check a custom domain's DNS records and verify it once they are published.",inputSchema:q({ref:C,hostname:C},["ref","hostname"])},{name:"remove_domain",description:"Stop serving a project at a custom domain.",inputSchema:q({ref:C,hostname:C},["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:q({ref:C},["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:q({ref:C,at:C,name:C},["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:q({project:Ze})},{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:q({project:Ze,sampleMs:{type:"integer"}})},{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:q({project:Ze,operation:Zi},["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:q({project:Ze,operation:Zi,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:q({project:Ze,id:er})},{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:q({project:Ze,id:er,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:q({project:Ze,id:er},["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:q({project:Ze,id:er},["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:q({ref:C},["ref"])}],Gf=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_plan","cluster_jobs","cluster_watch_job"]),zf=new Set(["delete_project","delete_function","reset_password","revoke_token","remove_domain","cluster_run"]),Qi=["get_connection_url","push_migrations","get_project","list_functions","deploy_function","delete_function","list_function_secrets"];function No(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.projects))return{...t,projects:t.projects.map(No)};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 Io(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 Wf(e){return{...e,annotations:Gf.has(e.name)?{readOnlyHint:!0}:{readOnlyHint:!1,destructiveHint:zf.has(e.name)}}}function Jf(e){let t=new Set;return e.filter(n=>!t.has(n.name)&&t.add(n.name))}function Vt(e,t){return{jsonrpc:"2.0",id:e,result:t}}function tr(e,t,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:n}}}function $(e,t,n=!1){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return Vt(e,{content:[{type:"text",text:r}],...n?{isError:!0}:{}})}function Vf(e,t=new Date){let n=Date.parse(e);return!Number.isFinite(n)||n<=t.getTime()?null:Math.ceil((n-t.getTime())/864e5)}function Wt(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 Ao(e){return{id:e.id,op:e.op,state:e.state,finished:Gt(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 ec(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"||!Oo.includes(r.op))return`${t}: operation.op must be one of ${Oo.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 Ro(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 Yf(e){let t=e instanceof Error?e.message:String(e),n=e?.details?.kind;return typeof n=="string"?{error:t,kind:n}:t}var Xf="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 Zf(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 $(e,Xf,!0);s=r.shards(a)}catch(u){return $(e,u instanceof Error?u.message:String(u),!0)}let l=o.shardsPlans??Kf,i=a??"";try{switch(t){case"cluster_status":return $(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,c=await s.advice(u);for(let p of c.advice)p.plan&&l.remember(p.request,i);return $(e,{summary:c.summary,advice:c.advice.map(p=>({op:p.op,reason:p.reason,metric:p.metric,operation:p.request,...p.plan?{plan:Wt(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:c.facts,assumptions:c.assumptions,...c.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_plan":{let u=ec(n,t);if(typeof u=="string")return $(e,u,!0);let c=await s.plan(u);return l.remember(u,i),$(e,{plan:Wt(c),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=ec(n,t);if(typeof u=="string")return $(e,u,!0);if(n.confirm!==!0||!l.shown(u,i)){let p=await s.plan(u);l.remember(u,i);let f=n.confirm===!0;return $(e,{ran:!1,plan:Wt(p),next:f?"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."},f)}let c=await s.submit(u);return l.forget(u,i),c.job===void 0?$(e,{ran:!0,done:c.done,answer:c.answer}):$(e,{ran:!0,job:c.job,plan:Wt(c.plan),next:`Follow it with cluster_watch_job {"id": ${c.job}}.`})}case"cluster_jobs":{if(n.id===void 0)return $(e,{jobs:await s.jobs()});let u=Ro(n);if(u===null)return $(e,"cluster_jobs: id is a job number. Call it without id to list them.",!0);let c=await s.job(u);return $(e,{...Ao(c),plan:c.plan&&Array.isArray(c.plan.steps)?Wt(c.plan):null})}case"cluster_watch_job":{let u=Ro(n);if(u===null)return $(e,"cluster_watch_job needs id, the job number cluster_run returned.",!0);let c=typeof n.timeoutSeconds=="number"&&n.timeoutSeconds>0?Math.min(n.timeoutSeconds,120):30,p=Date.now()+c*1e3;for(;;){let f=await s.job(u);if(Gt(f.state))return $(e,Ao(f),f.state!=="done");if(Date.now()>=p)return $(e,{...Ao(f),note:`Still ${f.state} after ${c}s. It carries on; call cluster_watch_job again to keep waiting.`});await new Promise(k=>setTimeout(k,o.shardsPollMs??1e3))}}case"cluster_cancel_job":case"cluster_resume_job":{let u=Ro(n);if(u===null)return $(e,`${t} needs id, a job number.`,!0);let c=t==="cluster_cancel_job"?await s.cancel(u):await s.resume(u);return $(e,{...c,next:`Follow it with cluster_watch_job {"id": ${u}}.`})}default:return tr(e,-32602,`unknown tool: ${t}`)}}catch(u){return $(e,Yf(u),!0)}}function V(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}async function tc(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 Vt(r,{protocolVersion:qf,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"snoutdata",version:n.version}});case"ping":return Vt(r,{});case"tools/list":return Vt(r,{tools:Jf([...Yt.map(Wf),...n.borrowed??[]])});case"tools/call":return Qf(r,s,t,n);default:return tr(r,-32601,`unknown method: ${o}`)}}async function Qf(e,t,n,r){let o=typeof t.name=="string"?t.name:"",s=t.arguments??{};if(!(Yt.some(c=>c.name===o)||(r.borrowed?.some(c=>c.name===o)??!1)))return tr(e,-32602,`unknown tool: ${o}`);let l=["get_connection_url","pause_project","resume_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_")&&Yt.some(c=>c.name===o))return Zf(e,o,s,n,r);let i=V(s,"ref");if(l.includes(o)&&!i)return $(e,`${o} needs a project ref. Call list_projects to see them.`,!0);let u=i&&n.localProject?n.localProject(i):null;if(u&&!Qi.includes(o))return $(e,`${i} is the self-hosted project in ${u.folder}, and ${o} is about SnoutData Cloud. On a local project these tools work: ${Qi.join(", ")}.`,!0);try{switch(o){case"whoami":return $(e,await n.whoami());case"list_projects":return $(e,No(await n.listProjects()));case"create_project":{let c=V(s,"name");return c?$(e,await n.createProject({name:c,region:V(s,"region")??void 0,teamId:V(s,"teamId")??void 0})):$(e,"create_project needs a name.",!0)}case"get_connection_url":{let c=await n.connection(i);return $(e,{url:c.uri,state:c.state,wakesInstantly:c.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 $(e,await n.setProjectState("pause",i));case"resume_project":return $(e,await n.setProjectState("resume",i));case"usage":{let c=typeof s.days=="number"?s.days:void 0;return $(e,await n.usage(i,c))}case"export_status":return $(e,await n.exportStatus(i));case"start_export":return $(e,await n.requestExport(i));case"reset_password":{let c=await n.resetPassword(i),p=await n.connection(i);return $(e,{url:p.uri,appliesIn:c.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 $(e,await n.listTeams());case"get_project":return $(e,No(await n.getProject(i)));case"list_products":return $(e,await n.getProducts(i));case"set_product":{let c=V(s,"product");return c!=="auth"&&c!=="storage"&&c!=="data-api"?$(e,"set_product needs product: auth, storage or data-api.",!0):typeof s.enabled!="boolean"?$(e,"set_product needs enabled: true or false.",!0):$(e,await n.setProduct(i,c,s.enabled))}case"list_domains":return $(e,await n.listDomains(i));case"add_domain":case"verify_domain":case"remove_domain":{let c=V(s,"hostname");return c?$(e,await n.domainAction(i,o.split("_")[0],c)):$(e,`${o} needs a hostname, e.g. api.example.com.`,!0)}case"restore_window":{let c=await n.restoreWindow(i),p=c&&c.restore?Io(i,c.restore):null;return $(e,p?{...c,reason:p}:c)}case"restore_to_point":{let c=V(s,"at");return c?$(e,await n.restoreTo(i,c,V(s,"name")??void 0)):$(e,"restore_to_point needs at: an ISO 8601 moment inside restore_window.",!0)}case"deploy_function":{let c=V(s,"ref"),p=V(s,"name");return!c||!p?$(e,"deploy_function needs a project ref and a function name.",!0):$(e,await n.deployFunction(c,p,{dir:V(s,"dir")??void 0,entrypoint:V(s,"entrypoint")??void 0,verifyJwt:s&&typeof s=="object"&&"openToAnyone"in s?s.openToAnyone!==!0:!0}))}case"list_functions":{let c=V(s,"ref");return c?$(e,await n.listFunctions(c)):$(e,"list_functions needs a project ref.",!0)}case"size_function":{let c=V(s,"ref"),p=V(s,"name");if(!c||!p)return $(e,"size_function needs a project ref and a function name.",!0);let f=typeof s.memoryMb=="number"?s.memoryMb:void 0,k=typeof s.concurrency=="number"?s.concurrency:void 0,v=s.reset===!0;return!v&&f===void 0&&k===void 0?$(e,"size_function needs memoryMb, concurrency, or reset: true.",!0):$(e,await n.sizeFunction(c,p,{memoryMb:f,concurrency:k,reset:v}))}case"delete_function":{let c=V(s,"ref"),p=V(s,"name");return!c||!p?$(e,"delete_function needs a project ref and a function name.",!0):$(e,await n.deleteFunction(c,p))}case"list_containers":{let c=V(s,"ref");return c?$(e,await n.listContainers(c)):$(e,"list_containers needs a project ref.",!0)}case"deploy_container":{let c=V(s,"ref"),p=V(s,"name"),f=V(s,"image");if(!c||!p||!f)return $(e,"deploy_container needs a project ref, a container name and an image.",!0);let k=typeof s.port=="number"?s.port:void 0;return $(e,await n.deployContainer(c,p,{image:f,...k===void 0?{}:{port:k}}))}case"restart_container":case"delete_container":{let c=V(s,"ref"),p=V(s,"name");return!c||!p?$(e,`${o} needs a project ref and a container name.`,!0):$(e,o==="restart_container"?await n.restartContainer(c,p):await n.deleteContainer(c,p))}case"container_logs":{let c=V(s,"ref");if(!c)return $(e,"container_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return $(e,await n.containerLogs(c,{name:V(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"container_egress":{let c=V(s,"ref");return c?$(e,await n.containerEgress(c)):$(e,"container_egress needs a project ref.",!0)}case"set_container_egress":{let c=V(s,"ref");if(!c)return $(e,"set_container_egress needs a project ref.",!0);let p=s.clear===!0,f=s.allow;return f!==void 0&&(!Array.isArray(f)||!f.every(k=>typeof k=="string"))?$(e,'set_container_egress takes allow as a list of destinations, such as ["api.example.com:443"].',!0):p===(f!==void 0)?$(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):$(e,await n.setContainerEgress(c,p?null:f))}case"list_function_secrets":{let c=V(s,"ref");return c?$(e,await n.listFunctionSecrets(c)):$(e,"list_function_secrets needs a project ref.",!0)}case"function_logs":{let c=V(s,"ref");if(!c)return $(e,"function_logs needs a project ref.",!0);let p=typeof s.limit=="number"?s.limit:void 0;return $(e,await n.functionLogs(c,{name:V(s,"name")??void 0,errorsOnly:s.errorsOnly===!0,limit:p}))}case"list_tokens":return $(e,await n.listTokens());case"create_token":{let c=V(s,"name");if(!c)return $(e,"create_token needs a name, so somebody can tell later what it was for.",!0);let p=V(s,"expires"),f=p?Vf(p):void 0;return f===null?$(e,`create_token: \`expires\` must be a date in the future, like 2026-12-31. Got "${p}".`,!0):$(e,await n.createToken(c,f,V(s,"project")??void 0))}case"revoke_token":{let c=V(s,"id");return c?$(e,await n.revokeToken(c)):$(e,"revoke_token needs the id of a token. list_tokens has them.",!0)}case"push_migrations":return $(e,await n.pushMigrations(i,{dir:V(s,"dir")??void 0,dryRun:s.dryRun===!0}));case"delete_project":return r.allowDelete?$(e,await n.setProjectState("delete",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(c=>c.name===o)?n.callBorrowed?Vt(e,await n.callBorrowed(o,s)):$(e,`${o} needs SnoutData Studio, which is no longer answering.`,!0):tr(e,-32602,`unknown tool: ${o}`)}}catch(c){return $(e,c instanceof Error?c.message:String(c),!0)}}function nc(e){let t=e.split(`
475
+ `),n=t.pop()??"";return{messages:t.map(r=>r.trim()).filter(r=>r.length>0),rest:n}}var nr=["auth","storage","data-api","push"];function dt(e){return{error:e instanceof Error?e.message:String(e)}}async function $t(e){let[t,n,r,o]=await Promise.all([_("cloud-project-auth",{ref:e,action:"status"}).then(s=>({enabled:s.enabled===!0,google:s.google?.enabled===!0,saml:s.saml?.enabled===!0}),dt),_("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}),dt),_("cloud-project-data-api",{ref:e}).then(s=>({enabled:s.dataApi?.enabled===!0,allowedOnPlan:s.dataApi?.allowed===!0}),dt),_("cloud-project-push",{ref:e}).then(s=>({enabled:s.push?.enabled===!0,scheduling:s.push?.scheduling===!0}),dt)]);return{ref:e,auth:t,storage:n,dataApi:r,push:o,realtime:eg}}var eg={enabled:!0,broadcast:!0,presence:!0,tableChanges:"Plus and Pro plans"};function oc(e){let t=(e??"").toLowerCase().replace("_","-").replace(/^dataapi$/,"data-api");if(!nr.includes(t))throw new m(`say which product: ${nr.join(", ")}`);return t}async function Co(e,t,n){if(t==="auth"){let r=await _("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 _("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==="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 sc(e){let t=await $t(e);h(t,()=>{let n=(l,i,u="")=>[l,i&&typeof i=="object"&&"error"in i?`could not read: ${i.error}`:i.enabled?x("on"):"off",u],r=t.storage,o=t.dataApi;process.stdout.write(`${B([["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 and Pro")])}
476
+ `);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&&d(w(` snoutdata products enable ${a} --ref ${e}`))})}async function ac(e,t,n){let r=await Co(e,t,n);h(r,()=>d(r.note))}async function rr(e){let t=await _("cloud-project-domain",{ref:e,action:"list"});return{ref:e,domains:t.domains??[]}}async function jo(e,t,n){if(!n)throw new m(`domains ${t} needs a hostname, e.g. api.example.com`);let r=await _("cloud-project-domain",{ref:e,action:t,hostname:n});return{ref:e,domain:r.domain??null,next:r.next??null}}function rc(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(`${B(n)}
477
+ `)}async function ic(e,t,n){if(t===void 0||t==="list"){let o=await rr(e);h(o,()=>{if(o.domains.length===0){d(`No domains on ${e}. \`snoutdata domains add api.example.com\`.`);return}process.stdout.write(`${B([["HOSTNAME","VERIFIED","CERTIFICATE"],...o.domains.map(s=>[s.hostname,s.verified?"yes":x("no"),s.certificate?.state??""])])}
478
+ `)});return}if(t!=="add"&&t!=="verify"&&t!=="remove")throw new m(`unknown command: domains ${t}`);let r=await jo(e,t,n??"");t==="verify"&&r.domain&&!r.domain.verified&&(Dn()||rc(r.domain,e),K("not-ready",r.domain.verificationError??`${n} is not verified yet. Publish the records above, then run this again.`,{ref:e,domain:r.domain})),h(r,()=>{if(t==="remove"){d(`${n} removed.`);return}r.domain&&(d(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||rc(r.domain,e)),r.next&&d(r.next)})}async function Do(e){return _("cloud-project-restore",{ref:e},"GET")}async function Mo(e,t,n){if(Number.isNaN(Date.parse(t)))throw new m(`--at needs a moment, e.g. 2026-09-20T14:30:00Z (got "${t}")`);return _("cloud-project-restore",{ref:e,at:new Date(t).toISOString(),...n?{name:n}:{}})}async function cc(e){let t=await Do(e);h(t,()=>{let n=t.restore,r=Io(e,n);if(r){d(r);return}d(`${e} can be restored to any moment from ${n.earliest} to ${n.latest}.`),d(w(` snoutdata db restore --at ${n.latest} --ref ${e}`))})}async function lc(e,t,n){let r=await Mo(e,t,n);h(r,()=>{d(`Restoring ${e} as it was at ${r.targetAt} into a new project, ${x(r.project.name)} (${r.project.ref}).`),d(w(" snoutdata projects list to see when it is ready"))})}async function Lo(e){let{projects:t}=await xe(),n=t.find(l=>l.ref===e);if(!n)throw new m(`no project ${e} on this account. \`snoutdata projects list\`.`);let[r,o,s,a]=await Promise.all([$t(e),_("cloud-project-functions",{ref:e}).then(l=>(l.functions??[]).map(i=>i.name),dt),_("cloud-project-secrets",{ref:e}).then(l=>(l.secrets??[]).map(i=>i.name),dt),rr(e).then(l=>l.domains.map(i=>({hostname:i.hostname,verified:i.verified})),dt)]);return{...n,products:r,functions:o,secretNames:s,domains:a}}async function dc(e){let t=await Lo(e);h(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(`${B([["name",n.name],["ref",n.ref],["state",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; table changes on Plus and Pro)"],["functions",o(n.functions)],["secrets",o(n.secretNames)],["domains",o(n.domains)]])}
479
+ `)})}oe();me();it();oe();ne();import{existsSync as tg,mkdirSync as ng,readFileSync as rg,renameSync as og,writeFileSync as sg}from"node:fs";import{homedir as Uo}from"node:os";import{dirname as ag,join as ig}from"node:path";import{rootCertificates as cg}from"node:tls";var lg="SNOUTDATA_DB_SSLMODE";function dg(e=Uo()){let t=ig(e,".snoutdata","ca-roots.pem"),n=`${cg.join(`
476
480
  `)}
477
- `,r=null;try{r=Wf(t)?Jf(t,"utf8"):null}catch{r=null}if(r!==n){zf(Xf(t),{recursive:!0,mode:448});let o=`${t}.${process.pid}.tmp`;Yf(o,n,{mode:420}),Vf(o,t)}return t}function Yt(e,t=process.env,n=Mo()){if(e==="disable")return{mode:"disable"};let r=t[eg]?.trim();return r?{mode:r}:{mode:"verify-full",rootCert:t.PGSSLROOTCERT||tg(n)}}function Xt(e,t=process.env,n=Mo()){let{mode:r,rootCert:o}=Yt(e,t,n);return o?{PGSSLMODE:r,PGSSLROOTCERT:o}:{PGSSLMODE:r}}async function gc(e){try{let{projects:t}=await xe(),n=t.find(r=>r.ref===e);n?.readOnly?Q(`${e} is read-only: it is over the storage limit on your plan. Reading works; writing does not.`):n?.readOnlyPending&&Q(`${e} is about to become read-only: it has grown past the storage limit on your plan.`)}catch{}}async function Uo(e){await gc(e);let t=await ke(e);h(t,()=>{process.stdout.write(`${t.uri}
478
- `)})}async function hc(e,t){if(t.length===0&&!ye()){let o=wt();H("usage",`db psql with no statements opens an interactive session, and ${o?yt(o):"there is nobody to use it"}. Pass statements after --, or use \`snoutdata db url\` and your own client.`)}await gc(e);let n=await ke(e);n.wakesInstantly||d("This project is paused; the connection will wake it, which takes a few seconds.");let r=Zt("psql",["--host",n.host,"--port",String(n.port),"--username",n.user,"--dbname",n.database,...t],{stdio:"inherit",env:{...process.env,PGPASSWORD:n.password,...Xt(n.ssl)}});return new Promise((o,s)=>{r.on("error",a=>{if(a.code==="ENOENT"){s(new P("tool-missing","psql is not installed. `snoutdata db url` prints a connection string for any client."));return}s(new P("failed",String(a)))}),r.on("close",a=>o(a??0))})}function yc(e,t,n="DATABASE_URL"){let r=or(e,".env"),o=`${n}=${t}`,s=ag(e);if(!rr(r))return xt(r,`${o}
479
- `,{mode:384}),{path:r,replaced:!1,ignored:s};process.platform!=="win32"&&ng(r).mode&63&&Q(`${r} can be read by other users on this machine, and it holds a database password. \`chmod 600 ${r}\` closes it.`);let a=mc(r,"utf8"),l=new RegExp(`^${n}=.*$`,"m");return l.test(a)?(xt(r,a.replace(l,o)),{path:r,replaced:!0,ignored:s}):(pc(r,a.endsWith(`
481
+ `,r=null;try{r=tg(t)?rg(t,"utf8"):null}catch{r=null}if(r!==n){ng(ag(t),{recursive:!0,mode:448});let o=`${t}.${process.pid}.tmp`;sg(o,n,{mode:420}),og(o,t)}return t}function Xt(e,t=process.env,n=Uo()){if(e==="disable")return{mode:"disable"};let r=t[lg]?.trim();return r?{mode:r}:{mode:"verify-full",rootCert:t.PGSSLROOTCERT||dg(n)}}function Zt(e,t=process.env,n=Uo()){let{mode:r,rootCert:o}=Xt(e,t,n);return o?{PGSSLMODE:r,PGSSLROOTCERT:o}:{PGSSLMODE:r}}async function hc(e){try{let{projects:t}=await xe(),n=t.find(r=>r.ref===e);n?.readOnly?ee(`${e} is read-only: it is over the storage limit on your plan. Reading works; writing does not.`):n?.readOnlyPending&&ee(`${e} is about to become read-only: it has grown past the storage limit on your plan.`)}catch{}}async function Fo(e){await hc(e);let t=await ke(e);h(t,()=>{process.stdout.write(`${t.uri}
482
+ `)})}async function yc(e,t){if(t.length===0&&!ye()){let o=wt();K("usage",`db psql with no statements opens an interactive session, and ${o?yt(o):"there is nobody to use it"}. Pass statements after --, or use \`snoutdata db url\` and your own client.`)}await hc(e);let n=await ke(e);n.wakesInstantly||d("This project is paused; the connection will wake it, which takes a few seconds.");let r=Qt("psql",["--host",n.host,"--port",String(n.port),"--username",n.user,"--dbname",n.database,...t],{stdio:"inherit",env:{...process.env,PGPASSWORD:n.password,...Zt(n.ssl)}});return new Promise((o,s)=>{r.on("error",a=>{if(a.code==="ENOENT"){s(new P("tool-missing","psql is not installed. `snoutdata db url` prints a connection string for any client."));return}s(new P("failed",String(a)))}),r.on("close",a=>o(a??0))})}function wc(e,t,n="DATABASE_URL"){let r=ar(e,".env"),o=`${n}=${t}`,s=gg(e);if(!sr(r))return xt(r,`${o}
483
+ `,{mode:384}),{path:r,replaced:!1,ignored:s};process.platform!=="win32"&&ug(r).mode&63&&ee(`${r} can be read by other users on this machine, and it holds a database password. \`chmod 600 ${r}\` closes it.`);let a=fc(r,"utf8"),l=new RegExp(`^${n}=.*$`,"m");return l.test(a)?(xt(r,a.replace(l,o)),{path:r,replaced:!0,ignored:s}):(mc(r,a.endsWith(`
480
484
  `)?`${o}
481
485
  `:`
482
486
  ${o}
483
- `),{path:r,replaced:!1,ignored:s})}function ag(e){let t=e;for(;!rr(or(t,".git"));){let s=og(t);if(s===t)return!1;t=s}let n=or(e,".gitignore"),r=rr(n)?mc(n,"utf8"):"";return r.split(/\r?\n/).some(s=>/^\/?(\.env|\.env\*|\*\.env|\.env\.\*)$/.test(s.trim()))?!1:(pc(n,r===""||r.endsWith(`
487
+ `),{path:r,replaced:!1,ignored:s})}function gg(e){let t=e;for(;!sr(ar(t,".git"));){let s=mg(t);if(s===t)return!1;t=s}let n=ar(e,".gitignore"),r=sr(n)?fc(n,"utf8"):"";return r.split(/\r?\n/).some(s=>/^\/?(\.env|\.env\*|\*\.env|\.env\.\*)$/.test(s.trim()))?!1:(mc(n,r===""||r.endsWith(`
484
488
  `)?`.env
485
489
  `:`
486
490
  .env
487
- `),!0)}async function wc(e,t={}){if(t.statusOnly){let{export:a}=await _t(e);return h({ref:e,export:a},()=>Lo(a)),0}let n=await Ut(e);if(!n.export.pending&&n.export.url&&!t.out)return h({ref:e,export:n.export},()=>Lo(n.export)),0;d("Taking a copy of the database. This runs on the server and can take a few minutes.");let r=await cg(e,t.timeoutMs);if(r.error&&H("failed",`The export did not finish: ${r.error}`,{ref:e}),!t.out)return h({ref:e,export:r},()=>Lo(r)),0;r.url||H("failed","The copy was taken, but no download link could be signed. Run this again to get one.",{ref:e});let o=await lg(r.url,t.out),s=r.rolesSql?ig(t.out):null;return s&&r.rolesSql&&xt(s,r.rolesSql.endsWith(`
491
+ `),!0)}async function bc(e,t={}){if(t.statusOnly){let{export:a}=await _t(e);return h({ref:e,export:a},()=>Bo(a)),0}let n=await Bt(e);if(!n.export.pending&&n.export.url&&!t.out)return h({ref:e,export:n.export},()=>Bo(n.export)),0;d("Taking a copy of the database. This runs on the server and can take a few minutes.");let r=await yg(e,t.timeoutMs);if(r.error&&K("failed",`The export did not finish: ${r.error}`,{ref:e}),!t.out)return h({ref:e,export:r},()=>Bo(r)),0;r.url||K("failed","The copy was taken, but no download link could be signed. Run this again to get one.",{ref:e});let o=await wg(r.url,t.out),s=r.rolesSql?hg(t.out):null;return s&&r.rolesSql&&xt(s,r.rolesSql.endsWith(`
488
492
  `)?r.rolesSql:`${r.rolesSql}
489
- `,"utf8"),h({ref:e,path:t.out,bytes:o,rolesPath:s},()=>{d(`Saved ${Ke(o)} to ${t.out}.`),d(w(`Into a SnoutData project: snoutdata db restore --file ${t.out} --ref <ref>`)),s?(d(`Saved the roles it needs to ${s}.`),d(w("Into any other Postgres, in this order:")),d(w(` psql --dbname <your database> -f ${s}`)),d(w(` pg_restore --dbname <your database> ${t.out}`)),d(w("The roles are created without passwords. Set them yourself if anything signs in as one."))):(d(w("Restore it with: pg_restore --no-owner --no-privileges --dbname <your database> "+t.out)),d(w("Owners and grants are skipped: this export carries no roles file.")))}),0}function ig(e){return e.replace(/\.[^./\\]*$/,"")+".roles.sql"}async function cg(e,t=30*6e4){let n=Date.now()+t;for(;;){let{export:r}=await _t(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 lg(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 fc(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 Lo(e){if(e.error){Q(`The last export did not finish: ${e.error}`);return}if(e.pending){d("An export is running. Ask again in a minute, or run `snoutdata db export`, which waits for it.");return}if(!e.completedAt){d("This project has never been exported.");return}d(`A copy taken ${Fe(e.completedAt)}, ${Ke(e.bytes??0)}.`),e.url?(process.stdout.write(`${e.url}
490
- `),e.urlExpiresAt&&d(w(`That link stops working ${Fe(e.urlExpiresAt)}.`))):d(w("The link has expired. Run the export again to sign a new one; the copy is kept."))}function Ke(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 bc(e,t){let n=t.file;n||H("usage","db restore needs --file, pointing at a dump. `snoutdata db export` writes one."),rr(n)||H("usage",`no file at ${n}`,{file:n});let r=await fc(n,"r"),o=new Uint8Array(512),s=await r.read(o,0,512,0);await r.close();let a=qi(o.slice(0,s.bytesRead)),l=await ke(e);l.wakesInstantly||d("This project is paused; the connection will wake it, which takes a few seconds.");let{projects:i}=await xe(),u=i.find(V=>V.ref===e),c=await dg(l);c===null&&H("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=Gi(a,{existingTables:c,readOnly:u?.readOnly===!0},{force:t.force});p.ok||H("conflict",p.reason,{ref:e,file:n,refusal:p.code});let f=null;if(p.tool==="pg_restore"){let V=await uc("pg_restore",["--list",n]),j=await uc("pg_restore",["--section=post-data","--file=-",n]);if((V.code!==0||j.code!==0)&&H("failed",`pg_restore could not read ${n}: ${(V.stderr||j.stderr).trim().slice(0,300)}`,{ref:e,file:n}),f=zi(V.stdout,j.stdout),f.products.length>0){let Y=await $t(e),R=O=>!!(O&&typeof O=="object"&&"enabled"in O&&O.enabled),ee=f.products.filter(O=>!R(Y[O]));ee.length>0&&H("conflict",`this dump holds ${ee.length>1?`${ee.slice(0,-1).join(", ")} and ${ee[ee.length-1]}`:ee[0]} data, and ${e} has ${ee.length===1?"it":"them"} off. Their tables are the platform's, so the product has to be on to take the rows. Switch ${ee.length===1?"it":"them"} on, wait a minute, and run this again:
491
- ${ee.map(O=>` snoutdata products enable ${O} --ref ${e}`).join(`
492
- `)}`,{ref:e,file:n,refusal:"products-off",products:ee})}}if(f&&f.platformData.length>0){let V=f.platformData.flatMap(({tables:R})=>R),j=await ug(l,V);j===null&&H("failed",`could not check ${e} for the tables this dump loads into.`,{ref:e});let Y=f.platformData.filter(({tables:R})=>R.some(ee=>j.includes(ee))).map(({product:R})=>R);Y.length>0&&H("conflict",`${Y.join(", ")} on ${e} ${Y.length===1?"has":"have"} not finished setting up ${Y.length===1?"its":"their"} tables yet. Run this again in a minute.`,{ref:e,file:n,refusal:"products-starting",products:Y})}d(`Restoring ${n} into ${e} with ${p.tool} (${p.format} format).`);let k=f?await pg(l,n,f):await nr(l,p.tool,n),v=Wi(k.stderr);for(let V of f?.notes??[])d(w(V));return k.code!==0&&v.fatal.length===0&&v.total>0?(h({ref:e,file:n,ok:!0,tool:p.tool,format:p.format,ignoredErrors:v.harmless},()=>{d(`Restored into ${e}.`),d(`${v.harmless} error${v.harmless===1?"":"s"} above ${v.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):(k.code!==0&&H("failed",`${p.tool} exited ${k.code}. Nothing here retried it: a half-finished restore is undone by deleting the project and making another.`,{ref:e,file:n,errors:v.fatal}),h({ref:e,file:n,ok:!0,tool:p.tool,format:p.format},()=>d(`Restored into ${e}.`)),0)}async function dg(e){return new Promise(t=>{let n=Zt("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,...Xt(e.ssl)}}),r="";n.stdout.on("data",o=>r+=String(o)),n.on("error",o=>{Q(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 ug(e,t){if(t.length===0)return Promise.resolve([]);let n=t.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return new Promise(r=>{let o=Zt("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,...Xt(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(`
493
- `).map(l=>l.trim()).filter(Boolean):null))})}function uc(e,t){return new Promise(n=>{let r=Zt(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=>{Q(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 pg(e,t,n){let r=or(sg(),`snoutdata-restore-${process.pid}-${Date.now()}`),o=0,s="";try{for(let{product:l,clear:i,lines:u}of n.platformData){if(i.length>0){xt(`${r}.sql`,`set role ${vo[l]};
493
+ `,"utf8"),h({ref:e,path:t.out,bytes:o,rolesPath:s},()=>{d(`Saved ${Ke(o)} to ${t.out}.`),d(w(`Into a SnoutData project: snoutdata db restore --file ${t.out} --ref <ref>`)),s?(d(`Saved the roles it needs to ${s}.`),d(w("Into any other Postgres, in this order:")),d(w(` psql --dbname <your database> -f ${s}`)),d(w(` pg_restore --dbname <your database> ${t.out}`)),d(w("The roles are created without passwords. Set them yourself if anything signs in as one."))):(d(w("Restore it with: pg_restore --no-owner --no-privileges --dbname <your database> "+t.out)),d(w("Owners and grants are skipped: this export carries no roles file.")))}),0}function hg(e){return e.replace(/\.[^./\\]*$/,"")+".roles.sql"}async function yg(e,t=30*6e4){let n=Date.now()+t;for(;;){let{export:r}=await _t(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 wg(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 gc(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 Bo(e){if(e.error){ee(`The last export did not finish: ${e.error}`);return}if(e.pending){d("An export is running. Ask again in a minute, or run `snoutdata db export`, which waits for it.");return}if(!e.completedAt){d("This project has never been exported.");return}d(`A copy taken ${Fe(e.completedAt)}, ${Ke(e.bytes??0)}.`),e.url?(process.stdout.write(`${e.url}
494
+ `),e.urlExpiresAt&&d(w(`That link stops working ${Fe(e.urlExpiresAt)}.`))):d(w("The link has expired. Run the export again to sign a new one; the copy is kept."))}function Ke(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 _c(e,t){let n=t.file;n||K("usage","db restore needs --file, pointing at a dump. `snoutdata db export` writes one."),sr(n)||K("usage",`no file at ${n}`,{file:n});let r=await gc(n,"r"),o=new Uint8Array(512),s=await r.read(o,0,512,0);await r.close();let a=Gi(o.slice(0,s.bytesRead)),l=await ke(e);l.wakesInstantly||d("This project is paused; the connection will wake it, which takes a few seconds.");let{projects:i}=await xe(),u=i.find(Y=>Y.ref===e),c=await bg(l);c===null&&K("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=zi(a,{existingTables:c,readOnly:u?.readOnly===!0},{force:t.force});p.ok||K("conflict",p.reason,{ref:e,file:n,refusal:p.code});let f=null;if(p.tool==="pg_restore"){let Y=await pc("pg_restore",["--list",n]),D=await pc("pg_restore",["--section=post-data","--file=-",n]);if((Y.code!==0||D.code!==0)&&K("failed",`pg_restore could not read ${n}: ${(Y.stderr||D.stderr).trim().slice(0,300)}`,{ref:e,file:n}),f=Ji(Y.stdout,D.stdout),f.products.length>0){let J=await $t(e),O=N=>!!(N&&typeof N=="object"&&"enabled"in N&&N.enabled),te=f.products.filter(N=>!O(J[N]));te.length>0&&K("conflict",`this dump holds ${te.length>1?`${te.slice(0,-1).join(", ")} and ${te[te.length-1]}`:te[0]} data, and ${e} has ${te.length===1?"it":"them"} off. Their tables are the platform's, so the product has to be on to take the rows. Switch ${te.length===1?"it":"them"} on, wait a minute, and run this again:
495
+ ${te.map(N=>` snoutdata products enable ${N} --ref ${e}`).join(`
496
+ `)}`,{ref:e,file:n,refusal:"products-off",products:te})}}if(f&&f.platformData.length>0){let Y=f.platformData.flatMap(({tables:O})=>O),D=await _g(l,Y);D===null&&K("failed",`could not check ${e} for the tables this dump loads into.`,{ref:e});let J=f.platformData.filter(({tables:O})=>O.some(te=>D.includes(te))).map(({product:O})=>O);J.length>0&&K("conflict",`${J.join(", ")} on ${e} ${J.length===1?"has":"have"} not finished setting up ${J.length===1?"its":"their"} tables yet. Run this again in a minute.`,{ref:e,file:n,refusal:"products-starting",products:J})}d(`Restoring ${n} into ${e} with ${p.tool} (${p.format} format).`);let k=f?await Sg(l,n,f):await or(l,p.tool,n),v=Wi(k.stderr);for(let Y of f?.notes??[])d(w(Y));return k.code!==0&&v.fatal.length===0&&v.total>0?(h({ref:e,file:n,ok:!0,tool:p.tool,format:p.format,ignoredErrors:v.harmless},()=>{d(`Restored into ${e}.`),d(`${v.harmless} error${v.harmless===1?"":"s"} above ${v.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):(k.code!==0&&K("failed",`${p.tool} exited ${k.code}. Nothing here retried it: a half-finished restore is undone by deleting the project and making another.`,{ref:e,file:n,errors:v.fatal}),h({ref:e,file:n,ok:!0,tool:p.tool,format:p.format},()=>d(`Restored into ${e}.`)),0)}async function bg(e){return new Promise(t=>{let n=Qt("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,...Zt(e.ssl)}}),r="";n.stdout.on("data",o=>r+=String(o)),n.on("error",o=>{ee(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 _g(e,t){if(t.length===0)return Promise.resolve([]);let n=t.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return new Promise(r=>{let o=Qt("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,...Zt(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(`
497
+ `).map(l=>l.trim()).filter(Boolean):null))})}function pc(e,t){return new Promise(n=>{let r=Qt(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=>{ee(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 Sg(e,t,n){let r=ar(fg(),`snoutdata-restore-${process.pid}-${Date.now()}`),o=0,s="";try{for(let{product:l,clear:i,lines:u}of n.platformData){if(i.length>0){xt(`${r}.sql`,`set role ${xo[l]};
494
498
  ${i.map(f=>`delete from ${f};`).join(`
495
499
  `)}
496
- `,"utf8");let p=await nr(e,"psql",`${r}.sql`,["--quiet"]);o=o||p.code,s+=p.stderr}xt(`${r}.platform`,`${u.join(`
500
+ `,"utf8");let p=await or(e,"psql",`${r}.sql`,["--quiet"]);o=o||p.code,s+=p.stderr}xt(`${r}.platform`,`${u.join(`
497
501
  `)}
498
- `,"utf8");let c=await nr(e,"pg_restore",t,["--data-only",`--role=${vo[l]}`,`--use-list=${r}.platform`]);o=o||c.code,s+=c.stderr}xt(`${r}.rest`,`${n.rest.join(`
502
+ `,"utf8");let c=await or(e,"pg_restore",t,["--data-only",`--role=${xo[l]}`,`--use-list=${r}.platform`]);o=o||c.code,s+=c.stderr}xt(`${r}.rest`,`${n.rest.join(`
499
503
  `)}
500
- `,"utf8");let a=await nr(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{rg(`${r}${a}`)}catch{}}}function nr(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=Zt(t,s,{stdio:["ignore","inherit","pipe"],env:{...process.env,PGPASSWORD:e.password,...Xt(e.ssl)}}),i="";l.stderr?.on("data",u=>{let c=String(u);i+=c,process.stderr.write(c)}),l.on("error",u=>{Q(u.code==="ENOENT"?`${t} is not installed, and this dump needs it.`:String(u)),a({code:127,stderr:i})}),l.on("close",u=>a({code:u??0,stderr:i}))})}re();be();te();function fg(e,t){let[n="list",r,...o]=e;if(o.length>0)throw new m(`db access ${n} takes one argument, not ${1+o.length}`);switch(n){case"list":if(r!==void 0)throw new m("db access list takes no argument");if(t!==void 0)throw new m("--level is for db access grant");return{action:"list"};case"grant":{if(!r||!r.includes("@"))throw new m("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 m(`--level is full or read, not ${JSON.stringify(s)}`);return{action:"grant",email:r,level:s}}case"revoke":if(!r)throw new m("db access revoke needs an email address or a role name");if(t!==void 0)throw new m("--level is for db access grant");return{action:"revoke",who:r};default:throw new m(`unknown command: db access ${n}. db access list|grant|revoke`)}}async function _c(e,t,n){let r=fg(t,n.level);if(r.action==="list"){let s=await _("cloud-project-db-access",{ref:e,action:"list"});h(s,()=>gg(s));return}if(r.action==="grant"){let s=await _("cloud-project-db-access",{ref:e,action:"grant",email:r.email,level:r.level});h(s,()=>hg(s));return}let o=await _("cloud-project-db-access",{ref:e,action:"revoke",who:r.who});h(o,()=>wg(o))}function gg(e){if(e.note&&d(e.note),e.access.length===0){d(`Nobody signs in to ${e.ref}'s database as themselves yet. \`snoutdata db access grant you@example.com --level full\`.`);return}process.stdout.write(`${L([["EMAIL","LEVEL","ROLE"],...e.access.map(n=>[n.you?x(n.email):n.email,n.level,n.role])])}
501
- `);let t=e.access.find(n=>n.you);t?.connection&&(d(""),d("You sign in with (psql 18; a browser approves it):"),d(w(` psql "${t.connection.keywords}"`)))}function hg(e){e.connection&&process.stdout.write(`${e.connection.keywords}
502
- `),d("");let t=e.outcome==="unchanged"?"already has":"now has";d(`${e.email} ${t} ${x(e.level)} access to ${e.ref}'s database, as ${e.role}${e.means?`: ${e.means}`:""}.`),e.outcome!=="unchanged"&&d(e.appliesIn),d("They sign in with psql 18 (libpq 18 with OAuth support) and approve the code it prints in a browser:"),e.connection&&d(w(` psql "${e.connection.keywords}"`))}function yg(e){return[...e.revoked.map(t=>`Took away ${t.email}'s ${t.level} access to ${e.ref}'s database (${t.role}).`),e.note]}function wg(e){let t=yg(e);for(let n of t.slice(0,-1))d(n);Q(t[t.length-1])}re();be();te();var bg=6e4;async function Bo(e,t={}){return _("cloud-project-realtime",{ref:e,...t.channel?{channel:t.channel}:{},...t.since!==void 0?{since:t.since}:{}})}function _g(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 m(`--since wants a duration like 10m, 2h or 1d, or a time like 2026-10-03T14:00, not "${e}"`)}function Sg(e){let t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Sc(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 kg={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 kc(e){let t=[e.presence_key?e.presence_key:null,e.socket!==void 0?`socket ${e.socket}`:null].filter(Boolean).join(", "),n=[Sg(e.at),kg[e.kind]??e.kind];return e.channel&&n.push(e.channel),t&&n.push(`(${t})`),e.reason?`${n.join(" ")}: ${e.reason}`:n.join(" ")}function vg(e){let t=Object.fromEntries(Object.entries(e).filter(([n])=>!n.startsWith("phx_ref")));return JSON.stringify(t)}function $g(e){let t=e.inspect;if(d(x(`Realtime for ${e.ref}`)),d(`${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){d("No channels are open.");return}for(let n of t.channels){let r=n.messages;if(d(""),d(x(`${n.name}${n.private?" (private)":""}`)+` ${n.clients.length} client${n.clients.length===1?"":"s"}`),d(w(` 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,Sc(Date.now()-a.joined_at),Sc(a.last_seen_ms_ago)+(a.last_seen_ms_ago!==null&&a.last_seen_ms_ago>bg?" (silent: likely gone)":"")]);d(L([["SOCKET","ROSTER KEY","JOINED","LAST HEARD"],...s]).split(`
504
+ `,"utf8");let a=await or(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{pg(`${r}${a}`)}catch{}}}function or(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=Qt(t,s,{stdio:["ignore","inherit","pipe"],env:{...process.env,PGPASSWORD:e.password,...Zt(e.ssl)}}),i="";l.stderr?.on("data",u=>{let c=String(u);i+=c,process.stderr.write(c)}),l.on("error",u=>{ee(u.code==="ENOENT"?`${t} is not installed, and this dump needs it.`:String(u)),a({code:127,stderr:i})}),l.on("close",u=>a({code:u??0,stderr:i}))})}oe();be();ne();function vg(e,t){let[n="list",r,...o]=e;if(o.length>0)throw new m(`db access ${n} takes one argument, not ${1+o.length}`);switch(n){case"list":if(r!==void 0)throw new m("db access list takes no argument");if(t!==void 0)throw new m("--level is for db access grant");return{action:"list"};case"grant":{if(!r||!r.includes("@"))throw new m("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 m(`--level is full or read, not ${JSON.stringify(s)}`);return{action:"grant",email:r,level:s}}case"revoke":if(!r)throw new m("db access revoke needs an email address or a role name");if(t!==void 0)throw new m("--level is for db access grant");return{action:"revoke",who:r};default:throw new m(`unknown command: db access ${n}. db access list|grant|revoke`)}}async function Sc(e,t,n){let r=vg(t,n.level);if(r.action==="list"){let s=await _("cloud-project-db-access",{ref:e,action:"list"});h(s,()=>$g(s));return}if(r.action==="grant"){let s=await _("cloud-project-db-access",{ref:e,action:"grant",email:r.email,level:r.level});h(s,()=>xg(s));return}let o=await _("cloud-project-db-access",{ref:e,action:"revoke",who:r.who});h(o,()=>Eg(o))}function $g(e){if(e.note&&d(e.note),e.access.length===0){d(`Nobody signs in to ${e.ref}'s database as themselves yet. \`snoutdata db access grant you@example.com --level full\`.`);return}process.stdout.write(`${B([["EMAIL","LEVEL","ROLE"],...e.access.map(n=>[n.you?x(n.email):n.email,n.level,n.role])])}
505
+ `);let t=e.access.find(n=>n.you);t?.connection&&(d(""),d("You sign in with (psql 18; a browser approves it):"),d(w(` psql "${t.connection.keywords}"`)))}function xg(e){e.connection&&process.stdout.write(`${e.connection.keywords}
506
+ `),d("");let t=e.outcome==="unchanged"?"already has":"now has";d(`${e.email} ${t} ${x(e.level)} access to ${e.ref}'s database, as ${e.role}${e.means?`: ${e.means}`:""}.`),e.outcome!=="unchanged"&&d(e.appliesIn),d("They sign in with psql 18 (libpq 18 with OAuth support) and approve the code it prints in a browser:"),e.connection&&d(w(` psql "${e.connection.keywords}"`))}function Pg(e){return[...e.revoked.map(t=>`Took away ${t.email}'s ${t.level} access to ${e.ref}'s database (${t.role}).`),e.note]}function Eg(e){let t=Pg(e);for(let n of t.slice(0,-1))d(n);ee(t[t.length-1])}oe();be();ne();var Ag=6e4;async function Ho(e,t={}){return _("cloud-project-realtime",{ref:e,...t.channel?{channel:t.channel}:{},...t.since!==void 0?{since:t.since}:{}})}function Rg(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 m(`--since wants a duration like 10m, 2h or 1d, or a time like 2026-10-03T14:00, not "${e}"`)}function Tg(e){let t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function kc(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 Og={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 vc(e){let t=[e.presence_key?e.presence_key:null,e.socket!==void 0?`socket ${e.socket}`:null].filter(Boolean).join(", "),n=[Tg(e.at),Og[e.kind]??e.kind];return e.channel&&n.push(e.channel),t&&n.push(`(${t})`),e.reason?`${n.join(" ")}: ${e.reason}`:n.join(" ")}function Ng(e){let t=Object.fromEntries(Object.entries(e).filter(([n])=>!n.startsWith("phx_ref")));return JSON.stringify(t)}function Ig(e){let t=e.inspect;if(d(x(`Realtime for ${e.ref}`)),d(`${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){d("No channels are open.");return}for(let n of t.channels){let r=n.messages;if(d(""),d(x(`${n.name}${n.private?" (private)":""}`)+` ${n.clients.length} client${n.clients.length===1?"":"s"}`),d(w(` 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,kc(Date.now()-a.joined_at),kc(a.last_seen_ms_ago)+(a.last_seen_ms_ago!==null&&a.last_seen_ms_ago>Ag?" (silent: likely gone)":"")]);d(B([["SOCKET","ROSTER KEY","JOINED","LAST HEARD"],...s]).split(`
503
507
  `).map(a=>` ${a}`).join(`
504
- `))}let o=Object.keys(n.presence);if(o.length>0){d(" roster:");for(let s of o)for(let a of n.presence[s].metas)d(` ${s} ${vg(a)}`)}}}async function vc(e,t={}){if(t.watch&&Cn())throw new m("--watch is for a person; with --json, poll `realtime inspect --json` or `realtime logs --since 1m --json`");let n=await Bo(e,{channel:t.channel});if(h(n.inspect,()=>$g(n)),!t.watch)return 0;d(""),d(w("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 Bo(e,{channel:t.channel,since:r});for(let a of s.events)process.stdout.write(`${kc(a)}
508
+ `))}let o=Object.keys(n.presence);if(o.length>0){d(" roster:");for(let s of o)for(let a of n.presence[s].metas)d(` ${s} ${Ng(a)}`)}}}async function $c(e,t={}){if(t.watch&&Dn())throw new m("--watch is for a person; with --json, poll `realtime inspect --json` or `realtime logs --since 1m --json`");let n=await Ho(e,{channel:t.channel});if(h(n.inspect,()=>Ig(n)),!t.watch)return 0;d(""),d(w("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 Ho(e,{channel:t.channel,since:r});for(let a of s.events)process.stdout.write(`${vc(a)}
505
509
  `);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(w(` now ${a||"no channels open"}
506
- `))}}}async function $c(e,t={}){let n=t.since?_g(t.since):0,r=await Bo(e,{channel:t.channel,since:n});return h({ref:r.ref,events:r.events,capacity:r.logCapacity},()=>{if(r.events.length===0){d(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(`${kc(o)}
507
- `);r.logCapacity!==null&&r.events.length>=r.logCapacity&&d(w(`The log keeps the newest ${r.logCapacity} events; older ones have gone.`))}),0}re();be();me();te();var sr=[{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 xc(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:!sr.some(r=>r.baseUrl&&r.kind==="openai"&&r.baseUrl===n)}function Pc(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 Ec(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 Pg(e){return e===void 0||e.trim()===""?void 0:Number(e)}function Ac(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(Pg);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 ir=class{send;constructor(t){this.send=t}providers(){return this.list("admin/providers")}putProvider(t,n){return this.call("PUT",`admin/providers/${qe(t)}`,n)}deleteProvider(t){return this.none("DELETE",`admin/providers/${qe(t)}`)}models(){return this.list("admin/models")}putModel(t,n){return this.call("PUT",`admin/models/${ar(t)}`,n)}deleteModel(t){return this.call("DELETE",`admin/models/${ar(t)}`)}routes(){return this.list("admin/routes")}putRoute(t,n){return this.call("PUT",`admin/routes/${ar(t)}`,n)}deleteRoute(t){return this.none("DELETE",`admin/routes/${ar(t)}`)}health(){return this.list("admin/health")}credentials(){return this.list("admin/credentials")}putCredential(t,n){return this.call("PUT",`admin/credentials/${qe(t)}`,n)}deleteCredential(t){return this.none("DELETE",`admin/credentials/${qe(t)}`)}keys(){return this.list("admin/keys")}createKey(t){return this.call("POST","admin/keys",t)}revokeKey(t){return this.none("DELETE",`admin/keys/${qe(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/${qe(t)}`,n)}deleteBudget(t){return this.none("DELETE",`admin/budgets/${qe(t)}`)}limits(){return this.list("admin/limits")}createLimit(t){return this.call("POST","admin/limits",t)}deleteLimit(t){return this.none("DELETE",`admin/limits/${qe(t)}`)}groups(){return this.list("admin/groups")}usage(t={}){return this.call("GET",`admin/usage${Rc(t)}`)}requests(t={}){return this.call("GET",`admin/requests${Rc(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 qe(e){return encodeURIComponent(e)}function ar(e){return e.split("/").map(qe).join("/")}function Rc(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 Qt(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}async function lr(e,t){return _("cloud-project-ai",t===void 0?{ref:e}:{ref:e,enable:t})}function Eg(e){if(e instanceof ge){let t=e.body?.error;if(t&&typeof t=="object"&&typeof t.message=="string")return new ge(e.status,t.message,typeof t.code=="string"?t.code:null,e.body)}return e}function Ag(e){return async(t,n,r)=>{try{return await _("cloud-project-ai",{ref:e,admin:{method:t,path:n,...r===void 0?{}:{body:r}}})}catch(o){throw Eg(o)}}}function fe(e){return new ir(Ag(e))}function Rg(e){return e instanceof ge&&(e.status===502||e.status===404&&e.serverCode!=="ai-off")}function Fo(e){return Number.isInteger(e)?`$${e}`:Math.abs(e*100-Math.round(e*100))<1e-9?`$${e.toFixed(2)}`:`$${e}`}function Oc(e){return e?`${Fo(e.input)} in, ${Fo(e.output)} out`:"no price"}function Nc(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 Ho(e){let t=e.period==="rolling"?`per ${e.days??"?"} days`:e.period==="since"?`since ${e.starts_on??"?"}`:`a ${e.period}`,n=Qt(e.amount);return`${n===null?`$${e.amount}`:Fo(n)} ${t}, ${e.hard?"hard":"soft"}`}function Tg(e){let t=Qt(e);return t===null?"-":`$${t.toFixed(t!==0&&t<.01?4:2)}`}function cr(e){return e===null?"never":new Date(e*1e3).toISOString().slice(0,16).replace("T"," ")}function Ic(e,t=Date.now()){return new Date(t-(e-1)*864e5).toISOString().slice(0,10)}function Og(e,t){return`${e} ${t}${e===1?"":"s"}`}async function Cc(e){let t=await lr(e);if(!t.ai.enabled){h({ref:e,enabled:!1,endpoint:t.ai.endpoint},()=>{d(`AI is off for ${e}.`),d(w(` snoutdata ai enable --ref ${e} ${t.ai.restartsDatabase}`))});return}let n=fe(e),[r,o,s]=await Promise.allSettled([n.models(),n.budgets(),n.usage({by:"day",from:Ic(30)})]),a=[r,o,s].find(f=>f.status==="rejected");if(a&&Rg(a.reason)){h({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 l=r.value,i=o.value,u=s.value.data,c=u.reduce((f,k)=>f+(Qt(k.cost)??0),0),p=u.reduce((f,k)=>f+k.requests,0);h({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!0,models:l,budgets:i,last30Days:{requests:p,cost:c}},()=>{d(`${x(`AI for ${e}`)}: on, at ${t.ai.endpoint}`),d(""),l.length===0?(d("No models yet. Add one:"),d(w(" snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):d(Dc(l)),d(""),d(i.length===0?"No budgets.":i.map(f=>`Budget: ${Nc(f)}, ${Ho(f)}`).join(`
508
- `)),d(`Last 30 days: ${Og(p,"request")}, $${c.toFixed(2)}.`)})}async function jc(e,t){let n=await lr(e,t);h(n,()=>{t?(d(`AI is on for ${e}. ${n.ai.restartsDatabase} The gateway answers at ${n.ai.endpoint} within a minute or two.`),d(w(" next: snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):d(`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 Dc(e){return L([["MODEL","PROVIDER","UPSTREAM","PRICE PER M TOKENS","SERVED"],...e.map(t=>[t.name,t.provider,t.upstream,Oc(t.price)+(t.price_from==="catalogue"?" (catalogue)":""),t.served?"yes":`no: ${t.problem??(t.enabled?"not served":"disabled")}`])])}async function Mc(e){let t=await fe(e).models();h(t,()=>{d(t.length===0?`No models on ${e}'s gateway yet.`:Dc(t))})}async function Lc(e){let t=await fe(e).providers();h(t,()=>{if(t.length===0){d(`No providers on ${e}'s gateway yet. \`snoutdata ai models add\` makes one with its first model.`);return}d(L([["PROVIDER","KIND","WHERE","KEY","MODELS"],...t.map(n=>[n.name,n.kind,n.kind==="bedrock"?n.region??"":n.base_url,Ng(n),n.models.join(", ")||"-"])]));for(let n of t.filter(r=>r.problem))Q(`${n.name}: ${n.problem}`)})}function Ng(e){return e.key==="environment"?"from the environment":e.key==="none"||e.credential===null?"none":e.credential_stored?"stored":"missing"}async function Uc(e,t){if(!t)throw new m("ai providers remove needs the provider's name (see `snoutdata ai providers`)");await fe(e).deleteProvider(t),h({ref:e,removed:t},()=>d(`Removed the provider ${t}.`))}function Ig(e){let t=sr.map(r=>r.id).join("|");if(!e)throw new m(`ai models add needs --source ${t}: where the model runs`);let n=sr.find(r=>r.id===e);if(!n)throw new m(`--source is one of ${t}, not "${e}"`);return n}function Cg(e){d(x(`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){d(""),d(x(n));for(let s of r.steps)d(` - ${s}`);let o=r.console??r.link;o&&d(w(` ${o.label}: ${o.href}`))}d("")}function jg(e,t,n){if(n)return{name:n,existing:t.find(o=>o.name===n)??null};let r=t.filter(o=>xc(e,o));if(r.length===1)return{name:r[0].name,existing:r[0]};if(r.length>1)throw new m(`${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 Bc(e,t,n){let r=Ig(n.source),o=n.upstream?.trim();if(!o)throw Cg(r),new m(`Give the model's id as ${r.name} names it, with --model (for example ${r.model.example})`);let s=t?.trim()||Pc(o),a=fe(e),[l,i]=await Promise.all([a.providers(),a.models()]);if(i.some(R=>R.name===s))throw new m(`${e} already has a model called ${s}. Name this one differently, or remove that one first.`);let{name:u,existing:c}=jg(r,l,n.provider);if(c&&c.kind!==r.kind)throw new m(`The provider ${u} speaks ${c.kind}, not ${r.name}: choose another --provider name`);if(c?.origin==="file"&&n.stdin)throw new m(`The provider ${u} comes from the gateway's providers file, so its key is set there, not here`);let p=n.stdin?await vt():void 0,f=r.auth==="bedrock"&&n.accessKeyId!==void 0,k=null;if(!c){if(r.auth!=="optional"&&!p)throw new m(f?"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 R=Ec(r,u,{baseUrl:n.baseUrl??r.baseUrl,region:n.region,apiKey:f?void 0:p,aws:f,accessKeyId:n.accessKeyId,secretAccessKey:f?p:void 0,authHeader:n.authHeader});if("problem"in R)throw new m(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":R.problem);k=R}let v=Ac({provider:u,upstream:o,input:n.priceIn,output:n.priceOut,caching:r.caching,enabled:!0,access:"everyone"});if("problem"in v)throw new m(v.problem.replace("input and the output rate","--price-in and --price-out"));let V=!1,j=!1,Y;try{if(k&&(await a.putProvider(u,k.provider),V=!0),Y=await a.putModel(s,v.model),j=!0,k?.credential)await a.putCredential(u,k.credential);else if(c&&p){if(!c.credential)throw new m(`The provider ${u} takes no key`);await a.putCredential(c.credential,f?{access_key_id:n.accessKeyId,secret_access_key:p}:{api_key:p})}}catch(R){throw j&&await a.deleteModel(s).catch(()=>{}),V&&await a.deleteProvider(u).catch(()=>{}),R}Y=(await a.models()).find(R=>R.name===s)??Y,h(Y,()=>{d(`Added ${x(s)} (${o} on ${u}${V?", a new provider":""}), at ${Oc(Y.price)}${Y.price_from==="catalogue"?" from the shipped catalogue":""}.`),Y.price||Q("Nothing prices this model, so signed-in users are refused it. Give it a price with --price-in and --price-out."),!Y.served&&Y.problem&&Q(`It is not served yet: ${Y.problem}`),d(w(` snoutdata ai test --model ${s}`))})}async function Fc(e,t){if(!t)throw new m("ai models remove needs the model's name (see `snoutdata ai models`)");let n=await fe(e).deleteModel(t);h(n,()=>d(n.disabled?`${t} comes from the gateway's providers file, so it was disabled rather than removed.`:`Removed ${t}.`))}function Dg(e){return(e??"").split(",").map(t=>t.trim()).filter(t=>t!=="")}function Mg(e){return L([["ROUTE","TRIES, IN ORDER","SORT","SKIPS"],...e.map(t=>[t.name,t.tried.join(", ")||"-",t.sort,t.skipped.join(", ")||"-"])])}async function Hc(e){let t=await fe(e).routes();h(t,()=>{if(t.length===0){d(`No routes on ${e}'s gateway. A route is one name for several models, each tried when the one before fails:`),d(w(" snoutdata ai routes set NAME --models first,second [--sort price]"));return}d(Mg(t))})}async function Kc(e,t,n){if(!t)throw new m("ai routes set needs the route's name: snoutdata ai routes set NAME --models first,second");let r=Dg(n.models);if(r.length===0)throw new m("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 m(`--sort is order (as written), price (the cheapest first), latency or throughput (the fastest first, as measured), not ${o}`);let s=fe(e);await s.putRoute(t,{targets:r,sort:o});let a=(await s.routes()).find(l=>l.name===t);h(a??{name:t,targets:r,sort:o},()=>{let l=a?.tried??r;d(`${x(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&&Q(`skipped, not served: ${a.skipped.join(", ")}`),d(w(` Call it as the model "${t}", or: snoutdata ai test --model ${t}`))})}async function qc(e,t){if(!t)throw new m("ai routes remove needs the route's name (see `snoutdata ai routes`)");await fe(e).deleteRoute(t),h({name:t,removed:!0},()=>d(`Removed the route ${t}. Its models are untouched.`))}function Lg(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 ${cr(e.expires_at).slice(0,10)}`:"active"}async function Gc(e){let t=await fe(e).keys();h(t,()=>{if(t.length===0){d(`No keys on ${e}'s gateway. \`snoutdata ai keys create --name my-server\` makes one for a server.`);return}d(L([["NAME","ID","KEY","MODELS","CREATED","LAST USED","STATE"],...t.map(n=>[n.name,n.id,n.hint,n.models?.join(", ")??"all",cr(n.created_at),n.last_used_at!==null?cr(n.last_used_at):n.last_used_on??"never",Lg(n)])]))})}async function Wc(e,t){if(!t.name)throw new m("ai keys create needs --name: what the key is for, shown in ai keys");if(t.expiresDays!==void 0&&t.expiresDays<=0)throw new m("--expires is a number of days, 1 or more");let n=t.models?.split(",").map(s=>s.trim()).filter(Boolean),r=await fe(e).createKey({name:t.name,...n&&n.length>0?{models:n}:{},...t.expiresDays!==void 0?{expires_in:t.expiresDays*86400}:{}}),o=await lr(e);h({...r,endpoint:o.ai.endpoint},()=>{process.stdout.write(`${r.key}
509
- `),d(""),d(`${x(r.name)}: ${r.models?`for ${r.models.join(", ")}`:"for every model"}, ${r.expires_at?`until ${cr(r.expires_at)}`:"until revoked"}.`),d("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."),d(w(` OPENAI_BASE_URL=${o.ai.endpoint} OPENAI_API_KEY=<that key>`))})}async function zc(e,t){if(!t)throw new m("ai keys revoke needs the key's id (see `snoutdata ai keys`)");await fe(e).revokeKey(t),h({ref:e,revoked:t},()=>d(`Revoked ${t}. A call with it is refused from now on.`))}async function Jc(e){let t=await fe(e).budgets();h(t,()=>{if(t.length===0){d(`No budgets on ${e}'s gateway. A browser call needs two hard ones:`),d(w(" snoutdata ai budgets set project --amount 5")),d(w(" snoutdata ai budgets set users --amount 0.50"));return}d(L([["ID","FOR","BUDGET"],...t.map(n=>[n.id,Nc(n),Ho(n)])]))})}function Ug(e){if(e==="project"||e==="users")return e;throw new m("ai budgets set takes project (the whole project) or users (each signed-in user)")}function Bg(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 Vc(e,t,n){let r=Ug(t),o=Number(n.amount);if(n.amount===void 0||!Number.isFinite(o)||o<0)throw new m("ai budgets set needs --amount, in dollars, zero or more");let s=n.period??"day";if(s!=="day"&&s!=="month")throw new m("--period is day or month");let a=fe(e),l=Bg(await a.budgets(),r,s),i=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}:{}});h(i,()=>d(`${l?"Changed":"Set"}: ${r==="users"?"every user":"the project"}, ${Ho(i)}.`))}async function Yc(e,t){if(!t)throw new m("ai budgets remove needs the budget's id (see `snoutdata ai budgets`)");await fe(e).deleteBudget(t),h({ref:e,removed:t},()=>d(`Removed the budget ${t}.`))}var Tc=["day","model","provider","operation","key","user","group"];async function Xc(e,t){let n=t.by??"model";if(!Tc.includes(n))throw new m(`--by is one of ${Tc.join("|")}`);let r=t.days??30;if(r<1||r>366)throw new m("--days is 1 to 366");let o=await fe(e).usage({by:n,from:Ic(r)});h(o,()=>{if(o.data.length===0){d(`No calls to ${e}'s gateway from ${o.from} to ${o.to}.`);return}let s=o.data.reduce((a,l)=>a+(Qt(l.cost)??0),0);d(L([[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),Tg(a.cost)+(a.unpriced>0?` (+${a.unpriced} unpriced)`:"")])])),d(`${o.from} to ${o.to}: $${s.toFixed(2)}.`)})}async function Zc(e,t){let n=await lr(e);if(!n.ai.enabled)throw new P("not-found",`AI is off for ${e}. Switch it on first: snoutdata ai enable.`);let r=fe(e),s=(await r.models()).filter(k=>k.served&&k.embeddings===null),a=t.model??s[0]?.name;if(!a)throw new P("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}),i=Date.now(),u=0,c={};try{let k=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."}]})});u=k.status;let v=await k.text();try{c=v?JSON.parse(v):{}}catch{c={error:{message:Bn(k.status,k.statusText,v)}}}}finally{await r.revokeKey(l.id).catch(()=>{})}let p=Date.now()-i;if(u<200||u>=300){let k=c.error?.message??`the gateway answered ${u}`;throw new P(Ue(u,c.error?.code??null),`${a} through ${e}'s gateway: ${k}`,{model:a,status:u,gatewayCode:c.error?.code??null})}let f=c.choices?.[0]?.message?.content??"";return h({ref:e,model:a,reply:f,usage:c.usage??null,ms:p},()=>{process.stdout.write(`${f}
510
- `),d(w(`${a}, ${p} ms, ${c.usage?.prompt_tokens??"?"} tokens in, ${c.usage?.completion_tokens??"?"} out, through ${n.ai.endpoint}`))}),0}re();be();te();import{readFile as Hg}from"node:fs/promises";var Kg="api.snoutdata.com";function tl(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}.${Kg}/auth/v1/callback`,anonymous:{enabled:t.anonymous?.enabled===!0,ready:t.anonymous?.ready===!0}}}async function qg(e){return tl(e,await _("cloud-project-auth",{ref:e,action:"status"}))}async function dr(e,t){return tl(e,await _("cloud-project-auth",{ref:e,action:"settings",settings:t}))}function Ko(e){let t=e.google,n="off";t.ready?n=x("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(`${L([["auth",e.enabled?x("on"):"off"],["site url",e.siteUrl??w("not set")],["redirects",e.redirects.length?e.redirects.join(", "):w("none")],["google",n],["google client id",t.clientId??w("not set")],["google callback",e.googleCallback],["guests",e.anonymous.ready?x("on"):e.anonymous.enabled?"switched on, not applied yet":"off"]])}
511
- `),e.enabled||d(w(` snoutdata products enable auth --ref ${e.ref}`))}async function Gg(){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 nl(e,t,n,r){if(t===void 0||t==="show"){let o=await qg(e);h(o,()=>Ko(o));return}if(t==="google"){if(n[0]==="off"){let a=await dr(e,{googleEnabled:!1});h(a,()=>d("Google sign-in is off. Your auth service restarts within about a minute."));return}if(n.length>0)throw new m('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 Gg();if(!a)throw new m("--stdin read nothing. Pipe the Google client secret in.");o.googleClientSecret=a}let s=await dr(e,o);h(s,()=>{s.google.ready?d("Google sign-in is on. Your auth service restarts within about a minute."):Ko(s),d(w(` 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 m('auth anonymous takes "on" or "off"');let s=await dr(e,{anonymousEnabled:o==="on"});h(s,()=>{o==="off"?d("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?d("Guest sign-in is on: guestSignIn() gives a browser a session with no email or password. Your auth service restarts within about a minute."):(d("Guest sign-in is switched on, and takes effect when auth is."),d(w(` 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 m("auth redirects needs --site-url and/or --allow URL,URL (an empty --allow= clears the list)");let s=await dr(e,o);h(s,()=>Ko(s));return}if(t==="templates"){let o=await _("cloud-project-auth",{ref:e,action:"templates"});h(o,()=>el(o.templates));return}if(t==="template"){let o=n[0];if(!o||!Qc.includes(o))throw new m(`auth template needs a kind: ${Qc.join(", ")}`);let s;if(n[1]==="reset")s={kind:o,reset:!0};else{if(!r.file)throw new m(`auth template ${o} needs --file body.html (and --subject), or "reset"`);let l=await Hg(r.file,"utf8"),i=await _("cloud-project-auth",{ref:e,action:"templates"}),u=r.subject??i.templates.find(c=>c.kind===o)?.subject;s={kind:o,subject:u,body:l}}let a=await _("cloud-project-auth",{ref:e,action:"template",template:s});h(a,()=>{el(a.templates),d(w(" Your auth service restarts with it within about a minute."))});return}throw new m(`unknown command: auth ${t}. auth [google [off] | anonymous on|off | redirects | templates | template KIND]`)}var Qc=["confirmation","recovery","magic_link","invite","email_change"];function el(e){process.stdout.write(`${L([["KIND","SOURCE","SUBJECT"],...e.map(t=>[t.kind,t.custom?x("yours"):"ours",t.subject])])}
512
- `)}re();te();me();import{createHash as uh}from"node:crypto";import{existsSync as ph,readdirSync as mh,readFileSync as fh,statSync as gh}from"node:fs";import{isAbsolute as hh,join as Jo,relative as yh,resolve as wh}from"node:path";function Wg(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function ur(e,t,n={}){let r=Wg(e),o=new Map(r.map(u=>[u.name,u])),s=[];for(let u of t){let c=o.get(u.name);if(!c){s.push({code:"missing",name:u.name,reason:`${u.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}c.checksum!==u.checksum&&s.push({code:"changed",name:u.name,reason:`${u.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(u=>u.name).sort((u,c)=>u<c?-1:u>c?1:0)[t.length-1],l=new Set(t.map(u=>u.name)),i=[];for(let u of r)if(!l.has(u.name)){if(a!==void 0&&u.name<a&&!n.outOfOrder){s.push({code:"out-of-order",name:u.name,reason:`${u.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}i.push(u)}return s.length>0?{ok:!1,problems:s}:{ok:!0,pending:i}}function Pt(e){return!/^[\t ]*--[\t ]*snoutdata:no-transaction[\t ]*$/im.test(e)}import{createHash as qo,createHmac as pr,pbkdf2Sync as zg,randomBytes as Jg,timingSafeEqual as Vg}from"node:crypto";import{readFileSync as Yg}from"node:fs";import{homedir as Xg}from"node:os";import{connect as Zg,isIP as Qg}from"node:net";import{connect as eh}from"node:tls";var et=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)}},se=class extends Error{constructor(t){super(t),this.name="PgConnectError"}},th=196608,nh=80877103;function rl(e,t){let n=Buffer.alloc(5);return n.write(e,0,"latin1"),n.writeInt32BE(t.length+4,1),Buffer.concat([n,t])}function Qe(e){return Buffer.concat([Buffer.from(e,"utf8"),Buffer.from([0])])}function rh(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 ol(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 Go=class{constructor(t,n=Jg(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(v=>[v.slice(0,1),v.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 se("the server answered the password exchange with a nonce that is not ours");if(!o||!Number.isInteger(s)||s<1)throw new se("the server answered the password exchange with no salt or iteration count");let a=zg(this.password.normalize("NFKC"),Buffer.from(o,"base64"),s,32,"sha256"),l=pr("sha256",a).update("Client Key").digest(),i=qo("sha256").update(l).digest(),u=`c=biws,r=${r}`,c=`${this.firstBare},${t},${u}`,p=pr("sha256",i).update(c).digest(),f=Buffer.alloc(l.length);for(let v=0;v<f.length;v++)f[v]=l[v]^p[v];let k=pr("sha256",a).update("Server Key").digest();return this.serverSignature=pr("sha256",k).update(c).digest(),`${u},p=${f.toString("base64")}`}verify(t){let n=/(?:^|,)e=([^,]*)/.exec(t);if(n)throw new se(`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||!Vg(o,this.serverSignature))throw new se("the server could not prove it knows the password, so this is not the database it claims to be")}},Wo=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 se(n.message))),t.on("close",()=>this.fail(new se("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 se("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 oh(e){return new Promise((t,n)=>{let r=l=>{if(a(),l.length!==1){n(new se("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 se(l.message))},s=()=>{a(),n(new se("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 sh(e,t){return new Promise((n,r)=>{let o=Zg({host:e,port:t}),s=a=>r(new se(`could not connect to ${e}:${t}: ${a.message}`));o.once("connect",()=>{o.off("error",s),n(o)}),o.once("error",s)})}async function ah(e,t,n,r){let o=await sh(e.host,e.port);if(r(o),t==="disable")return o;let s=Buffer.alloc(8);if(s.writeInt32BE(8,0),s.writeInt32BE(nh,4),o.write(s),await oh(o)!=="S"){if(t==="allow"||t==="prefer")return o;throw new se(`${e.host} does not accept TLS, and this connection requires it (sslmode ${t})`)}let l=t==="verify-ca"||t==="verify-full";return new Promise((i,u)=>{let c=eh({socket:o,host:e.host,...Qg(e.host)===0?{servername:e.host}:{},rejectUnauthorized:l,...l&&n?{ca:Yg(n,"utf8")}:{},...t==="verify-ca"?{checkServerIdentity:()=>{}}:{}});r(c),c.once("secureConnect",()=>{c.off("error",p),i(c)});let p=f=>u(new se(`TLS to ${e.host} failed: ${f.message}`));c.once("error",p)})}var mr=class e{constructor(t,n){this.socket=t;this.reader=n}static async open(t,n={}){let r=n.env??process.env,o=Yt(t.ssl,r,n.home??Xg()),s=o.rootCert??(r.PGSSLROOTCERT||void 0),a=o.mode==="require"&&s?"verify-ca":o.mode,l=n.connectTimeoutMs??12e4,i=[],u=()=>{for(let f of i)f.destroy()},c,p=new Promise((f,k)=>{c=setTimeout(()=>{u(),k(new se(`${t.host}:${t.port} did not answer within ${Math.round(l/1e3)} seconds`))},l)});try{return await Promise.race([(async()=>{let f=await ah(t,a,s,v=>i.push(v)),k=new e(f,new Wo(f));return await k.startup(t),k})(),p])}catch(f){throw u(),f}finally{clearTimeout(c)}}send(t,n){this.socket.write(rl(t,n))}async startup(t){let n=Buffer.concat([...[["user",t.user],["database",t.database],["application_name","snoutdata"],["client_encoding","UTF8"]].flatMap(([s,a])=>[Qe(s),Qe(a)]),Buffer.from([0])]),r=Buffer.alloc(8);r.writeInt32BE(n.length+8,0),r.writeInt32BE(th,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",Qe(t.password));else if(a===5){let l=qo("md5").update(t.password+t.user).digest("hex"),i=qo("md5").update(Buffer.concat([Buffer.from(l),s.body.subarray(4,8)])).digest("hex");this.send("p",Qe(`md5${i}`))}else if(a===10){let l=rh(s.body,4);if(!l.includes("SCRAM-SHA-256"))throw new se(`the server asked for ${l.join(", ")||"a password exchange"}, which this client does not speak`);o=new Go(t.password);let i=Buffer.from(o.first(),"utf8"),u=Buffer.alloc(4);u.writeInt32BE(i.length,0),this.send("p",Buffer.concat([Qe("SCRAM-SHA-256"),u,i]))}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 se(`the server asked for an authentication method (${a}) this client does not speak`);break}case"E":throw new et(ol(s.body));case"Z":return;default:break}}}async query(t,n){this.send("Q",Qe(t));let r=[],o=null,s=null;for(;;){let a=await this.reader.next();switch(a.type){case"T":r=[];break;case"D":{let l=a.body.readInt16BE(0),i=[],u=2;for(let c=0;c<l;c++){let p=a.body.readInt32BE(u);u+=4,p<0?i.push(null):(i.push(a.body.toString("utf8",u,u+p)),u+=p)}r.push(i);break}case"C":o=a.body.toString("utf8",0,Math.max(0,a.body.indexOf(0)));break;case"E":s??=new et(ol(a.body));break;case"G":n===void 0?this.send("f",Qe("db push has 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",Qe("COPY BOTH is not something a migration can do"));break;case"Z":if(s)throw s;return{rows:r,command:o};default:break}}}close(){this.socket.destroyed||this.socket.end(rl("X",Buffer.alloc(0)))}};function sl(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(u=>u===`
510
+ `))}}}async function xc(e,t={}){let n=t.since?Rg(t.since):0,r=await Ho(e,{channel:t.channel,since:n});return h({ref:r.ref,events:r.events,capacity:r.logCapacity},()=>{if(r.events.length===0){d(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(`${vc(o)}
511
+ `);r.logCapacity!==null&&r.events.length>=r.logCapacity&&d(w(`The log keeps the newest ${r.logCapacity} events; older ones have gone.`))}),0}oe();be();me();ne();var ir=[{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 Pc(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:!ir.some(r=>r.baseUrl&&r.kind==="openai"&&r.baseUrl===n)}function Ec(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 Ac(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 jg(e){return e===void 0||e.trim()===""?void 0:Number(e)}function Rc(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(jg);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 lr=class{send;constructor(t){this.send=t}providers(){return this.list("admin/providers")}putProvider(t,n){return this.call("PUT",`admin/providers/${qe(t)}`,n)}deleteProvider(t){return this.none("DELETE",`admin/providers/${qe(t)}`)}models(){return this.list("admin/models")}putModel(t,n){return this.call("PUT",`admin/models/${cr(t)}`,n)}deleteModel(t){return this.call("DELETE",`admin/models/${cr(t)}`)}routes(){return this.list("admin/routes")}putRoute(t,n){return this.call("PUT",`admin/routes/${cr(t)}`,n)}deleteRoute(t){return this.none("DELETE",`admin/routes/${cr(t)}`)}health(){return this.list("admin/health")}credentials(){return this.list("admin/credentials")}putCredential(t,n){return this.call("PUT",`admin/credentials/${qe(t)}`,n)}deleteCredential(t){return this.none("DELETE",`admin/credentials/${qe(t)}`)}keys(){return this.list("admin/keys")}createKey(t){return this.call("POST","admin/keys",t)}revokeKey(t){return this.none("DELETE",`admin/keys/${qe(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/${qe(t)}`,n)}deleteBudget(t){return this.none("DELETE",`admin/budgets/${qe(t)}`)}limits(){return this.list("admin/limits")}createLimit(t){return this.call("POST","admin/limits",t)}deleteLimit(t){return this.none("DELETE",`admin/limits/${qe(t)}`)}groups(){return this.list("admin/groups")}usage(t={}){return this.call("GET",`admin/usage${Tc(t)}`)}requests(t={}){return this.call("GET",`admin/requests${Tc(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 qe(e){return encodeURIComponent(e)}function cr(e){return e.split("/").map(qe).join("/")}function Tc(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 en(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}async function ur(e,t){return _("cloud-project-ai",t===void 0?{ref:e}:{ref:e,enable:t})}function Dg(e){if(e instanceof ge){let t=e.body?.error;if(t&&typeof t=="object"&&typeof t.message=="string")return new ge(e.status,t.message,typeof t.code=="string"?t.code:null,e.body)}return e}function Mg(e){return async(t,n,r)=>{try{return await _("cloud-project-ai",{ref:e,admin:{method:t,path:n,...r===void 0?{}:{body:r}}})}catch(o){throw Dg(o)}}}function fe(e){return new lr(Mg(e))}function Lg(e){return e instanceof ge&&(e.status===502||e.status===404&&e.serverCode!=="ai-off")}function Ko(e){return Number.isInteger(e)?`$${e}`:Math.abs(e*100-Math.round(e*100))<1e-9?`$${e.toFixed(2)}`:`$${e}`}function Nc(e){return e?`${Ko(e.input)} in, ${Ko(e.output)} out`:"no price"}function Ic(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 qo(e){let t=e.period==="rolling"?`per ${e.days??"?"} days`:e.period==="since"?`since ${e.starts_on??"?"}`:`a ${e.period}`,n=en(e.amount);return`${n===null?`$${e.amount}`:Ko(n)} ${t}, ${e.hard?"hard":"soft"}`}function Ug(e){let t=en(e);return t===null?"-":`$${t.toFixed(t!==0&&t<.01?4:2)}`}function dr(e){return e===null?"never":new Date(e*1e3).toISOString().slice(0,16).replace("T"," ")}function Cc(e,t=Date.now()){return new Date(t-(e-1)*864e5).toISOString().slice(0,10)}function Bg(e,t){return`${e} ${t}${e===1?"":"s"}`}async function jc(e){let t=await ur(e);if(!t.ai.enabled){h({ref:e,enabled:!1,endpoint:t.ai.endpoint},()=>{d(`AI is off for ${e}.`),d(w(` snoutdata ai enable --ref ${e} ${t.ai.restartsDatabase}`))});return}let n=fe(e),[r,o,s]=await Promise.allSettled([n.models(),n.budgets(),n.usage({by:"day",from:Cc(30)})]),a=[r,o,s].find(f=>f.status==="rejected");if(a&&Lg(a.reason)){h({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 l=r.value,i=o.value,u=s.value.data,c=u.reduce((f,k)=>f+(en(k.cost)??0),0),p=u.reduce((f,k)=>f+k.requests,0);h({ref:e,enabled:!0,endpoint:t.ai.endpoint,serving:!0,models:l,budgets:i,last30Days:{requests:p,cost:c}},()=>{d(`${x(`AI for ${e}`)}: on, at ${t.ai.endpoint}`),d(""),l.length===0?(d("No models yet. Add one:"),d(w(" snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):d(Mc(l)),d(""),d(i.length===0?"No budgets.":i.map(f=>`Budget: ${Ic(f)}, ${qo(f)}`).join(`
512
+ `)),d(`Last 30 days: ${Bg(p,"request")}, $${c.toFixed(2)}.`)})}async function Dc(e,t){let n=await ur(e,t);h(n,()=>{t?(d(`AI is on for ${e}. ${n.ai.restartsDatabase} The gateway answers at ${n.ai.endpoint} within a minute or two.`),d(w(" next: snoutdata ai models add --source openai --model gpt-4o-mini --stdin < key.txt"))):d(`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 Mc(e){return B([["MODEL","PROVIDER","UPSTREAM","PRICE PER M TOKENS","SERVED"],...e.map(t=>[t.name,t.provider,t.upstream,Nc(t.price)+(t.price_from==="catalogue"?" (catalogue)":""),t.served?"yes":`no: ${t.problem??(t.enabled?"not served":"disabled")}`])])}async function Lc(e){let t=await fe(e).models();h(t,()=>{d(t.length===0?`No models on ${e}'s gateway yet.`:Mc(t))})}async function Uc(e){let t=await fe(e).providers();h(t,()=>{if(t.length===0){d(`No providers on ${e}'s gateway yet. \`snoutdata ai models add\` makes one with its first model.`);return}d(B([["PROVIDER","KIND","WHERE","KEY","MODELS"],...t.map(n=>[n.name,n.kind,n.kind==="bedrock"?n.region??"":n.base_url,Fg(n),n.models.join(", ")||"-"])]));for(let n of t.filter(r=>r.problem))ee(`${n.name}: ${n.problem}`)})}function Fg(e){return e.key==="environment"?"from the environment":e.key==="none"||e.credential===null?"none":e.credential_stored?"stored":"missing"}async function Bc(e,t){if(!t)throw new m("ai providers remove needs the provider's name (see `snoutdata ai providers`)");await fe(e).deleteProvider(t),h({ref:e,removed:t},()=>d(`Removed the provider ${t}.`))}function Hg(e){let t=ir.map(r=>r.id).join("|");if(!e)throw new m(`ai models add needs --source ${t}: where the model runs`);let n=ir.find(r=>r.id===e);if(!n)throw new m(`--source is one of ${t}, not "${e}"`);return n}function Kg(e){d(x(`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){d(""),d(x(n));for(let s of r.steps)d(` - ${s}`);let o=r.console??r.link;o&&d(w(` ${o.label}: ${o.href}`))}d("")}function qg(e,t,n){if(n)return{name:n,existing:t.find(o=>o.name===n)??null};let r=t.filter(o=>Pc(e,o));if(r.length===1)return{name:r[0].name,existing:r[0]};if(r.length>1)throw new m(`${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 Fc(e,t,n){let r=Hg(n.source),o=n.upstream?.trim();if(!o)throw Kg(r),new m(`Give the model's id as ${r.name} names it, with --model (for example ${r.model.example})`);let s=t?.trim()||Ec(o),a=fe(e),[l,i]=await Promise.all([a.providers(),a.models()]);if(i.some(O=>O.name===s))throw new m(`${e} already has a model called ${s}. Name this one differently, or remove that one first.`);let{name:u,existing:c}=qg(r,l,n.provider);if(c&&c.kind!==r.kind)throw new m(`The provider ${u} speaks ${c.kind}, not ${r.name}: choose another --provider name`);if(c?.origin==="file"&&n.stdin)throw new m(`The provider ${u} comes from the gateway's providers file, so its key is set there, not here`);let p=n.stdin?await vt():void 0,f=r.auth==="bedrock"&&n.accessKeyId!==void 0,k=null;if(!c){if(r.auth!=="optional"&&!p)throw new m(f?"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 O=Ac(r,u,{baseUrl:n.baseUrl??r.baseUrl,region:n.region,apiKey:f?void 0:p,aws:f,accessKeyId:n.accessKeyId,secretAccessKey:f?p:void 0,authHeader:n.authHeader});if("problem"in O)throw new m(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":O.problem);k=O}let v=Rc({provider:u,upstream:o,input:n.priceIn,output:n.priceOut,caching:r.caching,enabled:!0,access:"everyone"});if("problem"in v)throw new m(v.problem.replace("input and the output rate","--price-in and --price-out"));let Y=!1,D=!1,J;try{if(k&&(await a.putProvider(u,k.provider),Y=!0),J=await a.putModel(s,v.model),D=!0,k?.credential)await a.putCredential(u,k.credential);else if(c&&p){if(!c.credential)throw new m(`The provider ${u} takes no key`);await a.putCredential(c.credential,f?{access_key_id:n.accessKeyId,secret_access_key:p}:{api_key:p})}}catch(O){throw D&&await a.deleteModel(s).catch(()=>{}),Y&&await a.deleteProvider(u).catch(()=>{}),O}J=(await a.models()).find(O=>O.name===s)??J,h(J,()=>{d(`Added ${x(s)} (${o} on ${u}${Y?", a new provider":""}), at ${Nc(J.price)}${J.price_from==="catalogue"?" from the shipped catalogue":""}.`),J.price||ee("Nothing prices this model, so signed-in users are refused it. Give it a price with --price-in and --price-out."),!J.served&&J.problem&&ee(`It is not served yet: ${J.problem}`),d(w(` snoutdata ai test --model ${s}`))})}async function Hc(e,t){if(!t)throw new m("ai models remove needs the model's name (see `snoutdata ai models`)");let n=await fe(e).deleteModel(t);h(n,()=>d(n.disabled?`${t} comes from the gateway's providers file, so it was disabled rather than removed.`:`Removed ${t}.`))}function Gg(e){return(e??"").split(",").map(t=>t.trim()).filter(t=>t!=="")}function zg(e){return B([["ROUTE","TRIES, IN ORDER","SORT","SKIPS"],...e.map(t=>[t.name,t.tried.join(", ")||"-",t.sort,t.skipped.join(", ")||"-"])])}async function Kc(e){let t=await fe(e).routes();h(t,()=>{if(t.length===0){d(`No routes on ${e}'s gateway. A route is one name for several models, each tried when the one before fails:`),d(w(" snoutdata ai routes set NAME --models first,second [--sort price]"));return}d(zg(t))})}async function qc(e,t,n){if(!t)throw new m("ai routes set needs the route's name: snoutdata ai routes set NAME --models first,second");let r=Gg(n.models);if(r.length===0)throw new m("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 m(`--sort is order (as written), price (the cheapest first), latency or throughput (the fastest first, as measured), not ${o}`);let s=fe(e);await s.putRoute(t,{targets:r,sort:o});let a=(await s.routes()).find(l=>l.name===t);h(a??{name:t,targets:r,sort:o},()=>{let l=a?.tried??r;d(`${x(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&&ee(`skipped, not served: ${a.skipped.join(", ")}`),d(w(` Call it as the model "${t}", or: snoutdata ai test --model ${t}`))})}async function Gc(e,t){if(!t)throw new m("ai routes remove needs the route's name (see `snoutdata ai routes`)");await fe(e).deleteRoute(t),h({name:t,removed:!0},()=>d(`Removed the route ${t}. Its models are untouched.`))}function Wg(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 ${dr(e.expires_at).slice(0,10)}`:"active"}async function zc(e){let t=await fe(e).keys();h(t,()=>{if(t.length===0){d(`No keys on ${e}'s gateway. \`snoutdata ai keys create --name my-server\` makes one for a server.`);return}d(B([["NAME","ID","KEY","MODELS","CREATED","LAST USED","STATE"],...t.map(n=>[n.name,n.id,n.hint,n.models?.join(", ")??"all",dr(n.created_at),n.last_used_at!==null?dr(n.last_used_at):n.last_used_on??"never",Wg(n)])]))})}async function Wc(e,t){if(!t.name)throw new m("ai keys create needs --name: what the key is for, shown in ai keys");if(t.expiresDays!==void 0&&t.expiresDays<=0)throw new m("--expires is a number of days, 1 or more");let n=t.models?.split(",").map(s=>s.trim()).filter(Boolean),r=await fe(e).createKey({name:t.name,...n&&n.length>0?{models:n}:{},...t.expiresDays!==void 0?{expires_in:t.expiresDays*86400}:{}}),o=await ur(e);h({...r,endpoint:o.ai.endpoint},()=>{process.stdout.write(`${r.key}
513
+ `),d(""),d(`${x(r.name)}: ${r.models?`for ${r.models.join(", ")}`:"for every model"}, ${r.expires_at?`until ${dr(r.expires_at)}`:"until revoked"}.`),d("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."),d(w(` OPENAI_BASE_URL=${o.ai.endpoint} OPENAI_API_KEY=<that key>`))})}async function Jc(e,t){if(!t)throw new m("ai keys revoke needs the key's id (see `snoutdata ai keys`)");await fe(e).revokeKey(t),h({ref:e,revoked:t},()=>d(`Revoked ${t}. A call with it is refused from now on.`))}async function Vc(e){let t=await fe(e).budgets();h(t,()=>{if(t.length===0){d(`No budgets on ${e}'s gateway. A browser call needs two hard ones:`),d(w(" snoutdata ai budgets set project --amount 5")),d(w(" snoutdata ai budgets set users --amount 0.50"));return}d(B([["ID","FOR","BUDGET"],...t.map(n=>[n.id,Ic(n),qo(n)])]))})}function Jg(e){if(e==="project"||e==="users")return e;throw new m("ai budgets set takes project (the whole project) or users (each signed-in user)")}function Vg(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 Yc(e,t,n){let r=Jg(t),o=Number(n.amount);if(n.amount===void 0||!Number.isFinite(o)||o<0)throw new m("ai budgets set needs --amount, in dollars, zero or more");let s=n.period??"day";if(s!=="day"&&s!=="month")throw new m("--period is day or month");let a=fe(e),l=Vg(await a.budgets(),r,s),i=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}:{}});h(i,()=>d(`${l?"Changed":"Set"}: ${r==="users"?"every user":"the project"}, ${qo(i)}.`))}async function Xc(e,t){if(!t)throw new m("ai budgets remove needs the budget's id (see `snoutdata ai budgets`)");await fe(e).deleteBudget(t),h({ref:e,removed:t},()=>d(`Removed the budget ${t}.`))}var Oc=["day","model","provider","operation","key","user","group"];async function Zc(e,t){let n=t.by??"model";if(!Oc.includes(n))throw new m(`--by is one of ${Oc.join("|")}`);let r=t.days??30;if(r<1||r>366)throw new m("--days is 1 to 366");let o=await fe(e).usage({by:n,from:Cc(r)});h(o,()=>{if(o.data.length===0){d(`No calls to ${e}'s gateway from ${o.from} to ${o.to}.`);return}let s=o.data.reduce((a,l)=>a+(en(l.cost)??0),0);d(B([[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),Ug(a.cost)+(a.unpriced>0?` (+${a.unpriced} unpriced)`:"")])])),d(`${o.from} to ${o.to}: $${s.toFixed(2)}.`)})}async function Qc(e,t){let n=await ur(e);if(!n.ai.enabled)throw new P("not-found",`AI is off for ${e}. Switch it on first: snoutdata ai enable.`);let r=fe(e),s=(await r.models()).filter(k=>k.served&&k.embeddings===null),a=t.model??s[0]?.name;if(!a)throw new P("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}),i=Date.now(),u=0,c={};try{let k=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."}]})});u=k.status;let v=await k.text();try{c=v?JSON.parse(v):{}}catch{c={error:{message:Hn(k.status,k.statusText,v)}}}}finally{await r.revokeKey(l.id).catch(()=>{})}let p=Date.now()-i;if(u<200||u>=300){let k=c.error?.message??`the gateway answered ${u}`;throw new P(Ue(u,c.error?.code??null),`${a} through ${e}'s gateway: ${k}`,{model:a,status:u,gatewayCode:c.error?.code??null})}let f=c.choices?.[0]?.message?.content??"";return h({ref:e,model:a,reply:f,usage:c.usage??null,ms:p},()=>{process.stdout.write(`${f}
514
+ `),d(w(`${a}, ${p} ms, ${c.usage?.prompt_tokens??"?"} tokens in, ${c.usage?.completion_tokens??"?"} out, through ${n.ai.endpoint}`))}),0}oe();be();ne();import{readFile as Xg}from"node:fs/promises";var Zg="api.snoutdata.com";function nl(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}.${Zg}/auth/v1/callback`,anonymous:{enabled:t.anonymous?.enabled===!0,ready:t.anonymous?.ready===!0}}}async function Qg(e){return nl(e,await _("cloud-project-auth",{ref:e,action:"status"}))}async function pr(e,t){return nl(e,await _("cloud-project-auth",{ref:e,action:"settings",settings:t}))}function Go(e){let t=e.google,n="off";t.ready?n=x("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(`${B([["auth",e.enabled?x("on"):"off"],["site url",e.siteUrl??w("not set")],["redirects",e.redirects.length?e.redirects.join(", "):w("none")],["google",n],["google client id",t.clientId??w("not set")],["google callback",e.googleCallback],["guests",e.anonymous.ready?x("on"):e.anonymous.enabled?"switched on, not applied yet":"off"]])}
515
+ `),e.enabled||d(w(` snoutdata products enable auth --ref ${e.ref}`))}async function eh(){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 rl(e,t,n,r){if(t===void 0||t==="show"){let o=await Qg(e);h(o,()=>Go(o));return}if(t==="google"){if(n[0]==="off"){let a=await pr(e,{googleEnabled:!1});h(a,()=>d("Google sign-in is off. Your auth service restarts within about a minute."));return}if(n.length>0)throw new m('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 eh();if(!a)throw new m("--stdin read nothing. Pipe the Google client secret in.");o.googleClientSecret=a}let s=await pr(e,o);h(s,()=>{s.google.ready?d("Google sign-in is on. Your auth service restarts within about a minute."):Go(s),d(w(` 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 m('auth anonymous takes "on" or "off"');let s=await pr(e,{anonymousEnabled:o==="on"});h(s,()=>{o==="off"?d("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?d("Guest sign-in is on: guestSignIn() gives a browser a session with no email or password. Your auth service restarts within about a minute."):(d("Guest sign-in is switched on, and takes effect when auth is."),d(w(` 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 m("auth redirects needs --site-url and/or --allow URL,URL (an empty --allow= clears the list)");let s=await pr(e,o);h(s,()=>Go(s));return}if(t==="templates"){let o=await _("cloud-project-auth",{ref:e,action:"templates"});h(o,()=>tl(o.templates));return}if(t==="template"){let o=n[0];if(!o||!el.includes(o))throw new m(`auth template needs a kind: ${el.join(", ")}`);let s;if(n[1]==="reset")s={kind:o,reset:!0};else{if(!r.file)throw new m(`auth template ${o} needs --file body.html (and --subject), or "reset"`);let l=await Xg(r.file,"utf8"),i=await _("cloud-project-auth",{ref:e,action:"templates"}),u=r.subject??i.templates.find(c=>c.kind===o)?.subject;s={kind:o,subject:u,body:l}}let a=await _("cloud-project-auth",{ref:e,action:"template",template:s});h(a,()=>{tl(a.templates),d(w(" Your auth service restarts with it within about a minute."))});return}throw new m(`unknown command: auth ${t}. auth [google [off] | anonymous on|off | redirects | templates | template KIND]`)}var el=["confirmation","recovery","magic_link","invite","email_change"];function tl(e){process.stdout.write(`${B([["KIND","SOURCE","SUBJECT"],...e.map(t=>[t.kind,t.custom?x("yours"):"ours",t.subject])])}
516
+ `)}oe();ne();me();import{createHash as _h}from"node:crypto";import{existsSync as Sh,readdirSync as kh,readFileSync as vh,statSync as $h}from"node:fs";import{isAbsolute as xh,join as Yo,relative as Ph,resolve as Eh}from"node:path";function th(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function mr(e,t,n={}){let r=th(e),o=new Map(r.map(u=>[u.name,u])),s=[];for(let u of t){let c=o.get(u.name);if(!c){s.push({code:"missing",name:u.name,reason:`${u.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}c.checksum!==u.checksum&&s.push({code:"changed",name:u.name,reason:`${u.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(u=>u.name).sort((u,c)=>u<c?-1:u>c?1:0)[t.length-1],l=new Set(t.map(u=>u.name)),i=[];for(let u of r)if(!l.has(u.name)){if(a!==void 0&&u.name<a&&!n.outOfOrder){s.push({code:"out-of-order",name:u.name,reason:`${u.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}i.push(u)}return s.length>0?{ok:!1,problems:s}:{ok:!0,pending:i}}function Pt(e){return!/^[\t ]*--[\t ]*snoutdata:no-transaction[\t ]*$/im.test(e)}import{createHash as zo,createHmac as fr,pbkdf2Sync as nh,randomBytes as rh,timingSafeEqual as oh}from"node:crypto";import{readFileSync as sh}from"node:fs";import{homedir as ah}from"node:os";import{connect as ih,isIP as ch}from"node:net";import{connect as lh}from"node:tls";var et=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)}},ae=class extends Error{constructor(t){super(t),this.name="PgConnectError"}},dh=196608,uh=80877103;function ol(e,t){let n=Buffer.alloc(5);return n.write(e,0,"latin1"),n.writeInt32BE(t.length+4,1),Buffer.concat([n,t])}function Qe(e){return Buffer.concat([Buffer.from(e,"utf8"),Buffer.from([0])])}function ph(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 sl(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 Wo=class{constructor(t,n=rh(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(v=>[v.slice(0,1),v.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 ae("the server answered the password exchange with a nonce that is not ours");if(!o||!Number.isInteger(s)||s<1)throw new ae("the server answered the password exchange with no salt or iteration count");let a=nh(this.password.normalize("NFKC"),Buffer.from(o,"base64"),s,32,"sha256"),l=fr("sha256",a).update("Client Key").digest(),i=zo("sha256").update(l).digest(),u=`c=biws,r=${r}`,c=`${this.firstBare},${t},${u}`,p=fr("sha256",i).update(c).digest(),f=Buffer.alloc(l.length);for(let v=0;v<f.length;v++)f[v]=l[v]^p[v];let k=fr("sha256",a).update("Server Key").digest();return this.serverSignature=fr("sha256",k).update(c).digest(),`${u},p=${f.toString("base64")}`}verify(t){let n=/(?:^|,)e=([^,]*)/.exec(t);if(n)throw new ae(`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||!oh(o,this.serverSignature))throw new ae("the server could not prove it knows the password, so this is not the database it claims to be")}},Jo=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 ae(n.message))),t.on("close",()=>this.fail(new ae("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 ae("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 mh(e){return new Promise((t,n)=>{let r=l=>{if(a(),l.length!==1){n(new ae("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 ae(l.message))},s=()=>{a(),n(new ae("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 fh(e,t){return new Promise((n,r)=>{let o=ih({host:e,port:t}),s=a=>r(new ae(`could not connect to ${e}:${t}: ${a.message}`));o.once("connect",()=>{o.off("error",s),n(o)}),o.once("error",s)})}async function gh(e,t,n,r){let o=await fh(e.host,e.port);if(r(o),t==="disable")return o;let s=Buffer.alloc(8);if(s.writeInt32BE(8,0),s.writeInt32BE(uh,4),o.write(s),await mh(o)!=="S"){if(t==="allow"||t==="prefer")return o;throw new ae(`${e.host} does not accept TLS, and this connection requires it (sslmode ${t})`)}let l=t==="verify-ca"||t==="verify-full";return new Promise((i,u)=>{let c=lh({socket:o,host:e.host,...ch(e.host)===0?{servername:e.host}:{},rejectUnauthorized:l,...l&&n?{ca:sh(n,"utf8")}:{},...t==="verify-ca"?{checkServerIdentity:()=>{}}:{}});r(c),c.once("secureConnect",()=>{c.off("error",p),i(c)});let p=f=>u(new ae(`TLS to ${e.host} failed: ${f.message}`));c.once("error",p)})}var gr=class e{constructor(t,n){this.socket=t;this.reader=n}static async open(t,n={}){let r=n.env??process.env,o=Xt(t.ssl,r,n.home??ah()),s=o.rootCert??(r.PGSSLROOTCERT||void 0),a=o.mode==="require"&&s?"verify-ca":o.mode,l=n.connectTimeoutMs??12e4,i=[],u=()=>{for(let f of i)f.destroy()},c,p=new Promise((f,k)=>{c=setTimeout(()=>{u(),k(new ae(`${t.host}:${t.port} did not answer within ${Math.round(l/1e3)} seconds`))},l)});try{return await Promise.race([(async()=>{let f=await gh(t,a,s,v=>i.push(v)),k=new e(f,new Jo(f));return await k.startup(t),k})(),p])}catch(f){throw u(),f}finally{clearTimeout(c)}}send(t,n){this.socket.write(ol(t,n))}async startup(t){let n=Buffer.concat([...[["user",t.user],["database",t.database],["application_name","snoutdata"],["client_encoding","UTF8"]].flatMap(([s,a])=>[Qe(s),Qe(a)]),Buffer.from([0])]),r=Buffer.alloc(8);r.writeInt32BE(n.length+8,0),r.writeInt32BE(dh,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",Qe(t.password));else if(a===5){let l=zo("md5").update(t.password+t.user).digest("hex"),i=zo("md5").update(Buffer.concat([Buffer.from(l),s.body.subarray(4,8)])).digest("hex");this.send("p",Qe(`md5${i}`))}else if(a===10){let l=ph(s.body,4);if(!l.includes("SCRAM-SHA-256"))throw new ae(`the server asked for ${l.join(", ")||"a password exchange"}, which this client does not speak`);o=new Wo(t.password);let i=Buffer.from(o.first(),"utf8"),u=Buffer.alloc(4);u.writeInt32BE(i.length,0),this.send("p",Buffer.concat([Qe("SCRAM-SHA-256"),u,i]))}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 ae(`the server asked for an authentication method (${a}) this client does not speak`);break}case"E":throw new et(sl(s.body));case"Z":return;default:break}}}async query(t,n){this.send("Q",Qe(t));let r=[],o=null,s=null;for(;;){let a=await this.reader.next();switch(a.type){case"T":r=[];break;case"D":{let l=a.body.readInt16BE(0),i=[],u=2;for(let c=0;c<l;c++){let p=a.body.readInt32BE(u);u+=4,p<0?i.push(null):(i.push(a.body.toString("utf8",u,u+p)),u+=p)}r.push(i);break}case"C":o=a.body.toString("utf8",0,Math.max(0,a.body.indexOf(0)));break;case"E":s??=new et(sl(a.body));break;case"G":n===void 0?this.send("f",Qe("db push has 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",Qe("COPY BOTH is not something a migration can do"));break;case"Z":if(s)throw s;return{rows:r,command:o};default:break}}}close(){this.socket.destroyed||this.socket.end(ol("X",Buffer.alloc(0)))}};function al(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(u=>u===`
513
517
  `).length,a=t.split(`
514
518
  `)[s]??"",l=o.length-(o.lastIndexOf(`
515
519
  `)+1),i=`LINE ${n+s}: `;r.push(`${i}${a.replace(/\r$/,"")}`,`${" ".repeat(i.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(`
516
- `)}var ih=/[A-Za-z0-9_$\u0080-￿]/,ch=/[A-Za-z_\u0080-￿]/,lh=/^\$(?:[A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$/;function dh(e){let t=zo(e);return/^\s*copy\b/i.test(t)&&/\bfrom\s+stdin\b/i.test(t)}function al(e){let t=zo(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 zo(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," ")}function il(e){let t=[],n=[],r=e.length,o=0,s=1,a=-1,l=1,i=0,u=0,c=[],p=0,f=()=>{a<0&&(a=o,l=s)},k=()=>{a=-1,i=0,u=0,c=[],p=0},v=O=>{let pe=Math.min(r,o+O);for(let W=o;W<pe;W++)e.charCodeAt(W)===10&&s++;o=pe},V=O=>v(O<0?r-o:O-o),j=null,Y=()=>{let O=a>=0?e.slice(a,o).trim():"";if(zo(O).replace(/;/g,"").trim()!=="")if(!dh(O))t.push({sql:O,line:l});else{let pe=e.indexOf(`
517
- `,o),W=[];if(pe>=0){let ce=pe+1,pn=s+1;for(;ce<r;){let pt=e.indexOf(`
518
- `,ce),mn=e.slice(ce,pt<0?r:pt).replace(/\r$/,"");if(ce=pt<0?r:pt+1,pn++,mn==="\\.")break;W.push(`${mn}
519
- `)}j={from:pe+1,to:ce,line:pn}}t.push({sql:O,line:l,copyData:W.join("")})}k()};for(;o<r;){if(j&&o>=j.from){o=j.to,s=j.line,j=null;continue}let O=e[o],pe=e[o+1];if(O===`
520
- `||O===" "||O===" "||O==="\r"||O==="\f"||O==="\v"){v(1);continue}if(O==="-"&&pe==="-"){V(e.indexOf(`
521
- `,o));continue}if(O==="/"&&pe==="*"){f();let W=0;for(;o<r;)if(e[o]==="/"&&e[o+1]==="*")W++,v(2);else if(e[o]==="*"&&e[o+1]==="/"){if(W--,v(2),W===0)break}else v(1);continue}if(O==="'"){f(),R(!1);continue}if(O==='"'){for(f(),v(1);;){let W=e.indexOf('"',o);if(W<0){V(-1);break}if(V(W+1),e[o]==='"'){v(1);continue}break}continue}if(O==="$"){f();let W=lh.exec(e.slice(o,o+64))?.[0];if(W){v(W.length);let ce=e.indexOf(W,o);V(ce<0?-1:ce+W.length)}else v(1);continue}if(O==="\\"){let W=e.indexOf(`
522
- `,o);n.push({line:s,text:e.slice(o,W<0?r:W).replace(/\r$/,"").trimEnd()}),V(W);continue}if(O==="("){f(),i++,v(1);continue}if(O===")"){f(),i>0&&i--,v(1);continue}if(O===";"){f(),v(1),i===0&&u===0&&Y();continue}if(ch.test(O)){f();let W=o+1;for(;W<r&&ih.test(e[W]);)W++;let ce=e.slice(o,W);if(v(W-o),e[o]==="'"){R(ce==="e"||ce==="E");continue}ee(ce.toLowerCase());continue}if(O>="0"&&O<="9"){f();let W=o+1;for(;W<r&&/[0-9A-Za-z_.]/.test(e[W]);)W++;v(W-o);continue}f(),v(1)}return Y(),{statements:t,metaCommands:n};function R(O){for(v(1);o<r;){let pe=e[o];if(O&&pe==="\\"){v(2);continue}if(pe==="'"){if(v(1),e[o]==="'"){v(1);continue}return}v(1)}}function ee(O){p<4&&["create","function","procedure","or","replace"].includes(O)&&(c[p]=O[0]),p++,!(!(c[0]==="c"&&(c[1]==="f"||c[1]==="p"||c[1]==="o"&&c[2]==="r"&&(c[3]==="f"||c[3]==="p")))||i!==0)&&(O==="begin"?u++:O==="case"?u>=1&&u++:O==="end"&&u>0&&u--)}}function ll(e){let t=yh(process.cwd(),e);return t&&!t.startsWith("..")?t:e}var fr="_snoutdata_migrations",bh=`create table if not exists ${fr} (
520
+ `)}var hh=/[A-Za-z0-9_$\u0080-￿]/,yh=/[A-Za-z_\u0080-￿]/,wh=/^\$(?:[A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$/;function bh(e){let t=Vo(e);return/^\s*copy\b/i.test(t)&&/\bfrom\s+stdin\b/i.test(t)}function il(e){let t=Vo(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 Vo(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," ")}function cl(e){let t=[],n=[],r=e.length,o=0,s=1,a=-1,l=1,i=0,u=0,c=[],p=0,f=()=>{a<0&&(a=o,l=s)},k=()=>{a=-1,i=0,u=0,c=[],p=0},v=N=>{let pe=Math.min(r,o+N);for(let W=o;W<pe;W++)e.charCodeAt(W)===10&&s++;o=pe},Y=N=>v(N<0?r-o:N-o),D=null,J=()=>{let N=a>=0?e.slice(a,o).trim():"";if(Vo(N).replace(/;/g,"").trim()!=="")if(!bh(N))t.push({sql:N,line:l});else{let pe=e.indexOf(`
521
+ `,o),W=[];if(pe>=0){let le=pe+1,fn=s+1;for(;le<r;){let pt=e.indexOf(`
522
+ `,le),gn=e.slice(le,pt<0?r:pt).replace(/\r$/,"");if(le=pt<0?r:pt+1,fn++,gn==="\\.")break;W.push(`${gn}
523
+ `)}D={from:pe+1,to:le,line:fn}}t.push({sql:N,line:l,copyData:W.join("")})}k()};for(;o<r;){if(D&&o>=D.from){o=D.to,s=D.line,D=null;continue}let N=e[o],pe=e[o+1];if(N===`
524
+ `||N===" "||N===" "||N==="\r"||N==="\f"||N==="\v"){v(1);continue}if(N==="-"&&pe==="-"){Y(e.indexOf(`
525
+ `,o));continue}if(N==="/"&&pe==="*"){f();let W=0;for(;o<r;)if(e[o]==="/"&&e[o+1]==="*")W++,v(2);else if(e[o]==="*"&&e[o+1]==="/"){if(W--,v(2),W===0)break}else v(1);continue}if(N==="'"){f(),O(!1);continue}if(N==='"'){for(f(),v(1);;){let W=e.indexOf('"',o);if(W<0){Y(-1);break}if(Y(W+1),e[o]==='"'){v(1);continue}break}continue}if(N==="$"){f();let W=wh.exec(e.slice(o,o+64))?.[0];if(W){v(W.length);let le=e.indexOf(W,o);Y(le<0?-1:le+W.length)}else v(1);continue}if(N==="\\"){let W=e.indexOf(`
526
+ `,o);n.push({line:s,text:e.slice(o,W<0?r:W).replace(/\r$/,"").trimEnd()}),Y(W);continue}if(N==="("){f(),i++,v(1);continue}if(N===")"){f(),i>0&&i--,v(1);continue}if(N===";"){f(),v(1),i===0&&u===0&&J();continue}if(yh.test(N)){f();let W=o+1;for(;W<r&&hh.test(e[W]);)W++;let le=e.slice(o,W);if(v(W-o),e[o]==="'"){O(le==="e"||le==="E");continue}te(le.toLowerCase());continue}if(N>="0"&&N<="9"){f();let W=o+1;for(;W<r&&/[0-9A-Za-z_.]/.test(e[W]);)W++;v(W-o);continue}f(),v(1)}return J(),{statements:t,metaCommands:n};function O(N){for(v(1);o<r;){let pe=e[o];if(N&&pe==="\\"){v(2);continue}if(pe==="'"){if(v(1),e[o]==="'"){v(1);continue}return}v(1)}}function te(N){p<4&&["create","function","procedure","or","replace"].includes(N)&&(c[p]=N[0]),p++,!(!(c[0]==="c"&&(c[1]==="f"||c[1]==="p"||c[1]==="o"&&c[2]==="r"&&(c[3]==="f"||c[3]==="p")))||i!==0)&&(N==="begin"?u++:N==="case"?u>=1&&u++:N==="end"&&u>0&&u--)}}function dl(e){let t=Ph(process.cwd(),e);return t&&!t.startsWith("..")?t:e}var hr="_snoutdata_migrations",Ah=`create table if not exists ${hr} (
523
527
  name text primary key,
524
528
  checksum text not null,
525
529
  applied_at timestamptz not null default now()
526
- );`;function _h(e){if(!ph(e)||!gh(e).isDirectory())throw new Error(`no migrations folder at ${ll(e)}. Put your .sql files there, or pass --dir.`);return mh(e).filter(t=>t.endsWith(".sql")).map(t=>{let n=Jo(e,t),r=fh(n,"utf8");return{name:t,path:n,sql:r,checksum:uh("sha256").update(r,"utf8").digest("hex")}})}var Sh={connection:e=>ke(e),open:e=>mr.open(e)};function dl(e,t){throw e instanceof se?new P("network",`Could not reach ${t}'s database: ${e.message}.`):e instanceof et?new P("failed",`${t}'s database refused the connection: ${e.message}`):e}async function ul(e,t,n){try{return await e.open(t)}catch(r){return dl(r,n)}}async function kh(e,t,n){let r=await ul(e,t,n);try{await r.query(bh);let{rows:o}=await r.query(`select name, checksum from ${fr};`);return o.map(([s,a])=>({name:s??"",checksum:a??""}))}catch(o){if(o instanceof et)throw new P("failed",`Could not read ${fr} on ${n}: ${o.message}`);return dl(o,n)}finally{r.close()}}async function vh(e,t,n){for(let r of t)try{await e.query(r.sql,r.copyData)}catch(o){if(o instanceof et)return`${r.line>0?`${n}:${r.line}: `:""}${sl(o,r.sql,r.line>0?r.line:1)}`;if(o instanceof se)return`the connection was lost: ${o.message}`;throw o}return null}function cl(e){return`'${e.replace(/'/g,"''")}'`}async function pl(e,t={}){let n=await Vo(e,t,r=>d(r));if(!n.ok){if(n.problems){let r=n.problems.map(o=>` ${o.reason}`).join(`
527
- `);n.problems.every(o=>o.code==="psql-command"||o.code==="ends-transaction")&&H("failed",`Refused, and nothing ran:
528
- ${r}`,{ref:e,problems:n.problems}),H("conflict",`Refused. This folder and ${e} do not agree:
529
- ${r}`,{ref:e,problems:n.problems})}H("failed",`${n.failed} failed, and nothing after it was tried.
530
- ${n.error??""}`.trimEnd(),{ref:e,failed:n.failed})}return h(n,()=>{if(n.wouldApply){d(`Would apply ${n.wouldApply.length} migration${n.wouldApply.length===1?"":"s"} to ${e}:`);for(let r of n.wouldApply)d(` ${r}`);return}if(n.upToDate){d(`${e} is up to date.`);return}d(`Applied ${n.applied.length} migration${n.applied.length===1?"":"s"} to ${e}.`)}),0}async function Vo(e,t={},n=()=>{},r=Sh){let o=wh(t.dir===void 0?Jo(process.cwd(),"migrations"):hh(t.dir)?t.dir:Jo(process.cwd(),t.dir)),s=[];function a(R){s.push(R),n(R)}let l=_h(o);if(l.length===0)return a(`No .sql files in ${ll(o)}.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};let i=await r.connection(e),u={host:i.host,port:i.port,database:i.database,user:i.user,password:i.password,ssl:i.ssl};i.wakesInstantly||a("This project is paused; the connection will wake it, which takes a few seconds.");let c=await kh(r,u,e),p=ur(l,c,{outOfOrder:t.outOfOrder});if(!p.ok)return{ref:e,directory:o,ok:!1,applied:[],problems:[...p.problems],notes:s};let f=new Map(l.map(R=>[R.name,R])),k=p.pending.map(R=>f.get(R.name)),v=new Map(k.map(R=>[R.name,il(R.sql)])),V=k.flatMap(R=>v.get(R.name).metaCommands.map(ee=>({code:"psql-command",name:R.name,reason:`${R.name} line ${ee.line} is a psql command (${ee.text.length>60?`${ee.text.slice(0,57)}...`:ee.text}), which only psql runs. db push sends SQL to the database itself, so put the SQL it stands for in the file instead.`}))),j=k.filter(R=>Pt(R.sql)).flatMap(R=>v.get(R.name).statements.flatMap(ee=>{let O=al(ee.sql);return O?[{code:"ends-transaction",name:R.name,reason:`${R.name} line ${ee.line} ends the transaction itself (${O}). db push already runs each file in one transaction and records it there, so a ${O} 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(V.length>0||j.length>0)return{ref:e,directory:o,ok:!1,applied:[],problems:[...V,...j],notes:s};if(k.length===0)return a(`${e} is up to date: ${c.length} migration${c.length===1?"":"s"} already applied.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};if(t.dryRun){for(let R of k)Pt(R.sql)||a(`${R.name} would run outside a transaction.`);return{ref:e,directory:o,ok:!0,applied:[],wouldApply:k.map(R=>R.name),notes:s}}let Y=[];for(let R of k){let ee=`insert into ${fr} (name, checksum) values (${cl(R.name)}, ${cl(R.checksum)});`,O=Pt(R.sql);O||a(`${R.name} runs outside a transaction, so an interruption can leave it half applied.`);let pe=[...O?[{sql:"begin;",line:0}]:[],...v.get(R.name).statements,{sql:ee,line:0},...O?[{sql:"commit;",line:0}]:[]],W=await ul(r,u,e),ce;try{ce=await vh(W,pe,R.name)}finally{W.close()}if(ce!==null)return O&&(a("It ran inside a transaction, so nothing from it is in the database."),/cannot run inside a transaction block/i.test(ce)&&a("Put -- snoutdata:no-transaction at the top of the file to run it outside one.")),{ref:e,directory:o,ok:!1,applied:Y,failed:R.name,error:ce,notes:s};Y.push(R.name),a(` applied ${R.name}`)}return{ref:e,directory:o,ok:!0,applied:Y,notes:s}}re();be();te();import{readFile as ml}from"node:fs/promises";function Yo(e){if(e==="apns"||e==="fcm")return e;throw new m("say which: apns (an Apple .p8) or fcm (a Firebase service account)")}async function $h(e){let t=await _("cloud-project-push",{ref:e,credentials:{list:!0}});return{ref:e,credentials:t??{}}}async function fl(e){if(!e.p8||!e.keyId||!e.teamId||!e.topic)throw new m("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 m("--environment is production or sandbox; leave it out for a key that serves both");return{topic:e.topic,keys:[{p8:await ml(e.p8,"utf8"),key_id:e.keyId,team_id:e.teamId,environment:e.environment??null}]}}async function gl(e){if(!e)throw new m("push credentials set fcm needs --file service-account.json");return{service_account:await ml(e,"utf8")}}async function xh(e,t,n){let r=await _("cloud-project-push",{ref:e,credentials:{set:{kind:t,body:n}}});return{ref:e,kind:t,summary:r}}async function Ph(e,t){return await _("cloud-project-push",{ref:e,credentials:{remove:t}}),{ref:e,kind:t,removed:!0}}async function hl(e){let t=await $h(e);h(t,()=>{let{apns:n,fcm:r,vapid:o}=t.credentials;process.stdout.write(`${L([["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}`:""]])}
531
- `),(!n||!r)&&d(w(` 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 yl(e,t,n){let r=await xh(e,t,n);h(r,()=>d(`${t==="apns"?"The Apple key signed":"Google accepted the service account"}, and it is stored in the project's own database.`))}async function wl(e,t){let n=await Ph(e,t);h(n,()=>d(`${t} credentials removed. Devices on it stop receiving until new ones are set.`))}re();me();te();import{spawn as Bh}from"node:child_process";import{writeFileSync as Fh}from"node:fs";import{isAbsolute as Hh,resolve as Kh}from"node:path";var Ah=" ";function U(e){return Ah.repeat(e)}function we(e){return JSON.stringify(e)}function Me(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:we(e)}function dt(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function Rh(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 Th={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"},Oh={sqlserver:{bit:"boolean"},"mysql-aurora":{bit:"number"},mariadb:{bit:"number"},sqlite:{bit:"number"},snowflake:{array:"json"}};function Nh(e,t){let n=Oh[e]?.[t];return n||(Th[t]??"unknown")}function gr(e,t){let{base:n,array:r}=Rh(t),o=e.enumRefs.get(n);if(o)return r?`${o}[]`:o;if(n==="array")return"unknown[]";let s=Nh(e.driverId,n),a=s==="json"?"Json":s;return r?`${a}[]`:a}function Ih(e){return e.nullable||e.autoIncrement===!0||e.default!==null&&e.default!==void 0}function Xo(e,t,n,r,o=!1){if(o&&t.generatedAlways===!0)return`${U(n)}${Me(t.name)}?: never`;let s=gr(e,t.dataType),a=t.nullable?`${s} | null`:s;return`${U(n)}${Me(t.name)}${r?"?":""}: ${a}`}function Ch(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 jh(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(`${U(t)}Relationships: []`),n;n.push(`${U(t)}Relationships: [`);for(let o of r)n.push(`${U(t+1)}{`),n.push(`${U(t+2)}foreignKeyName: ${we(o.constraintName)}`),n.push(`${U(t+2)}columns: [${o.columns.map(we).join(", ")}]`),n.push(`${U(t+2)}isOneToOne: ${Ch(e,o)?"true":"false"}`),n.push(`${U(t+2)}referencedRelation: ${we(o.referencedTable)}`),n.push(`${U(t+2)}referencedColumns: [${o.referencedColumns.map(we).join(", ")}]`),n.push(`${U(t+1)}},`);return n.push(`${U(t)}]`),n}function bl(e,t,n){let r=dt(t.columns),o=[];o.push(`${U(n)}${Me(t.name)}: {`),o.push(`${U(n+1)}Row: {`);for(let s of r)o.push(Xo(e,s,n+2,!1));if(o.push(`${U(n+1)}}`),t.kind!=="view"){o.push(`${U(n+1)}Insert: {`);for(let s of r)o.push(Xo(e,s,n+2,Ih(s),!0));o.push(`${U(n+1)}}`),o.push(`${U(n+1)}Update: {`);for(let s of r)o.push(Xo(e,s,n+2,!0,!0));o.push(`${U(n+1)}}`)}return o.push(...jh(t,n+1)),o.push(`${U(n)}}`),o}function en(e,t){return[`${U(t)}${e}: {`,`${U(t+1)}[_ in never]: never`,`${U(t)}}`]}function Dh(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}[]`:`${gr(e,s)}[]`}return r==="record"||r==="trigger"||r==="event_trigger"?"unknown":e.rowRefs.get(r)??gr(e,n)}function Mh(e,t,n){let r=[],o=dt((t.parameters??[]).filter(s=>s.name.length>0&&(s.mode??"IN").toUpperCase()!=="OUT").map(s=>({name:s.name,dataType:s.dataType})));if(r.push(`${U(n)}${Me(t.name)}: {`),o.length===0)r.push(`${U(n+1)}Args: never`);else{r.push(`${U(n+1)}Args: {`);for(let s of o)r.push(`${U(n+2)}${Me(s.name)}: ${gr(e,s.dataType)}`);r.push(`${U(n+1)}}`)}return r.push(`${U(n+1)}Returns: ${Dh(e,t)}`),r.push(`${U(n)}}`),r}function Et(e,t){return e.schema&&e.schema.length>0?e.schema:t}function _l(e,t={}){let n=t.defaultSchema??"public",r=t.driverId??"postgres",o=t.enums??[],s=new Map;for(let p of o){let f=p.schema&&p.schema.length>0?p.schema:n;s.set(p.name.toLowerCase(),`Database[${we(f)}][${we("Enums")}][${we(p.name)}]`)}let a=new Map;for(let p of e.tables){let f=Et(p,n),k=p.kind==="view"?"Views":"Tables";a.set(p.name.toLowerCase(),`Database[${we(f)}][${we(k)}][${we(p.name)}][${we("Row")}]`)}let l={driverId:r,defaultSchema:n,enumRefs:s,rowRefs:a},i=new Set([n]);for(let p of e.tables)i.add(Et(p,n));for(let p of e.routines??[])i.add(Et(p,n));for(let p of o)i.add(p.schema&&p.schema.length>0?p.schema:n);let u=[...i].sort(),c=[];c.push("export type Json ="),c.push(" | string"),c.push(" | number"),c.push(" | boolean"),c.push(" | null"),c.push(" | { [key: string]: Json | undefined }"),c.push(" | Json[]"),c.push(""),c.push("export type Database = {");for(let p of u){let f=dt(e.tables.filter(j=>Et(j,n)===p&&j.kind!=="view")),k=dt(e.tables.filter(j=>Et(j,n)===p&&j.kind==="view")),v=dt((e.routines??[]).filter(j=>Et(j,n)===p)),V=dt(o.filter(j=>(j.schema&&j.schema.length>0?j.schema:n)===p));if(c.push(`${U(1)}${Me(p)}: {`),f.length===0)c.push(...en("Tables",2));else{c.push(`${U(2)}Tables: {`);for(let j of f)c.push(...bl(l,j,3));c.push(`${U(2)}}`)}if(k.length===0)c.push(...en("Views",2));else{c.push(`${U(2)}Views: {`);for(let j of k)c.push(...bl(l,j,3));c.push(`${U(2)}}`)}if(v.length===0)c.push(...en("Functions",2));else{c.push(`${U(2)}Functions: {`);for(let j of v)c.push(...Mh(l,j,3));c.push(`${U(2)}}`)}if(V.length===0)c.push(...en("Enums",2));else{c.push(`${U(2)}Enums: {`);for(let j of V)c.push(`${U(3)}${Me(j.name)}: ${j.values.map(we).join(" | ")}`);c.push(`${U(2)}}`)}c.push(...en("CompositeTypes",2)),c.push(`${U(1)}}`)}return c.push("}"),t.helpers!==!1&&(c.push(""),c.push(Uh(n))),t.constants!==!1&&(c.push(""),c.push(Lh(u,o,n))),`${c.join(`
530
+ );`;function Rh(e){if(!Sh(e)||!$h(e).isDirectory())throw new Error(`no migrations folder at ${dl(e)}. Put your .sql files there, or pass --dir.`);return kh(e).filter(t=>t.endsWith(".sql")).map(t=>{let n=Yo(e,t),r=vh(n,"utf8");return{name:t,path:n,sql:r,checksum:_h("sha256").update(r,"utf8").digest("hex")}})}var Th={connection:e=>ke(e),open:e=>gr.open(e)};function ul(e,t){throw e instanceof ae?new P("network",`Could not reach ${t}'s database: ${e.message}.`):e instanceof et?new P("failed",`${t}'s database refused the connection: ${e.message}`):e}async function pl(e,t,n){try{return await e.open(t)}catch(r){return ul(r,n)}}async function Oh(e,t,n){let r=await pl(e,t,n);try{await r.query(Ah);let{rows:o}=await r.query(`select name, checksum from ${hr};`);return o.map(([s,a])=>({name:s??"",checksum:a??""}))}catch(o){if(o instanceof et)throw new P("failed",`Could not read ${hr} on ${n}: ${o.message}`);return ul(o,n)}finally{r.close()}}async function Nh(e,t,n){for(let r of t)try{await e.query(r.sql,r.copyData)}catch(o){if(o instanceof et)return`${r.line>0?`${n}:${r.line}: `:""}${al(o,r.sql,r.line>0?r.line:1)}`;if(o instanceof ae)return`the connection was lost: ${o.message}`;throw o}return null}function ll(e){return`'${e.replace(/'/g,"''")}'`}async function ml(e,t={}){let n=await Xo(e,t,r=>d(r));if(!n.ok){if(n.problems){let r=n.problems.map(o=>` ${o.reason}`).join(`
531
+ `);n.problems.every(o=>o.code==="psql-command"||o.code==="ends-transaction")&&K("failed",`Refused, and nothing ran:
532
+ ${r}`,{ref:e,problems:n.problems}),K("conflict",`Refused. This folder and ${e} do not agree:
533
+ ${r}`,{ref:e,problems:n.problems})}K("failed",`${n.failed} failed, and nothing after it was tried.
534
+ ${n.error??""}`.trimEnd(),{ref:e,failed:n.failed})}return h(n,()=>{if(n.wouldApply){d(`Would apply ${n.wouldApply.length} migration${n.wouldApply.length===1?"":"s"} to ${e}:`);for(let r of n.wouldApply)d(` ${r}`);return}if(n.upToDate){d(`${e} is up to date.`);return}d(`Applied ${n.applied.length} migration${n.applied.length===1?"":"s"} to ${e}.`)}),0}async function Xo(e,t={},n=()=>{},r=Th){let o=Eh(t.dir===void 0?Yo(process.cwd(),"migrations"):xh(t.dir)?t.dir:Yo(process.cwd(),t.dir)),s=[];function a(O){s.push(O),n(O)}let l=Rh(o);if(l.length===0)return a(`No .sql files in ${dl(o)}.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};let i=await r.connection(e),u={host:i.host,port:i.port,database:i.database,user:i.user,password:i.password,ssl:i.ssl};i.wakesInstantly||a("This project is paused; the connection will wake it, which takes a few seconds.");let c=await Oh(r,u,e),p=mr(l,c,{outOfOrder:t.outOfOrder});if(!p.ok)return{ref:e,directory:o,ok:!1,applied:[],problems:[...p.problems],notes:s};let f=new Map(l.map(O=>[O.name,O])),k=p.pending.map(O=>f.get(O.name)),v=new Map(k.map(O=>[O.name,cl(O.sql)])),Y=k.flatMap(O=>v.get(O.name).metaCommands.map(te=>({code:"psql-command",name:O.name,reason:`${O.name} line ${te.line} is a psql command (${te.text.length>60?`${te.text.slice(0,57)}...`:te.text}), which only psql runs. db push sends SQL to the database itself, so put the SQL it stands for in the file instead.`}))),D=k.filter(O=>Pt(O.sql)).flatMap(O=>v.get(O.name).statements.flatMap(te=>{let N=il(te.sql);return N?[{code:"ends-transaction",name:O.name,reason:`${O.name} line ${te.line} ends the transaction itself (${N}). db push already runs each file in one transaction and records it there, so a ${N} 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(Y.length>0||D.length>0)return{ref:e,directory:o,ok:!1,applied:[],problems:[...Y,...D],notes:s};if(k.length===0)return a(`${e} is up to date: ${c.length} migration${c.length===1?"":"s"} already applied.`),{ref:e,directory:o,ok:!0,applied:[],upToDate:!0,notes:s};if(t.dryRun){for(let O of k)Pt(O.sql)||a(`${O.name} would run outside a transaction.`);return{ref:e,directory:o,ok:!0,applied:[],wouldApply:k.map(O=>O.name),notes:s}}let J=[];for(let O of k){let te=`insert into ${hr} (name, checksum) values (${ll(O.name)}, ${ll(O.checksum)});`,N=Pt(O.sql);N||a(`${O.name} runs outside a transaction, so an interruption can leave it half applied.`);let pe=[...N?[{sql:"begin;",line:0}]:[],...v.get(O.name).statements,{sql:te,line:0},...N?[{sql:"commit;",line:0}]:[]],W=await pl(r,u,e),le;try{le=await Nh(W,pe,O.name)}finally{W.close()}if(le!==null)return N&&(a("It ran inside a transaction, so nothing from it is in the database."),/cannot run inside a transaction block/i.test(le)&&a("Put -- snoutdata:no-transaction at the top of the file to run it outside one.")),{ref:e,directory:o,ok:!1,applied:J,failed:O.name,error:le,notes:s};J.push(O.name),a(` applied ${O.name}`)}return{ref:e,directory:o,ok:!0,applied:J,notes:s}}oe();be();ne();import{readFile as fl}from"node:fs/promises";function Zo(e){if(e==="apns"||e==="fcm")return e;throw new m("say which: apns (an Apple .p8) or fcm (a Firebase service account)")}async function Ih(e){let t=await _("cloud-project-push",{ref:e,credentials:{list:!0}});return{ref:e,credentials:t??{}}}async function gl(e){if(!e.p8||!e.keyId||!e.teamId||!e.topic)throw new m("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 m("--environment is production or sandbox; leave it out for a key that serves both");return{topic:e.topic,keys:[{p8:await fl(e.p8,"utf8"),key_id:e.keyId,team_id:e.teamId,environment:e.environment??null}]}}async function hl(e){if(!e)throw new m("push credentials set fcm needs --file service-account.json");return{service_account:await fl(e,"utf8")}}async function Ch(e,t,n){let r=await _("cloud-project-push",{ref:e,credentials:{set:{kind:t,body:n}}});return{ref:e,kind:t,summary:r}}async function jh(e,t){return await _("cloud-project-push",{ref:e,credentials:{remove:t}}),{ref:e,kind:t,removed:!0}}async function yl(e){let t=await Ih(e);h(t,()=>{let{apns:n,fcm:r,vapid:o}=t.credentials;process.stdout.write(`${B([["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}`:""]])}
535
+ `),(!n||!r)&&d(w(` 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 wl(e,t,n){let r=await Ch(e,t,n);h(r,()=>d(`${t==="apns"?"The Apple key signed":"Google accepted the service account"}, and it is stored in the project's own database.`))}async function bl(e,t){let n=await jh(e,t);h(n,()=>d(`${t} credentials removed. Devices on it stop receiving until new ones are set.`))}oe();me();ne();import{spawn as Vh}from"node:child_process";import{writeFileSync as Yh}from"node:fs";import{isAbsolute as Xh,resolve as Zh}from"node:path";var Mh=" ";function F(e){return Mh.repeat(e)}function we(e){return JSON.stringify(e)}function Me(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:we(e)}function ut(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function Lh(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 Uh={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"},Bh={sqlserver:{bit:"boolean"},"mysql-aurora":{bit:"number"},mariadb:{bit:"number"},sqlite:{bit:"number"},snowflake:{array:"json"}};function Fh(e,t){let n=Bh[e]?.[t];return n||(Uh[t]??"unknown")}function yr(e,t){let{base:n,array:r}=Lh(t),o=e.enumRefs.get(n);if(o)return r?`${o}[]`:o;if(n==="array")return"unknown[]";let s=Fh(e.driverId,n),a=s==="json"?"Json":s;return r?`${a}[]`:a}function Hh(e){return e.nullable||e.autoIncrement===!0||e.default!==null&&e.default!==void 0}function Qo(e,t,n,r,o=!1){if(o&&t.generatedAlways===!0)return`${F(n)}${Me(t.name)}?: never`;let s=yr(e,t.dataType),a=t.nullable?`${s} | null`:s;return`${F(n)}${Me(t.name)}${r?"?":""}: ${a}`}function Kh(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 qh(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(`${F(t)}Relationships: []`),n;n.push(`${F(t)}Relationships: [`);for(let o of r)n.push(`${F(t+1)}{`),n.push(`${F(t+2)}foreignKeyName: ${we(o.constraintName)}`),n.push(`${F(t+2)}columns: [${o.columns.map(we).join(", ")}]`),n.push(`${F(t+2)}isOneToOne: ${Kh(e,o)?"true":"false"}`),n.push(`${F(t+2)}referencedRelation: ${we(o.referencedTable)}`),n.push(`${F(t+2)}referencedColumns: [${o.referencedColumns.map(we).join(", ")}]`),n.push(`${F(t+1)}},`);return n.push(`${F(t)}]`),n}function _l(e,t,n){let r=ut(t.columns),o=[];o.push(`${F(n)}${Me(t.name)}: {`),o.push(`${F(n+1)}Row: {`);for(let s of r)o.push(Qo(e,s,n+2,!1));if(o.push(`${F(n+1)}}`),t.kind!=="view"){o.push(`${F(n+1)}Insert: {`);for(let s of r)o.push(Qo(e,s,n+2,Hh(s),!0));o.push(`${F(n+1)}}`),o.push(`${F(n+1)}Update: {`);for(let s of r)o.push(Qo(e,s,n+2,!0,!0));o.push(`${F(n+1)}}`)}return o.push(...qh(t,n+1)),o.push(`${F(n)}}`),o}function tn(e,t){return[`${F(t)}${e}: {`,`${F(t+1)}[_ in never]: never`,`${F(t)}}`]}function Gh(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}[]`:`${yr(e,s)}[]`}return r==="record"||r==="trigger"||r==="event_trigger"?"unknown":e.rowRefs.get(r)??yr(e,n)}function zh(e,t,n){let r=[],o=ut((t.parameters??[]).filter(s=>s.name.length>0&&(s.mode??"IN").toUpperCase()!=="OUT").map(s=>({name:s.name,dataType:s.dataType})));if(r.push(`${F(n)}${Me(t.name)}: {`),o.length===0)r.push(`${F(n+1)}Args: never`);else{r.push(`${F(n+1)}Args: {`);for(let s of o)r.push(`${F(n+2)}${Me(s.name)}: ${yr(e,s.dataType)}`);r.push(`${F(n+1)}}`)}return r.push(`${F(n+1)}Returns: ${Gh(e,t)}`),r.push(`${F(n)}}`),r}function Et(e,t){return e.schema&&e.schema.length>0?e.schema:t}function Sl(e,t={}){let n=t.defaultSchema??"public",r=t.driverId??"postgres",o=t.enums??[],s=new Map;for(let p of o){let f=p.schema&&p.schema.length>0?p.schema:n;s.set(p.name.toLowerCase(),`Database[${we(f)}][${we("Enums")}][${we(p.name)}]`)}let a=new Map;for(let p of e.tables){let f=Et(p,n),k=p.kind==="view"?"Views":"Tables";a.set(p.name.toLowerCase(),`Database[${we(f)}][${we(k)}][${we(p.name)}][${we("Row")}]`)}let l={driverId:r,defaultSchema:n,enumRefs:s,rowRefs:a},i=new Set([n]);for(let p of e.tables)i.add(Et(p,n));for(let p of e.routines??[])i.add(Et(p,n));for(let p of o)i.add(p.schema&&p.schema.length>0?p.schema:n);let u=[...i].sort(),c=[];c.push("export type Json ="),c.push(" | string"),c.push(" | number"),c.push(" | boolean"),c.push(" | null"),c.push(" | { [key: string]: Json | undefined }"),c.push(" | Json[]"),c.push(""),c.push("export type Database = {");for(let p of u){let f=ut(e.tables.filter(D=>Et(D,n)===p&&D.kind!=="view")),k=ut(e.tables.filter(D=>Et(D,n)===p&&D.kind==="view")),v=ut((e.routines??[]).filter(D=>Et(D,n)===p)),Y=ut(o.filter(D=>(D.schema&&D.schema.length>0?D.schema:n)===p));if(c.push(`${F(1)}${Me(p)}: {`),f.length===0)c.push(...tn("Tables",2));else{c.push(`${F(2)}Tables: {`);for(let D of f)c.push(..._l(l,D,3));c.push(`${F(2)}}`)}if(k.length===0)c.push(...tn("Views",2));else{c.push(`${F(2)}Views: {`);for(let D of k)c.push(..._l(l,D,3));c.push(`${F(2)}}`)}if(v.length===0)c.push(...tn("Functions",2));else{c.push(`${F(2)}Functions: {`);for(let D of v)c.push(...zh(l,D,3));c.push(`${F(2)}}`)}if(Y.length===0)c.push(...tn("Enums",2));else{c.push(`${F(2)}Enums: {`);for(let D of Y)c.push(`${F(3)}${Me(D.name)}: ${D.values.map(we).join(" | ")}`);c.push(`${F(2)}}`)}c.push(...tn("CompositeTypes",2)),c.push(`${F(1)}}`)}return c.push("}"),t.helpers!==!1&&(c.push(""),c.push(Jh(n))),t.constants!==!1&&(c.push(""),c.push(Wh(u,o,n))),`${c.join(`
532
536
  `)}
533
- `}function Lh(e,t,n){let r=["export const Constants = {"];for(let o of e){let s=dt(t.filter(a=>(a.schema&&a.schema.length>0?a.schema:n)===o));if(s.length===0){r.push(`${U(1)}${Me(o)}: {`),r.push(`${U(2)}Enums: {},`),r.push(`${U(1)}},`);continue}r.push(`${U(1)}${Me(o)}: {`),r.push(`${U(2)}Enums: {`);for(let a of s)r.push(`${U(3)}${Me(a.name)}: [${a.values.map(we).join(", ")}],`);r.push(`${U(2)}},`),r.push(`${U(1)}},`)}return r.push("} as const"),r.join(`
534
- `)}function Uh(e){return`type DefaultSchemaName = Extract<keyof Database, ${we(e)}>
537
+ `}function Wh(e,t,n){let r=["export const Constants = {"];for(let o of e){let s=ut(t.filter(a=>(a.schema&&a.schema.length>0?a.schema:n)===o));if(s.length===0){r.push(`${F(1)}${Me(o)}: {`),r.push(`${F(2)}Enums: {},`),r.push(`${F(1)}},`);continue}r.push(`${F(1)}${Me(o)}: {`),r.push(`${F(2)}Enums: {`);for(let a of s)r.push(`${F(3)}${Me(a.name)}: [${a.values.map(we).join(", ")}],`);r.push(`${F(2)}},`),r.push(`${F(1)}},`)}return r.push("} as const"),r.join(`
538
+ `)}function Jh(e){return`type DefaultSchemaName = Extract<keyof Database, ${we(e)}>
535
539
 
536
540
  type InSchema = { schema: keyof Database }
537
541
 
@@ -568,7 +572,7 @@ export type Enums<
568
572
  export type CompositeTypes<
569
573
  Choice extends keyof Database[DefaultSchemaName]["CompositeTypes"] | InSchema,
570
574
  Name extends Choice extends InSchema ? keyof Database[Choice["schema"]]["CompositeTypes"] : never = never,
571
- > = Lookup<Database[SchemaOf<Choice>]["CompositeTypes"], NameOf<Choice, Name>>`}function qh(e){let t=Yt(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 hr(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 Zo(e,t){return new Promise(n=>{let r=Bh("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 Gh=`
575
+ > = Lookup<Database[SchemaOf<Choice>]["CompositeTypes"], NameOf<Choice, Name>>`}function Qh(e){let t=Xt(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 wr(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 es(e,t){return new Promise(n=>{let r=Vh("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 ey=`
572
576
  with wanted as (select unnest($SCHEMAS$::text[]) as nspname)
573
577
  select json_build_object(
574
578
  'tables', coalesce((
@@ -672,40 +676,40 @@ select json_build_object(
672
676
  where t.typtype = 'e' and n.nspname in (select nspname from wanted)
673
677
  ), '[]'::json)
674
678
  )::text
675
- `;function Wh(e){return`'{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",").replace(/'/g,"''")}}'`}function zh(e,t,n=0){let r=e.tables.map(a=>{let l=a.primaryKey??[],i=new Set(l),u=a.columns.map(c=>({name:c.name,dataType:c.dataType,nullable:c.nullable,isPrimaryKey:i.has(c.name),default:c.default,autoIncrement:c.autoIncrement,...c.generatedAlways===!0?{generatedAlways:!0}:{}}));return{name:a.name,schema:a.schema,kind:a.kind,columns:u,primaryKey:l,foreignKeys:(a.foreignKeys??[]).map(c=>({constraintName:c.constraintName,columns:c.columns??[],referencedTable:c.referencedTable,referencedColumns:c.referencedColumns??[]})),indexes:(a.indexes??[]).filter(c=>Array.isArray(c.columns)&&c.columns.every(p=>typeof p=="string")).map(c=>({name:c.name,unique:c.unique,columns:c.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 Jh=`select exists (
679
+ `;function ty(e){return`'{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",").replace(/'/g,"''")}}'`}function ny(e,t,n=0){let r=e.tables.map(a=>{let l=a.primaryKey??[],i=new Set(l),u=a.columns.map(c=>({name:c.name,dataType:c.dataType,nullable:c.nullable,isPrimaryKey:i.has(c.name),default:c.default,autoIncrement:c.autoIncrement,...c.generatedAlways===!0?{generatedAlways:!0}:{}}));return{name:a.name,schema:a.schema,kind:a.kind,columns:u,primaryKey:l,foreignKeys:(a.foreignKeys??[]).map(c=>({constraintName:c.constraintName,columns:c.columns??[],referencedTable:c.referencedTable,referencedColumns:c.referencedColumns??[]})),indexes:(a.indexes??[]).filter(c=>Array.isArray(c.columns)&&c.columns.every(p=>typeof p=="string")).map(c=>({name:c.name,unique:c.unique,columns:c.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 ry=`select exists (
676
680
  select from pg_class c join pg_namespace n on n.oid = c.relnamespace
677
681
  where n.nspname = 'lepis' and c.relname = 'relation'
678
- )::text`,Vh=`select coalesce(json_agg(json_build_object(
682
+ )::text`,oy=`select coalesce(json_agg(json_build_object(
679
683
  'schema', schema_name, 'table', table_name, 'kind', kind, 'keyColumn', key_column
680
- ) order by schema_name, table_name), '[]'::json)::text from lepis.relation`;function Yh(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:Xh(t)}function Xh(e){let t=(n,r)=>{let o=new Set,s=[];for(let a of n)for(let l of a??[]){let i=r(l);o.has(i)||(o.add(i),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 Zh(e,t){let n=await e(Jh);if(n.code!==0||n.out.trim()!=="true")return[];let r=await e(Vh);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 Qh(e){let t=e.schemas&&e.schemas.length>0?[...e.schemas]:["public"],n=e.dbUrl?hr(e.dbUrl):qh(await ke(ey(e))),r=!1,o=async v=>{if(e.sql)return e.sql(v);if(r&&e.ref)return Sl(e.ref,v);let V=await Zo(n,v);return V.code===127&&!e.dbUrl&&e.ref?(r=!0,Sl(e.ref,v)):V},s=Gh.replace("$SCHEMAS$",Wh(t)),a=await o(s);a.code===127&&H("tool-missing",a.err.trim()),a.code!==0&&H("failed",a.err.trim()||`could not read the schema of ${n.label}`);let l=a.out.trim();l||H("failed",`${n.label} returned nothing for the schema query`);let i=Yh(l);i||H("failed",`could not read the schema of ${n.label}: the answer was not JSON`);let u=await Zh(o,t),{schema:c,enums:p}=zh(i,n.database,Date.now()),f=_l(c,{driverId:"postgres",defaultSchema:e.defaultSchema??t[0]??"public",enums:p}),k=null;return e.out&&(k=Hh(e.out)?e.out:Kh(process.cwd(),e.out),Fh(k,f,"utf8")),{target:n.label,schemas:t,tables:c.tables.filter(v=>v.kind!=="view").length,views:c.tables.filter(v=>v.kind==="view").length,functions:(c.routines??[]).length,enums:p.length,path:k,distribution:u,types:f}}async function Sl(e,t,n=_){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 ey(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 kl(e,t){let n=(e??"typescript").toLowerCase();n!=="typescript"&&n!=="ts"&&H("usage",`gen types does not know how to write ${e}. It writes typescript, which is the only language it claims.`);let r=await Qh(t);return r.path&&d(`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}.`),h(r,()=>{r.path||process.stdout.write(r.types)}),0}me();import{createHash as Iw}from"node:crypto";import{existsSync as Cs,mkdirSync as Cw,readFileSync as js,readdirSync as jw,statSync as Dw,writeFileSync as Mw}from"node:fs";import{dirname as Lw,isAbsolute as vu,join as dn,resolve as $u}from"node:path";import{pathToFileURL as Uw}from"node:url";te();function Bw(e){return/^[a-z][a-z0-9+.-]+:/i.test(e)?e:vu(e)||e.startsWith("./")||e.startsWith("../")?Uw($u(e)).href:e}function Fw(){let e=process.env.SNOUTDATA_LOCAL_RUNTIME;return e?import(Bw(e)):Promise.resolve().then(()=>(bu(),wu))}function Hw(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 _u="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 Su(e,t){try{return await e.localImageFor(t)}catch(n){return n instanceof Error?n.message:String(n)}}async function un(){let e;try{e=await Fw()}catch(t){H("tool-missing",Hw(t))}return{ready:async t=>{let n=await Su(e,t);return typeof n=="string"?await e.podmanReady(_u)??n:e.podmanReady(_u,n.name)},ensureImage:async(t,n)=>{let r=await Su(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 xu(e){return dn(e,".snoutdata","local.json")}function Ar(e){let t=xu(e);if(!Cs(t))return null;try{let n=JSON.parse(js(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 Kw(e,t){let n=xu(e);return Cw(Lw(n),{recursive:!0}),Mw(n,`${JSON.stringify(t,null,2)}
681
- `,{encoding:"utf8",mode:384}),n}var qw=54322;async function Pu(e,t){let n=await e.ensureImage(t,o=>d(o));n&&H("tool-missing",n);let r=await e.ready(t);r&&H("tool-missing",r),await e.prepare()}function Eu(e,t,n,r=Zo){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 Gw(e,t={}){let n=t.cwd??process.cwd(),r=Ar(n);await Pu(e,r?.ref??null);let o=r??e.mint(t.port??qw),s=r?null:Kw(n,o),a=await e.start(o,p=>d(p)),l=e.uri(o);if(t.noMigrations)return{status:a,uri:l,applied:[],seeded:!1,created:s};let i=Eu(e,o,hr(l)),u=await Ww(i,n,t),c=await zw(i,n,u.length>0||!!s);return{status:a,uri:l,applied:u,seeded:c,created:s}}async function Ww(e,t,n){let r=$u(n.dir===void 0?dn(t,"migrations"):vu(n.dir)?n.dir:dn(t,n.dir));if(!Cs(r)||!Dw(r).isDirectory())return[];let o=jw(r).filter(p=>p.endsWith(".sql")).map(p=>{let f=js(dn(r,p),"utf8");return{name:p,sql:f,checksum:Iw("sha256").update(f,"utf8").digest("hex")}});if(o.length===0)return[];let s=await e(Jw);s.code!==0&&H(s.code===127?"tool-missing":"failed",s.err.trim()||`could not create ${ln}`);let a=await e(`select name || E'\\t' || checksum from ${ln};`);a.code!==0&&H("failed",a.err.trim()||`could not read ${ln}`);let l=a.out.split(`
682
- `).map(p=>p.trim()).filter(p=>p.length>0).map(p=>{let f=p.indexOf(" ");return{name:p.slice(0,f),checksum:p.slice(f+1)}}),i=ur(o,l,{outOfOrder:n.outOfOrder});i.ok||H("conflict",`Refused. This folder and the local database do not agree:
684
+ ) order by schema_name, table_name), '[]'::json)::text from lepis.relation`;function sy(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:ay(t)}function ay(e){let t=(n,r)=>{let o=new Set,s=[];for(let a of n)for(let l of a??[]){let i=r(l);o.has(i)||(o.add(i),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 iy(e,t){let n=await e(ry);if(n.code!==0||n.out.trim()!=="true")return[];let r=await e(oy);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 cy(e){let t=e.schemas&&e.schemas.length>0?[...e.schemas]:["public"],n=e.dbUrl?wr(e.dbUrl):Qh(await ke(ly(e))),r=!1,o=async v=>{if(e.sql)return e.sql(v);if(r&&e.ref)return kl(e.ref,v);let Y=await es(n,v);return Y.code===127&&!e.dbUrl&&e.ref?(r=!0,kl(e.ref,v)):Y},s=ey.replace("$SCHEMAS$",ty(t)),a=await o(s);a.code===127&&K("tool-missing",a.err.trim()),a.code!==0&&K("failed",a.err.trim()||`could not read the schema of ${n.label}`);let l=a.out.trim();l||K("failed",`${n.label} returned nothing for the schema query`);let i=sy(l);i||K("failed",`could not read the schema of ${n.label}: the answer was not JSON`);let u=await iy(o,t),{schema:c,enums:p}=ny(i,n.database,Date.now()),f=Sl(c,{driverId:"postgres",defaultSchema:e.defaultSchema??t[0]??"public",enums:p}),k=null;return e.out&&(k=Xh(e.out)?e.out:Zh(process.cwd(),e.out),Yh(k,f,"utf8")),{target:n.label,schemas:t,tables:c.tables.filter(v=>v.kind!=="view").length,views:c.tables.filter(v=>v.kind==="view").length,functions:(c.routines??[]).length,enums:p.length,path:k,distribution:u,types:f}}async function kl(e,t,n=_){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 ly(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 vl(e,t){let n=(e??"typescript").toLowerCase();n!=="typescript"&&n!=="ts"&&K("usage",`gen types does not know how to write ${e}. It writes typescript, which is the only language it claims.`);let r=await cy(t);return r.path&&d(`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}.`),h(r,()=>{r.path||process.stdout.write(r.types)}),0}me();import{createHash as Vw}from"node:crypto";import{existsSync as Cs,mkdirSync as Yw,readFileSync as js,readdirSync as Xw,statSync as Zw,writeFileSync as Qw}from"node:fs";import{dirname as eb,isAbsolute as Au,join as pn,resolve as Ru}from"node:path";import{pathToFileURL as tb}from"node:url";ne();function nb(e){return/^[a-z][a-z0-9+.-]+:/i.test(e)?e:Au(e)||e.startsWith("./")||e.startsWith("../")?tb(Ru(e)).href:e}function rb(){let e=process.env.SNOUTDATA_LOCAL_RUNTIME;return e?import(nb(e)):Promise.resolve().then(()=>($u(),vu))}function ob(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 xu="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 Pu(e,t){try{return await e.localImageFor(t)}catch(n){return n instanceof Error?n.message:String(n)}}async function mn(){let e;try{e=await rb()}catch(t){K("tool-missing",ob(t))}return{ready:async t=>{let n=await Pu(e,t);return typeof n=="string"?await e.podmanReady(xu)??n:e.podmanReady(xu,n.name)},ensureImage:async(t,n)=>{let r=await Pu(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 Tu(e){return pn(e,".snoutdata","local.json")}function Tr(e){let t=Tu(e);if(!Cs(t))return null;try{let n=JSON.parse(js(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 sb(e,t){let n=Tu(e);return Yw(eb(n),{recursive:!0}),Qw(n,`${JSON.stringify(t,null,2)}
685
+ `,{encoding:"utf8",mode:384}),n}var ab=54322;async function Ou(e,t){let n=await e.ensureImage(t,o=>d(o));n&&K("tool-missing",n);let r=await e.ready(t);r&&K("tool-missing",r),await e.prepare()}function Nu(e,t,n,r=es){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 ib(e,t={}){let n=t.cwd??process.cwd(),r=Tr(n);await Ou(e,r?.ref??null);let o=r??e.mint(t.port??ab),s=r?null:sb(n,o),a=await e.start(o,p=>d(p)),l=e.uri(o);if(t.noMigrations)return{status:a,uri:l,applied:[],seeded:!1,created:s};let i=Nu(e,o,wr(l)),u=await cb(i,n,t),c=await lb(i,n,u.length>0||!!s);return{status:a,uri:l,applied:u,seeded:c,created:s}}async function cb(e,t,n){let r=Ru(n.dir===void 0?pn(t,"migrations"):Au(n.dir)?n.dir:pn(t,n.dir));if(!Cs(r)||!Zw(r).isDirectory())return[];let o=Xw(r).filter(p=>p.endsWith(".sql")).map(p=>{let f=js(pn(r,p),"utf8");return{name:p,sql:f,checksum:Vw("sha256").update(f,"utf8").digest("hex")}});if(o.length===0)return[];let s=await e(db);s.code!==0&&K(s.code===127?"tool-missing":"failed",s.err.trim()||`could not create ${un}`);let a=await e(`select name || E'\\t' || checksum from ${un};`);a.code!==0&&K("failed",a.err.trim()||`could not read ${un}`);let l=a.out.split(`
686
+ `).map(p=>p.trim()).filter(p=>p.length>0).map(p=>{let f=p.indexOf(" ");return{name:p.slice(0,f),checksum:p.slice(f+1)}}),i=mr(o,l,{outOfOrder:n.outOfOrder});i.ok||K("conflict",`Refused. This folder and the local database do not agree:
683
687
  ${i.problems.map(p=>` ${p.reason}`).join(`
684
- `)}`,{problems:i.problems});let u=new Map(o.map(p=>[p.name,p])),c=[];for(let p of i.pending){let f=u.get(p.name),k=`insert into ${ln} (name, checksum) values (${ku(f.name)}, ${ku(f.checksum)});`,v=Pt(f.sql);v||d(`${f.name} runs outside a transaction, so an interruption can leave it half applied.`);let V=v?`begin;
688
+ `)}`,{problems:i.problems});let u=new Map(o.map(p=>[p.name,p])),c=[];for(let p of i.pending){let f=u.get(p.name),k=`insert into ${un} (name, checksum) values (${Eu(f.name)}, ${Eu(f.checksum)});`,v=Pt(f.sql);v||d(`${f.name} runs outside a transaction, so an interruption can leave it half applied.`);let Y=v?`begin;
685
689
  ${f.sql}
686
690
  ${k}
687
691
  commit;
688
692
  `:`${f.sql}
689
693
  ${k}
690
- `,j=await e(V);j.code!==0&&H("failed",`${f.name} failed, and nothing after it was tried.
691
- ${j.err.trim()}`,{failed:f.name,applied:c}),c.push(f.name),d(` applied ${f.name}`)}return c}async function zw(e,t,n){let r=dn(t,"seed.sql");if(!n||!Cs(r))return!1;let o=await e(js(r,"utf8"));return o.code!==0&&H("failed",`seed.sql failed.
692
- ${o.err.trim()}`),d(" ran seed.sql"),!0}var ln="_snoutdata_migrations",Jw=`create table if not exists ${ln} (
694
+ `,D=await e(Y);D.code!==0&&K("failed",`${f.name} failed, and nothing after it was tried.
695
+ ${D.err.trim()}`,{failed:f.name,applied:c}),c.push(f.name),d(` applied ${f.name}`)}return c}async function lb(e,t,n){let r=pn(t,"seed.sql");if(!n||!Cs(r))return!1;let o=await e(js(r,"utf8"));return o.code!==0&&K("failed",`seed.sql failed.
696
+ ${o.err.trim()}`),d(" ran seed.sql"),!0}var un="_snoutdata_migrations",db=`create table if not exists ${un} (
693
697
  name text primary key,
694
698
  checksum text not null,
695
699
  applied_at timestamptz not null default now()
696
- );`;function ku(e){return`'${e.replace(/'/g,"''")}'`}function Vw(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 Au(e,t={}){let n=await Gw(e,t);return h(n,()=>{n.created&&(d(""),d(`Wrote ${n.created}. It holds a password, so put .snoutdata/ in your .gitignore.`)),d(""),d(` ${x("Database")} running on port ${n.status.port}`),n.applied.length>0&&d(` ${x("Migrations")} ${n.applied.length} applied`),n.seeded&&d(` ${x("Seed")} seed.sql ran`),d(""),process.stdout.write(`${n.uri}
697
- `),d(w(" snoutdata gen types typescript --local > database.types.ts")),d(w(" snoutdata stop"))}),0}async function Ru(e,t={}){let n=t.cwd??process.cwd(),r=Ar(n);r||H("not-found","there is no local database for this folder. `snoutdata start` makes one."),await Pu(e,r.ref);let o=await e.stop(r.ref);return h(o,()=>d("Stopped. The data is still there; `snoutdata start` brings it back.")),0}async function Tu(e,t={}){let n=t.cwd??process.cwd(),r=Ar(n);if(!r)return h({exists:!1,ref:null,status:"absent"},()=>d("No local database for this folder. `snoutdata start` makes one.")),0;let o=await e.ready(r.ref);if(o)return h({exists:!1,ref:r.ref,status:"unknown",reason:o},()=>d(o)),0;let s=await e.status(r);return h({...s,uri:s.uri},()=>{d(` ${x("Project")} ${s.ref}`),d(` ${x("State")} ${s.ready?"running":s.status}`),d(` ${x("Port")} ${s.port}`),d(` ${x("Size")} ${Vw(s.databaseBytes)}`),s.services.length>0&&d(` ${x("Services")} ${s.services.join(", ")}`),s.uri&&process.stdout.write(`${s.uri}
698
- `)}),0}async function Ou(e,t=process.cwd()){let n=Ar(t);n||H("not-found","there is no local database for this folder. `snoutdata start` makes one.");let r=e.uri(n);return{dbUrl:r,sql:Eu(e,n,hr(r))}}re();te();$n();Ct();Ge();import{resolve as Nu}from"node:path";function Yw(){let e=n=>He(n),t;return{shards:n=>{if(n!==void 0)return Gt({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??=Gt({}),t},whoami:()=>it(),listProjects:async()=>({...await xe(),local:Xw()}),localProject:n=>e(n),createProject:async n=>{let r=await _("cloud-project-create",{name:n.name,...n.region?{region:n.region}:{},...n.teamId?{teamId:n.teamId}:{}});try{return await Ft(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)=>_("cloud-project-usage",{ref:n,...r?{days:r}:{}}),exportStatus:n=>_t(n),requestExport:n=>Ut(n),resetPassword:n=>_("cloud-project-reset-password",{ref:n}),listTeams:()=>_("cloud-team-list",{}),deployFunction:(n,r,o)=>{let s=e(n);return s?to(s,r,o):co(n,r,o).then(a=>a.answer)},listFunctions:async n=>{let r=e(n);return r?Kn(r):lo(n)},deleteFunction:(n,r)=>{let o=e(n);return o?ro(o,r):uo(n,r)},sizeFunction:(n,r,o)=>po(n,r,o),listFunctionSecrets:async n=>{let r=e(n);return r?Gn(r):_("cloud-project-secrets",{ref:n})},functionLogs:(n,r)=>_("cloud-project-functions",{ref:n,action:"logs",...r.name?{name:r.name}:{},...r.errorsOnly?{errorsOnly:!0}:{},...r.limit?{limit:r.limit}:{}}),listContainers:n=>kt(n),deployContainer:(n,r,o)=>wo(n,r,o),restartContainer:(n,r)=>_o(n,r),deleteContainer:(n,r)=>bo(n,r),containerLogs:(n,r)=>zn(n,r),containerEgress:async n=>{let r=await kt(n);return{ref:r.ref,allowlist:r.allowlist??null}},setContainerEgress:async(n,r)=>{let o=await Jn(n,r);return{ref:o.ref,allowlist:o.allowlist??null,note:"Running containers follow it within a minute; nothing restarts."}},listTokens:()=>_("cloud-token-list",{}),createToken:(n,r,o)=>_("cloud-token-create",{name:n,...r?{expiresInDays:r}:{},...o?{project:o}:{}}),revokeToken:n=>_("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:Kn(r).functions.map(o=>o.name),secretNames:Gn(r).secrets.map(o=>o.name)}:Do(n)},getProducts:n=>$t(n),setProduct:(n,r,o)=>No(n,r,o),listDomains:n=>tr(n),domainAction:(n,r,o)=>Io(n,r,o),restoreWindow:n=>Co(n),restoreTo:(n,r,o)=>jo(n,r,o),setProjectState:async(n,r)=>{let o=await _(`cloud-project-${n}`,{ref:r});try{let s=await Bt(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.`}}},connection:n=>ke(n),pushMigrations:(n,r)=>Vo(n,{dir:r.dir,dryRun:r.dryRun})}}function Xw(){let e=yn().filter(n=>n.ref!==null).map(n=>({ref:n.ref,name:n.name,folder:n.folder})),t=ft(process.cwd())?.local;if(t&&!e.some(n=>Nu(n.folder)===Nu(t)))try{let n=ze(t);e.push({ref:n.ref,name:n.name,folder:n.folder})}catch{}return e}var Iu="app_";async function Zw(){if(process.env.SNOUTDATA_NO_DESKTOP)return{tools:[],config:null};let e=await kn();if(!e.available)return{tools:[],config:null};let t=e.config;try{return{tools:(await fa(t)).map(o=>({name:`${Iu}${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 Cu(e){Lt(!0);let{tools:t,config:n}=await Zw(),r=Yw();n&&(r.callBorrowed=(i,u)=>ga(n,i.slice(Iu.length),u));let o={...e,borrowed:t};Q(t.length>0?`snoutdata mcp: ${Vt.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 i=await it();Q(`snoutdata mcp: signed in as ${i.email??"this account"}.`)}catch(i){if(Q(`snoutdata mcp: ${i instanceof Error?i.message:String(i)}`),!process.env.LEPIS_ADMIN_URL)return Q("Sign in with `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN."),3;Q(`snoutdata mcp: not signed in, so only the cluster tools will work (router ${process.env.LEPIS_ADMIN_URL}).`)}Q(`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(i){a.add(i),i.finally(()=>a.delete(i))}return new Promise(i=>{process.stdin.on("data",u=>{let c=tc(s+u);s=c.rest;for(let p of c.messages)l(Qw(p,r,o))}),process.stdin.on("end",()=>{(async()=>{for(;a.size>0;)await Promise.allSettled([...a]);i(0)})()}),process.stdin.on("error",()=>i(1))})}async function Qw(e,t,n){let r;try{r=JSON.parse(e)}catch{Q(`snoutdata mcp: ignoring a line that is not JSON: ${e.slice(0,120)}`);return}try{let o=await ec(r,t,n);o&&process.stdout.write(`${JSON.stringify(o)}
700
+ );`;function Eu(e){return`'${e.replace(/'/g,"''")}'`}function ub(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 Iu(e,t={}){let n=await ib(e,t);return h(n,()=>{n.created&&(d(""),d(`Wrote ${n.created}. It holds a password, so put .snoutdata/ in your .gitignore.`)),d(""),d(` ${x("Database")} running on port ${n.status.port}`),n.applied.length>0&&d(` ${x("Migrations")} ${n.applied.length} applied`),n.seeded&&d(` ${x("Seed")} seed.sql ran`),d(""),process.stdout.write(`${n.uri}
701
+ `),d(w(" snoutdata gen types typescript --local > database.types.ts")),d(w(" snoutdata stop"))}),0}async function Cu(e,t={}){let n=t.cwd??process.cwd(),r=Tr(n);r||K("not-found","there is no local database for this folder. `snoutdata start` makes one."),await Ou(e,r.ref);let o=await e.stop(r.ref);return h(o,()=>d("Stopped. The data is still there; `snoutdata start` brings it back.")),0}async function ju(e,t={}){let n=t.cwd??process.cwd(),r=Tr(n);if(!r)return h({exists:!1,ref:null,status:"absent"},()=>d("No local database for this folder. `snoutdata start` makes one.")),0;let o=await e.ready(r.ref);if(o)return h({exists:!1,ref:r.ref,status:"unknown",reason:o},()=>d(o)),0;let s=await e.status(r);return h({...s,uri:s.uri},()=>{d(` ${x("Project")} ${s.ref}`),d(` ${x("State")} ${s.ready?"running":s.status}`),d(` ${x("Port")} ${s.port}`),d(` ${x("Size")} ${ub(s.databaseBytes)}`),s.services.length>0&&d(` ${x("Services")} ${s.services.join(", ")}`),s.uri&&process.stdout.write(`${s.uri}
702
+ `)}),0}async function Du(e,t=process.cwd()){let n=Tr(t);n||K("not-found","there is no local database for this folder. `snoutdata start` makes one.");let r=e.uri(n);return{dbUrl:r,sql:Nu(e,n,wr(r))}}oe();ne();Pn();jt();Ge();import{resolve as Mu}from"node:path";function pb(){let e=n=>He(n),t;return{shards:n=>{if(n!==void 0)return zt({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??=zt({}),t},whoami:()=>ct(),listProjects:async()=>({...await xe(),local:mb()}),localProject:n=>e(n),createProject:async n=>{let r=await _("cloud-project-create",{name:n.name,...n.region?{region:n.region}:{},...n.teamId?{teamId:n.teamId}:{}});try{return await Ht(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)=>_("cloud-project-usage",{ref:n,...r?{days:r}:{}}),exportStatus:n=>_t(n),requestExport:n=>Bt(n),resetPassword:n=>_("cloud-project-reset-password",{ref:n}),listTeams:()=>_("cloud-team-list",{}),deployFunction:(n,r,o)=>{let s=e(n);return s?ro(s,r,o):uo(n,r,o).then(a=>a.answer)},listFunctions:async n=>{let r=e(n);return r?Gn(r):po(n)},deleteFunction:(n,r)=>{let o=e(n);return o?so(o,r):mo(n,r)},sizeFunction:(n,r,o)=>fo(n,r,o),listFunctionSecrets:async n=>{let r=e(n);return r?Wn(r):_("cloud-project-secrets",{ref:n})},functionLogs:(n,r)=>_("cloud-project-functions",{ref:n,action:"logs",...r.name?{name:r.name}:{},...r.errorsOnly?{errorsOnly:!0}:{},...r.limit?{limit:r.limit}:{}}),listContainers:n=>kt(n),deployContainer:(n,r,o)=>_o(n,r,o),restartContainer:(n,r)=>ko(n,r),deleteContainer:(n,r)=>So(n,r),containerLogs:(n,r)=>Vn(n,r),containerEgress:async n=>{let r=await kt(n);return{ref:r.ref,allowlist:r.allowlist??null}},setContainerEgress:async(n,r)=>{let o=await Yn(n,r);return{ref:o.ref,allowlist:o.allowlist??null,note:"Running containers follow it within a minute; nothing restarts."}},listTokens:()=>_("cloud-token-list",{}),createToken:(n,r,o)=>_("cloud-token-create",{name:n,...r?{expiresInDays:r}:{},...o?{project:o}:{}}),revokeToken:n=>_("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:Gn(r).functions.map(o=>o.name),secretNames:Wn(r).secrets.map(o=>o.name)}:Lo(n)},getProducts:n=>$t(n),setProduct:(n,r,o)=>Co(n,r,o),listDomains:n=>rr(n),domainAction:(n,r,o)=>jo(n,r,o),restoreWindow:n=>Do(n),restoreTo:(n,r,o)=>Mo(n,r,o),setProjectState:async(n,r)=>{let o=await _(`cloud-project-${n}`,{ref:r});try{let s=await Ft(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.`}}},connection:n=>ke(n),pushMigrations:(n,r)=>Xo(n,{dir:r.dir,dryRun:r.dryRun})}}function mb(){let e=bn().filter(n=>n.ref!==null).map(n=>({ref:n.ref,name:n.name,folder:n.folder})),t=ft(process.cwd())?.local;if(t&&!e.some(n=>Mu(n.folder)===Mu(t)))try{let n=We(t);e.push({ref:n.ref,name:n.name,folder:n.folder})}catch{}return e}var Lu="app_";async function fb(){if(process.env.SNOUTDATA_NO_DESKTOP)return{tools:[],config:null};let e=await $n();if(!e.available)return{tools:[],config:null};let t=e.config;try{return{tools:(await fa(t)).map(o=>({name:`${Lu}${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 Uu(e){Ut(!0);let{tools:t,config:n}=await fb(),r=pb();n&&(r.callBorrowed=(i,u)=>ga(n,i.slice(Lu.length),u));let o={...e,borrowed:t};ee(t.length>0?`snoutdata mcp: ${Yt.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 i=await ct();ee(`snoutdata mcp: signed in as ${i.email??"this account"}.`)}catch(i){if(ee(`snoutdata mcp: ${i instanceof Error?i.message:String(i)}`),!process.env.LEPIS_ADMIN_URL)return ee("Sign in with `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN."),3;ee(`snoutdata mcp: not signed in, so only the cluster tools will work (router ${process.env.LEPIS_ADMIN_URL}).`)}ee(`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(i){a.add(i),i.finally(()=>a.delete(i))}return new Promise(i=>{process.stdin.on("data",u=>{let c=nc(s+u);s=c.rest;for(let p of c.messages)l(gb(p,r,o))}),process.stdin.on("end",()=>{(async()=>{for(;a.size>0;)await Promise.allSettled([...a]);i(0)})()}),process.stdin.on("error",()=>i(1))})}async function gb(e,t,n){let r;try{r=JSON.parse(e)}catch{ee(`snoutdata mcp: ignoring a line that is not JSON: ${e.slice(0,120)}`);return}try{let o=await tc(r,t,n);o&&process.stdout.write(`${JSON.stringify(o)}
699
703
  `)}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)}})}
700
- `)}}Ct();re();te();function eb(e){return e>=1?"over":e>=.8?"near":"ok"}function ju(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:eb(n.dbBytes/t.maxStorageBytes)}:null;return{days:e.length,latest:n,peakDbBytes:r,computeSeconds:o,connections:s,storage:a}}function Ds(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 Du(e,t={}){let n=await _("cloud-project-usage",{ref:e,...t.days?{days:t.days}:{}}),r=ju(n.days,n.limit);return h({...n,summary:r},()=>{if(d(x(`${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=`${Ke(r.storage.usedBytes)} of ${Ke(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(`${Ke(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"}: ${Ds(r.computeSeconds)} of compute, ${r.connections} connection${r.connections===1?"":"s"}.`),r.peakDbBytes!==null&&r.latest&&r.peakDbBytes>r.latest.dbBytes&&d(w(`Peak in that window was ${Ke(r.peakDbBytes)}.`)),t.history&&n.days.length>0&&(d(""),d(L([["DAY","SIZE","BACKUPS","COMPUTE","CONNS"],...n.days.map(o=>[o.day,o.dbBytes===null?"-":Ke(o.dbBytes),o.repoBytes===null?"-":Ke(o.repoBytes),Ds(o.computeSeconds),String(o.connections)])])),d(w("A dash is a day nothing measured it, which is what a paused project looks like.")))}),0}be();me();at();te();import{createInterface as tb}from"node:readline/promises";var nb=new Set(["node.drain","node.remove","table.distribute","table.reference","table.global","range.split","range.merge","range.move","tenant.pin","rebalance","scale","cleanup","dissolve"]),Ms={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"},rb="nodes add|drain|remove, keyspace create|drop, table distribute|reference|global, range split|merge|move, tenant pin, rebalance, scale, verify, cleanup, dissolve";function Mu(e,t,n=!1){let[r,o,...s]=e,a=c=>S(t,c),l=(c,p)=>{if(c===void 0||c==="")throw new m(p);return c},i,u=`${r??""}${o!==void 0&&ob(r)?` ${o}`:""}`;if(n&&(u==="nodes add"||u==="node add")){if(s.length>0||a("host")!==void 0)throw new m("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:N(t,"no-join")?{op:"node.add",join:!1}:{op:"node.add"},destructive:!1}}if(u==="nodes attach"||u==="node attach"){if(!n)throw new m("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&&u==="scale"){if(a("add")!==void 0||a("remove")!==void 0)throw new m("in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");let c=ot(t,"nodes","nodes");if(!c.nodes)throw new m("scale needs --nodes N: how many nodes the project should have, the home included");i={op:"scale",...c};for(let[p,f]of Object.entries(Ms))Object.assign(i,ot(t,f,p));return{body:i,destructive:!0}}switch(u){case"nodes add":case"node add":i={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"),...ot(t,"port","port"),...rt(t,"dbname","dbname"),...rt(t,"sslmode","sslmode"),...rt(t,"peer-host","peer_host")};break;case"nodes drain":case"node drain":i={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:Or(a("to"))}:{}};break;case"nodes remove":case"node remove":i={op:"node.remove",node:l(s[0]??a("node"),"nodes remove needs a node: cluster nodes remove <id|name>")};break;case"keyspace create":i={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, ...)"),...ot(t,"ranges","ranges"),...a("seed")!==void 0?{seed:sb(a("seed"))}:{},...a("nodes")?{nodes:Or(a("nodes"))}:{}};break;case"keyspace drop":i={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 m("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:l(s[0],"table distribute needs a table: cluster table distribute <schema.table> --column C --keyspace K"),column:l(a("column"),"table distribute needs --column, the distribution key column"),keyspace:l(a("keyspace"),"table distribute needs --keyspace")};break;case"table reference":case"table global":i={op:`table.${o}`,table:l(s[0],`table ${o} needs a table: cluster table ${o} <schema.table>`)};break;case"range split":{let c=Rr(s[0],t);i={op:"range.split",keyspace:c.keyspace,range:c.lo,...a("at")!==void 0?{at:Ls(a("at"),"--at")}:{},...a("to")?{to:a("to")}:{}};break}case"range move":{let c=Rr(s[0],t);i={op:"range.move",keyspace:c.keyspace,range:c.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 m("range merge needs two adjacent ranges: cluster range merge <keyspace:lo> <keyspace:lo>");let c=Rr(s[0],t),p=Rr(s[1],t);if(c.keyspace!==p.keyspace)throw new m(`range merge: ${c.keyspace} and ${p.keyspace} are different keyspaces`);i={op:"range.merge",keyspace:c.keyspace,a:c.lo,b:p.lo};break}case"tenant pin":{let c=a("keyspace")??s[0],p=a("value")??(a("keyspace")?s[0]:s[1]);i={op:"tenant.pin",keyspace:l(c,"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":i={op:"rebalance",...rt(t,"keyspace","keyspace")};break;case"scale":{let c=a("add")?Or(a("add")).map(f=>ab(f,t)):[],p=ot(t,"remove","remove");if(c.length===0&&!p.remove)throw new m("scale needs --add name=host[:port],... or --remove N (or both)");i={op:"scale",...c.length>0?{add:c}:{},...p};break}case"verify":i={op:"verify",...rt(t,"keyspace","keyspace")};break;case"cleanup":i={op:"cleanup",...rt(t,"node","node")};break;default:throw new m(`unknown operation: cluster ${e.join(" ")}. One of ${rb}`)}for(let[c,p]of Object.entries(Ms)){let f=ot(t,p,c);Object.assign(i,f)}return{body:i,destructive:nb.has(i.op)}}function ob(e){return e==="nodes"||e==="node"||e==="keyspace"||e==="table"||e==="range"||e==="tenant"}function Or(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function rt(e,t,n){let r=S(e,t);return r===void 0?{}:{[n]:r}}function ot(e,t,n){let r=S(e,t);if(r===void 0)return{};let o=Number(r);if(!/^\d+$/.test(r)||!Number.isSafeInteger(o))throw new m(`--${t} must be a whole number, not "${r}"`);return{[n]:o}}function Ls(e,t){let n=e.trim();if(!/^-?\d+$/.test(n)||BigInt(n)<-(2n**63n)||BigInt(n)>=2n**63n)throw new m(`${t} must be a 64-bit whole number, not "${e}"`);return BigInt(n).toString()}function sb(e){let t=e.trim();if(!/^\d+$/.test(t)||BigInt(t)>=2n**64n)throw new m(`--seed must be an unsigned 64-bit whole number, not "${e}"`);return BigInt(t).toString()}function Rr(e,t){let n=S(t,"keyspace"),r=S(t,"range");if(e!==void 0&&e.includes(":")){let s=e.lastIndexOf(":"),a=e.slice(0,s);if(!a)throw new m(`a range is keyspace:lo, as cluster status prints it, not "${e}"`);return{keyspace:a,lo:Ls(e.slice(s+1),`the range's lower bound in "${e}"`)}}let o=r??e;if(!n||o===void 0)throw new m("name the range as keyspace:lo (as cluster status prints it), or with --keyspace K --range LO");return{keyspace:n,lo:Ls(o,"--range")}}function ab(e,t){let n=/^([^=]+)=([^:]+)(?::(\d+))?$/.exec(e);if(!n)throw new m(`scale --add takes name=host[:port], not "${e}"`);return{name:n[1],host:n[2],...n[3]?{port:Number(n[3])}:{},...rt(t,"dbname","dbname"),...rt(t,"sslmode","sslmode")}}function Tr(e,t){if(e===void 0||!/^\d+$/.test(e))throw new m(`jobs ${t} needs a job id: cluster jobs ${t} <id>`);return Number(e)}async function Bu(e,t={}){let n=e.command.slice(1),[r,o,s]=n,a=S(e,"project")??S(e,"ref"),l=a!==void 0,i=()=>t.client??Gt({project:a,admin:S(e,"admin"),token:S(e,"token")});switch(r){case"enable":{if(!l)throw new m("cluster enable is for a SnoutData Cloud project: cluster enable --project <ref>. A standalone router is a cluster from the moment it runs");let c=i();if(!(c instanceof De))throw new m("cluster enable needs --project <ref>");if(N(e,"plan")){let f=await c.enable(!0);return h(f,()=>Ee(f,process.stdout)),0}if(!N(e,"yes")){if(!t.confirm&&!ye())throw new m("making it a cluster restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(Ee(await c.enable(!0),process.stderr),!await(t.confirm??Nt)(`Make a cluster of ${c.target}?`))throw new P("failed","Not turned on. Nothing was changed.")}let p=await c.enable(!1);return h(p,()=>d(Xe(p))),0}case"disable":{if(!l)throw new m("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 c=i();if(!(c instanceof De))throw new m("cluster disable needs --project <ref>");if(N(e,"plan")){let f=await c.disable(!0);return h(f,()=>Ee(f,process.stdout)),0}if(!N(e,"yes")){if(!t.confirm&&!ye())throw new m("turning the cluster off restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(Ee(await c.disable(!0),process.stderr),!await(t.confirm??Nt)(`Turn the cluster of ${c.target} off?`))throw new P("failed","Not turned off. Nothing was changed.")}let p=await c.disable(!1);return h(p,()=>d(Xe(p))),0}case"spread":{if(!l)throw new m("cluster spread is for a SnoutData Cloud project (--project). On a standalone router: cluster keyspace create, then cluster table distribute and cluster rebalance");let c=i();if(!(c instanceof De))throw new m("cluster spread needs --project <ref>");let p={table:o??Ot(S(e,"table"),"cluster spread needs the table: cluster spread <schema.table> --column C --key-type T"),column:Ot(S(e,"column"),"cluster spread needs --column, the column to spread the rows by"),key_type:Ot(S(e,"key-type"),"cluster spread needs --key-type, the column's type (bigint, uuid, text, ...)")};if(N(e,"plan")){let k=await c.spread(p,!0);return h(k,()=>Ee(k,process.stdout)),0}if(!N(e,"yes")){if(!t.confirm&&!ye())throw new m("spreading a table moves its rows, and nothing was asked: pass --yes, or --plan to see what it does");if(Ee(await c.spread(p,!0),process.stderr),!await(t.confirm??Nt)(`Spread ${p.table} over ${c.target}?`))throw new P("failed","Not spread. Nothing was changed.")}let f=await c.spread(p,!1);return h(f,()=>d(Xe(f))),0}case"retry":{if(!l)throw new m("cluster retry is for a SnoutData Cloud project (--project): a stopped job on a standalone router is resumed with cluster jobs resume <id>");let c=i();if(!(c instanceof De))throw new m("cluster retry needs --project <ref>");let p=N(e,"queue")?await c.retry({queue:!0}):await c.retry({node:Ot(o??S(e,"node"),"cluster retry needs the node pod whose join stopped, or --queue")});return h(p,()=>d(Xe(p))),0}case"replica":{if(!l)throw new m("cluster replica is for a SnoutData Cloud project (--project): cluster replica add|remove <node-ref> --project <ref>");if(o!=="add"&&o!=="remove")throw new m("cluster replica add|remove <node-ref> --project <ref>: the node pod, as cluster status lists it");let c=i();if(!(c instanceof De))throw new m("cluster replica needs --project <ref>");let p=o==="remove",f=Ot(s??S(e,"node"),`cluster replica ${o} needs the node pod's ref, as cluster status lists it`);if(N(e,"plan")){let v=await c.replica(f,p,!0);return h(v,()=>Ee(v,process.stdout)),0}if(!N(e,"yes")){if(!t.confirm&&!ye())throw new m(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(Ee(await c.replica(f,p,!0),process.stderr),!await(t.confirm??Nt)(p?`Remove the replica of node ${f}?`:`Add a replica to node ${f}?`))throw new P("failed","Nothing was changed.")}let k=await c.replica(f,p,!1);return h(k,()=>d(Xe(k))),0}case"alerts":{if(!l)throw new m("cluster alerts is for a SnoutData Cloud project (--project <ref>)");let c=i();if(!(c instanceof De))throw new m("cluster alerts needs --project <ref>");if(o===void 0||o==="list"){let p=await c.alerts();return h({alerts:p},()=>Hu(p,process.stdout,!0,c.ref)),0}if(o==="seen"||o==="acknowledge"){let p=Ot(s,`cluster alerts ${o} needs the alert's id, as cluster alerts lists it`);if(!/^[0-9a-f-]{36}$/i.test(p))throw new m(`not an alert id: ${p} (as cluster alerts lists it)`);let f=await c.acknowledge(p.toLowerCase());return h(f,()=>d(Xe(f))),0}throw new m(`unknown command: cluster alerts ${o}. alerts [list], or alerts seen <id>`)}case void 0:case"status":{let c=await i().status();return h(c,()=>mb(c)),0}case"ops":{let c=await i().ops();return h(c,()=>{process.stdout.write(`${c.ops.join(`
704
+ `)}}jt();oe();ne();function hb(e){return e>=1?"over":e>=.8?"near":"ok"}function Bu(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:hb(n.dbBytes/t.maxStorageBytes)}:null;return{days:e.length,latest:n,peakDbBytes:r,computeSeconds:o,connections:s,storage:a}}function Ds(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 Fu(e,t={}){let n=await _("cloud-project-usage",{ref:e,...t.days?{days:t.days}:{}}),r=Bu(n.days,n.limit);return h({...n,summary:r},()=>{if(d(x(`${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=`${Ke(r.storage.usedBytes)} of ${Ke(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(`${Ke(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"}: ${Ds(r.computeSeconds)} of compute, ${r.connections} connection${r.connections===1?"":"s"}.`),r.peakDbBytes!==null&&r.latest&&r.peakDbBytes>r.latest.dbBytes&&d(w(`Peak in that window was ${Ke(r.peakDbBytes)}.`)),t.history&&n.days.length>0&&(d(""),d(B([["DAY","SIZE","BACKUPS","COMPUTE","CONNS"],...n.days.map(o=>[o.day,o.dbBytes===null?"-":Ke(o.dbBytes),o.repoBytes===null?"-":Ke(o.repoBytes),Ds(o.computeSeconds),String(o.connections)])])),d(w("A dash is a day nothing measured it, which is what a paused project looks like.")))}),0}be();me();it();ne();import{createInterface as yb}from"node:readline/promises";var wb=new Set(["node.drain","node.remove","table.distribute","table.reference","table.global","range.split","range.merge","range.move","tenant.pin","rebalance","scale","cleanup","dissolve"]),Ms={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"},bb="nodes add|drain|remove, keyspace create|drop, table distribute|reference|global, range split|merge|move, tenant pin, rebalance, scale, verify, cleanup, dissolve";function Hu(e,t,n=!1){let[r,o,...s]=e,a=c=>S(t,c),l=(c,p)=>{if(c===void 0||c==="")throw new m(p);return c},i,u=`${r??""}${o!==void 0&&_b(r)?` ${o}`:""}`;if(n&&(u==="nodes add"||u==="node add")){if(s.length>0||a("host")!==void 0)throw new m("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:I(t,"no-join")?{op:"node.add",join:!1}:{op:"node.add"},destructive:!1}}if(u==="nodes attach"||u==="node attach"){if(!n)throw new m("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&&u==="scale"){if(a("add")!==void 0||a("remove")!==void 0)throw new m("in SnoutData Cloud, scale takes --nodes N: how many nodes the project should have, the home included");let c=st(t,"nodes","nodes");if(!c.nodes)throw new m("scale needs --nodes N: how many nodes the project should have, the home included");i={op:"scale",...c};for(let[p,f]of Object.entries(Ms))Object.assign(i,st(t,f,p));return{body:i,destructive:!0}}switch(u){case"nodes add":case"node add":i={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"),...st(t,"port","port"),...ot(t,"dbname","dbname"),...ot(t,"sslmode","sslmode"),...ot(t,"peer-host","peer_host")};break;case"nodes drain":case"node drain":i={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:Ir(a("to"))}:{}};break;case"nodes remove":case"node remove":i={op:"node.remove",node:l(s[0]??a("node"),"nodes remove needs a node: cluster nodes remove <id|name>")};break;case"keyspace create":i={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, ...)"),...st(t,"ranges","ranges"),...a("seed")!==void 0?{seed:Sb(a("seed"))}:{},...a("nodes")?{nodes:Ir(a("nodes"))}:{}};break;case"keyspace drop":i={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 m("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:l(s[0],"table distribute needs a table: cluster table distribute <schema.table> --column C --keyspace K"),column:l(a("column"),"table distribute needs --column, the distribution key column"),keyspace:l(a("keyspace"),"table distribute needs --keyspace")};break;case"table reference":case"table global":i={op:`table.${o}`,table:l(s[0],`table ${o} needs a table: cluster table ${o} <schema.table>`)};break;case"range split":{let c=Or(s[0],t);i={op:"range.split",keyspace:c.keyspace,range:c.lo,...a("at")!==void 0?{at:Ls(a("at"),"--at")}:{},...a("to")?{to:a("to")}:{}};break}case"range move":{let c=Or(s[0],t);i={op:"range.move",keyspace:c.keyspace,range:c.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 m("range merge needs two adjacent ranges: cluster range merge <keyspace:lo> <keyspace:lo>");let c=Or(s[0],t),p=Or(s[1],t);if(c.keyspace!==p.keyspace)throw new m(`range merge: ${c.keyspace} and ${p.keyspace} are different keyspaces`);i={op:"range.merge",keyspace:c.keyspace,a:c.lo,b:p.lo};break}case"tenant pin":{let c=a("keyspace")??s[0],p=a("value")??(a("keyspace")?s[0]:s[1]);i={op:"tenant.pin",keyspace:l(c,"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":i={op:"rebalance",...ot(t,"keyspace","keyspace")};break;case"scale":{let c=a("add")?Ir(a("add")).map(f=>kb(f,t)):[],p=st(t,"remove","remove");if(c.length===0&&!p.remove)throw new m("scale needs --add name=host[:port],... or --remove N (or both)");i={op:"scale",...c.length>0?{add:c}:{},...p};break}case"verify":i={op:"verify",...ot(t,"keyspace","keyspace")};break;case"cleanup":i={op:"cleanup",...ot(t,"node","node")};break;default:throw new m(`unknown operation: cluster ${e.join(" ")}. One of ${bb}`)}for(let[c,p]of Object.entries(Ms)){let f=st(t,p,c);Object.assign(i,f)}return{body:i,destructive:wb.has(i.op)}}function _b(e){return e==="nodes"||e==="node"||e==="keyspace"||e==="table"||e==="range"||e==="tenant"}function Ir(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function ot(e,t,n){let r=S(e,t);return r===void 0?{}:{[n]:r}}function st(e,t,n){let r=S(e,t);if(r===void 0)return{};let o=Number(r);if(!/^\d+$/.test(r)||!Number.isSafeInteger(o))throw new m(`--${t} must be a whole number, not "${r}"`);return{[n]:o}}function Ls(e,t){let n=e.trim();if(!/^-?\d+$/.test(n)||BigInt(n)<-(2n**63n)||BigInt(n)>=2n**63n)throw new m(`${t} must be a 64-bit whole number, not "${e}"`);return BigInt(n).toString()}function Sb(e){let t=e.trim();if(!/^\d+$/.test(t)||BigInt(t)>=2n**64n)throw new m(`--seed must be an unsigned 64-bit whole number, not "${e}"`);return BigInt(t).toString()}function Or(e,t){let n=S(t,"keyspace"),r=S(t,"range");if(e!==void 0&&e.includes(":")){let s=e.lastIndexOf(":"),a=e.slice(0,s);if(!a)throw new m(`a range is keyspace:lo, as cluster status prints it, not "${e}"`);return{keyspace:a,lo:Ls(e.slice(s+1),`the range's lower bound in "${e}"`)}}let o=r??e;if(!n||o===void 0)throw new m("name the range as keyspace:lo (as cluster status prints it), or with --keyspace K --range LO");return{keyspace:n,lo:Ls(o,"--range")}}function kb(e,t){let n=/^([^=]+)=([^:]+)(?::(\d+))?$/.exec(e);if(!n)throw new m(`scale --add takes name=host[:port], not "${e}"`);return{name:n[1],host:n[2],...n[3]?{port:Number(n[3])}:{},...ot(t,"dbname","dbname"),...ot(t,"sslmode","sslmode")}}function Nr(e,t){if(e===void 0||!/^\d+$/.test(e))throw new m(`jobs ${t} needs a job id: cluster jobs ${t} <id>`);return Number(e)}async function Gu(e,t={}){let n=e.command.slice(1),[r,o,s]=n,a=S(e,"project")??S(e,"ref"),l=a!==void 0,i=()=>t.client??zt({project:a,admin:S(e,"admin"),token:S(e,"token")});switch(r){case"enable":{if(!l)throw new m("cluster enable is for a SnoutData Cloud project: cluster enable --project <ref>. A standalone router is a cluster from the moment it runs");let c=i();if(!(c instanceof De))throw new m("cluster enable needs --project <ref>");if(I(e,"plan")){let f=await c.enable(!0);return h(f,()=>Ae(f,process.stdout)),0}if(!I(e,"yes")){if(!t.confirm&&!ye())throw new m("making it a cluster restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(Ae(await c.enable(!0),process.stderr),!await(t.confirm??It)(`Make a cluster of ${c.target}?`))throw new P("failed","Not turned on. Nothing was changed.")}let p=await c.enable(!1);return h(p,()=>d(Xe(p))),0}case"disable":{if(!l)throw new m("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 c=i();if(!(c instanceof De))throw new m("cluster disable needs --project <ref>");if(I(e,"plan")){let f=await c.disable(!0);return h(f,()=>Ae(f,process.stdout)),0}if(!I(e,"yes")){if(!t.confirm&&!ye())throw new m("turning the cluster off restarts the database once, and nothing was asked: pass --yes, or --plan to see what it does");if(Ae(await c.disable(!0),process.stderr),!await(t.confirm??It)(`Turn the cluster of ${c.target} off?`))throw new P("failed","Not turned off. Nothing was changed.")}let p=await c.disable(!1);return h(p,()=>d(Xe(p))),0}case"spread":{if(!l)throw new m("cluster spread is for a SnoutData Cloud project (--project). On a standalone router: cluster keyspace create, then cluster table distribute and cluster rebalance");let c=i();if(!(c instanceof De))throw new m("cluster spread needs --project <ref>");let p={table:o??Nt(S(e,"table"),"cluster spread needs the table: cluster spread <schema.table> --column C --key-type T"),column:Nt(S(e,"column"),"cluster spread needs --column, the column to spread the rows by"),key_type:Nt(S(e,"key-type"),"cluster spread needs --key-type, the column's type (bigint, uuid, text, ...)")};if(I(e,"plan")){let k=await c.spread(p,!0);return h(k,()=>Ae(k,process.stdout)),0}if(!I(e,"yes")){if(!t.confirm&&!ye())throw new m("spreading a table moves its rows, and nothing was asked: pass --yes, or --plan to see what it does");if(Ae(await c.spread(p,!0),process.stderr),!await(t.confirm??It)(`Spread ${p.table} over ${c.target}?`))throw new P("failed","Not spread. Nothing was changed.")}let f=await c.spread(p,!1);return h(f,()=>d(Xe(f))),0}case"retry":{if(!l)throw new m("cluster retry is for a SnoutData Cloud project (--project): a stopped job on a standalone router is resumed with cluster jobs resume <id>");let c=i();if(!(c instanceof De))throw new m("cluster retry needs --project <ref>");let p=I(e,"queue")?await c.retry({queue:!0}):await c.retry({node:Nt(o??S(e,"node"),"cluster retry needs the node pod whose join stopped, or --queue")});return h(p,()=>d(Xe(p))),0}case"replica":{if(!l)throw new m("cluster replica is for a SnoutData Cloud project (--project): cluster replica add|remove <node-ref> --project <ref>");if(o!=="add"&&o!=="remove")throw new m("cluster replica add|remove <node-ref> --project <ref>: the node pod, as cluster status lists it");let c=i();if(!(c instanceof De))throw new m("cluster replica needs --project <ref>");let p=o==="remove",f=Nt(s??S(e,"node"),`cluster replica ${o} needs the node pod's ref, as cluster status lists it`);if(I(e,"plan")){let v=await c.replica(f,p,!0);return h(v,()=>Ae(v,process.stdout)),0}if(!I(e,"yes")){if(!t.confirm&&!ye())throw new m(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(Ae(await c.replica(f,p,!0),process.stderr),!await(t.confirm??It)(p?`Remove the replica of node ${f}?`:`Add a replica to node ${f}?`))throw new P("failed","Nothing was changed.")}let k=await c.replica(f,p,!1);return h(k,()=>d(Xe(k))),0}case"alerts":{if(!l)throw new m("cluster alerts is for a SnoutData Cloud project (--project <ref>)");let c=i();if(!(c instanceof De))throw new m("cluster alerts needs --project <ref>");if(o===void 0||o==="list"){let p=await c.alerts();return h({alerts:p},()=>Wu(p,process.stdout,!0,c.ref)),0}if(o==="seen"||o==="acknowledge"){let p=Nt(s,`cluster alerts ${o} needs the alert's id, as cluster alerts lists it`);if(!/^[0-9a-f-]{36}$/i.test(p))throw new m(`not an alert id: ${p} (as cluster alerts lists it)`);let f=await c.acknowledge(p.toLowerCase());return h(f,()=>d(Xe(f))),0}throw new m(`unknown command: cluster alerts ${o}. alerts [list], or alerts seen <id>`)}case void 0:case"status":{let c=await i().status();return h(c,()=>Rb(c)),0}case"ops":{let c=await i().ops();return h(c,()=>{process.stdout.write(`${c.ops.join(`
701
705
  `)}
702
- `),d(w(`Default settings: ${Object.entries(c.settings).map(([p,f])=>`${p}=${f}`).join(", ")}`)),c.refusals&&c.refusals.length>0&&d(w(`Refusal kinds: ${c.refusals.map(p=>`${p.kind} (${p.status})`).join(", ")}`))}),0}case"settings":return lb(e,i);case"advise":case"advice":{let c=ot(e,"sample-ms","sampleMs").sampleMs,p=await i().advice(c);return h(p,()=>pb(p,process.stdout)),0}case"jobs":return db(o,s,e,i(),t);case"nodes":case"node":if(o===void 0||o==="list"){let c=await i().status();return h({nodes:c.nodes??[]},()=>Fu(c)),0}break;case"plan":{let c=Mu(n.slice(1),e,l),p=await i().plan(c.body);return h(p,()=>Ee(p,process.stdout)),0}}let u=Mu(n,e,l);if(N(e,"plan")){let c=await i().plan(u.body);return h(c,()=>Ee(c,process.stdout)),0}return ib(u,e,i,t)}async function ib(e,t,n,r){let o=N(t,"yes"),s=e.body.op;if(e.destructive&&!o&&!r.confirm&&!ye())throw new m(`${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 u=await a.plan(e.body);if(Ee(u,process.stderr),!await(r.confirm??Nt)(`Run ${s} on ${a.target}?`))throw new P("failed","Not run. Nothing was changed.")}let l=await a.submit(e.body);if(l.job===void 0)return h(l.answer,()=>d(l.done)),0;if(N(t,"no-wait"))return h({job:l.job,state:"pending",plan:l.plan},()=>{process.stdout.write(`${l.job}
703
- `),d(`Job ${l.job} (${s}) is queued. Follow it: snoutdata cluster jobs watch ${l.job}`)}),0;d(`Job ${l.job} (${s}) is queued; following it. Ctrl+C stops following, not the job.`);let i=await Us(a,l.job,r);return Bs(i)}function Ot(e,t){if(e===void 0||e==="")throw new m(t);return e}async function Nt(e){let t=tb({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 cb(e){let t=[...xo,...Vi],n={};for(let r of Or(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 m(`--set: unknown setting "${s}". One of ${t.join(", ")}`);let l=Number(a);if(!/^\d+$/.test(a)||!Number.isSafeInteger(l))throw new m(`--set ${s} must be a whole number, not "${a}"`);n[s]=l}return n}async function lb(e,t){let n={};for(let s of xo)Object.assign(n,ot(e,Ms[s],s));let r=S(e,"set");if(r!==void 0&&Object.assign(n,cb(r)),Object.keys(n).length===0){let s=await t().status(),a={...s.settings??{},...s.advice_settings??{}};return h({settings:a},()=>process.stdout.write(`${L(Object.entries(a).map(([l,i])=>[l,String(i)]))}
704
- `)),0}let o=await t().settings(n);return h(o,()=>d(`Set ${Object.entries(o.settings).map(([s,a])=>`${s}=${a}`).join(", ")}.`)),0}async function db(e,t,n,r,o){switch(e){case void 0:case"list":{let s=await r.jobs();return h({jobs:s},()=>bb(s)),0}case"show":{let s=await r.job(Tr(t,"show"));return h(s,()=>_b(s)),0}case"watch":{let s=await Us(r,Tr(t,"watch"),o);return Bs(s)}case"cancel":{let s=Tr(t,"cancel");if(!N(n,"yes")){if(!o.confirm&&!ye())throw new m(`cancelling job ${s} stops a running operation, and nothing was asked: pass --yes`);if(!await(o.confirm??Nt)(`Cancel job ${s} on ${r.target}?`))throw new P("failed","Not cancelled. Nothing was changed.")}let a=await r.cancel(s);return h(a,()=>d(`Job ${s}: ${a.state}.`)),0}case"resume":{let s=Tr(t,"resume"),a=await r.resume(s);return N(n,"no-wait")?(h(a,()=>d(`Job ${s}: ${a.state}. Follow it: snoutdata cluster jobs watch ${s}`)),0):Bs(await Us(r,s,o))}default:throw new m(`unknown command: cluster jobs ${e}. jobs [list|show|watch|cancel|resume] <id>`)}}async function Us(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 i=typeof l.detail?.phase=="string"?l.detail.phase:"",u=`${l.state}${i?` ${i}`:""}`;s.get(l.n)!==u&&(s.set(l.n,u),l.state!=="pending"&&d(w(` step ${l.n+1}/${a.steps.length} ${l.kind}: ${u}`)))}if(qt(a.state))return a;if(Date.now()>=o)throw new P("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 Bs(e){if(e.state==="done")return h(e,()=>process.stdout.write(`Job ${e.id} (${e.op}): done, ${e.steps.length} step${e.steps.length===1?"":"s"}.
705
- `)),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 P("failed",`job ${e.id} (${e.op}) ${t}`,{job:e})}function D(e,t=""){e.write(`${t}
706
- `)}function Fs(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 Ee(e,t){D(t,`${x(e.op)}: ${e.steps.length} step${e.steps.length===1?"":"s"}, ${e.cutovers} cutover${e.cutovers===1?"":"s"}`),e.moves.length>0&&D(t,L([[" 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")}`,Fs(n.estimated_bytes),`~${n.estimated_copy_seconds}s`,`~${n.expected_pause_ms}ms`])])),D(t,` total: ~${e.estimated_rows.toLocaleString("en-US")} rows, ${Fs(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)`),D(t,` steps: ${e.steps.map(n=>n.kind).join(", ")||"none"}`);for(let n of e.warnings)D(t,` warning: ${n}`);e.assumptions&&D(t,w(` ${e.assumptions}`))}function Oe(e){let t=String(e);return/^[\w.:@+-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function ub(e){let t=e,n="snoutdata cluster";switch(e.op){case"range.split":return`${n} range split ${Oe(`${t.keyspace}:${t.range}`)}${t.at!==void 0?` --at ${Oe(t.at)}`:""}${t.to!==void 0?` --to ${Oe(t.to)}`:""}`;case"range.move":return`${n} range move ${Oe(`${t.keyspace}:${t.range}`)} --to ${Oe(t.to)}`;case"tenant.pin":return`${n} tenant pin ${Oe(t.keyspace)} --value ${Oe(t.value)}${t.node!==void 0?` --node ${Oe(t.node)}`:""}`;case"node.add":return`${n} nodes add ${Oe(t.name)} --host ${t.host?Oe(t.host):"<its address>"}, then ${n} rebalance`;case"rebalance":return`${n} rebalance${t.keyspace?` --keyspace ${Oe(t.keyspace)}`:""}`;default:return null}}function pb(e,t){D(t,e.summary),e.advice.forEach((n,r)=>{D(t),D(t,`${x(`${r+1}. ${n.op}`)} (${n.metric})`),D(t,` ${n.reason}`);let o=ub(n.request);if(D(t,` run: ${o??JSON.stringify(n.request)}`),n.plan){let s=n.plan;D(t,` plan: ${s.cutovers} cutover${s.cutovers===1?"":"s"}, ~${s.estimated_rows.toLocaleString("en-US")} rows, ${Fs(s.estimated_bytes)}, ~${s.estimated_copy_seconds}s to copy, expected write pause ~${s.expected_pause_ms}ms`);for(let a of s.warnings??[])D(t,` warning: ${a}`)}else n.needs.length>0?D(t,` needs: ${n.needs.join(", ")}, so it has no plan yet`):n.plan_error&&D(t,` no plan: ${n.plan_error.message} (${n.plan_error.kind})`)}),e.assumptions&&(D(t),D(t,w(e.assumptions)))}function Lu(e,t){return e.nodes?.find(n=>n.id===t)?.name??`node ${t}`}function Fu(e){let t=e.nodes??[];if(t.length===0){d("No nodes in the catalog.");return}D(process.stdout,L([["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 mb(e){let t=process.stdout;if(e.cloud&&(wb(e.cloud,t),!e.cloud.sharded))return;if(!e.catalog){D(t,"The home node has no Lepis catalog yet (schema lepis).");return}D(t,`${x("Cluster")} at epoch ${e.epoch}`),D(t),Fu(e);for(let s of e.keyspaces??[]){D(t),D(t,`${x(`Keyspace ${s.name}`)} (${s.key_type}, ${s.ranges.length} range${s.ranges.length===1?"":"s"})`),D(t,L([[" RANGE","HI","NODE"],...s.ranges.map(a=>[` ${s.name}:${a.lo}`,a.hi,Lu(e,a.node)])]));for(let a of s.pins)D(t,` pinned: ${a.value} on ${Lu(e,a.node)}`)}let n=e.tables??[];n.length>0&&(D(t),D(t,L([["TABLE","KIND","KEYSPACE","COLUMN"],...n.map(s=>[s.table,s.kind,s.keyspace??"",s.column??""])])));let r=e.routers??[];r.length>0&&(D(t),D(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&&D(t,`Unfinished jobs: ${o.map(s=>`${s.id} ${s.op} ${s.state}`).join("; ")}`),e.settings&&d(w(`Settings: ${Object.entries(e.settings).map(([s,a])=>`${s}=${a}`).join(", ")}`))}function fb(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 gb(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 Uu(e){return e.severity.toUpperCase()}function Hu(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)D(t,`${x(Uu(a))} ${a.message}${a.acknowledged?w(" (seen)"):""}`);o.length>0&&D(t,w(` 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)D(t,`${x(Uu(a))} ${a.message}`),D(t,w(` ${a.id}, opened ${a.openedAt.slice(0,16).replace("T"," ")}${a.acknowledged?", seen":""}`));if(s.length>0){o.length>0&&D(t),D(t,"Resolved in the last day:");for(let a of s)D(t,` ${a.message}${a.resolution?` ${w(a.resolution)}`:""}`)}}function hb(e){return e.projectsUsed===null||e.maxProjects===null?0:Math.max(0,e.maxProjects-e.projectsUsed)}function yb(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 wb(e,t){let n=yb(e);if(!e.sharded){D(t,`${x(e.ref)} is not a cluster (${n}).`),hb(e)>0&&D(t,`Make it a cluster: snoutdata cluster enable --project ${e.ref} (the database restarts once).`);return}Hu(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(D(t,`${x(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(i=>i.replicaOf!==void 0);D(t,L([[" POD","STATE","NEXT",...l?["REPLICA"]:[]],...e.pods.map(i=>[` ${i.ref}`,i.state,fb(e,i),...l?[gb(i)]:[]])]))}e.router==="starting"?D(t,"The router is starting beside the database, which takes about twenty seconds."):e.router==="paused"&&D(t,"The project is paused; the router wakes with it on the next connection."),e.routerError&&D(t,`The router is not answering: ${e.routerError}`);let a=e.automation;a&&a.queueError?D(t,`Stopped: ${a.queueError}. Retry: snoutdata cluster retry --queue --project ${e.ref}`):a&&(a.queue.length>0||a.queueJob!==null)&&D(t,`Working through a request${a.queueJob!==null?` (job ${a.queueJob})`:""}${a.queue.length>0?`; then ${a.queue.join(", ")}`:""}.`),D(t)}function bb(e){if(e.length===0){d("No jobs yet.");return}D(process.stdout,L([["ID","OPERATION","STATE","STEPS","CREATED","ERROR"],...e.map(t=>[String(t.id),t.op,t.state,`${t.steps_done}/${t.steps}`,t.created_at.slice(0,19).replace("T"," "),t.error??""])]))}function _b(e){let t=process.stdout;D(t,`${x(`Job ${e.id}`)} ${e.op}: ${e.state}${e.error?` (${e.error})`:""}`),D(t,L([[" 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)&&(D(t),Ee(e.plan,t))}me();te();Dt();import{spawn as Sb}from"node:child_process";import{createHash as kb}from"node:crypto";import{chmodSync as vb,renameSync as Nr,rmSync as Ku,writeFileSync as $b}from"node:fs";import{dirname as xb,join as Pb}from"node:path";var Ir=process.env.SNOUTDATA_NPM_REGISTRY??"https://registry.npmjs.org",Eb="https://github.com/snoutdata/studio/releases/download";function Ab(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 Rb(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 Tb(){let e;try{e=await fetch(`${Ir}/snoutdata/latest`,{headers:{accept:"application/json"}})}catch(n){throw new P("network",`could not reach ${Ir} to find the newest version: ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw new P("server",`${Ir} answered ${e.status} when asked for the newest version`);let t=await e.json();if(typeof t.version!="string")throw new P("server",`${Ir} did not say which version is newest`);return t.version}async function qu(e){let t;try{t=await fetch(e)}catch(n){throw new P("network",`could not download ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t.ok)throw new P("failed",`download failed (${t.status}): ${e}`);return Buffer.from(await t.arrayBuffer())}function Ob(e,t){let n=Pb(xb(e),`.snoutdata-upgrade-${process.pid}`);$b(n,t,{mode:493});try{if(process.platform==="win32"){let r=`${e}.old`;Ku(r,{force:!0}),Nr(e,r);try{Nr(n,e)}catch(o){throw Nr(r,e),o}}else vb(n,493),Nr(n,e)}catch(r){Ku(n,{force:!0});let o=r.code;throw o==="EACCES"||o==="EPERM"?new P("forbidden",`${e} is not writable by this user. Run the installer instead: ${process.platform==="win32"?Be:jt}`):r}}function Nb(){return new Promise((e,t)=>{let n=Sb(process.platform==="win32"?"npm.cmd":"npm",["install","-g","snoutdata@latest"],{stdio:["ignore","inherit","inherit"],shell:process.platform==="win32"});n.on("error",r=>t(new P("tool-missing",`npm could not be run (${r.message}). Run it yourself: ${Be}`))),n.on("exit",r=>e(r??1))})}async function Gu(e={}){let t=e.kind??Rn(),n=await Tb(),r=wa(ue,n),o={installed:ue,latest:n,upToDate:!r,install:t};if(!r||e.check)return h({...o,upgraded:!1},()=>{d(r?`snoutdata ${ue} is installed; ${n} is the newest. \`snoutdata upgrade\` installs it.`:`snoutdata ${ue} is the newest version.`)}),0;switch(t){case"npx":return h({...o,upgraded:!1},()=>{d(`This is a copy npx fetched (${ue}). Run \`npx snoutdata@latest\` to use ${n}; there is nothing installed to upgrade.`)}),0;case"source":throw new P("usage",`this snoutdata (${ue}) is running from source, so there is nothing to replace. Install the published one: ${process.platform==="win32"?Be:jt}`);case"npm":{d(`Upgrading snoutdata ${ue} to ${n} with npm\u2026`);let s=await Nb();if(s!==0)throw new P("failed",`npm exited ${s}. Run it yourself: ${Be}`);return h({...o,upgraded:!0},()=>d(`Upgraded to ${n}.`)),0}case"binary":{let s=Ab(process.platform,process.arch);if(!s)throw new P("failed",`no snoutdata binary is built for ${process.platform}-${process.arch}. Use npm: ${Be}`);d(`Downloading snoutdata ${n} for ${process.platform}-${process.arch}\u2026`);let a=`${Eb}/cli-v${n}`,[l,i]=await Promise.all([qu(`${a}/${s}`),qu(`${a}/SHA256SUMS`)]),u=Rb(i.toString("utf8"),s);if(!u)throw new P("failed",`${s} is not listed in the release's SHA256SUMS. Refusing to install.`);let c=kb("sha256").update(l).digest("hex");if(c!==u)throw new P("failed",`checksum mismatch for ${s}. Refusing to install.
706
+ `),d(w(`Default settings: ${Object.entries(c.settings).map(([p,f])=>`${p}=${f}`).join(", ")}`)),c.refusals&&c.refusals.length>0&&d(w(`Refusal kinds: ${c.refusals.map(p=>`${p.kind} (${p.status})`).join(", ")}`))}),0}case"settings":return xb(e,i);case"advise":case"advice":{let c=st(e,"sample-ms","sampleMs").sampleMs,p=await i().advice(c);return h(p,()=>Ab(p,process.stdout)),0}case"jobs":return Pb(o,s,e,i(),t);case"nodes":case"node":if(o===void 0||o==="list"){let c=await i().status();return h({nodes:c.nodes??[]},()=>zu(c)),0}break;case"plan":{let c=Hu(n.slice(1),e,l),p=await i().plan(c.body);return h(p,()=>Ae(p,process.stdout)),0}}let u=Hu(n,e,l);if(I(e,"plan")){let c=await i().plan(u.body);return h(c,()=>Ae(c,process.stdout)),0}return vb(u,e,i,t)}async function vb(e,t,n,r){let o=I(t,"yes"),s=e.body.op;if(e.destructive&&!o&&!r.confirm&&!ye())throw new m(`${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 u=await a.plan(e.body);if(Ae(u,process.stderr),!await(r.confirm??It)(`Run ${s} on ${a.target}?`))throw new P("failed","Not run. Nothing was changed.")}let l=await a.submit(e.body);if(l.job===void 0)return h(l.answer,()=>d(l.done)),0;if(I(t,"no-wait"))return h({job:l.job,state:"pending",plan:l.plan},()=>{process.stdout.write(`${l.job}
707
+ `),d(`Job ${l.job} (${s}) is queued. Follow it: snoutdata cluster jobs watch ${l.job}`)}),0;d(`Job ${l.job} (${s}) is queued; following it. Ctrl+C stops following, not the job.`);let i=await Us(a,l.job,r);return Bs(i)}function Nt(e,t){if(e===void 0||e==="")throw new m(t);return e}async function It(e){let t=yb({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 $b(e){let t=[...Eo,...Yi],n={};for(let r of Ir(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 m(`--set: unknown setting "${s}". One of ${t.join(", ")}`);let l=Number(a);if(!/^\d+$/.test(a)||!Number.isSafeInteger(l))throw new m(`--set ${s} must be a whole number, not "${a}"`);n[s]=l}return n}async function xb(e,t){let n={};for(let s of Eo)Object.assign(n,st(e,Ms[s],s));let r=S(e,"set");if(r!==void 0&&Object.assign(n,$b(r)),Object.keys(n).length===0){let s=await t().status(),a={...s.settings??{},...s.advice_settings??{}};return h({settings:a},()=>process.stdout.write(`${B(Object.entries(a).map(([l,i])=>[l,String(i)]))}
708
+ `)),0}let o=await t().settings(n);return h(o,()=>d(`Set ${Object.entries(o.settings).map(([s,a])=>`${s}=${a}`).join(", ")}.`)),0}async function Pb(e,t,n,r,o){switch(e){case void 0:case"list":{let s=await r.jobs();return h({jobs:s},()=>jb(s)),0}case"show":{let s=await r.job(Nr(t,"show"));return h(s,()=>Db(s)),0}case"watch":{let s=await Us(r,Nr(t,"watch"),o);return Bs(s)}case"cancel":{let s=Nr(t,"cancel");if(!I(n,"yes")){if(!o.confirm&&!ye())throw new m(`cancelling job ${s} stops a running operation, and nothing was asked: pass --yes`);if(!await(o.confirm??It)(`Cancel job ${s} on ${r.target}?`))throw new P("failed","Not cancelled. Nothing was changed.")}let a=await r.cancel(s);return h(a,()=>d(`Job ${s}: ${a.state}.`)),0}case"resume":{let s=Nr(t,"resume"),a=await r.resume(s);return I(n,"no-wait")?(h(a,()=>d(`Job ${s}: ${a.state}. Follow it: snoutdata cluster jobs watch ${s}`)),0):Bs(await Us(r,s,o))}default:throw new m(`unknown command: cluster jobs ${e}. jobs [list|show|watch|cancel|resume] <id>`)}}async function Us(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 i=typeof l.detail?.phase=="string"?l.detail.phase:"",u=`${l.state}${i?` ${i}`:""}`;s.get(l.n)!==u&&(s.set(l.n,u),l.state!=="pending"&&d(w(` step ${l.n+1}/${a.steps.length} ${l.kind}: ${u}`)))}if(Gt(a.state))return a;if(Date.now()>=o)throw new P("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 Bs(e){if(e.state==="done")return h(e,()=>process.stdout.write(`Job ${e.id} (${e.op}): done, ${e.steps.length} step${e.steps.length===1?"":"s"}.
709
+ `)),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 P("failed",`job ${e.id} (${e.op}) ${t}`,{job:e})}function L(e,t=""){e.write(`${t}
710
+ `)}function Fs(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 Ae(e,t){L(t,`${x(e.op)}: ${e.steps.length} step${e.steps.length===1?"":"s"}, ${e.cutovers} cutover${e.cutovers===1?"":"s"}`),e.moves.length>0&&L(t,B([[" 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")}`,Fs(n.estimated_bytes),`~${n.estimated_copy_seconds}s`,`~${n.expected_pause_ms}ms`])])),L(t,` total: ~${e.estimated_rows.toLocaleString("en-US")} rows, ${Fs(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)`),L(t,` steps: ${e.steps.map(n=>n.kind).join(", ")||"none"}`);for(let n of e.warnings)L(t,` warning: ${n}`);e.assumptions&&L(t,w(` ${e.assumptions}`))}function Oe(e){let t=String(e);return/^[\w.:@+-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Eb(e){let t=e,n="snoutdata cluster";switch(e.op){case"range.split":return`${n} range split ${Oe(`${t.keyspace}:${t.range}`)}${t.at!==void 0?` --at ${Oe(t.at)}`:""}${t.to!==void 0?` --to ${Oe(t.to)}`:""}`;case"range.move":return`${n} range move ${Oe(`${t.keyspace}:${t.range}`)} --to ${Oe(t.to)}`;case"tenant.pin":return`${n} tenant pin ${Oe(t.keyspace)} --value ${Oe(t.value)}${t.node!==void 0?` --node ${Oe(t.node)}`:""}`;case"node.add":return`${n} nodes add ${Oe(t.name)} --host ${t.host?Oe(t.host):"<its address>"}, then ${n} rebalance`;case"rebalance":return`${n} rebalance${t.keyspace?` --keyspace ${Oe(t.keyspace)}`:""}`;default:return null}}function Ab(e,t){L(t,e.summary),e.advice.forEach((n,r)=>{L(t),L(t,`${x(`${r+1}. ${n.op}`)} (${n.metric})`),L(t,` ${n.reason}`);let o=Eb(n.request);if(L(t,` run: ${o??JSON.stringify(n.request)}`),n.plan){let s=n.plan;L(t,` plan: ${s.cutovers} cutover${s.cutovers===1?"":"s"}, ~${s.estimated_rows.toLocaleString("en-US")} rows, ${Fs(s.estimated_bytes)}, ~${s.estimated_copy_seconds}s to copy, expected write pause ~${s.expected_pause_ms}ms`);for(let a of s.warnings??[])L(t,` warning: ${a}`)}else n.needs.length>0?L(t,` needs: ${n.needs.join(", ")}, so it has no plan yet`):n.plan_error&&L(t,` no plan: ${n.plan_error.message} (${n.plan_error.kind})`)}),e.assumptions&&(L(t),L(t,w(e.assumptions)))}function Ku(e,t){return e.nodes?.find(n=>n.id===t)?.name??`node ${t}`}function zu(e){let t=e.nodes??[];if(t.length===0){d("No nodes in the catalog.");return}L(process.stdout,B([["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 Rb(e){let t=process.stdout;if(e.cloud&&(Cb(e.cloud,t),!e.cloud.sharded))return;if(!e.catalog){L(t,"The home node has no Lepis catalog yet (schema lepis).");return}L(t,`${x("Cluster")} at epoch ${e.epoch}`),L(t),zu(e);for(let s of e.keyspaces??[]){L(t),L(t,`${x(`Keyspace ${s.name}`)} (${s.key_type}, ${s.ranges.length} range${s.ranges.length===1?"":"s"})`),L(t,B([[" RANGE","HI","NODE"],...s.ranges.map(a=>[` ${s.name}:${a.lo}`,a.hi,Ku(e,a.node)])]));for(let a of s.pins)L(t,` pinned: ${a.value} on ${Ku(e,a.node)}`)}let n=e.tables??[];n.length>0&&(L(t),L(t,B([["TABLE","KIND","KEYSPACE","COLUMN"],...n.map(s=>[s.table,s.kind,s.keyspace??"",s.column??""])])));let r=e.routers??[];r.length>0&&(L(t),L(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&&L(t,`Unfinished jobs: ${o.map(s=>`${s.id} ${s.op} ${s.state}`).join("; ")}`),e.settings&&d(w(`Settings: ${Object.entries(e.settings).map(([s,a])=>`${s}=${a}`).join(", ")}`))}function Tb(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 Ob(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 qu(e){return e.severity.toUpperCase()}function Wu(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)L(t,`${x(qu(a))} ${a.message}${a.acknowledged?w(" (seen)"):""}`);o.length>0&&L(t,w(` 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)L(t,`${x(qu(a))} ${a.message}`),L(t,w(` ${a.id}, opened ${a.openedAt.slice(0,16).replace("T"," ")}${a.acknowledged?", seen":""}`));if(s.length>0){o.length>0&&L(t),L(t,"Resolved in the last day:");for(let a of s)L(t,` ${a.message}${a.resolution?` ${w(a.resolution)}`:""}`)}}function Nb(e){return e.projectsUsed===null||e.maxProjects===null?0:Math.max(0,e.maxProjects-e.projectsUsed)}function Ib(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 Cb(e,t){let n=Ib(e);if(!e.sharded){L(t,`${x(e.ref)} is not a cluster (${n}).`),Nb(e)>0&&L(t,`Make it a cluster: snoutdata cluster enable --project ${e.ref} (the database restarts once).`);return}Wu(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(L(t,`${x(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(i=>i.replicaOf!==void 0);L(t,B([[" POD","STATE","NEXT",...l?["REPLICA"]:[]],...e.pods.map(i=>[` ${i.ref}`,i.state,Tb(e,i),...l?[Ob(i)]:[]])]))}e.router==="starting"?L(t,"The router is starting beside the database, which takes about twenty seconds."):e.router==="paused"&&L(t,"The project is paused; the router wakes with it on the next connection."),e.routerError&&L(t,`The router is not answering: ${e.routerError}`);let a=e.automation;a&&a.queueError?L(t,`Stopped: ${a.queueError}. Retry: snoutdata cluster retry --queue --project ${e.ref}`):a&&(a.queue.length>0||a.queueJob!==null)&&L(t,`Working through a request${a.queueJob!==null?` (job ${a.queueJob})`:""}${a.queue.length>0?`; then ${a.queue.join(", ")}`:""}.`),L(t)}function jb(e){if(e.length===0){d("No jobs yet.");return}L(process.stdout,B([["ID","OPERATION","STATE","STEPS","CREATED","ERROR"],...e.map(t=>[String(t.id),t.op,t.state,`${t.steps_done}/${t.steps}`,t.created_at.slice(0,19).replace("T"," "),t.error??""])]))}function Db(e){let t=process.stdout;L(t,`${x(`Job ${e.id}`)} ${e.op}: ${e.state}${e.error?` (${e.error})`:""}`),L(t,B([[" 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)&&(L(t),Ae(e.plan,t))}me();ne();Mt();import{spawn as Mb}from"node:child_process";import{createHash as Lb}from"node:crypto";import{chmodSync as Ub,renameSync as Cr,rmSync as Ju,writeFileSync as Bb}from"node:fs";import{dirname as Fb,join as Hb}from"node:path";var jr=process.env.SNOUTDATA_NPM_REGISTRY??"https://registry.npmjs.org",Kb="https://github.com/snoutdata/studio/releases/download";function qb(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 Gb(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 zb(){let e;try{e=await fetch(`${jr}/snoutdata/latest`,{headers:{accept:"application/json"}})}catch(n){throw new P("network",`could not reach ${jr} to find the newest version: ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw new P("server",`${jr} answered ${e.status} when asked for the newest version`);let t=await e.json();if(typeof t.version!="string")throw new P("server",`${jr} did not say which version is newest`);return t.version}async function Vu(e){let t;try{t=await fetch(e)}catch(n){throw new P("network",`could not download ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t.ok)throw new P("failed",`download failed (${t.status}): ${e}`);return Buffer.from(await t.arrayBuffer())}function Wb(e,t){let n=Hb(Fb(e),`.snoutdata-upgrade-${process.pid}`);Bb(n,t,{mode:493});try{if(process.platform==="win32"){let r=`${e}.old`;Ju(r,{force:!0}),Cr(e,r);try{Cr(n,e)}catch(o){throw Cr(r,e),o}}else Ub(n,493),Cr(n,e)}catch(r){Ju(n,{force:!0});let o=r.code;throw o==="EACCES"||o==="EPERM"?new P("forbidden",`${e} is not writable by this user. Run the installer instead: ${process.platform==="win32"?Be:Dt}`):r}}function Jb(){return new Promise((e,t)=>{let n=Mb(process.platform==="win32"?"npm.cmd":"npm",["install","-g","snoutdata@latest"],{stdio:["ignore","inherit","inherit"],shell:process.platform==="win32"});n.on("error",r=>t(new P("tool-missing",`npm could not be run (${r.message}). Run it yourself: ${Be}`))),n.on("exit",r=>e(r??1))})}async function Yu(e={}){let t=e.kind??On(),n=await zb(),r=wa(ue,n),o={installed:ue,latest:n,upToDate:!r,install:t};if(!r||e.check)return h({...o,upgraded:!1},()=>{d(r?`snoutdata ${ue} is installed; ${n} is the newest. \`snoutdata upgrade\` installs it.`:`snoutdata ${ue} is the newest version.`)}),0;switch(t){case"npx":return h({...o,upgraded:!1},()=>{d(`This is a copy npx fetched (${ue}). Run \`npx snoutdata@latest\` to use ${n}; there is nothing installed to upgrade.`)}),0;case"source":throw new P("usage",`this snoutdata (${ue}) is running from source, so there is nothing to replace. Install the published one: ${process.platform==="win32"?Be:Dt}`);case"npm":{d(`Upgrading snoutdata ${ue} to ${n} with npm\u2026`);let s=await Jb();if(s!==0)throw new P("failed",`npm exited ${s}. Run it yourself: ${Be}`);return h({...o,upgraded:!0},()=>d(`Upgraded to ${n}.`)),0}case"binary":{let s=qb(process.platform,process.arch);if(!s)throw new P("failed",`no snoutdata binary is built for ${process.platform}-${process.arch}. Use npm: ${Be}`);d(`Downloading snoutdata ${n} for ${process.platform}-${process.arch}\u2026`);let a=`${Kb}/cli-v${n}`,[l,i]=await Promise.all([Vu(`${a}/${s}`),Vu(`${a}/SHA256SUMS`)]),u=Gb(i.toString("utf8"),s);if(!u)throw new P("failed",`${s} is not listed in the release's SHA256SUMS. Refusing to install.`);let c=Lb("sha256").update(l).digest("hex");if(c!==u)throw new P("failed",`checksum mismatch for ${s}. Refusing to install.
707
711
  expected ${u}
708
- actual ${c}`);return Ob(process.execPath,l),h({...o,upgraded:!0,path:process.execPath},()=>d(`Upgraded ${process.execPath} to ${n}.`)),0}}}Mn();Ge();Dt();var Wu=`snoutdata ${ue} \u2014 hosted Postgres, from a terminal or an agent
712
+ actual ${c}`);return Wb(process.execPath,l),h({...o,upgraded:!0,path:process.execPath},()=>d(`Upgraded ${process.execPath} to ${n}.`)),0}}}Un();Ge();Mt();var Xu=`snoutdata ${ue} \u2014 hosted Postgres, from a terminal or an agent
709
713
 
710
714
  snoutdata init [--name X] [--env] a database for this folder, linked, ready to use;
711
715
  --env writes DATABASE_URL into ./.env (and adds
@@ -879,11 +883,11 @@ that re-signs Postgres traffic.
879
883
  Docs: https://docs.snoutdata.com/developers/cli
880
884
  Examples: https://github.com/snoutdata/snoutdata (a star helps other people find it)
881
885
  Source: https://github.com/snoutdata/snout-cli
882
- `,Ib=["yes","token"];async function Cb(e){let[t,n,...r]=e.command;if(N(e,"version")||t==="version")return h({version:ue},()=>process.stdout.write(`${ue}
883
- `)),0;if(N(e,"help")&&t&&t!=="help"){let i=zs(t,n);if(i.length>0)return h({commands:i.map(u=>({...u,flagHelp:Object.fromEntries(u.flags.map(c=>[c,Dr(u.name,c)]))}))},()=>{for(let u of i){let c="args"in u&&u.args?` ${u.args}`:"",p=u.flags.length>0?` ${u.flags.join(" ")}`:"";process.stdout.write(` snoutdata ${u.name}${c}${p}
886
+ `,Vb=["yes","token"];async function Yb(e){let[t,n,...r]=e.command;if(I(e,"version")||t==="version")return h({version:ue},()=>process.stdout.write(`${ue}
887
+ `)),0;if(I(e,"help")&&t&&t!=="help"){let i=Ws(t,n);if(i.length>0)return h({commands:i.map(u=>({...u,flagHelp:Object.fromEntries(u.flags.map(c=>[c,Lr(u.name,c)]))}))},()=>{for(let u of i){let c="args"in u&&u.args?` ${u.args}`:"",p=u.flags.length>0?` ${u.flags.join(" ")}`:"";process.stdout.write(` snoutdata ${u.name}${c}${p}
884
888
  ${u.summary}
885
- `);let f=Math.max(0,...u.flags.map(k=>k.length));for(let k of u.flags)process.stdout.write(` ${k.padEnd(f)} ${Dr(u.name,k)}
889
+ `);let f=Math.max(0,...u.flags.map(k=>k.length));for(let k of u.flags)process.stdout.write(` ${k.padEnd(f)} ${Lr(u.name,k)}
886
890
  `)}process.stdout.write(`
887
891
  Every command also takes --json, --quiet and --help.
888
- `)}),0}let o=N(e,"help")||t==="help";if(o||!t)return h({version:ue,usage:Wu.trim(),commands:jr},()=>process.stdout.write(Wu)),o?0:Le.usage;let s=()=>{let i=_e(e,"timeout");if(i!==void 0){if(!(i>0))throw new m("--timeout is a number of seconds greater than zero");return i*1e3}},a=()=>{let i=hn({flag:S(e,"ref")});if(!i)throw new m("no project: pass --ref, set SNOUTDATA_PROJECT, or run `snoutdata link --ref <ref>`");return i},l=()=>{let i=hn({flag:S(e,"ref")});return i?He(i):null};for(let i of Ib)if(e.flags[i]!==void 0&&t!=="cluster")throw new m(`--${i} is only for snoutdata cluster`);switch(t){case"cluster":return Bu(e,{timeoutMs:s()});case"login":{if(N(e,"device")){let p=await Tn({name:vn(),platform:process.platform});h({verifyUrl:p.verifyUrl,code:p.code,expiresAt:p.expiresAt},()=>{d(""),d(` Open ${p.verifyUrl}`),d(` Type ${p.code}`),d(""),d(w("Waiting for that to be approved\u2026"))});let f=await On(p.secret,{intervalMs:Math.max(1,p.interval)*1e3,expiresAt:p.expiresAt});Ne({accessToken:f.token});let k=S(e,"email"),v=k?(await it()).email??void 0:void 0;return k&&Xr(k,{accessToken:f.token,email:v}),h({ok:!0,name:f.name??null,email:v??null},()=>d(`Signed in${v?` as ${v}`:""}.`)),0}let i=S(e,"domain"),u=N(e,"sso")||i!==void 0;if(u&&S(e,"provider"))throw new m("--sso and --provider are two different doors: pass one or the other");let c=await Dn({provider:S(e,"provider"),sso:u,domain:i,noBrowser:N(e,"no-browser")||!ye(),timeoutMs:s(),email:S(e,"email")});return h({email:c.email??null},()=>d(`Signed in${c.email?` as ${c.email}`:""}.`)),0}case"logout":{Qs();let i=!!process.env.SNOUTDATA_ACCESS_TOKEN;return h({ok:!0,environmentTokenStillSet:i},()=>{d("Signed out."),i&&(d("SNOUTDATA_ACCESS_TOKEN is still set in this shell, so commands will keep working."),d(w(" unset SNOUTDATA_ACCESS_TOKEN")))}),0}case"whoami":{let i=await it(),u=gn()?.expectedEmail,c=!!(u&&i.email&&!Zr(u,i.email));return c&&Q(`This session is ${i.email}, and login asked for ${u}. Run "snoutdata login --email ${u}" to sign in as that account.`),h({...i,...u?{expectedEmail:u,matchesExpected:!c}:{}},()=>{process.stdout.write(`${i.email??i.id}
889
- `),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 oi(),0;case"create":{let i=S(e,"name")??r[0];if(!i)throw new m("tokens create needs --name (what is it for, and where does it live)");return await ri({name:i,expiresInDays:_e(e,"expires"),project:S(e,"project")}),0}case"revoke":{let i=r[0];if(!i)throw new m("tokens revoke needs the token's id or its sdt_ prefix");return await si(i),0}default:throw new m(`unknown command: tokens ${n}`)}case"projects":switch(n){case void 0:case"list":return await Za(),0;case"create":{let i=S(e,"name")??r[0];if(!i)throw new m("projects create needs --name");let u=S(e,"team");return await so({teamId:u?await ni(u):void 0,name:i,region:S(e,"region"),wait:!N(e,"no-wait"),timeoutMs:s(),link:void 0,showUrl:N(e,"show-url")}),0}case"pause":case"resume":case"delete":return await Qa(n,S(e,"ref")??r[0]??a(),{wait:!N(e,"no-wait"),timeoutMs:s()}),0;case"show":{let i=S(e,"ref")??r[0]??a(),u=He(i);u?Da(u):await lc(i)}return 0;default:throw new m(`unknown command: projects ${n}`)}case"functions":{let i=l();if(i){if(n==="deploy"){if(!r[0])throw new m("functions deploy needs a name: snoutdata functions deploy <name>");return await Ga(i,r[0],{dir:S(e,"dir"),verifyJwt:!N(e,"no-verify-jwt")}),0}if(n===void 0||n==="list")return Wa(i),0;if((n==="delete"||n==="remove")&&r[0])return await za(i,r[0]),0}switch(n){case"deploy":{let u=r[0];if(!u)throw new m("functions deploy needs a name: snoutdata functions deploy <name>");return await pi(a(),u,{dir:S(e,"dir"),entrypoint:S(e,"entrypoint"),verifyJwt:!N(e,"no-verify-jwt")}),0}case void 0:case"list":return await gi(a()),0;case"size":{let u=r[0];if(!u)throw new m("functions size needs a name: snoutdata functions size <name> --memory MB --concurrency N");return await fi(a(),u,{memoryMb:_e(e,"memory"),concurrency:_e(e,"concurrency"),reset:N(e,"reset")}),0}case"logs":return await hi(a(),r[0],{errorsOnly:N(e,"errors"),limit:_e(e,"tail"),follow:N(e,"follow")}),0;case"delete":case"remove":{let u=r[0];if(!u)throw new m("functions delete needs a name");return await yi(a(),u),0}default:throw new m(`unknown command: functions ${n}`)}}case"containers":switch(n){case"deploy":{let i=r[0],u=r[1],c=S(e,"dockerfile");if(i&&c){if(u)throw new m("containers deploy takes an image or --dockerfile, not both");if(S(e,"registry-user")||N(e,"clear-registry"))throw new m("an image built with --dockerfile is uploaded to the project and needs no registry login");return await Ii(a(),i,{path:c,port:_e(e,"port"),wait:!N(e,"no-wait")}),0}if(!i||!u)throw new m("containers deploy needs a name and an image: snoutdata containers deploy <name> <image>, or <name> --dockerfile <dir>");let p=S(e,"registry-user");if(p&&!N(e,"stdin"))throw new m('a registry login takes its token on stdin: echo "$TOKEN" | snoutdata containers deploy <name> <image> --registry-user U --stdin');return await Ri(a(),i,{image:u,port:_e(e,"port"),registryUser:p,registryPassword:p?await vt():void 0,clearCredential:N(e,"clear-registry"),wait:!N(e,"no-wait")}),0}case void 0:case"list":return await Ci(a()),0;case"logs":return await Mi(a(),r[0],{errorsOnly:N(e,"errors"),limit:_e(e,"tail"),follow:N(e,"follow")}),0;case"restart":{if(!r[0])throw new m("containers restart needs a name");return await ji(a(),r[0]),0}case"delete":case"remove":{if(!r[0])throw new m("containers delete needs a name");return await Di(a(),r[0]),0}case"egress":{let i=r[0];if(i===void 0||i==="list"||i==="show")return await Yn(a(),{}),0;if(i==="clear")return await Yn(a(),{clear:!0}),0;if(i==="set"){let u=r.slice(1);if(u.length===0&&!N(e,"none"))throw new m("containers egress set needs at least one destination (api.example.com:443), or --none for nothing outside the project");if(u.length>0&&N(e,"none"))throw new m("containers egress set takes destinations or --none, not both");return await Yn(a(),{set:u}),0}throw new m(`unknown command: containers egress ${i}; it is egress, egress set or egress clear`)}default:throw new m(`unknown command: containers ${n}`)}case"secrets":{let i=l();if(i){if(n==="set")return await Va(i,await Bi(r,{stdin:N(e,"stdin")})),0;if(n===void 0||n==="list")return Ya(i),0;if((n==="unset"||n==="remove")&&r[0])return await Xa(i,r[0]),0}switch(n){case"set":return await Fi(a(),r,{stdin:N(e,"stdin")}),0;case void 0:case"list":return await Ki(a()),0;case"unset":case"remove":{let u=r[0];if(!u)throw new m("secrets unset needs a name");return await Hi(a(),u),0}default:throw new m(`unknown command: secrets ${n}`)}}case"keys":switch(n){case void 0:case"show":case"list":return await ai(a()),0;case"rotate":return await ii(a(),{force:N(e,"force")}),0;default:throw new m(`unknown command: keys ${n}`)}case"products":{if(n===void 0||n==="list")return await oc(a()),0;if(n==="enable"||n==="disable")return await sc(a(),rc(r[0]),n==="enable"),0;throw new m(`unknown command: products ${n}. products [enable|disable ${er.join("|")}]`)}case"push":{if(n!=="credentials")throw new m("push credentials [set apns|fcm | remove apns|fcm]");let i=r[0];if(i===void 0||i==="list")return await hl(a()),0;if(i==="set"){let u=Yo(r[1]),c=u==="apns"?await fl({p8:S(e,"p8"),keyId:S(e,"key-id"),teamId:S(e,"team-id"),topic:S(e,"topic"),environment:S(e,"environment")}):await gl(S(e,"file"));return await yl(a(),u,c),0}if(i==="remove"||i==="unset")return await wl(a(),Yo(r[1])),0;throw new m(`unknown command: push credentials ${i}`)}case"auth":return await nl(a(),n,r,{clientId:S(e,"client-id"),stdin:N(e,"stdin"),siteUrl:S(e,"site-url"),allow:S(e,"allow"),file:S(e,"file"),subject:S(e,"subject")}),0;case"realtime":{if(n===void 0||n==="inspect")return vc(a(),{channel:S(e,"channel"),watch:N(e,"watch")});if(n==="logs")return $c(a(),{channel:S(e,"channel"),since:S(e,"since")});throw new m(`unknown command: realtime ${n}. realtime inspect|logs`)}case"ai":{let i=r[0];switch(n){case void 0:case"status":return await Cc(a()),0;case"enable":case"disable":return await jc(a(),n==="enable"),0;case"models":if(i===void 0||i==="list")return await Mc(a()),0;if(i==="add")return await Bc(a(),r[1],{source:S(e,"source"),upstream:S(e,"model"),provider:S(e,"provider"),baseUrl:S(e,"base-url"),region:S(e,"region"),priceIn:S(e,"price-in"),priceOut:S(e,"price-out"),accessKeyId:S(e,"access-key-id"),authHeader:S(e,"auth-header"),stdin:N(e,"stdin")}),0;if(i==="remove"||i==="delete")return await Fc(a(),r[1]),0;throw new m(`unknown command: ai models ${i}. ai models [add|remove]`);case"providers":if(i===void 0||i==="list")return await Lc(a()),0;if(i==="remove"||i==="delete")return await Uc(a(),r[1]),0;throw new m(`unknown command: ai providers ${i}. ai providers [remove NAME]`);case"routes":if(i===void 0||i==="list")return await Hc(a()),0;if(i==="set")return await Kc(a(),r[1],{models:S(e,"models"),sort:S(e,"sort")}),0;if(i==="remove"||i==="delete")return await qc(a(),r[1]),0;throw new m(`unknown command: ai routes ${i}. ai routes [set NAME --models a,b | remove NAME]`);case"keys":if(i===void 0||i==="list")return await Gc(a()),0;if(i==="create")return await Wc(a(),{name:S(e,"name"),models:S(e,"models"),expiresDays:_e(e,"expires")}),0;if(i==="revoke")return await zc(a(),r[1]),0;throw new m(`unknown command: ai keys ${i}. ai keys [create|revoke]`);case"budgets":if(i===void 0||i==="list")return await Jc(a()),0;if(i==="set")return await Vc(a(),r[1],{amount:S(e,"amount"),period:S(e,"period"),soft:N(e,"soft")}),0;if(i==="remove"||i==="delete")return await Yc(a(),r[1]),0;throw new m(`unknown command: ai budgets ${i}. ai budgets [set|remove]`);case"usage":return await Xc(a(),{days:_e(e,"days"),by:S(e,"by")}),0;case"test":return Zc(a(),{model:S(e,"model"),prompt:S(e,"prompt")});default:throw new m(`unknown command: ai ${n}. ai [enable|disable|models|providers|keys|budgets|usage|test]`)}}case"domains":return await ac(a(),n,r[0]),0;case"teams":return await ti(),0;case"link":{if(N(e,"local")){let c;try{c=oa(n)}catch(f){throw new P("not-found",f instanceof Error?f.message:String(f))}let p=gt(process.cwd(),{ref:c.ref,...c.name?{name:c.name}:{},local:c.folder});return h({ref:c.ref,local:c.folder,api:c.apiUrl,path:p},()=>{d(`Linked ${c.name??c.ref}, the local project in ${c.folder} (${p}).`),d(`Its API is ${c.apiUrl}; its database is on 127.0.0.1:${c.dbPort}.`)}),0}let i=S(e,"ref")??n;if(!i)throw new m("link needs --ref");let u=gt(process.cwd(),{ref:i});return h({ref:i,path:u},()=>d(`Linked ${i} (${u}).`)),0}case"db":switch(n){case"url":return await Uo(a()),0;case"psql":return hc(a(),r);case"reset-password":return await ei(a()),0;case"access":return await _c(a(),r,{level:S(e,"level")}),0;case"push":return pl(a(),{dir:S(e,"dir"),dryRun:!!e.flags["dry-run"],outOfOrder:!!e.flags["out-of-order"]});case"restore":return N(e,"window")?(await ic(a()),0):S(e,"at")?(await cc(a(),S(e,"at"),S(e,"name")),0):bc(a(),{file:S(e,"file"),force:!!e.flags.force});case"export":return wc(a(),{timeoutMs:s(),out:S(e,"out"),statusOnly:!!e.flags.status});default:throw new m(n?`unknown command: db ${n}`:"db needs an action: url, psql, reset-password, access, export, push, restore")}case"gen":{if(n!=="types")throw new m(n?`unknown command: gen ${n}`:"gen needs an action: types");let i=N(e,"local")?await Ou(await un()):null,u=i?i.dbUrl:S(e,"db-url");return kl(r[0],{ref:u?void 0:a(),dbUrl:u,schemas:(S(e,"schema")??"public").split(",").map(c=>c.trim()).filter(Boolean),out:S(e,"out"),sql:i?.sql})}case"start":{let i=l();if(i)return Ca(i)}return Au(await un(),{port:_e(e,"port"),dir:S(e,"dir"),noMigrations:N(e,"no-migrations"),outOfOrder:N(e,"out-of-order")});case"stop":{let i=l();return i?ja(i):Ru(await un())}case"status":{let i=l();return i?Ia(i):Tu(await un())}case"usage":return Du(a(),{days:_e(e,"days"),history:!!e.flags.history});case"mcp":return Cu({version:ue,allowDelete:!!e.flags["allow-delete"]});case"init":return jb(e);case"upgrade":return Gu({check:N(e,"check")});default:throw new m(`unknown command: ${t}`)}}async function jb(e){let t=na({flag:S(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.`),N(e,"env")?await zu(o):await Uo(o),t.kind==="link"){let s=He(o),a=gt(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=S(e,"name")??Db(process.cwd());d(`Creating a project called "${n}"\u2026`),await so({name:n,region:S(e,"region"),wait:!0,link:process.cwd(),showUrl:!N(e,"env")});let r=hn({cwd:process.cwd()});return r&&N(e,"env")&&await zu(r),0}async function zu(e){let{connection:t}=await Promise.resolve().then(()=>(re(),Ae)),n=await t(e),r=yc(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 Db(e){let t=e.split(/[\\/]/).filter(Boolean);return t[t.length-1]??"project"}function Mb(e){if(e instanceof P)return Ve(e.code,e.message,e.details),e.exitCode;if(e instanceof m)return Ve("usage",e.message),Le.usage;if(e instanceof Ye)return Ve("not-signed-in",e.message),Le["not-signed-in"];if(e instanceof ge){let r=Ue(e.status,e.serverCode);return Ve(r,e.message,{status:e.status,...e.serverCode?{serverCode:e.serverCode}:{}}),Le[r]}let t=ia(e);if(t)return Ve("usage",t),Le.usage;let n=bn(e);return Ve(n,e instanceof Error?e.message:String(e)),Le[n]}function Hs(e){process.exitCode=e,setTimeout(()=>process.exit(e),2e3).unref()}function Lb(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}async function Ub(){Lt(Lb(process.argv.slice(2)));let e;try{e=Gs(process.argv.slice(2))}catch(t){Ve("usage",String(t instanceof Error?t.message:t)),Hs(Le.usage);return}Lt(e.json),Sa(e.flags.quiet===!0),ca(_n({isTty:!!process.stdin.isTTY,json:e.json,env:process.env}));try{Hs(await Cb(e))}catch(t){Hs(Mb(t))}}Ub();
892
+ `)}),0}let o=I(e,"help")||t==="help";if(o||!t)return h({version:ue,usage:Xu.trim(),commands:Mr},()=>process.stdout.write(Xu)),o?0:Le.usage;let s=()=>{let i=_e(e,"timeout");if(i!==void 0){if(!(i>0))throw new m("--timeout is a number of seconds greater than zero");return i*1e3}},a=()=>{let i=wn({flag:S(e,"ref")});if(!i)throw new m("no project: pass --ref, set SNOUTDATA_PROJECT, or run `snoutdata link --ref <ref>`");return i},l=()=>{let i=wn({flag:S(e,"ref")});return i?He(i):null};for(let i of Vb)if(e.flags[i]!==void 0&&t!=="cluster")throw new m(`--${i} is only for snoutdata cluster`);switch(t){case"cluster":return Gu(e,{timeoutMs:s()});case"login":{if(I(e,"device")){let p=await Nn({name:xn(),platform:process.platform});h({verifyUrl:p.verifyUrl,code:p.code,expiresAt:p.expiresAt},()=>{d(""),d(` Open ${p.verifyUrl}`),d(` Type ${p.code}`),d(""),d(w("Waiting for that to be approved\u2026"))});let f=await In(p.secret,{intervalMs:Math.max(1,p.interval)*1e3,expiresAt:p.expiresAt});Ne({accessToken:f.token});let k=S(e,"email"),v=k?(await ct()).email??void 0:void 0;return k&&Qr(k,{accessToken:f.token,email:v}),h({ok:!0,name:f.name??null,email:v??null},()=>d(`Signed in${v?` as ${v}`:""}.`)),0}let i=S(e,"domain"),u=I(e,"sso")||i!==void 0;if(u&&S(e,"provider"))throw new m("--sso and --provider are two different doors: pass one or the other");let c=await Ln({provider:S(e,"provider"),sso:u,domain:i,noBrowser:I(e,"no-browser")||!ye(),timeoutMs:s(),email:S(e,"email")});return h({email:c.email??null},()=>d(`Signed in${c.email?` as ${c.email}`:""}.`)),0}case"logout":{Qs();let i=!!process.env.SNOUTDATA_ACCESS_TOKEN;return h({ok:!0,environmentTokenStillSet:i},()=>{d("Signed out."),i&&(d("SNOUTDATA_ACCESS_TOKEN is still set in this shell, so commands will keep working."),d(w(" unset SNOUTDATA_ACCESS_TOKEN")))}),0}case"whoami":{let i=await ct(),u=yn()?.expectedEmail,c=!!(u&&i.email&&!eo(u,i.email));return c&&ee(`This session is ${i.email}, and login asked for ${u}. Run "snoutdata login --email ${u}" to sign in as that account.`),h({...i,...u?{expectedEmail:u,matchesExpected:!c}:{}},()=>{process.stdout.write(`${i.email??i.id}
893
+ `),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 si(),0;case"create":{let i=S(e,"name")??r[0];if(!i)throw new m("tokens create needs --name (what is it for, and where does it live)");return await oi({name:i,expiresInDays:_e(e,"expires"),project:S(e,"project")}),0}case"revoke":{let i=r[0];if(!i)throw new m("tokens revoke needs the token's id or its sdt_ prefix");return await ai(i),0}default:throw new m(`unknown command: tokens ${n}`)}case"projects":switch(n){case void 0:case"list":return await Qa(),0;case"create":{let i=S(e,"name")??r[0];if(!i)throw new m("projects create needs --name");let u=S(e,"team");return await io({teamId:u?await ri(u):void 0,name:i,region:S(e,"region"),wait:!I(e,"no-wait"),timeoutMs:s(),link:void 0,showUrl:I(e,"show-url")}),0}case"pause":case"resume":case"delete":return await ei(n,S(e,"ref")??r[0]??a(),{wait:!I(e,"no-wait"),timeoutMs:s()}),0;case"show":{let i=S(e,"ref")??r[0]??a(),u=He(i);u?Ma(u):await dc(i)}return 0;default:throw new m(`unknown command: projects ${n}`)}case"functions":{let i=l();if(i){if(n==="deploy"){if(!r[0])throw new m("functions deploy needs a name: snoutdata functions deploy <name>");return await za(i,r[0],{dir:S(e,"dir"),verifyJwt:!I(e,"no-verify-jwt")}),0}if(n===void 0||n==="list")return Wa(i),0;if((n==="delete"||n==="remove")&&r[0])return await Ja(i,r[0]),0}switch(n){case"deploy":{let u=r[0];if(!u)throw new m("functions deploy needs a name: snoutdata functions deploy <name>");return await mi(a(),u,{dir:S(e,"dir"),entrypoint:S(e,"entrypoint"),verifyJwt:!I(e,"no-verify-jwt")}),0}case void 0:case"list":return await hi(a()),0;case"size":{let u=r[0];if(!u)throw new m("functions size needs a name: snoutdata functions size <name> --memory MB --concurrency N");return await gi(a(),u,{memoryMb:_e(e,"memory"),concurrency:_e(e,"concurrency"),reset:I(e,"reset")}),0}case"logs":return await yi(a(),r[0],{errorsOnly:I(e,"errors"),limit:_e(e,"tail"),follow:I(e,"follow")}),0;case"delete":case"remove":{let u=r[0];if(!u)throw new m("functions delete needs a name");return await wi(a(),u),0}default:throw new m(`unknown command: functions ${n}`)}}case"containers":switch(n){case"deploy":{let i=r[0],u=r[1],c=S(e,"dockerfile");if(i&&c){if(u)throw new m("containers deploy takes an image or --dockerfile, not both");if(S(e,"registry-user")||I(e,"clear-registry"))throw new m("an image built with --dockerfile is uploaded to the project and needs no registry login");return await Ci(a(),i,{path:c,port:_e(e,"port"),wait:!I(e,"no-wait")}),0}if(!i||!u)throw new m("containers deploy needs a name and an image: snoutdata containers deploy <name> <image>, or <name> --dockerfile <dir>");let p=S(e,"registry-user");if(p&&!I(e,"stdin"))throw new m('a registry login takes its token on stdin: echo "$TOKEN" | snoutdata containers deploy <name> <image> --registry-user U --stdin');return await Ti(a(),i,{image:u,port:_e(e,"port"),registryUser:p,registryPassword:p?await vt():void 0,clearCredential:I(e,"clear-registry"),wait:!I(e,"no-wait")}),0}case void 0:case"list":return await ji(a()),0;case"logs":return await Li(a(),r[0],{errorsOnly:I(e,"errors"),limit:_e(e,"tail"),follow:I(e,"follow")}),0;case"restart":{if(!r[0])throw new m("containers restart needs a name");return await Di(a(),r[0]),0}case"delete":case"remove":{if(!r[0])throw new m("containers delete needs a name");return await Mi(a(),r[0]),0}case"egress":{let i=r[0];if(i===void 0||i==="list"||i==="show")return await Zn(a(),{}),0;if(i==="clear")return await Zn(a(),{clear:!0}),0;if(i==="set"){let u=r.slice(1);if(u.length===0&&!I(e,"none"))throw new m("containers egress set needs at least one destination (api.example.com:443), or --none for nothing outside the project");if(u.length>0&&I(e,"none"))throw new m("containers egress set takes destinations or --none, not both");return await Zn(a(),{set:u}),0}throw new m(`unknown command: containers egress ${i}; it is egress, egress set or egress clear`)}default:throw new m(`unknown command: containers ${n}`)}case"secrets":{let i=l();if(i){if(n==="set")return await Ya(i,await Fi(r,{stdin:I(e,"stdin")})),0;if(n===void 0||n==="list")return Xa(i),0;if((n==="unset"||n==="remove")&&r[0])return await Za(i,r[0]),0}switch(n){case"set":return await Hi(a(),r,{stdin:I(e,"stdin")}),0;case void 0:case"list":return await qi(a()),0;case"unset":case"remove":{let u=r[0];if(!u)throw new m("secrets unset needs a name");return await Ki(a(),u),0}default:throw new m(`unknown command: secrets ${n}`)}}case"keys":switch(n){case void 0:case"show":case"list":return await ii(a()),0;case"rotate":return await ci(a(),{force:I(e,"force")}),0;default:throw new m(`unknown command: keys ${n}`)}case"products":{if(n===void 0||n==="list")return await sc(a()),0;if(n==="enable"||n==="disable")return await ac(a(),oc(r[0]),n==="enable"),0;throw new m(`unknown command: products ${n}. products [enable|disable ${nr.join("|")}]`)}case"push":{if(n!=="credentials")throw new m("push credentials [set apns|fcm | remove apns|fcm]");let i=r[0];if(i===void 0||i==="list")return await yl(a()),0;if(i==="set"){let u=Zo(r[1]),c=u==="apns"?await gl({p8:S(e,"p8"),keyId:S(e,"key-id"),teamId:S(e,"team-id"),topic:S(e,"topic"),environment:S(e,"environment")}):await hl(S(e,"file"));return await wl(a(),u,c),0}if(i==="remove"||i==="unset")return await bl(a(),Zo(r[1])),0;throw new m(`unknown command: push credentials ${i}`)}case"auth":return await rl(a(),n,r,{clientId:S(e,"client-id"),stdin:I(e,"stdin"),siteUrl:S(e,"site-url"),allow:S(e,"allow"),file:S(e,"file"),subject:S(e,"subject")}),0;case"realtime":{if(n===void 0||n==="inspect")return $c(a(),{channel:S(e,"channel"),watch:I(e,"watch")});if(n==="logs")return xc(a(),{channel:S(e,"channel"),since:S(e,"since")});throw new m(`unknown command: realtime ${n}. realtime inspect|logs`)}case"ai":{let i=r[0];switch(n){case void 0:case"status":return await jc(a()),0;case"enable":case"disable":return await Dc(a(),n==="enable"),0;case"models":if(i===void 0||i==="list")return await Lc(a()),0;if(i==="add")return await Fc(a(),r[1],{source:S(e,"source"),upstream:S(e,"model"),provider:S(e,"provider"),baseUrl:S(e,"base-url"),region:S(e,"region"),priceIn:S(e,"price-in"),priceOut:S(e,"price-out"),accessKeyId:S(e,"access-key-id"),authHeader:S(e,"auth-header"),stdin:I(e,"stdin")}),0;if(i==="remove"||i==="delete")return await Hc(a(),r[1]),0;throw new m(`unknown command: ai models ${i}. ai models [add|remove]`);case"providers":if(i===void 0||i==="list")return await Uc(a()),0;if(i==="remove"||i==="delete")return await Bc(a(),r[1]),0;throw new m(`unknown command: ai providers ${i}. ai providers [remove NAME]`);case"routes":if(i===void 0||i==="list")return await Kc(a()),0;if(i==="set")return await qc(a(),r[1],{models:S(e,"models"),sort:S(e,"sort")}),0;if(i==="remove"||i==="delete")return await Gc(a(),r[1]),0;throw new m(`unknown command: ai routes ${i}. ai routes [set NAME --models a,b | remove NAME]`);case"keys":if(i===void 0||i==="list")return await zc(a()),0;if(i==="create")return await Wc(a(),{name:S(e,"name"),models:S(e,"models"),expiresDays:_e(e,"expires")}),0;if(i==="revoke")return await Jc(a(),r[1]),0;throw new m(`unknown command: ai keys ${i}. ai keys [create|revoke]`);case"budgets":if(i===void 0||i==="list")return await Vc(a()),0;if(i==="set")return await Yc(a(),r[1],{amount:S(e,"amount"),period:S(e,"period"),soft:I(e,"soft")}),0;if(i==="remove"||i==="delete")return await Xc(a(),r[1]),0;throw new m(`unknown command: ai budgets ${i}. ai budgets [set|remove]`);case"usage":return await Zc(a(),{days:_e(e,"days"),by:S(e,"by")}),0;case"test":return Qc(a(),{model:S(e,"model"),prompt:S(e,"prompt")});default:throw new m(`unknown command: ai ${n}. ai [enable|disable|models|providers|keys|budgets|usage|test]`)}}case"domains":return await ic(a(),n,r[0]),0;case"teams":return await ni(),0;case"link":{if(I(e,"local")){let c;try{c=oa(n)}catch(f){throw new P("not-found",f instanceof Error?f.message:String(f))}let p=gt(process.cwd(),{ref:c.ref,...c.name?{name:c.name}:{},local:c.folder});return h({ref:c.ref,local:c.folder,api:c.apiUrl,path:p},()=>{d(`Linked ${c.name??c.ref}, the local project in ${c.folder} (${p}).`),d(`Its API is ${c.apiUrl}; its database is on 127.0.0.1:${c.dbPort}.`)}),0}let i=S(e,"ref")??n;if(!i)throw new m("link needs --ref");let u=gt(process.cwd(),{ref:i});return h({ref:i,path:u},()=>d(`Linked ${i} (${u}).`)),0}case"db":switch(n){case"url":return await Fo(a()),0;case"psql":return yc(a(),r);case"reset-password":return await ti(a()),0;case"access":return await Sc(a(),r,{level:S(e,"level")}),0;case"push":return ml(a(),{dir:S(e,"dir"),dryRun:!!e.flags["dry-run"],outOfOrder:!!e.flags["out-of-order"]});case"restore":return I(e,"window")?(await cc(a()),0):S(e,"at")?(await lc(a(),S(e,"at"),S(e,"name")),0):_c(a(),{file:S(e,"file"),force:!!e.flags.force});case"export":return bc(a(),{timeoutMs:s(),out:S(e,"out"),statusOnly:!!e.flags.status});default:throw new m(n?`unknown command: db ${n}`:"db needs an action: url, psql, reset-password, access, export, push, restore")}case"gen":{if(n!=="types")throw new m(n?`unknown command: gen ${n}`:"gen needs an action: types");let i=I(e,"local")?await Du(await mn()):null,u=i?i.dbUrl:S(e,"db-url");return vl(r[0],{ref:u?void 0:a(),dbUrl:u,schemas:(S(e,"schema")??"public").split(",").map(c=>c.trim()).filter(Boolean),out:S(e,"out"),sql:i?.sql})}case"start":{let i=l();if(i)return ja(i)}return Iu(await mn(),{port:_e(e,"port"),dir:S(e,"dir"),noMigrations:I(e,"no-migrations"),outOfOrder:I(e,"out-of-order")});case"stop":{let i=l();return i?Da(i):Cu(await mn())}case"status":{let i=l();return i?Ca(i):ju(await mn())}case"usage":return Fu(a(),{days:_e(e,"days"),history:!!e.flags.history});case"mcp":return Uu({version:ue,allowDelete:!!e.flags["allow-delete"]});case"init":return Xb(e);case"upgrade":return Yu({check:I(e,"check")});default:throw new m(`unknown command: ${t}`)}}async function Xb(e){let t=na({flag:S(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.`),I(e,"env")?await Zu(o):await Fo(o),t.kind==="link"){let s=He(o),a=gt(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=S(e,"name")??Zb(process.cwd());d(`Creating a project called "${n}"\u2026`),await io({name:n,region:S(e,"region"),wait:!0,link:process.cwd(),showUrl:!I(e,"env")});let r=wn({cwd:process.cwd()});return r&&I(e,"env")&&await Zu(r),0}async function Zu(e){let{connection:t}=await Promise.resolve().then(()=>(oe(),Re)),n=await t(e),r=wc(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 Zb(e){let t=e.split(/[\\/]/).filter(Boolean);return t[t.length-1]??"project"}function Qb(e){if(e instanceof P)return Ve(e.code,e.message,e.details),e.exitCode;if(e instanceof m)return Ve("usage",e.message),Le.usage;if(e instanceof Ye)return Ve("not-signed-in",e.message),Le["not-signed-in"];if(e instanceof ge){let r=Ue(e.status,e.serverCode);return Ve(r,e.message,{status:e.status,...e.serverCode?{serverCode:e.serverCode}:{}}),Le[r]}let t=ia(e);if(t)return Ve("usage",t),Le.usage;let n=Sn(e);return Ve(n,e instanceof Error?e.message:String(e)),Le[n]}function Hs(e){process.exitCode=e,setTimeout(()=>process.exit(e),2e3).unref()}function e_(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}async function t_(){Ut(e_(process.argv.slice(2)));let e;try{e=Gs(process.argv.slice(2))}catch(t){Ve("usage",String(t instanceof Error?t.message:t)),Hs(Le.usage);return}Ut(e.json),Sa(e.flags.quiet===!0),ca(kn({isTty:!!process.stdin.isTTY,json:e.json,env:process.env}));try{Hs(await Yb(e))}catch(t){Hs(Qb(t))}}t_();