snoutdata 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,21 +1,158 @@
1
1
  # snoutdata
2
2
 
3
- An AI data tool. **Early development** — this `0.0.1` release reserves the name and ships a placeholder entry point. APIs will land in future versions.
3
+ Hosted Postgres from a terminal, or from an agent. One bundled file with no dependencies, so
4
+ `npx snoutdata` is a download rather than an install. Needs Node 20 or newer.
4
5
 
5
- ## Install
6
+ ```bash
7
+ npx snoutdata init --env
8
+ ```
9
+
10
+ An empty folder becomes a folder with a working database: a project is created, the command
11
+ waits until it is actually serving, writes `.snoutdata/project.json`, and puts `DATABASE_URL`
12
+ in `.env`. It is idempotent, so running it twice gives you the same project, not two.
13
+
14
+ Driven end to end holding nothing but an access token (no browser, no session, no human) in
15
+ 21 seconds, with a `DATABASE_URL` that connected on the first try.
16
+
17
+ ---
18
+
19
+ ## For an agent
20
+
21
+ This CLI is built to be driven by a program. The contract, which every command holds:
22
+
23
+ | | |
24
+ | --- | --- |
25
+ | `--json` | Accepted everywhere. **Exactly one JSON value on stdout and nothing else**, so a pipe into `jq` needs no filtering. Progress, warnings and prompts go to stderr. |
26
+ | Failures are structured | In `--json` mode a failure is `{"ok":false,"code":"...","error":"..."}` on stdout. Including a bad flag, a bad command, and a bad credential. |
27
+ | No prompts | Nothing asks a question when stdin is not a terminal, or under `--json`, or in CI. A command that would have to ask says which flag to pass and exits 2 immediately, rather than blocking on a question nobody will answer. |
28
+ | Unknown flags are errors | Never ignored. A typo that quietly does something else is worse than a stop. |
29
+ | Typed exit codes | The code says what kind of problem it was, so a caller can decide whether to retry, re-authenticate, or give up. |
30
+
31
+ ### Exit codes
32
+
33
+ | Code | Meaning | What a caller should do |
34
+ | --- | --- | --- |
35
+ | `0` | Fine | Continue. |
36
+ | `1` | The operation failed | Read the error. |
37
+ | `2` | The command was wrong | Fix the call. Do not retry. |
38
+ | `3` | The credential is no good | Never signed in, expired, or revoked. The message says which. |
39
+ | `4` | Not ready yet | Retry. |
40
+ | `5` | Forbidden | Do not retry. |
41
+ | `6` | Not found | Do not retry. |
42
+ | `7` | Conflict | |
43
+ | `8` | Over a quota | The plan's limit. Do not retry. |
44
+ | `9` | Network | Retry. |
45
+ | `10` | Timed out | Retry, or raise `--timeout`. |
46
+
47
+ ### Credentials, without a browser
48
+
49
+ ```bash
50
+ export SNOUTDATA_ACCESS_TOKEN=sdt_... # made once by a person: snoutdata tokens create
51
+ ```
52
+
53
+ `SNOUTDATA_ACCESS_TOKEN` outranks everything and never expires, which is what CI and an agent
54
+ should use: a script's behaviour should not depend on who happens to be logged in on the machine
55
+ it runs on. Failing that, `~/.snoutdata/auth.json` (written by `snoutdata login`, mode 0600),
56
+ whose session lasts an hour.
57
+
58
+ The token is exchanged for a short-lived session by the control plane, so row-level security is
59
+ still the only thing deciding what it can see.
60
+
61
+ ### As an MCP server
62
+
63
+ ```bash
64
+ snoutdata mcp
65
+ ```
66
+
67
+ Serves the operations below as tools over stdio, so an agent configures one server instead of
68
+ being handed a connection string. Anything destructive is off unless you pass `--allow-delete`,
69
+ and it is present-but-refusing rather than absent, so an agent can tell you what to turn on
70
+ instead of inventing something else.
71
+
72
+ If the SnoutData desktop app is running on the same machine, its own database tools are borrowed
73
+ onto the same endpoint under an `app_` prefix, so one configured server covers both the cloud and
74
+ the databases already set up locally. `SNOUTDATA_NO_DESKTOP=1` opts out.
75
+
76
+ ---
6
77
 
7
- ```sh
8
- npm install snoutdata
78
+ ## Commands
79
+
80
+ **Setup**
81
+
82
+ ```bash
83
+ snoutdata init [--name X] [--env] # a database for this folder, linked and ready
84
+ snoutdata link --ref R # point this folder at an existing project
85
+ ```
86
+
87
+ **Auth**
88
+
89
+ ```bash
90
+ snoutdata login # through a browser
91
+ snoutdata login --device # print a code to type into a browser anywhere
92
+ snoutdata login --no-browser # print the URL instead of opening one
93
+ snoutdata logout
94
+ snoutdata whoami
95
+ snoutdata tokens create --name ci [--expires DAYS]
96
+ snoutdata tokens list
97
+ snoutdata tokens revoke <id|sdt_prefix>
9
98
  ```
10
99
 
11
- ## Usage
100
+ **Projects**
101
+
102
+ ```bash
103
+ snoutdata projects list
104
+ snoutdata projects create --name X [--region R] [--no-wait]
105
+ snoutdata projects pause|resume|delete [--ref R]
106
+ snoutdata usage [--ref R] [--days 30] [--history]
107
+ snoutdata teams
108
+ ```
109
+
110
+ **Database**
111
+
112
+ ```bash
113
+ snoutdata db url [--ref R] # a connection string
114
+ snoutdata db psql [--ref R] [-- ...] # opens psql, no password typed
115
+ snoutdata db reset-password [--ref R]
116
+ snoutdata db export [--ref R] [--out FILE] # take a dump and download it
117
+ snoutdata db push [--dir migrations] [--dry-run] # run the .sql files, once each
118
+ snoutdata db restore --file DUMP [--force]
119
+ ```
12
120
 
13
- ```js
14
- import snoutdata from "snoutdata";
121
+ **Agents**
15
122
 
16
- console.log(snoutdata.version); // "0.0.1"
123
+ ```bash
124
+ snoutdata mcp [--allow-delete]
17
125
  ```
18
126
 
19
- ## License
127
+ Every command takes `--json`, `--quiet` and `--help`, and anything that waits takes
128
+ `--timeout SECONDS`. `snoutdata --help --json` returns the whole command surface as JSON.
129
+
130
+ ---
131
+
132
+ ## Where things come from
133
+
134
+ **A project**, in order: `--ref`, then `SNOUTDATA_PROJECT`, then `.snoutdata/project.json` in
135
+ this folder or a parent.
136
+
137
+ **A token**, in order: `SNOUTDATA_ACCESS_TOKEN`, then `~/.snoutdata/auth.json`.
138
+
139
+ **Sign-in, when there is no credential and a person is present**, in order: the SnoutData
140
+ desktop app if it is running here and willing, then a browser, then a pairing code for a
141
+ terminal that has no browser at all. With no person present (not a terminal, `--json`, CI, or
142
+ `SNOUTDATA_NO_INTERACTIVE`) nothing is asked and it exits 3 at once.
143
+
144
+ ---
145
+
146
+ ## Documentation
147
+
148
+ - Everything an agent needs, on one page: <https://docs.snoutdata.com/cloud/agent>
149
+ - Full CLI reference: <https://docs.snoutdata.com/cloud/cli>
150
+ - Getting started: <https://docs.snoutdata.com/cloud/getting-started>
151
+ - Plans and limits: <https://docs.snoutdata.com/cloud/limits>
152
+
153
+ SnoutData Cloud is hosted Postgres that costs nothing when idle: a database pauses when nobody
154
+ is using it and wakes on the next connection, while the client waits.
155
+
156
+ ---
20
157
 
21
- MIT
158
+ © SnoutData. See <https://snoutdata.com/terms>.
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ var tn=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var nn=(e,t)=>{for(var n in t)tn(e,n,{get:t[n],enumerable:!0})};import{chmodSync as an,existsSync as Ke,mkdirSync as ze,readFileSync as Ye,rmSync as cn,writeFileSync as Ve}from"node:fs";import{homedir as le}from"node:os";import{dirname as $e,join as Xe,parse as ln,resolve as dn}from"node:path";function Pe(e=le()){return Xe(e,".snoutdata","auth.json")}function Ze(e=le()){let t=process.env.SNOUTDATA_ACCESS_TOKEN;if(t)return{accessToken:t};let n=Pe(e);if(!Ke(n))return null;try{let r=JSON.parse(Ye(n,"utf8"));return typeof r.accessToken=="string"?r:null}catch{return null}}function j(e,t=le()){let n=Pe(t);ze($e(n),{recursive:!0}),Ve(n,`${JSON.stringify(e,null,2)}
3
+ `,{mode:384}),an(n,384)}function Qe(e=le()){cn(Pe(e),{force:!0})}function et(e,t=Date.now()){return e.expiresAt?e.expiresAt*1e3-6e4<=t:!1}function tt(e){return Xe(e,".snoutdata","project.json")}function un(e){let t=dn(e),n=ln(t).root;for(;;){let r=tt(t);if(Ke(r))try{let o=JSON.parse(Ye(r,"utf8"));if(typeof o.ref=="string"&&o.ref)return{ref:o.ref,directory:t}}catch{}if(t===n)return null;t=$e(t)}}function de(e,t){let n=tt(e);return ze($e(n),{recursive:!0}),Ve(n,`${JSON.stringify(t,null,2)}
4
+ `),n}function ue(e){let t=e.environment??process.env;return e.flag?e.flag:t.SNOUTDATA_PROJECT?t.SNOUTDATA_PROJECT:un(e.cwd??process.cwd())?.ref??null}var z=_(()=>{"use strict"});function pe(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 pn){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 me(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 nt(e){Ee=e}function Y(){return(Ee??pe({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).canAsk}function fe(){return(Ee??pe({isTty:!!process.stdin.isTTY,json:!1,env:process.env})).reason}var pn,Ee,ee=_(()=>{"use strict";pn=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD"];Ee=null});import{existsSync as mn,readFileSync as fn}from"node:fs";import{homedir as Oe,hostname as gn}from"node:os";import{join as V}from"node:path";function hn(e,t,n){if(t==="win32"){let r=n.APPDATA??V(Oe(),"AppData","Roaming");return V(r,e)}return t==="darwin"?V(Oe(),"Library","Application Support",e):V(n.XDG_CONFIG_HOME??V(Oe(),".config"),e)}function ot(e=process.platform,t=process.env){return t.SNOUTDATA_DESKTOP_CONFIG?[t.SNOUTDATA_DESKTOP_CONFIG]:["snoutdata","snoutdata-dev"].map(n=>V(hn(n,e,t),"mcp.json"))}function wn(e=process.platform,t=process.env){return ot(e,t)[0]}function yn(e=wn()){if(!mn(e))return null;try{let t=JSON.parse(fn(e,"utf8"));return typeof t.port!="number"||typeof t.token!="string"||!t.token?null:t}catch{return null}}function kn(e){return e?e.enabled===!1?"server-disabled":e.signInHandoff===!1?"handoff-disabled":null:"no-config"}async function ge(e){if(e!==void 0)return rt(e);let t="no-config";for(let n of ot()){let r=yn(n);if(!r)continue;let o=await rt(r);if(o.available)return o;(o.skip!=="not-running"||t==="no-config")&&(t=o.skip)}return{available:!1,skip:t}}async function rt(e){let t=kn(e);if(t)return{available:!1,skip:t};let n=e,r;try{let o=await fetch(`http://127.0.0.1:${n.port}/cli/whoami`,{headers:{Authorization:`Bearer ${n.token}`},signal:AbortSignal.timeout(bn)});if(!o.ok)return{available:!1,skip:"not-running"};r=await o.json()}catch{return{available:!1,skip:"not-running"}}return r.signedIn?r.canMintToken?{available:!0,who:r,config:n}:{available:!1,skip:"cannot-mint"}:{available:!1,skip:"signed-out"}}async function st(e,t){let n=await fetch(`http://127.0.0.1:${e.port}/cli/token`,{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"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??`the app refused (${n.status})`}}function he(){return gn()}async function _e(e,t,n,r){let o=await fetch(`http://127.0.0.1:${e.port}/mcp`,{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"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??"the app refused");return s.result}async function at(e){return await _e(e,"initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"snoutdata-cli",version:"0"}},3e3),(await _e(e,"tools/list",{},3e3)).tools??[]}async function it(e,t,n){return _e(e,"tools/call",{name:t,arguments:n},12e4)}var bn,we=_(()=>{"use strict";bn=1500});function g(e,t,n){throw new B(e,t,n)}function lt(e){return e===403?"forbidden":e===404?"not-found":e===409?"conflict":e===402||e===429?"quota":e===503?"not-ready":e===504?"timeout":e>=500?"server":"failed"}function dt(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(xn.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 L,B,xn,te=_(()=>{"use strict";L={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,"tool-missing":127,server:1},B=class extends Error{code;details;constructor(t,n,r){super(n),this.name="CliFailure",this.code=t,this.details=r}get exitCode(){return L[this.code]}};xn=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","CERT_HAS_EXPIRED","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT"])});async function ut(e,t){let n=await fetch(`${R}/functions/v1/${e}`,{method:"POST",headers:{apikey:F,"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));return{status:n.status,body:r}}async function ye(e={}){let{status:t,body:n}=await ut("cloud-device-start",{client:e});return t===429&&g("quota",n.error??"too many pairing attempts from here: wait a few minutes"),t===404&&g("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)&&g("server",n.error??`could not start a pairing (${t})`),n}async function ke(e,t){let n=t.intervalMs,r=Date.parse(t.expiresAt);for(;;){Date.now()>r&&g("timeout","that pairing code expired before it was approved. Run the command again for a new one."),await new Promise(d=>setTimeout(d,n));let{status:o,body:s}=await ut("cloud-device-poll",{secret:e});switch(o===404&&g("not-found","that pairing is not known to the server. Run the command again for a new code."),o===400&&g("usage",s.error??"that is not a pairing secret"),o!==200&&g("server",s.error??`the pairing could not be checked (${o})`),s.status){case"approved":return{token:s.token,name:s.name};case"denied":g("forbidden",s.error??"that pairing was refused in the browser");case"used":g("conflict",s.error??"that pairing has already been completed");case"expired":g("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 je=_(()=>{"use strict";T();te()});function ne(e){be=e}function mt(e){pt=e}function y(e){return ft?`\x1B[2m${e}\x1B[0m`:e}function A(e){return ft?`\x1B[1m${e}\x1B[0m`:e}function p(e,t){if(be){process.stdout.write(`${JSON.stringify(e,null,2)}
5
+ `);return}t()}function i(e){!be&&!pt&&process.stderr.write(`${e}
6
+ `)}function G(e,t,n){process.stderr.write(`${t}
7
+ `),be&&process.stdout.write(`${JSON.stringify({ok:!1,code:e,error:t,...n},null,2)}
8
+ `)}function $(e){process.stderr.write(`${e}
9
+ `)}function W(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(`
10
+ `)}function H(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,d="second";for(let[c,l]of o){if(s<c)break;s=Math.round(s/c),d=l}let a=`${s} ${d}${s===1?"":"s"}`;return n?`in ${a}`:`${a} ago`}var be,pt,ft,E=_(()=>{"use strict";be=!1,pt=!1;ft=process.stdout.isTTY&&!process.env.NO_COLOR});import{createHash as gt,randomBytes as Re}from"node:crypto";import{createServer as ht}from"node:http";import{spawn as vn}from"node:child_process";function xe(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Se(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.":Nn(t??"Something went wrong.");return`<!doctype html><html><head><meta charset="utf-8"><title>SnoutData</title>
11
+ <meta name="viewport" content="width=device-width,initial-scale=1"></head>
12
+ <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">
13
+ <div style="text-align:center;max-width:460px;padding:40px 24px">
14
+ <div style="width:44px;height:44px;margin:0 auto 30px;border-radius:12px;background:#191714;border:1px solid #262320;display:grid;place-items:center">
15
+ <div style="width:14px;height:14px;border-radius:50%;background:${n}"></div>
16
+ </div>
17
+ <div style="font-size:12px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#8f887e;margin-bottom:22px">SnoutData</div>
18
+ <h1 style="margin:0 0 12px;font-size:30px;font-weight:600;letter-spacing:-.01em">${r}</h1>
19
+ <p style="color:#8f887e;margin:0;font-size:15px;line-height:1.5">${o}</p>
20
+ ${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>'}
21
+ </div>
22
+ </body></html>`}function wt(){let e=xe(Re(32)),t=xe(gt("sha256").update(e).digest());return{verifier:e,challenge:t}}function Tn(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 yt(e){let{command:t,args:n,verbatim:r}=Tn(process.platform,e),o=vn(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}function En(e){let t=e??xe(Re(32));return{raw:t,hashed:gt("sha256").update(t).digest("hex")}}function On(e){return`${An}?${new URLSearchParams({client_id:kt,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 _n(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?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 jn(e,t,n){let r=await fetch($n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:kt,client_secret:Pn,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 Rn(e){let{verifier:t,challenge:n}=wt(),{raw:r,hashed:o}=En(),s=xe(Re(16)),{code:d,redirectUri:a}=await new Promise((w,m)=>{let k="",u=ht((O,K)=>{let P=_n(O.url??"/",s);if(P.kind==="ignore"){K.writeHead(404).end();return}K.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),K.end(P.kind==="ok"?Se("ok"):Se("failed",P.message)),u.close(),P.kind==="ok"?w({code:P.code,redirectUri:k}):m(new Error(P.message))});u.listen(0,"127.0.0.1",()=>{let O=u.address();k=`http://127.0.0.1:${typeof O=="object"&&O?O.port:0}`;let P=On({redirectUri:k,challenge:n,hashedNonce:o,state:s});process.stdout.write(`${P}
23
+ `),e.noBrowser?i("Open that in a browser, on any machine, and sign in."):(i("Opening that in your browser. If nothing opens, paste it into one."),yt(P))}),u.on("error",m),setTimeout(()=>{u.close(),m(new Error("timed out waiting for the browser"))},e.timeoutMs??3e5).unref()}),c=await jn(d,t,a),l=await fetch(`${R}/auth/v1/token?grant_type=id_token`,{method:"POST",headers:{apikey:F,"Content-Type":"application/json"},body:JSON.stringify({provider:"google",id_token:c,nonce:r})});if(!l.ok)throw new Error(`could not turn the Google sign-in into a session: ${(await l.text()).slice(0,200)}`);return bt(await l.json())}function bt(e){let t=e,n={accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,email:t.user?.email};return j(n),n}async function ve(e={}){let t=e.provider??"google";if(t==="google")return Rn(e);let{verifier:n,challenge:r}=wt(),o=await new Promise((d,a)=>{let c=ht((w,m)=>{let k=new URL(w.url??"/","http://127.0.0.1"),u=k.searchParams.get("code"),M=k.searchParams.get("error_description")??k.searchParams.get("error");m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(u?Se("ok"):Se("failed",M??"No code came back.")),c.close(),u?d(u):a(new Error(M??"the browser came back without a code"))});c.listen(0,"127.0.0.1",()=>{let w=c.address(),k=`http://127.0.0.1:${typeof w=="object"&&w?w.port:0}/callback`,u=new URL(`${R}/auth/v1/authorize`);u.searchParams.set("provider",t),u.searchParams.set("redirect_to",k),u.searchParams.set("code_challenge",r),u.searchParams.set("code_challenge_method","s256"),u.searchParams.set("prompt","select_account"),process.stdout.write(`${u.toString()}
24
+ `),e.noBrowser?i("Open that in a browser, on any machine, and sign in."):(i("Opening that in your browser. If nothing opens, paste it into one."),yt(u.toString()))}),setTimeout(()=>{c.close(),a(new Error("timed out waiting for the browser"))},e.timeoutMs??3e5).unref()}),s=await fetch(`${R}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{apikey:F,"Content-Type":"application/json"},body:JSON.stringify({auth_code:o,code_verifier:n})});if(!s.ok)throw new Error(`could not exchange the code: ${(await s.text()).slice(0,200)}`);return bt(await s.json())}function Nn(e){return e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t])}var An,$n,kt,Pn,Ne=_(()=>{"use strict";T();z();E();An="https://accounts.google.com/o/oauth2/v2/auth",$n="https://oauth2.googleapis.com/token",kt="1064562458607-9fqmghjoqjr7d56b98agkvjt9vt26pdc.apps.googleusercontent.com",Pn="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"});import{createInterface as Dn}from"node:readline/promises";async function De(e){let t=Dn({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 Cn(){let e=await ge();if(!e.available)return(e.skip==="handoff-disabled"||e.skip==="server-disabled")&&i(y("The SnoutData app is running but is not set to hand out sign-ins.")),null;let t=e.who.email??"the signed-in account";if(i(""),i(`The SnoutData app is open here, signed in as ${A(t)}.`),i(y("It can create an access token for this terminal. Your sign-in itself is not handed over,")),i(y("and you can revoke the token later with `snoutdata tokens revoke`.")),!await De("Use it?"))return null;i("Asking the app. Approve it there.");let n=await st(e.config,process.argv.slice(2).join(" ").slice(0,60)||"snoutdata");if("declined"in n)return i(`The app did not create a token: ${n.reason}`),null;let r={accessToken:n.token};return j(r),i(`Signed in with "${n.name}".`),r}async function In(){if(!await De("Sign in with a browser?"))return null;try{let e=await ve({});return i(`Signed in${e.email?` as ${e.email}`:""}.`),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}catch(e){return i(`That did not finish: ${e instanceof Error?e.message:String(e)}`),null}}async function Mn(){if(!await De("Sign in by typing a code into a browser on another machine?"))return null;let e=await ye({name:he(),platform:process.platform});i(""),i(` Open ${A(e.verifyUrl)}`),i(` Type ${A(e.code)}`),i(""),i(y("The code is typed rather than in the link on purpose: it is what proves the person")),i(y("at the browser is the person at this terminal. Waiting\u2026"));let t=await ke(e.secret,{intervalMs:Math.max(1,e.interval)*1e3,expiresAt:e.expiresAt}),n={accessToken:t.token};return j(n),i(`Signed in${t.name?` with "${t.name}"`:""}.`),n}async function xt(){if(!Y())return null;let e=await Cn();if(e)return e;let t=await In();return t||Mn()}var St=_(()=>{"use strict";z();we();je();ee();Ne();E()});var Q={};nn(Q,{ANON_KEY:()=>F,ApiError:()=>N,FUNCTIONS:()=>vt,NotSignedIn:()=>q,SUPABASE_URL:()=>R,call:()=>f,connection:()=>C,exportStatus:()=>Z,listProjects:()=>D,listTeams:()=>Te,requestExport:()=>re,waitForReady:()=>oe,whoami:()=>X});function Un(){let e=fe();return e?`not signed in, and ${me(e)}. Set SNOUTDATA_ACCESS_TOKEN to a token from \`snoutdata tokens create\`.`:"not signed in: run `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN"}async function Bn(){let e=Ze();if(e||(e=await xt()),!e)throw new q;if(!et(e)||!e.refreshToken)return e.accessToken;let t=await fetch(`${R}/auth/v1/token?grant_type=refresh_token`,{method:"POST",headers:{apikey:F,"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refreshToken})});if(!t.ok)throw new q;let n=await t.json(),r={accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,email:e.email};return j(r),r.accessToken}async function f(e,t={},n="POST"){let r=await Bn(),o=n==="GET"&&typeof t=="object"&&t?`?${new URLSearchParams(t).toString()}`:"",s=await fetch(`${vt}/${e}${o}`,{method:n,headers:{Authorization:`Bearer ${r}`,apikey:F,"Content-Type":"application/json"},body:n==="GET"?void 0:JSON.stringify(t)}),d=await s.text(),a;try{a=d?JSON.parse(d):{}}catch{throw new N(s.status,d.slice(0,300)||s.statusText)}if(!s.ok){let c=typeof a=="object"&&a&&"error"in a?String(a.error):`${s.status} ${s.statusText}`;throw s.status===401?new q(c):new N(s.status,c)}return a}async function X(){return f("cloud-whoami")}async function D(){return f("cloud-project-list")}async function C(e){return f("cloud-project-connection",{ref:e})}async function Te(){return f("cloud-team-list")}async function re(e){return f("cloud-project-export",{ref:e})}async function Z(e){return f("cloud-project-export",{ref:e},"GET")}async function oe(e,t={}){let n=Date.now()+(t.timeoutMs??3e5);for(;;){let{projects:r}=await D(),o=r.find(s=>s.ref===e);if(!o)throw new N(404,`no project ${e}`);if(t.onTick?.(o.state),o.state==="ready")return o;if(Date.now()>=n)throw new N(504,`${e} is still ${o.state} after waiting`);await new Promise(s=>setTimeout(s,2e3))}}var R,F,vt,N,q,T=_(()=>{"use strict";z();ee();St();R=process.env.SNOUTDATA_SUPABASE_URL??"https://krlhuuvhhgkwfsutvxtb.supabase.co",F=process.env.SNOUTDATA_ANON_KEY??"sb_publishable_B0gbZinAncINGbDGOcP9rg_odcbriG3",vt=`${R}/functions/v1`,N=class extends Error{status;constructor(t,n){super(n),this.status=t}},q=class extends Error{constructor(t){super(t??Un())}}});var b=class extends Error{},rn=new Set(["name","region","ref","file","provider","expires","timeout","out","team","dir","days"]);function He(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,d]=sn(o);if(rn.has(s)){let a=d??e[++r];if(a===void 0)throw new b(`--${s} needs a value`);n[s]=a;continue}if(d!==void 0)throw new b(`--${s} does not take a value`);if(!on.has(s))throw new b(`unknown option --${s}`);n[s]=!0}return{command:t,flags:n,json:n.json===!0}}var on=new Set(["json","help","version","force","quiet","status","no-wait","no-browser","device","env","dry-run","out-of-order","allow-delete","history"]);function sn(e){let t=e.replace(/^--?/,""),n=t.indexOf("=");return n===-1?[t,void 0]:[t.slice(0,n),t.slice(n+1)]}function x(e,t){let n=e.flags[t];return typeof n=="string"?n:void 0}function U(e,t){return e.flags[t]===!0}function ce(e,t){let n=x(e,t);if(n===void 0)return;let r=Number(n);if(!Number.isInteger(r))throw new b(`--${t} must be a whole number, not "${n}"`);return r}T();te();ee();z();je();we();E();Ne();T();T();z();E();async function Tt(){let{projects:e,allowance:t}=await D();p({projects:e,allowance:t},()=>{if(e.length===0){i('No projects yet. `snoutdata projects create --name "my project"`.');return}process.stdout.write(`${W([["REF","NAME","STATE","REGION","LAST CONNECTION"],...e.map(n=>[n.ref,n.name,n.readOnly?A("read-only"):n.state==="ready"?n.state:A(n.state),n.region,H(n.lastConnectionAt)])])}
25
+ `)})}async function Ce(e){let t=await f("cloud-project-create",{name:e.name,region:e.region,teamId:e.teamId}),n=t.project.ref;i(`Created ${n}.`);let r=t.project;e.wait&&(i("Waiting for it to start\u2026"),r=await oe(n,{timeoutMs:e.timeoutMs,onTick:o=>i(y(` ${o}`))})),e.link&&de(e.link,{ref:n,name:r.name}),p({project:r,password:t.password,uri:`postgres://${r.user}:${encodeURIComponent(t.password)}@${r.host}:5432/${r.database}?sslmode=require`},()=>{process.stdout.write(`postgres://${r.user}:${encodeURIComponent(t.password)}@${r.host}:5432/${r.database}?sslmode=require
26
+ `),i(""),i(`Ready. ${A(n)} in ${r.region}.`),i("The password is stored for you: `snoutdata db url` prints this again.")})}async function At(e,t){let n=`cloud-project-${e}`,r=await f(n,{ref:t});p(r,()=>{i(r.changed?`${t}: ${e}d.`:`${t} was already ${e==="delete"?"deleted":`${e}d`}.`)})}async function $t(e){let t=await f("cloud-project-reset-password",{ref:e});p(t,()=>{process.stdout.write(`${t.password}
27
+ `),i(`New password for ${t.user}. It applies ${t.appliesIn}.`)})}async function Pt(){let{teams:e}=await Te();p({teams:e},()=>{if(e.length===0){i("You are not on any teams.");return}process.stdout.write(`${W([["NAME","ID","SHARE"],...e.map(t=>[t.name,t.id,t.mayShare?"yes":t.why??"no"])])}
28
+ `)})}async function Et(e){let{teams:t}=await Te(),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}T();E();async function Ot(e){let t=await f("cloud-token-create",{name:e.name,expiresInDays:e.expiresInDays});p(t,()=>{process.stdout.write(`${t.token}
29
+ `),i(""),i(`${A(t.name)} \u2014 ${t.expiresAt?`expires ${t.expiresAt.slice(0,10)}`:"does not expire"}.`),i("This is the only time it is shown: only its hash is stored."),i(y(" export SNOUTDATA_ACCESS_TOKEN=<that token>"))})}async function _t(){let{tokens:e}=await f("cloud-token-list");p({tokens:e},()=>{if(e.length===0){i("No access tokens. `snoutdata tokens create --name ci`.");return}process.stdout.write(`${W([["PREFIX","NAME","STATE","LAST USED","EXPIRES"],...e.map(t=>[t.current?A(t.prefix):t.prefix,t.name,t.revokedAt?"revoked":t.live?"live":"expired",H(t.lastUsedAt),t.expiresAt?t.expiresAt.slice(0,10):"never"])])}
30
+ `)})}async function jt(e){let t=e.startsWith("sdt_")?{prefix:e}:{id:e},n=await f("cloud-token-revoke",t);p(n,()=>{i(n.changed?`Revoked ${n.token.prefix} (${n.token.name}).`:`${n.token.prefix} was already revoked.`)})}import{spawn as Me}from"node:child_process";import{appendFileSync as qn,existsSync as It,readFileSync as Jn,writeFileSync as Ct}from"node:fs";import{join as Gn}from"node:path";import{open as Mt}from"node:fs/promises";function Rt(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 Nt(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 Dt(e){let t=e.split(`
31
+ `).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}}T();te();ee();T();E();async function Ut(e){try{let{projects:t}=await D(),n=t.find(r=>r.ref===e);n?.readOnly?$(`${e} is read-only: it is over the storage limit on your plan. Reading works; writing does not.`):n?.readOnlyPending&&$(`${e} is about to become read-only: it has grown past the storage limit on your plan.`)}catch{}}async function Ue(e){await Ut(e);let t=await C(e);p(t,()=>{process.stdout.write(`${t.uri}
32
+ `)})}async function Bt(e,t){if(t.length===0&&!Y()){let o=fe();g("usage",`db psql with no statements opens an interactive session, and ${o?me(o):"there is nobody to use it"}. Pass statements after --, or use \`snoutdata db url\` and your own client.`)}await Ut(e);let n=await C(e);n.wakesInstantly||i("This project is paused; the connection will wake it, which takes a few seconds.");let r=Me("psql",["--host",n.host,"--port",String(n.port),"--username",n.user,"--dbname",n.database,...t],{stdio:"inherit",env:{...process.env,PGPASSWORD:n.password,PGSSLMODE:"require"}});return new Promise((o,s)=>{r.on("error",d=>{if(d.code==="ENOENT"){s(new B("tool-missing","psql is not installed. `snoutdata db url` prints a connection string for any client."));return}s(new B("failed",String(d)))}),r.on("close",d=>o(d??0))})}function Lt(e,t,n="DATABASE_URL"){let r=Gn(e,".env"),o=`${n}=${t}`;if(!It(r))return Ct(r,`${o}
33
+ `),{path:r,replaced:!1};let s=Jn(r,"utf8"),d=new RegExp(`^${n}=.*$`,"m");return d.test(s)?(Ct(r,s.replace(d,o)),{path:r,replaced:!0}):(qn(r,s.endsWith(`
34
+ `)?`${o}
35
+ `:`
36
+ ${o}
37
+ `),{path:r,replaced:!1})}async function Ft(e,t={}){if(t.statusOnly){let{export:s}=await Z(e);return p({ref:e,export:s},()=>Ie(s)),0}let n=await re(e);if(!n.export.pending&&n.export.url&&!t.out)return p({ref:e,export:n.export},()=>Ie(n.export)),0;i("Taking a copy of the database. This runs on the server and can take a few minutes.");let r=await Wn(e,t.timeoutMs);if(r.error&&g("failed",`The export did not finish: ${r.error}`,{ref:e}),!t.out)return p({ref:e,export:r},()=>Ie(r)),0;r.url||g("failed","The copy was taken, but no download link could be signed. Run this again to get one.",{ref:e});let o=await Hn(r.url,t.out);return p({ref:e,path:t.out,bytes:o},()=>{i(`Saved ${I(o)} to ${t.out}.`),i(y("Restore it with: pg_restore --dbname <your database> "+t.out))}),0}async function Wn(e,t=30*6e4){let n=Date.now()+t;for(;;){let{export:r}=await Z(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 Hn(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 Mt(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 Ie(e){if(e.error){$(`The last export did not finish: ${e.error}`);return}if(e.pending){i("An export is running. Ask again in a minute, or run `snoutdata db export`, which waits for it.");return}if(!e.completedAt){i("This project has never been exported.");return}i(`A copy taken ${H(e.completedAt)}, ${I(e.bytes??0)}.`),e.url?(process.stdout.write(`${e.url}
38
+ `),e.urlExpiresAt&&i(y(`That link stops working ${H(e.urlExpiresAt)}.`))):i(y("The link has expired. Run the export again to sign a new one; the copy is kept."))}function I(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 qt(e,t){let n=t.file;n||g("usage","db restore needs --file, pointing at a dump. `snoutdata db export` writes one."),It(n)||g("usage",`no file at ${n}`,{file:n});let r=await Mt(n,"r"),o=new Uint8Array(512),s=await r.read(o,0,512,0);await r.close();let d=Rt(o.slice(0,s.bytesRead)),a=await C(e);a.wakesInstantly||i("This project is paused; the connection will wake it, which takes a few seconds.");let{projects:c}=await D(),l=c.find(M=>M.ref===e),w=await Kn(a);w===null&&g("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 m=Nt(d,{existingTables:w,readOnly:l?.readOnly===!0},{force:t.force});m.ok||g("conflict",m.reason,{ref:e,file:n,refusal:m.code}),i(`Restoring ${n} into ${e} with ${m.tool} (${m.format} format).`);let k=await zn(a,m.tool,n),u=Dt(k.stderr);return k.code!==0&&u.fatal.length===0&&u.total>0?(p({ref:e,file:n,ok:!0,tool:m.tool,format:m.format,ignoredErrors:u.harmless},()=>{i(`Restored into ${e}.`),i(`${u.harmless} error${u.harmless===1?"":"s"} above ${u.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&&g("failed",`${m.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:u.fatal}),p({ref:e,file:n,ok:!0,tool:m.tool,format:m.format},()=>i(`Restored into ${e}.`)),0)}async function Kn(e){return new Promise(t=>{let n=Me("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')"],{stdio:["ignore","pipe","pipe"],env:{...process.env,PGPASSWORD:e.password,PGSSLMODE:"require"}}),r="";n.stdout.on("data",o=>r+=String(o)),n.on("error",o=>{$(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 zn(e,t,n){let r=["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database],o=t==="psql"?[...r,"--no-psqlrc","-v","ON_ERROR_STOP=1","-f",n]:[...r,"--no-owner","--no-privileges",n];return new Promise(s=>{let d=Me(t,o,{stdio:["ignore","inherit","pipe"],env:{...process.env,PGPASSWORD:e.password,PGSSLMODE:"require"}}),a="";d.stderr?.on("data",c=>{let l=String(c);a+=l,process.stderr.write(l)}),d.on("error",c=>{$(c.code==="ENOENT"?`${t} is not installed, and this dump needs it.`:String(c)),s({code:127,stderr:a})}),d.on("close",c=>s({code:c??0,stderr:a}))})}T();E();te();import{spawn as Xn}from"node:child_process";import{createHash as Zn}from"node:crypto";import{existsSync as Qn,readdirSync as er,readFileSync as tr,statSync as nr}from"node:fs";import{isAbsolute as rr,join as Le,relative as or,resolve as sr}from"node:path";function Vn(e){return[...e].sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:0)}function Jt(e,t,n={}){let r=Vn(e),o=new Map(r.map(l=>[l.name,l])),s=[];for(let l of t){let w=o.get(l.name);if(!w){s.push({code:"missing",name:l.name,reason:`${l.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}w.checksum!==l.checksum&&s.push({code:"changed",name:l.name,reason:`${l.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 d=t.map(l=>l.name).sort((l,w)=>l<w?-1:l>w?1:0)[t.length-1],a=new Set(t.map(l=>l.name)),c=[];for(let l of r)if(!a.has(l.name)){if(d!==void 0&&l.name<d&&!n.outOfOrder){s.push({code:"out-of-order",name:l.name,reason:`${l.name} sorts before ${d}, 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}c.push(l)}return s.length>0?{ok:!1,problems:s}:{ok:!0,pending:c}}function Be(e){return!/^[\t ]*--[\t ]*snoutdata:no-transaction[\t ]*$/im.test(e)}function Wt(e){let t=or(process.cwd(),e);return t&&!t.startsWith("..")?t:e}var se="_snoutdata_migrations",ar=`create table if not exists ${se} (
39
+ name text primary key,
40
+ checksum text not null,
41
+ applied_at timestamptz not null default now()
42
+ );`;function ir(e){if(!Qn(e)||!nr(e).isDirectory())throw new Error(`no migrations folder at ${Wt(e)}. Put your .sql files there, or pass --dir.`);return er(e).filter(t=>t.endsWith(".sql")).map(t=>{let n=Le(e,t),r=tr(n,"utf8");return{name:t,path:n,sql:r,checksum:Zn("sha256").update(r,"utf8").digest("hex")}})}function Fe(e,t,n=[]){return new Promise(r=>{let o=Xn("psql",["--host",e.host,"--port",String(e.port),"--username",e.user,"--dbname",e.database,"--no-psqlrc","-v","ON_ERROR_STOP=1",...n],{stdio:["pipe","pipe","pipe"],env:{...process.env,PGPASSWORD:e.password,PGSSLMODE:"require"}}),s="",d="";o.stdout.on("data",a=>s+=String(a)),o.stderr.on("data",a=>d+=String(a)),o.on("error",a=>{r({code:127,out:"",err:a.code==="ENOENT"?"psql is not installed, and db push needs it to run your migrations. `snoutdata db url` prints a connection string for any client.":String(a)})}),o.on("close",a=>r({code:a??0,out:s,err:d})),o.stdin.end(t)})}async function cr(e){let t=await Fe(e,ar);if(t.code!==0)throw new Error(t.err.trim()||`could not create ${se}`);let n=await Fe(e,`select name || E'\\t' || checksum from ${se};`,["-tA"]);if(n.code!==0)throw new Error(n.err.trim()||`could not read ${se}`);return n.out.split(`
43
+ `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>{let o=r.indexOf(" ");return{name:r.slice(0,o),checksum:r.slice(o+1)}})}function Gt(e){return`'${e.replace(/'/g,"''")}'`}async function Ht(e,t={}){let n=await qe(e,t,r=>i(r));if(!n.ok){if(n.problems){let r=n.problems.map(o=>` ${o.reason}`).join(`
44
+ `);g("conflict",`Refused. This folder and ${e} do not agree:
45
+ ${r}`,{ref:e,problems:n.problems})}g("failed",`${n.failed} failed, and nothing after it was tried.
46
+ ${n.error??""}`.trimEnd(),{ref:e,failed:n.failed})}return p(n,()=>{if(n.wouldApply){i(`Would apply ${n.wouldApply.length} migration${n.wouldApply.length===1?"":"s"} to ${e}:`);for(let r of n.wouldApply)i(` ${r}`);return}if(n.upToDate){i(`${e} is up to date.`);return}i(`Applied ${n.applied.length} migration${n.applied.length===1?"":"s"} to ${e}.`)}),0}async function qe(e,t={},n=()=>{}){let r=sr(t.dir===void 0?Le(process.cwd(),"migrations"):rr(t.dir)?t.dir:Le(process.cwd(),t.dir)),o=[];function s(u){o.push(u),n(u)}let d=ir(r);if(d.length===0)return s(`No .sql files in ${Wt(r)}.`),{ref:e,directory:r,ok:!0,applied:[],upToDate:!0,notes:o};let a=await C(e);a.wakesInstantly||s("This project is paused; the connection will wake it, which takes a few seconds.");let c=await cr(a),l=Jt(d,c,{outOfOrder:t.outOfOrder});if(!l.ok)return{ref:e,directory:r,ok:!1,applied:[],problems:[...l.problems],notes:o};let w=new Map(d.map(u=>[u.name,u])),m=l.pending.map(u=>w.get(u.name));if(m.length===0)return s(`${e} is up to date: ${c.length} migration${c.length===1?"":"s"} already applied.`),{ref:e,directory:r,ok:!0,applied:[],upToDate:!0,notes:o};if(t.dryRun){for(let u of m)Be(u.sql)||s(`${u.name} would run outside a transaction.`);return{ref:e,directory:r,ok:!0,applied:[],wouldApply:m.map(u=>u.name),notes:o}}let k=[];for(let u of m){let M=`insert into ${se} (name, checksum) values (${Gt(u.name)}, ${Gt(u.checksum)});`,O=Be(u.sql);O||s(`${u.name} runs outside a transaction, so an interruption can leave it half applied.`);let K=O?`begin;
47
+ ${u.sql}
48
+ ${M}
49
+ commit;
50
+ `:`${u.sql}
51
+ ${M}
52
+ `,P=await Fe(a,K);if(P.code!==0)return O&&s("It ran inside a transaction, so nothing from it is in the database."),{ref:e,directory:r,ok:!1,applied:k,failed:u.name,error:P.err.trim(),notes:o};k.push(u.name),s(` applied ${u.name}`)}return{ref:e,directory:r,ok:!0,applied:k,notes:o}}T();E();var lr="2024-11-05";function S(e,t=[]){return{type:"object",properties:e,additionalProperties:!1,...t.length?{required:t}:{}}}var v={type:"string"},Ae=[{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:S({})},{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.",inputSchema:S({})},{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:S({name:v,region:v,teamId:v},["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:S({ref:v},["ref"])},{name:"pause_project",description:"Stop a project. Its data is kept and the next connection wakes it. A production project refuses this.",inputSchema:S({ref:v},["ref"])},{name:"resume_project",description:"Start a paused project without waiting for a connection to wake it.",inputSchema:S({ref:v},["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 psql on this machine.",inputSchema:S({ref:v,dir:v,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:S({ref:v,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:S({ref:v},["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:S({ref:v},["ref"])},{name:"reset_password",description:"Rotate the project's database password. THE OLD ONE STOPS WORKING IMMEDIATELY, including any DATABASE_URL already written into a file or a running process. Returns the new connection URL. Use it when a credential has leaked, not routinely.",inputSchema:S({ref:v},["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:S({})},{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:S({})},{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. It is as capable as this account, so hand it over deliberately. Optionally expires, as an ISO date.",inputSchema:S({name:v,expires:v},["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:S({id:v},["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:S({ref:v},["ref"])}];function dr(e){let t=new Set;return e.filter(n=>!t.has(n.name)&&t.add(n.name))}function ae(e,t){return{jsonrpc:"2.0",id:e,result:t}}function Je(e,t,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:n}}}function h(e,t,n=!1){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return ae(e,{content:[{type:"text",text:r}],...n?{isError:!0}:{}})}function J(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}async function Kt(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 ae(r,{protocolVersion:lr,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"snoutdata",version:n.version}});case"ping":return ae(r,{});case"tools/list":return ae(r,{tools:dr([...Ae,...n.borrowed??[]])});case"tools/call":return ur(r,s,t,n);default:return Je(r,-32601,`unknown method: ${o}`)}}async function ur(e,t,n,r){let o=typeof t.name=="string"?t.name:"",s=t.arguments??{};if(!(Ae.some(l=>l.name===o)||(r.borrowed?.some(l=>l.name===o)??!1)))return Je(e,-32602,`unknown tool: ${o}`);let a=["get_connection_url","pause_project","resume_project","delete_project","push_migrations","usage","export_status","start_export","reset_password"],c=J(s,"ref");if(a.includes(o)&&!c)return h(e,`${o} needs a project ref. Call list_projects to see them.`,!0);try{switch(o){case"whoami":return h(e,await n.whoami());case"list_projects":return h(e,await n.listProjects());case"create_project":{let l=J(s,"name");return l?h(e,await n.createProject({name:l,region:J(s,"region")??void 0,teamId:J(s,"teamId")??void 0})):h(e,"create_project needs a name.",!0)}case"get_connection_url":{let l=await n.connection(c);return h(e,{url:l.uri,state:l.state,wakesInstantly:l.wakesInstantly,warning:"This URL contains a live database password. Put it in an environment variable, not in a file that is committed."})}case"pause_project":return h(e,await n.setProjectState("pause",c));case"resume_project":return h(e,await n.setProjectState("resume",c));case"usage":{let l=typeof s.days=="number"?s.days:void 0;return h(e,await n.usage(c,l))}case"export_status":return h(e,await n.exportStatus(c));case"start_export":return h(e,await n.requestExport(c));case"reset_password":return h(e,await n.resetPassword(c));case"list_teams":return h(e,await n.listTeams());case"list_tokens":return h(e,await n.listTokens());case"create_token":{let l=J(s,"name");return l?h(e,await n.createToken(l,J(s,"expires")??void 0)):h(e,"create_token needs a name, so somebody can tell later what it was for.",!0)}case"revoke_token":{let l=J(s,"id");return l?h(e,await n.revokeToken(l)):h(e,"revoke_token needs the id of a token. list_tokens has them.",!0)}case"push_migrations":return h(e,await n.pushMigrations(c,{dir:J(s,"dir")??void 0,dryRun:s.dryRun===!0}));case"delete_project":return r.allowDelete?h(e,await n.setProjectState("delete",c)):h(e,"delete_project is off. The person running this server started it without --allow-delete, so deleting a database is theirs to do. Tell them that is what you wanted.",!0);default:return r.borrowed?.some(l=>l.name===o)?n.callBorrowed?ae(e,await n.callBorrowed(o,s)):h(e,`${o} needs the SnoutData app, which is no longer answering.`,!0):Je(e,-32602,`unknown tool: ${o}`)}}catch(l){return h(e,l instanceof Error?l.message:String(l),!0)}}function zt(e){let t=e.split(`
53
+ `),n=t.pop()??"";return{messages:t.map(r=>r.trim()).filter(r=>r.length>0),rest:n}}we();function pr(){return{whoami:()=>X(),listProjects:()=>D(),createProject:async e=>{let t=await f("cloud-project-create",{name:e.name,...e.region?{region:e.region}:{},...e.teamId?{teamId:e.teamId}:{}});try{return await oe(t.project.ref)}catch{return{...t.project,ready:!1,note:`${t.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:(e,t)=>f("cloud-project-usage",{ref:e,...t?{days:t}:{}}),exportStatus:e=>Z(e),requestExport:e=>re(e),resetPassword:e=>f("cloud-project-reset-password",{ref:e}),listTeams:()=>f("cloud-team-list",{}),listTokens:()=>f("cloud-token-list",{}),createToken:(e,t)=>f("cloud-token-create",{name:e,...t?{expires:t}:{}}),revokeToken:e=>f("cloud-token-revoke",{id:e}),setProjectState:(e,t)=>f(`cloud-project-${e}`,{ref:t}),connection:e=>C(e),pushMigrations:(e,t)=>qe(e,{dir:t.dir,dryRun:t.dryRun})}}var Yt="app_";async function mr(){if(process.env.SNOUTDATA_NO_DESKTOP)return{tools:[],config:null};let e=await ge();if(!e.available)return{tools:[],config:null};let t=e.config;try{return{tools:(await at(t)).map(o=>({name:`${Yt}${o.name}`,description:`[SnoutData app, on this machine] ${o.description??o.name}`,inputSchema:o.inputSchema??{type:"object",properties:{}}})),config:t}}catch{return{tools:[],config:null}}}async function Vt(e){ne(!0);let{tools:t,config:n}=await mr(),r=pr();n&&(r.callBorrowed=(c,l)=>it(n,c.slice(Yt.length),l));let o={...e,borrowed:t};$(t.length>0?`snoutdata mcp: ${Ae.length} cloud tools, and ${t.length} borrowed from the SnoutData app on this machine.`:"snoutdata mcp: cloud tools only. The SnoutData app is not answering here, so its database tools are not on this endpoint.");let s="";process.stdin.setEncoding("utf8");try{let c=await X();$(`snoutdata mcp: signed in as ${c.email??"this account"}.`)}catch(c){return $(`snoutdata mcp: ${c instanceof Error?c.message:String(c)}`),$("Sign in with `snoutdata login`, or set SNOUTDATA_ACCESS_TOKEN."),3}$(`snoutdata mcp: ready${e.allowDelete?" (delete_project is ON)":""}. Speaking MCP on stdin/stdout; stop it with Ctrl-C.`);let d=new Set;function a(c){d.add(c),c.finally(()=>d.delete(c))}return new Promise(c=>{process.stdin.on("data",l=>{let w=zt(s+l);s=w.rest;for(let m of w.messages)a(fr(m,r,o))}),process.stdin.on("end",()=>{(async()=>{for(;d.size>0;)await Promise.allSettled([...d]);c(0)})()}),process.stdin.on("error",()=>c(1))})}async function fr(e,t,n){let r;try{r=JSON.parse(e)}catch{$(`snoutdata mcp: ignoring a line that is not JSON: ${e.slice(0,120)}`);return}try{let o=await Kt(r,t,n);o&&process.stdout.write(`${JSON.stringify(o)}
54
+ `)}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)}})}
55
+ `)}}T();E();function gr(e){return e>=1?"over":e>=.8?"near":"ok"}function Xt(e,t){let n=null,r=null,o=0,s=0;for(let a of e)o+=Number.isFinite(a.computeSeconds)?a.computeSeconds:0,s+=Number.isFinite(a.connections)?a.connections:0,!(a.dbBytes===null||!Number.isFinite(a.dbBytes))&&(r=r===null?a.dbBytes:Math.max(r,a.dbBytes),(!n||a.day>=n.day)&&(n={day:a.day,dbBytes:a.dbBytes,repoBytes:a.repoBytes}));let d=n&&t&&t.maxStorageBytes>0?{limitBytes:t.maxStorageBytes,usedBytes:n.dbBytes,fraction:n.dbBytes/t.maxStorageBytes,state:gr(n.dbBytes/t.maxStorageBytes)}:null;return{days:e.length,latest:n,peakDbBytes:r,computeSeconds:o,connections:s,storage:d}}function Ge(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 Zt(e,t={}){let n=await f("cloud-project-usage",{ref:e,...t.days?{days:t.days}:{}}),r=Xt(n.days,n.limit);return p({...n,summary:r},()=>{if(i(A(`${n.name} (${n.ref})`)),!r.latest)i("Nothing measured yet. The host samples every fifteen minutes.");else if(r.storage){let o=Math.round(r.storage.fraction*100),s=`${I(r.storage.usedBytes)} of ${I(r.storage.limitBytes)} on ${n.limit?.tier}`;i(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 i(`${I(r.latest.dbBytes)} as of ${r.latest.day}.`);n.readOnly&&r.storage?.state!=="over"&&i("This project is currently read-only."),i(`Over ${r.days} day${r.days===1?"":"s"}: ${Ge(r.computeSeconds)} of compute, ${r.connections} connection${r.connections===1?"":"s"}.`),r.peakDbBytes!==null&&r.latest&&r.peakDbBytes>r.latest.dbBytes&&i(y(`Peak in that window was ${I(r.peakDbBytes)}.`)),t.history&&n.days.length>0&&(i(""),i(W([["DAY","SIZE","BACKUPS","COMPUTE","CONNS"],...n.days.map(o=>[o.day,o.dbBytes===null?"-":I(o.dbBytes),o.repoBytes===null?"-":I(o.repoBytes),Ge(o.computeSeconds),String(o.connections)])])),i(y("A dash is a day nothing measured it, which is what a paused project looks like.")))}),0}var ie="0.1.0",Qt=[{name:"init",summary:"Create or link a project and write a DATABASE_URL",flags:["--name","--region","--env","--ref"]},{name:"login",summary:"Sign in through a browser, or with --device by typing a code into one anywhere",flags:["--provider","--no-browser","--device","--timeout"]},{name:"logout",summary:"Forget the stored session",flags:[]},{name:"whoami",summary:"Who this credential belongs to",flags:[]},{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"]},{name:"tokens revoke",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",flags:["--name","--region","--team","--no-wait","--timeout"]},{name:"projects pause",summary:"Stop a project",flags:["--ref"]},{name:"projects resume",summary:"Start a paused project",flags:["--ref"]},{name:"projects delete",summary:"Delete a project",flags:["--ref"]},{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:"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 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",flags:["--file","--force"]},{name:"mcp",summary:"Serve these operations as tools over stdio",flags:["--allow-delete"]}],en=`snoutdata ${ie} \u2014 hosted Postgres, from a terminal or an agent
56
+
57
+ snoutdata init [--name X] [--env] a database for this folder, linked, ready to use
58
+ snoutdata login [--provider github] sign in through a browser
59
+ snoutdata login --device sign in by typing a code into a browser anywhere
60
+ snoutdata login --no-browser print the URL instead of opening one
61
+ snoutdata logout
62
+ snoutdata whoami
63
+
64
+ snoutdata tokens create --name ci [--expires DAYS] a credential for CI, shown once
65
+ snoutdata tokens list
66
+ snoutdata tokens revoke <id|sdt_prefix>
67
+
68
+ snoutdata projects list
69
+ snoutdata projects create --name X [--region R] [--no-wait]
70
+ snoutdata projects pause|resume|delete [--ref R]
71
+ snoutdata link --ref R write .snoutdata/project.json here
72
+
73
+ snoutdata usage [--ref R] [--days 30] [--history] size, compute, and the plan's limit
74
+
75
+ snoutdata teams teams you can share a project with
76
+ snoutdata db url [--ref R] print a connection string
77
+ snoutdata db psql [--ref R] [-- ...] open psql, with no password typed
78
+ snoutdata db reset-password [--ref R]
79
+ snoutdata db export [--ref R] [--out FILE] take a copy, and download it
80
+ snoutdata db export --status [--ref R] what the last copy is doing
81
+ snoutdata db push [--dir migrations] [--dry-run] run the .sql files, once each
82
+ snoutdata db restore --file DUMP [--force] put a dump into this project
83
+
84
+ snoutdata mcp [--allow-delete] serve these operations to an agent, over stdio
85
+ (plus the SnoutData app's own tools, when it is
86
+ running here; SNOUTDATA_NO_DESKTOP opts out)
87
+
88
+ Every command takes --json, --quiet and --help, and anything that waits takes --timeout
89
+ SECONDS. A failure in --json mode is {"ok":false,"code","error"} on stdout, and the exit
90
+ code says the same thing more coarsely: 2 the command was wrong, 3 the credential, 4 not
91
+ ready yet, 5 forbidden, 6 not found, 7 conflict, 8 quota, 9 network, 10 timed out.
92
+
93
+ With no credential and a person present, sign-in is offered: the SnoutData app if it is
94
+ running here, then a pairing code. With no person (not a terminal, --json, CI, or
95
+ SNOUTDATA_NO_INTERACTIVE) nothing is asked and it exits 3 at once.
96
+
97
+ A project comes from --ref, then SNOUTDATA_PROJECT, then
98
+ .snoutdata/project.json in this folder or a parent. A token comes from
99
+ SNOUTDATA_ACCESS_TOKEN, then ~/.snoutdata/auth.json. The session that login writes lasts
100
+ an hour, so CI wants "tokens create", which does not expire.
101
+ `;async function hr(e){let[t,n,...r]=e.command;if(U(e,"version")||t==="version")return p({version:ie},()=>process.stdout.write(`${ie}
102
+ `)),0;if(U(e,"help")&&t&&t!=="help"){let a=Qt.filter(c=>c.name===t||c.name.startsWith(`${t} `));if(a.length>0)return p({commands:a},()=>{for(let c of a){let l=c.flags.length>0?` ${c.flags.join(" ")}`:"";process.stdout.write(` snoutdata ${c.name}${l}
103
+ ${c.summary}
104
+ `)}process.stdout.write(`
105
+ Every command also takes --json, --quiet and --help.
106
+ `)}),0}let o=U(e,"help")||t==="help";if(o||!t)return p({version:ie,usage:en.trim(),commands:Qt},()=>process.stdout.write(en)),o?0:L.usage;let s=()=>{let a=ce(e,"timeout");if(a!==void 0){if(!(a>0))throw new b("--timeout is a number of seconds greater than zero");return a*1e3}},d=()=>{let a=ue({flag:x(e,"ref")});if(!a)throw new b("no project: pass --ref, set SNOUTDATA_PROJECT, or run `snoutdata link --ref <ref>`");return a};switch(t){case"login":{if(U(e,"device")){let c=await ye({name:he(),platform:process.platform});p({verifyUrl:c.verifyUrl,code:c.code,expiresAt:c.expiresAt},()=>{i(""),i(` Open ${c.verifyUrl}`),i(` Type ${c.code}`),i(""),i(y("Waiting for that to be approved\u2026"))});let l=await ke(c.secret,{intervalMs:Math.max(1,c.interval)*1e3,expiresAt:c.expiresAt});return j({accessToken:l.token}),p({ok:!0,name:l.name??null},()=>i("Signed in.")),0}let a=await ve({provider:x(e,"provider"),noBrowser:U(e,"no-browser")||!Y(),timeoutMs:s()});return p({email:a.email??null},()=>i(`Signed in${a.email?` as ${a.email}`:""}.`)),0}case"logout":{Qe();let a=!!process.env.SNOUTDATA_ACCESS_TOKEN;return p({ok:!0,environmentTokenStillSet:a},()=>{i("Signed out."),a&&(i("SNOUTDATA_ACCESS_TOKEN is still set in this shell, so commands will keep working."),i(y(" unset SNOUTDATA_ACCESS_TOKEN")))}),0}case"whoami":{let a=await X();return p(a,()=>{process.stdout.write(`${a.email??a.id}
107
+ `),a.token&&i(`via access token ${a.token.prefix} (${a.token.name}).`)}),0}case"tokens":switch(n){case void 0:case"list":return await _t(),0;case"create":{let a=x(e,"name")??r[0];if(!a)throw new b("tokens create needs --name (what is it for, and where does it live)");return await Ot({name:a,expiresInDays:ce(e,"expires")}),0}case"revoke":{let a=r[0];if(!a)throw new b("tokens revoke needs the token's id or its sdt_ prefix");return await jt(a),0}default:throw new b(`unknown command: tokens ${n}`)}case"projects":switch(n){case void 0:case"list":return await Tt(),0;case"create":{let a=x(e,"name")??r[0];if(!a)throw new b("projects create needs --name");let c=x(e,"team");return await Ce({teamId:c?await Et(c):void 0,name:a,region:x(e,"region"),wait:!U(e,"no-wait"),timeoutMs:s(),link:void 0}),0}case"pause":case"resume":case"delete":return await At(n,x(e,"ref")??r[0]??d()),0;default:throw new b(`unknown command: projects ${n}`)}case"teams":return await Pt(),0;case"link":{let a=x(e,"ref")??n;if(!a)throw new b("link needs --ref");let c=de(process.cwd(),{ref:a});return p({ref:a,path:c},()=>i(`Linked ${a} (${c}).`)),0}case"db":switch(n){case"url":return await Ue(d()),0;case"psql":return Bt(d(),r);case"reset-password":return await $t(d()),0;case"push":return Ht(d(),{dir:x(e,"dir"),dryRun:!!e.flags["dry-run"],outOfOrder:!!e.flags["out-of-order"]});case"restore":return qt(d(),{file:x(e,"file"),force:!!e.flags.force});case"export":return Ft(d(),{timeoutMs:s(),out:x(e,"out"),statusOnly:!!e.flags.status});default:throw new b(n?`unknown command: db ${n}`:"db needs an action: url, psql, reset-password, export, push, restore")}case"usage":return Zt(d(),{days:ce(e,"days"),history:!!e.flags.history});case"mcp":return Vt({version:ie,allowDelete:!!e.flags["allow-delete"]});case"init":return wr(e);default:throw new b(`unknown command: ${t}`)}}async function wr(e){let t=ue({flag:x(e,"ref")});if(t)return i(`This folder is already linked to ${t}.`),await Ue(t),0;let n=x(e,"name")??yr(process.cwd());i(`Creating a project called "${n}"\u2026`),await Ce({name:n,region:x(e,"region"),wait:!0,link:process.cwd()});let r=ue({cwd:process.cwd()});if(r&&U(e,"env")){let{connection:o}=await Promise.resolve().then(()=>(T(),Q)),s=await o(r),d=Lt(process.cwd(),s.uri);i(`${d.replaced?"Updated":"Wrote"} DATABASE_URL in ${d.path}.`)}return 0}function yr(e){let t=e.split(/[\\/]/).filter(Boolean);return t[t.length-1]??"project"}function kr(e){if(e instanceof B)return G(e.code,e.message,e.details),e.exitCode;if(e instanceof b)return G("usage",e.message),L.usage;if(e instanceof q)return G("not-signed-in",e.message),L["not-signed-in"];if(e instanceof N){let n=lt(e.status);return G(n,e.message,{status:e.status}),L[n]}let t=dt(e);return G(t,e instanceof Error?e.message:String(e)),L[t]}function We(e){process.exitCode=e,setTimeout(()=>process.exit(e),2e3).unref()}function br(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}async function xr(){ne(br(process.argv.slice(2)));let e;try{e=He(process.argv.slice(2))}catch(t){G("usage",String(t instanceof Error?t.message:t)),We(L.usage);return}ne(e.json),mt(e.flags.quiet===!0),nt(pe({isTty:!!process.stdin.isTTY,json:e.json,env:process.env}));try{We(await hr(e))}catch(t){We(kr(t))}}xr();
package/package.json CHANGED
@@ -1,22 +1,48 @@
1
1
  {
2
- "name": "snoutdata",
3
- "version": "0.0.1",
4
- "description": "AI data tool (early development).",
5
- "type": "module",
6
- "main": "index.js",
7
- "exports": "./index.js",
8
- "scripts": {
9
- "test": "node --test"
10
- },
11
- "keywords": [
12
- "ai",
13
- "data"
14
- ],
15
- "author": "Joel Oliver <joel2oliver@gmail.com>",
16
- "license": "MIT",
17
- "files": [
18
- "index.js",
19
- "README.md",
20
- "LICENSE"
21
- ]
2
+ "name": "snoutdata",
3
+ "version": "0.1.1",
4
+ "description": "Hosted Postgres from a terminal or an agent. Create a database, get a DATABASE_URL, run migrations, and serve the same operations to an AI agent over MCP.",
5
+ "license": "UNLICENSED",
6
+ "author": "SnoutData",
7
+ "homepage": "https://snoutdata.com",
8
+ "bugs": {
9
+ "url": "https://snoutdata.com/contact"
10
+ },
11
+ "keywords": [
12
+ "postgres",
13
+ "postgresql",
14
+ "database",
15
+ "hosted-database",
16
+ "serverless-postgres",
17
+ "cli",
18
+ "mcp",
19
+ "model-context-protocol",
20
+ "agent",
21
+ "ai-agent",
22
+ "migrations",
23
+ "devops",
24
+ "snoutdata"
25
+ ],
26
+ "type": "module",
27
+ "bin": {
28
+ "snoutdata": "dist/snoutdata.mjs"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.json && node build.mjs",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "test": "tsc -p tsconfig.json && node --test \"out/**/*.test.js\"",
41
+ "prepublishOnly": "npm run build"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^22.20.1",
45
+ "esbuild": "^0.24.0",
46
+ "typescript": "^5.6.0"
47
+ }
22
48
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Joel Oliver
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/index.js DELETED
@@ -1,6 +0,0 @@
1
- // snoutdata — AI data tool (early development).
2
- // This is a placeholder entry point; real API to follow.
3
-
4
- export const version = "0.0.1";
5
-
6
- export default { version };