palbase 0.49.2 → 0.49.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.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{6KDYTSBW.js → 2PXD67HF.js} +2 -2
- package/dist/chunks/{F7YGHYPE.js → 5SR25JV2.js} +1 -1
- package/dist/chunks/{TJXEAKZH.js → A4WOA3WG.js} +1 -1
- package/dist/chunks/{MDUU6F7S.js → AMYDFDFA.js} +2 -2
- package/dist/chunks/{XWHDZWXY.js → EDTU3Q6F.js} +1 -1
- package/dist/chunks/{BVYPUWPA.js → ESCVGUOF.js} +2 -2
- package/dist/chunks/{KKIBIULO.js → FQASFH4O.js} +2 -2
- package/dist/chunks/{ATMJMBCH.js → FXORGUPY.js} +2 -2
- package/dist/chunks/{3FGMN6RY.js → GJAVN2XF.js} +2 -2
- package/dist/chunks/{2UAWAVQQ.js → H3PO5HOB.js} +2 -2
- package/dist/chunks/{7ZI7MROG.js → HGHEX7IF.js} +2 -2
- package/dist/chunks/{7K4TPV5K.js → IIEF4Z7A.js} +2 -2
- package/dist/chunks/{6A2VBW6K.js → JMXJM2YS.js} +1 -1
- package/dist/chunks/{6KMUQIWT.js → LFX2KQIC.js} +1 -1
- package/dist/chunks/{WP6DXNB4.js → LGDEO2AN.js} +2 -2
- package/dist/chunks/{PNLFGVB5.js → LH4SFIAD.js} +2 -2
- package/dist/chunks/{ITYU3ULX.js → MJSDYCD3.js} +2 -2
- package/dist/chunks/{FTMPWUYS.js → NBJNGISZ.js} +1 -1
- package/dist/chunks/{YZW6CRBE.js → O76G47YX.js} +2 -2
- package/dist/chunks/{MHOFOVSN.js → UGK2IRVE.js} +1 -1
- package/dist/chunks/{XHKKFLT7.js → VASNHFJS.js} +2 -2
- package/dist/chunks/{ZHCIXVJU.js → WFFKR4UU.js} +2 -2
- package/dist/chunks/{UIJMULI2.js → YNG6I7WU.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/internal/src/modules/auth.d.ts +9 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.49.
|
|
2
|
+
/*! palbase 0.49.3 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Ov}from"node:util";var Yw=Symbol.for("palbase.data"),Xw=globalThis,xd=Xw[Yw]??=new WeakSet;function Zw(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Za(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||xd.has(n)||Zw(n))){xd.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Qw="X-PoW-Challenge-ID",ev="X-PoW-Nonce";function Nd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function tv(e){return 8*2**e}var ps;async function nv(){if(ps)return ps;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return ps=a=>new Uint8Array(s("sha256").update(a).digest()),ps}catch{}let t=new TextEncoder;return ps=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),ps}function sv(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var av=4096,iv=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function qd(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await nv(),s=tv(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<s;i++){if(i%av===0&&i>0){if(await iv(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let r=n(e.prefix+i),o=r instanceof Uint8Array?r:await r;if(sv(o)>=e.difficulty)return{[Qw]:e.id,[ev]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var E=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function c(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new E({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var rv=new Set(["apikey","authorization"]),ov=64*1024;function Hr(e){let t=Qa(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(i,r)=>{let o=pv(t,i),l=new Headers;for(let[y,w]of Object.entries(i.headers??{}))w!=null&&!rv.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(r))l.set(y,w);await uv(i,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:i.method,headers:l,redirect:"manual",signal:i.signal,...i.keepalive?{keepalive:!0}:{}};i.body&&i.body.value!==void 0&&(l.set("content-type",i.body.contentType),d.body=cv(i.body.kind,i.body.value),us(d.body)||(d.duplex="half"));let p;try{p=i.onUploadProgress&&e.xmlHttpRequest?await lv(e.xmlHttpRequest,i.op,o,d,i.onUploadProgress):await n(o,d)}catch(y){throw i.signal?.aborted||y instanceof E?y:new E({op:i.op,status:0,code:"network_error",message:`${i.op}: the request did not reach ${t.origin}`,cause:y})}let u=i.answers[p.status]??(i.ownResponse&&p.status>=200&&p.status<300?"raw":void 0);if(u===void 0)throw p.status>=200&&p.status<300?(await p.body?.cancel(),new E({op:i.op,status:p.status,code:"undeclared_answer",message:`${i.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await mv(i.op,p);let g;switch(u){case"json":try{g=Za(await p.json())}catch(y){throw new E({op:i.op,status:p.status,code:"invalid_json",message:`${i.op}: the answer is not JSON`,cause:y})}break;case"raw":g=p;break;default:await p.body?.cancel(),g=void 0}return{status:p.status,data:g,headers:p.headers}};return{async send(i){try{return await a(i,{})}catch(r){let o=s&&r instanceof E&&r.status===403?Nd(r.body):null,l=i.body?.value;if(!o||i.body?.kind==="raw"&&!us(l))throw r;let d=r,p;try{p=await qd(o,{signal:i.signal})}catch(u){throw i.signal?.aborted?u:new E({op:i.op,status:403,code:"pow_unsolved",message:`${i.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(i,p)}}}}function lv(e,t,n,s,a){return new Promise((i,r)=>{let o=s.signal;if(o?.aborted)return r(o.reason);let l=new e,d=()=>l.abort();o?.addEventListener("abort",d,{once:!0});let p=u=>{o?.removeEventListener("abort",d),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,g)=>l.setRequestHeader(g,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){r(new E({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return r(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;i(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:dv(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>r(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>r(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function dv(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function Qa(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function pv(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new E({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+hv(t.query),e);if(n.origin!==e.origin)throw new E({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function uv(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(r=>r.includes("userJWT"))?await t.accessToken?.():void 0,a=r=>{switch(r){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},i=e.auth.filter(r=>r.every(a)).reduce((r,o)=>r===void 0||o.length>r.length?o:r,void 0);if(!i)throw new E({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(r=>r.length===0?"nothing":r.join(" + ")).join(" | ")}`});for(let r of i)r==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(r==="SecretKeyAuth"||r==="AdminAuth"||r==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):r==="SecretKeyAuth"||r==="AdminAuth"?n.set("apikey",t.secretKey):r==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function cv(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))Yr(n,s,a);return n}case"raw":return t}}function us(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function hv(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))Yr(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function Yr(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)Yr(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function mv(e,t){let n=await gv(t,ov).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=fv(s)?s:void 0,i=Number(t.headers.get("retry-after")),r=t.status>=300&&t.status<400;return new E({op:e,status:t.status,code:a?.error??(r?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(r?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(i)&&i>0?i:void 0),body:s})}async function gv(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:o,value:l}=await n.read();if(o)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let i=new Uint8Array(Math.min(a,t)),r=0;for(let o of s){let l=Math.min(o.byteLength,i.byteLength-r);if(i.set(o.subarray(0,l),r),r+=l,r>=i.byteLength)break}return new TextDecoder().decode(i)}function fv(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var ei={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var f=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function m(e,t){return new f("usage",e,{hint:t,exitCode:2})}var ti=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
|
|
4
4
|
`):n()}line(t=""){this.io.stdout(`${q(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${q(t)}
|
|
@@ -9,7 +9,7 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let r;try{r=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new f("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
10
10
|
`),r.status!==503||!s||i>=Ev||!Tv.has(await Qr(r)??""))return r;await r.body?.cancel();let o=Number(r.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(o)&&o>0?Math.min(o,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),i=await this.send(t,n,s,a.value);if(i.status===401&&a.renewable){let r=await this.renew(await this.currentSession());i=await this.send(t,n,s,r.access_token)}return{res:i,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let i=await s.text(),r=i===""?void 0:Cv(i);if(s.ok)return r;let o=r??{};throw s.status===401?o.error==="token_not_for_machines"?tp(new URL(this.cloud.studioApi).host):a?cs():this.tokenRefused("Studio"):new E({op:`${t} ${n}`,status:s.status,code:o.error??`http_${s.status}`,message:o.error_description??`Studio answered ${s.status}`,requestId:o.request_id??s.headers.get("x-request-id")??void 0,body:r})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new f("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await Xd(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let i=`${this.cloud.studioApi}${Rv}${n}`;this.debug&&this.io.stderr(`> ${t} ${i}
|
|
11
11
|
`);try{let r=await this.io.fetch(i,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
12
|
-
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function tp(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Qr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Cv(e){try{return JSON.parse(e)}catch{return e}}var np={version:"0.49.
|
|
12
|
+
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function tp(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Qr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Cv(e){try{return JSON.parse(e)}catch{return e}}var np={version:"0.49.3"};var ri=np.version;async function op(e,t,n){let s=new Map(n.map(r=>[r.name,r])),a=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:o}=Mv(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${ri}
|
|
13
13
|
`),0):(t.stdout(rp(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let S=e[o+1],$=S===void 0?void 0:s.get(S);if(S!==void 0&&!$)throw sp(S,n);return t.stdout($?ip($):rp(n)),0}let l=s.get(r);if(!l)throw sp(r,n);let d=[...e.slice(0,o),...e.slice(o+1)];if(d.includes("--help")||d.includes("-h"))return t.stdout(ip(l)),0;let{flags:p,positionals:u}=Iv(l,d),g=l.args??{min:0,max:0};if(u.length<g.min)throw m(`${l.name} needs ${g.min===1?"an argument":`${g.min} arguments`}`,to(l));if(u.length>g.max)throw m(`${l.name} takes ${g.max===0?"no argument":`at most ${g.max}`}: ${JSON.stringify(u.slice(g.max))} is left over`,to(l));let y={project:p.project,env:p.env,json:p.json===!0,nonInteractive:p["non-interactive"]===!0,yes:p.yes===!0,debug:p.debug===!0},w=Wd(t.env),_=new ni(Vd(t.configDir,w)),P={io:t,state:_,out:new ti(t,y.json),global:y,args:u,flags:p,interactive:t.interactive&&!y.nonInteractive,cloud:w,studio:new ii(t,w,_,y.debug)};return await l.run(P)??0}catch(r){return Lv(r,t,a,i)}}function Mv(e){let t=new Set;for(let[n,s]of Object.entries(ei))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function Iv(e,t){let n={...ei,...e.flags??{}},s={};for(let[a,i]of Object.entries(n))s[a]={type:i.type,...i.short?{short:i.short}:{},...i.multiple?{multiple:!0}:{}};try{let{values:a,positionals:i}=Ov({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:i}}catch(a){throw m(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function Lv(e,t,n,s){let a="error",i,r,o=1,l;return e instanceof f?(a=e.code,i=e.message,r=e.hint,o=e.exitCode):e instanceof E?(a=e.code,i=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(i=`${e.op} refused PALBASE_TOKEN: ${e.message}`,r="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):i=e instanceof Error?e.message:String(e),n&&e instanceof f&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:i,...r?{hint:r}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${q(i)}${l?` (request ${q(l)})`:""}
|
|
15
15
|
`),r&&t.stderr(` ${q(r)}
|
|
@@ -27,7 +27,7 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
27
27
|
`)?"":`
|
|
28
28
|
`}# palbase env:pull: your own key
|
|
29
29
|
/${i}
|
|
30
|
-
`),"added"}var qp={name:"run",summary:"run a command with the environment's address and your own key in its environment, nothing written to disk",usage:"[--secrets development|production] -- <command> [args\u2026]",details:["palbase run -- bun dev, palbase run -- npm test: the app reads the project's secrets at boot (PALBASE_SECRETS)."],args:{min:1,max:1e3},flags:{secrets:Ti},scope:"environment",async run(e){let t=await b(e),n=Ai(e);(t.env_slug===Be||n==="production")&&await v(e,t,`run ${e.args[0]} with a key of ${t.env_slug}`,Ri(t,n));let s=await Pi(e,t);e.out.note(`${N(t)}: ${e.args.join(" ")}`);let a=await e.io.run(e.args[0],e.args.slice(1),{cwd:e.io.cwd,env:{PALBASE_URL:s.url,PALBASE_PROJECT_ID:s.projectId,PALBASE_SECRET_KEY:s.key.key,PALBASE_SECRETS:n},inherit:!0});if(a.code===127)throw new f("not_found",`${e.args[0]}: no such program`);return a.code}};var p0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,Kp=20;async function u0(e,t,n,s){if(n.length===0)return{};let a=n.map(r=>({email:`${r.toLowerCase()}.${s}@test.invalid`,password:Gp(18).toString("base64url")})),i=await h(e,t,"POST","/admin/test-users",{users:a,with_tokens:!0},j()).catch(r=>{throw r instanceof E&&r.code==="token_out_of_scope"&&Jt(e.io)?new f("token_out_of_scope",`PALBASE_TOKEN, an environment's token, may not make test users: its scopes do not name auth:test-users (${r.message})`,{hint:"a token's scopes are fixed when it is minted, and a person's yes does not widen them: mint one with --scope auth:test-users (palbase env:tokens:create, an admin)"}):r});if(i.users.length!==n.length)throw new f("unexpected_answer",`auth made ${i.users.length} test users of the ${n.length} asked for`);return Object.fromEntries(n.map((r,o)=>{let l=i.users[o];return[r,{id:l.user_id,email:l.email??a[o].email,password:a[o].password,...l.access_token?{accessToken:l.access_token}:{}}]}))}async function c0(e,t,n){let s=[];for(let a of Object.values(n))try{await h(e,t,"DELETE",`/admin/test-users/${k(a.id)}`)}catch(i){i.status!==404&&s.push(a.id)}return s}async function h0(e,t,n){if(e.out.note(`${t}'s test command, as the platform holds it: ${m0(n)}`),e.global.yes)return;if(!e.interactive)throw new f("confirmation_needed",`palbase test would run ${t}'s test command on this computer \u2014 a setting on the platform, not code of this checkout`,{hint:"read it above, then confirm with -y"});let s=(await e.io.prompt("Run it on this computer? [y/N] ")).trim().toLowerCase();if(s!=="y"&&s!=="yes")throw new f("cancelled","nothing was run")}function m0(e){return A(e).replace(/\p{Cf}/gu,t=>`\\u${t.codePointAt(0).toString(16).padStart(4,"0")}`)}function Ro(e){let t=[...new Set(oe(e)??[])];for(let s of t)if(!p0.test(s))throw m(`${JSON.stringify(s)} is no test user's name: letters, digits, _ and -, 64 at most`);let n=new Map;for(let s of t){let a=n.get(s.toLowerCase());if(a!==void 0)throw m(`${JSON.stringify(a)} and ${JSON.stringify(s)} are one test user (its address is in lower case): name it once`);n.set(s.toLowerCase(),s)}if(t.length>Kp)throw m(`--users names ${t.length}; a run makes ${Kp} at most`);return t}var Up={SIGHUP:1,SIGINT:2,SIGTERM:15};function g0(){let e,t=Object.keys(Up).map(n=>[n,()=>{e??=n}]);for(let[n,s]of t)process.on(n,s);return{got:()=>e,release:()=>{for(let[n,s]of t)process.off(n,s)}}}var Bp={name:"test",summary:"run the backend's tests as the platform does before a build goes out: test users made for the run and deleted after, PALBASE_TEST_* in the command's environment",usage:"[--machine <name>] [--users <names>] [--base-url <url>] [--secrets development|production] [-- <command> [args\u2026]]",details:["palbase test --machine backend --base-url http://localhost:8080: the machine's own test command and test users, as the platform runs them before each build of it rolls out.",'palbase test --users alice,bob --base-url http://localhost:8080 -- bun test: api.signInAs("alice") acts as a test user made for this run.',"The command gets what palbase run gives it, and PALBASE_TEST_AUTH_URL (the environment's address), PALBASE_TEST_IDENTITIES (the run's test users, each with its token) and, with --base-url, PALBASE_TEST_BASE_URL (where the app under test answers; without it HTTP tests skip themselves).","The test users are deleted when the command ends, however it ends \u2014 Ctrl-C too: the command is stopped, they are deleted, and palbase test ends as the signal would have.","With an environment's token (PALBASE_TOKEN, scope auth:test-users) the test users are made and deleted with the token, and no key is made: the command gets no PALBASE_SECRET_KEY, so test the app where it is deployed \u2014 palbase test --users alice,bob --base-url https://<ref>.app.palbase.studio -- bun test ./tests (the machine named backend; https://<name>-<ref>.app.palbase.studio for another, as machines:list shows)."],args:{min:0,max:1e3},flags:{machine:{type:"string",value:"name",description:"a machine whose test command (when no command is given) and test users (when --users is not) are run"},users:{type:"string",value:"names",description:"the test users to make for the run, comma-separated"},"base-url":{type:"string",value:"url",description:"where the app under test answers (http://localhost:8080)"},secrets:Ti},scope:"environment",async run(e){let t=Ro(e.flags.users),n=e.flags["base-url"];if(n!==void 0&&!/^https?:\/\/[^\s/]+/.test(n))throw m(`--base-url is an http(s) address, not ${JSON.stringify(n)}`);let s=e.flags.machine;if(e.args.length===0&&s===void 0)throw m("which tests? give their command after --, or --machine <name> to run its own","palbase test -- bun test");let a=await b(e),i=e.args.length>0?{cmd:e.args[0],args:e.args.slice(1)}:void 0;if(s!==void 0){let w=await h(e,a,"GET",`/machines/${k(s)}`);if(e.flags.users===void 0&&(t=w.test_users??[]),i===void 0){if(!w.test_command)throw m(`the machine ${s} runs no tests`,`give their command after --, or set it: palbase machines:update ${s} --test-command "bun test"`);await h0(e,s,w.test_command),i={cmd:"sh",args:["-c",w.test_command]}}}let r=i,o=Jt(e.io);if(o&&e.flags.secrets!==void 0)throw m("--secrets names the secrets an app started here reads with your key, and an environment's token makes no key: leave it out");let l=Ai(e);o?(a.env_slug===Be&&t.length>0&&await v(e,a,`make ${t.length} test user(s) there for ${r.cmd}, deleted when it ends`),e.out.note(`PALBASE_TOKEN is an environment's token: no key is made, and ${r.cmd} gets no PALBASE_SECRET_KEY \u2014 ${n!==void 0?`it tests the app at ${n}`:"with no --base-url the HTTP tests skip themselves: give the deployed machine's address (palbase machines:list shows it)"}`)):(a.env_slug===Be||l==="production")&&await v(e,a,`run ${r.cmd} with a key of ${a.env_slug}${t.length?` and ${t.length} test user(s) made there`:""}`,Ri(a,l));let d=o?{...await Ao(e,a),key:void 0}:await Pi(e,a),p=Gp(4).toString("hex"),u=t.length>0?g0():void 0,g=0;try{let w=await u0(e,a,t,p);t.length>0&&e.out.note(`${N(a)}: test users ${t.join(", ")} made for this run (${p})`);try{if(u?.got()===void 0){let _=await e.io.run(r.cmd,r.args,{cwd:e.io.cwd,env:{PALBASE_URL:d.url,PALBASE_PROJECT_ID:d.projectId,...d.key?{PALBASE_SECRET_KEY:d.key.key,PALBASE_SECRETS:l}:{},PALBASE_TEST_AUTH_URL:d.url,PALBASE_TEST_IDENTITIES:JSON.stringify(w),...n!==void 0?{PALBASE_TEST_BASE_URL:n}:{}},inherit:!0});if(_.code===127)throw new f("not_found",`${r.cmd}: no such program`);g=_.code}}finally{if(t.length>0){let _=await c0(e,a,w);_.length>0?e.out.warn(`test users not deleted: ${_.join(", ")} \u2014 palbase auth:test-users:delete <id> deletes one`):e.out.note(`the run's ${t.length} test user(s) deleted`)}}}finally{u?.release()}let y=u?.got();return y===void 0?g:128+Up[y]}};var zp={name:"auth:settings:get",summary:"the environment's auth settings: passwords, email confirmation, sessions, tokens, passkeys, risk",scope:"environment",async run(e){let t=await b(e),{body:n}=await Ke(e,t,"/admin/auth-settings");e.out.result(n,()=>gs(e,n))}},Wp={name:"auth:settings:set",summary:'change auth settings: key=value, a value read as JSON when it is JSON (12, true, ["https://\u2026"])',usage:"<key=value>\u2026",details:[`Text needs no quotes (site_url=https://shop.example); quote text that reads as JSON: from_name='"123"'.`,"The change is made on the revision read: one made beside it in the meantime (Studio, another terminal) is refused, not overwritten.","palbase auth:settings:get lists the keys."],args:{min:1,max:50},scope:"environment",async run(e){let t=await b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/admin/auth-settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the auth settings",s);await v(e,t,`set the auth settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(r.map(l=>[l,i[l]])),je(a));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},_s=["google","apple","github","microsoft"],f0={google:"web_client_id",apple:"services_id",microsoft:"application_id",github:"oauth_client_id"},y0=new Set(["organizations","consumers","common"]),Fp={name:"auth:providers:list",summary:"the sign-in methods: email, phone and the social providers, whether each is on, their clients and stored secrets (by name)",scope:"environment",async run(e){let t=await b(e),[n,s]=await Promise.all([h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth")]),a=[...n.providers.map(i=>({provider:i.id,on:i.enabled,detail:i.settings?`codes by ${i.settings.sender??"sms"}, ${i.settings.otp_ttl_seconds}s, ${i.settings.otp_max_attempts} tries, sign-up ${i.settings.allow_signups?"on":"off"}`:"",secrets:""})),..._s.map(i=>{let r=s.providers[i]??{enabled:!1,browser_clients:[],native_clients:[]},o=[...r.browser_clients.map(l=>`${l.key} (${l.platform})`),...r.native_clients.map(l=>`${l.key} (${l.platform}, native)`)];return{provider:i,on:r.enabled,detail:o.length===0?"no client":o.join(", "),secrets:s.credentials.filter(l=>l.provider===i).map(l=>`${l.key} ${l.configured?"set":"not set"}`).join(", ")}})];e.out.result({providers:n.providers,social:s.providers,credentials:s.credentials},()=>e.out.table(a,[{header:"provider",value:i=>i.provider},{header:"on",value:i=>i.on?"yes":"no"},{header:"clients / settings",value:i=>i.detail},{header:"secrets",value:i=>i.secrets}]))}},Jp={name:"auth:providers:set",summary:"turn a sign-in provider on or off and set it up: its client, its secret (from stdin), phone codes",usage:"<provider> [--enable|--disable] [setting=value\u2026] [--client-id <id>] [--secret-stdin] \u2026",details:["email is always on. phone: --enable/--disable, and its code settings as setting=value (allow_signups, otp_ttl_seconds, otp_max_attempts, sender, sms_second_factor).","google, apple, github, microsoft: --client-id sets the browser client --client names (default web), made when the provider has none of that name.","--secret-stdin reads the client's secret from stdin (Apple: the .p8 signing key, with --team-id and --key-id) and keeps it under --credential (default: the provider's name). It is never taken from the command line and never printed.",`--clients-file replaces the provider's clients with the file's {"browser_clients": [\u2026], "native_clients": [\u2026]} (native apps, several clients).`],args:{min:1,max:20},flags:{...pa,client:{type:"string",value:"key",description:"the browser client --client-id, --return-uri and the secret go to (default web)"},"client-id":{type:"string",value:"id",description:"the provider's id of your app (Google web client id, Apple services id, Microsoft application id, GitHub client id)"},"return-uri":{type:"string",multiple:!0,value:"url",description:"where your app is sent back after sign-in (repeat it; replaces the list)"},application:{type:"string",value:"key",description:"the application the client is for (default app)"},variant:{type:"string",value:"name",description:"the build variant the client is for (default release)"},directory:{type:"string",value:"tenant",description:"microsoft: a tenant id, organizations, consumers or common (default common)"},"secret-stdin":{type:"boolean",description:"read the client's secret (Apple: the .p8 key) from stdin"},credential:{type:"string",value:"key",description:"the name the secret is kept under (default: the provider's)"},"team-id":{type:"string",value:"id",description:"apple: your team's id, with --secret-stdin"},"key-id":{type:"string",value:"id",description:"apple: the signing key's id, with --secret-stdin"},"clients-file":{type:"string",value:"path",description:"replace the provider's clients with the file's (JSON)"}},scope:"environment",async run(e){let t=e.args[0],n=await b(e);if(t==="email")throw new f("always_on","email sign-in is always on, and has no settings of its own here",{hint:"its policy is in palbase auth:settings:set"});if(t==="phone")return b0(e,n,e.args.slice(1));if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: email, phone, ${_s.join(", ")}`);if(e.args.length>1)throw m(`${t} takes flags, not settings: palbase help auth:providers:set`);await v0(e,n,t)}};async function b0(e,t,n){let s=fs(e),a=cn(n);if(s===void 0&&a.length===0)throw m("nothing to change: --enable, --disable or setting=value","palbase help auth:providers:set");let i=await h(e,t,"GET","/admin/providers/phone/settings"),r=hn(i,a),o=Vt(i,r);if(s===void 0&&o.length===0)return Fe(e,"the phone settings",i);await v(e,t,`phone sign-in: ${[...s===void 0?[]:[s?"turn it on":"turn it off"],...o.map(p=>`set ${p}`)].join(", ")}`);let l=o.length>0?await h(e,t,"PUT","/admin/providers/phone/settings",r):i,d=s===void 0?void 0:await h(e,t,"POST","/admin/providers/phone",{enabled:s});e.out.result({provider:"phone",...d?{enabled:d.enabled}:{},settings:l},()=>{d&&e.out.line(`phone sign-in is ${d.enabled?"on":"off"}.`);for(let p of o)e.out.line(`${p}: ${Oe(i[p])} \u2192 ${Oe(l[p])}`)})}function w0(e){if(y0.has(e))return{mode:e};if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return{mode:"tenant",tenant_id:e};throw m("--directory is a tenant id, organizations, consumers or common")}async function v0(e,t,n){let s=e.flags,a=fs(e),i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=i.body.providers[n]??{enabled:!1,browser_clients:[],native_clients:[]},l={},d=[],p=s.credential??n,u;if(s["secret-stdin"]===!0){if(n==="apple"&&(s["team-id"]===void 0||s["key-id"]===void 0))throw m("Apple's signing key goes with --team-id and --key-id");u=await Me(e,n==="apple"?"Apple's .p8 signing key":`${n}'s client secret`),d.push(`keep its secret as ${p}`)}let g=["client","client-id","return-uri","application","variant","directory","credential"].filter(P=>s[P]!==void 0);if(s["clients-file"]!==void 0){if(g.length>0)throw m(`--clients-file and --${g[0]} are one or the other`);let P=me(await ke(e,s["clients-file"],"the clients"),"the clients file");if(typeof P!="object"||P===null||P.browser_clients===void 0&&P.native_clients===void 0)throw m('the clients file is {"browser_clients": [\u2026], "native_clients": [\u2026]}');l.browser_clients=P.browser_clients??o.browser_clients,l.native_clients=P.native_clients??o.native_clients,d.push(`set its clients from ${s["clients-file"]}`)}else if(g.length>0||u!==void 0){let P=s.client??"web",S=[...o.browser_clients],$=S.findIndex(T=>T.key===P),R=u!==void 0&&g.every(T=>T==="credential");if($>=0||!R){let T=$>=0?{...S[$]}:{key:P,enabled:!0,application_key:"app",platform:"web",variant:"release",return_uris:[]},D=f0[n];if(s["client-id"]!==void 0&&(T[D]=s["client-id"]),!T[D])throw m(`the ${n} client ${P} is new: give it --client-id`);if(s["return-uri"]!==void 0&&(T.return_uris=s["return-uri"]),s.application!==void 0&&(T.application_key=s.application),s.variant!==void 0&&(T.variant=s.variant),n==="microsoft")T.directory=s.directory!==void 0?w0(s.directory):T.directory??{mode:"common"};else if(s.directory!==void 0)throw m("--directory is a Microsoft client's");(u!==void 0||s.credential!==void 0||!T.credential_ref)&&(T.credential_ref=p),S[$>=0?$:S.length]=T,l.browser_clients=S,d.push(`${$>=0?"change":"add"} its browser client ${P}`)}}if(a!==void 0&&(l.enabled=a,d.push(a?"turn it on":"turn it off")),d.length===0)throw m("nothing to change: give a flag","palbase help auth:providers:set");await v(e,t,`${n} sign-in: ${d.join(", ")}`);let y=i.body;if(u!==void 0){let P=n==="apple"?{provider:n,kind:"apple_signing_key",team_id:s["team-id"],key_id:s["key-id"],private_key:u}:{provider:n,kind:"oauth_client_secret",client_secret:u};r=(await qe(e,t,"PUT",`/admin/social-auth/credentials/${k(p)}`,P,je(r))).etag??r}Object.keys(l).length>0?y=await h(e,t,"PATCH",`/admin/social-auth/providers/${k(n)}`,l,je(r)):y=await h(e,t,"GET","/admin/social-auth");let w=y.providers[n],_=y.credentials.filter(P=>P.provider===n);e.out.result({provider:n,...w,credentials:_},()=>{e.out.line(`${n} sign-in is ${w.enabled?"on":"off"}: ${w.browser_clients.length} browser client(s), ${w.native_clients.length} native.`);for(let P of _)e.out.line(` secret ${P.key}: ${P.configured?"set":"not set"}`)})}var Vp={name:"auth:providers:secret:delete",summary:"delete a sign-in provider's stored secret by its name; one a client still uses is refused",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e),{body:s,etag:a}=await Ke(e,n,"/admin/social-auth");if(!s.credentials.some(i=>i.key===t))throw m(`the environment holds no provider secret ${JSON.stringify(t)}`,"palbase auth:providers:list names them");await v(e,n,`delete the provider secret ${t}`),await h(e,n,"DELETE",`/admin/social-auth/credentials/${k(t)}`,void 0,je(a)),e.out.result({deleted:t},()=>e.out.line(`Deleted the provider secret ${t}.`))}},Hp={name:"auth:providers:disable",summary:"turn a sign-in provider off (phone, google, apple, github, microsoft); its clients and secrets stay",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);if(t==="email")throw new f("always_on","email sign-in cannot be turned off");if(t==="phone"){await v(e,n,"turn phone sign-in off");let i=await h(e,n,"POST","/admin/providers/phone",{enabled:!1});e.out.result(i,()=>e.out.line("phone sign-in is off."));return}if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: phone, ${_s.join(", ")}`);let{etag:s}=await Ke(e,n,"/admin/social-auth");await v(e,n,`turn ${t} sign-in off`);let a=await h(e,n,"PATCH",`/admin/social-auth/providers/${k(t)}`,{enabled:!1},je(s));e.out.result({provider:t,...a.providers[t]},()=>e.out.line(`${t} sign-in is off; its clients and secrets stay.`))}},Yp={name:"auth:roles:list",summary:"the environment's roles: their permissions, which one new users get, how many users hold each",scope:"environment",async run(e){let t=await b(e),{roles:n}=await h(e,t,"GET","/admin/roles");e.out.result({roles:n},()=>{n.length===0&&e.out.line("No role yet: palbase auth:roles:set <name> --permissions \u2026 makes one."),e.out.table(n,[{header:"role",value:s=>`${s.name}${s.is_default?" (default)":""}`},{header:"permissions",value:s=>s.permissions.join(", ")},{header:"users",value:s=>String(s.user_count??0)},{header:"description",value:s=>s.description}])})}},Xp={name:"auth:roles:set",summary:"make a role, or change one: its permissions (the list is replaced), description, whether new users get it",usage:"<name> [--permissions <a.b,c.d>] [--description <text>] [--default yes|no]",args:{min:1,max:1},flags:{permissions:{type:"string",multiple:!0,value:"list",description:'resource.action permissions, comma-separated or repeated; replaces the list ("" for none)'},description:{type:"string",value:"text",description:"what the role is for"},default:{type:"string",value:"yes|no",description:"whether new users get it (one role at most)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0],{roles:s}=await h(e,t,"GET","/admin/roles"),a=s.find(p=>p.name===n),i=oe(e.flags.permissions),r=mn(e.flags.default,"default");if(a&&i===void 0&&e.flags.description===void 0&&r===void 0)throw m("nothing to change: give a flag","palbase help auth:roles:set");let o={permissions:i??a?.permissions??[],description:e.flags.description??a?.description??"",is_default:r??a?.is_default??!1};await v(e,t,`${a?"change":"make"} the role ${n}${a?.user_count?` (${a.user_count} users hold it)`:""}`);let l=await h(e,t,"PUT",`/admin/roles/${k(n)}`,o),d=l.roles.find(p=>p.name===n);e.out.result(d??l,()=>e.out.line(`${a?"Changed":"Made"} the role ${n}: ${(d?.permissions??o.permissions).join(", ")||"no permission"}${d?.is_default?", given to new users":""}.`))}},Zp={name:"auth:roles:delete",summary:"delete a role; one users hold is deleted only with --force, and is taken from them",usage:"<name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete it although users hold it"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];await v(e,t,`delete the role ${n}${e.flags.force===!0?", taking it from the users who hold it":""}`),await h(e,t,"DELETE",`/admin/roles/${k(n)}${e.flags.force===!0?"?confirm=true":""}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the role ${n}.`))}},Qp={event:{type:"string",value:"event",description:"before.user.create, before.login, before.token.issue, \u2026 (the module lists them)"},url:{type:"string",value:"url",description:"the https endpoint auth calls and waits for"},"failure-mode":{type:"string",value:"deny|allow",description:"what auth does when the hook does not answer in time (default deny)"},timeout:{type:"string",value:"ms",description:"how long auth waits, 100\u20135000 ms (default 5000)"}},eu={name:"auth:hooks:list",summary:"the blocking hooks: what auth calls, and waits for, before a sign-up, a sign-in, a token",scope:"environment",async run(e){let t=await b(e),{hooks:n}=await h(e,t,"GET","/admin/hooks");e.out.result({hooks:n},()=>{n.length===0&&e.out.line("No hook: palbase auth:hooks:create --event \u2026 --url \u2026 registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"event",value:s=>s.event},{header:"url",value:s=>s.url},{header:"on failure",value:s=>s.failure_mode},{header:"timeout",value:s=>`${s.timeout_ms} ms`},{header:"on",value:s=>s.enabled?"yes":"no"}])})}},tu={name:"auth:hooks:create",summary:"register a blocking hook; its signing secret is printed this once",usage:"--event <event> --url <url> [--failure-mode deny|allow] [--timeout <ms>] [--disable]",flags:{...Qp,disable:{type:"boolean",description:"register it turned off"}},scope:"environment",async run(e){let t=await b(e);if(e.flags.event===void 0||e.flags.url===void 0)throw m("a hook needs --event and --url");let n=uo({event:e.flags.event,url:e.flags.url,failure_mode:e.flags["failure-mode"],timeout_ms:se(e.flags.timeout,"timeout"),...e.flags.disable===!0?{enabled:!1}:{}});await v(e,t,`register a hook on ${String(n.event)} calling ${String(n.url)}`);let s=await h(e,t,"POST","/admin/hooks",n,j());e.out.result(s,()=>{e.out.line(`Registered ${s.id}: ${s.event} \u2192 ${s.url}.`),s.secret&&e.out.line(`signing secret (shown this once): ${s.secret}`)})}},nu={name:"auth:hooks:update",summary:"change a blocking hook: its event, endpoint, timeout, failure mode, on or off (its secret stays)",usage:"<id> [--event \u2026] [--url \u2026] [--failure-mode \u2026] [--timeout \u2026] [--enable|--disable]",args:{min:1,max:1},flags:{...Qp,...pa},scope:"environment",async run(e){let t=await b(e),{hooks:n}=await h(e,t,"GET","/admin/hooks"),s=n.find(o=>o.id===e.args[0]);if(!s)throw new f("no_such_hook",`no hook ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:hooks:list shows them"});let a={event:e.flags.event??s.event,url:e.flags.url??s.url,failure_mode:e.flags["failure-mode"]??s.failure_mode,timeout_ms:se(e.flags.timeout,"timeout")??s.timeout_ms,enabled:fs(e)??s.enabled},i=Vt(_0(s),a);if(i.length===0)throw m("nothing to change: give a flag","palbase help auth:hooks:update");await v(e,t,`change the hook ${s.id}: ${i.join(", ")}`);let r=await h(e,t,"PUT",`/admin/hooks/${k(s.id)}`,a);e.out.result(r,()=>e.out.line(`${r.id}: ${r.event} \u2192 ${r.url}, ${r.failure_mode} on failure, ${r.timeout_ms} ms, ${r.enabled?"on":"off"}.`))}};function _0(e){return{event:e.event,url:e.url,failure_mode:e.failure_mode,timeout_ms:e.timeout_ms,enabled:e.enabled}}var su={name:"auth:hooks:delete",summary:"delete a blocking hook; auth stops calling it",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`delete the hook ${e.args[0]}`),await h(e,t,"DELETE",`/admin/hooks/${k(e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the hook ${e.args[0]}.`))}},au={name:"auth:oauth-clients:list",summary:"the OAuth clients of the environment's OpenID provider (apps that sign in with your users' accounts)",scope:"environment",async run(e){let t=await b(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients");e.out.result({clients:n},()=>{n.length===0&&e.out.line("No OAuth client: palbase auth:oauth-clients:create <name> registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"client id",value:s=>s.client_id},{header:"name",value:s=>s.client_name},{header:"kind",value:s=>s.is_public?"public":s.token_endpoint_auth_method},{header:"grants",value:s=>s.grant_types.join(", ")},{header:"redirect uris",value:s=>s.redirect_uris.join(", ")}])})}},iu={name:"auth:oauth-clients:create",summary:"register an OAuth client; a confidential client's secret is printed this once",usage:"<name> [--public] [--redirect-uri <url>\u2026] [--grant <type>\u2026] [--scope <scope>\u2026] [--client-id <id>]",args:{min:1,max:1},flags:{public:{type:"boolean",description:"a public client (a CLI, a mobile app): it has no secret"},"redirect-uri":{type:"string",multiple:!0,value:"url",description:"where it may send the browser back (repeat it)"},grant:{type:"string",multiple:!0,value:"type",description:"authorization_code (default), refresh_token, client_credentials, urn:ietf:params:oauth:grant-type:device_code"},scope:{type:"string",multiple:!0,value:"scope",description:"what it may ask for (default openid, profile, email)"},"client-id":{type:"string",value:"id",description:"a client_id to use as it is (default: a random one)"}},scope:"environment",async run(e){let t=await b(e),n=uo({client_name:e.args[0],client_id:e.flags["client-id"],is_public:e.flags.public===!0?!0:void 0,redirect_uris:e.flags["redirect-uri"],grant_types:oe(e.flags.grant),scopes:oe(e.flags.scope)});await v(e,t,`register the OAuth client ${e.args[0]}`);let s=await h(e,t,"POST","/admin/oauth-clients",n,j());e.out.result(s,()=>{e.out.line(`Registered ${s.client_name}: client_id ${s.client_id} (${s.id}).`),s.client_secret&&e.out.line(`client secret (shown this once): ${s.client_secret}`)})}},ru={name:"auth:oauth-clients:delete",summary:"delete an OAuth client (by its id or its client_id)",usage:"<id|client-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients"),s=n.find(a=>a.id===e.args[0]||a.client_id===e.args[0]);if(!s)throw new f("no_such_client",`no OAuth client ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:oauth-clients:list shows them"});await v(e,t,`delete the OAuth client ${s.client_name} (${s.client_id})`),await h(e,t,"DELETE",`/admin/oauth-clients/${k(s.id)}`),e.out.result({deleted:s.id},()=>e.out.line(`Deleted the OAuth client ${s.client_name}.`))}};function k0(e){return{...e.client_id.startsWith("oidc_")?{}:{client_id:e.client_id},is_public:e.is_public,grant_types:[...e.grant_types].sort(),redirect_uris:e.redirect_uris,post_logout_redirect_uris:e.post_logout_redirect_uris,response_types:e.response_types,scopes:e.scopes,token_endpoint_auth_method:e.token_endpoint_auth_method,id_token_lifetime_secs:e.id_token_lifetime_secs,dpop_bound_access_tokens:e.dpop_bound_access_tokens,...e.jwks?{jwks:e.jwks}:{}}}var ou={name:"auth",async read(e,t){let[n,s,a,i,r,o]=await Promise.all([h(e,t,"GET","/admin/auth-settings"),h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth"),h(e,t,"GET","/admin/roles"),h(e,t,"GET","/admin/hooks"),h(e,t,"GET","/admin/oauth-clients")]),l={};for(let[p,u]of Object.entries(n))l[`settings.${p}`]=u;let d=s.providers.find(p=>p.id==="phone");d&&(l["phone.enabled"]=d.enabled,d.settings&&(l["phone.settings"]=d.settings));for(let p of _s){let u=a.providers[p];u&&(l[`social.${p}`]={enabled:u.enabled,browser_clients:u.browser_clients,native_clients:u.native_clients})}for(let p of a.credentials)l[`secrets.${p.key}`]={provider:p.provider,kind:p.kind,value:p.configured?"set":"not set"};for(let p of i.roles)l[`roles.${p.name}`]={description:p.description,is_default:p.is_default,permissions:[...p.permissions].sort()};for(let p of r.hooks)l[`hooks.${p.event} ${p.url}`]={failure_mode:p.failure_mode,timeout_ms:p.timeout_ms,enabled:p.enabled};for(let p of o.clients)l[`oauth_clients.${p.client_name}`]=k0(p);return l},async copy(e,t,n,s){await S0(e,t,fe(n,"settings."),s);for(let i of fe(n,"phone."))i.name==="enabled"&&await Q(s,`turn phone sign-in ${i.from?"on":"off"}`,async()=>{await h(e,t,"POST","/admin/providers/phone",{enabled:i.from===!0})}),i.name==="settings"&&i.from!==void 0&&await Q(s,"set the phone code settings",async()=>{await h(e,t,"PUT","/admin/providers/phone/settings",i.from)});await $0(e,t,fe(n,"social."),fe(n,"secrets."),s);let a=fe(n,"roles.").sort((i,r)=>+(i.from?.is_default===!0)-+(r.from?.is_default===!0));for(let i of a)i.from===void 0?await Q(s,`delete the role ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/roles/${k(i.name)}`)}):await Q(s,`set the role ${i.name}`,async()=>{await h(e,t,"PUT",`/admin/roles/${k(i.name)}`,i.from)});await P0(e,t,fe(n,"hooks."),s),await A0(e,t,fe(n,"oauth_clients."),s)}};async function S0(e,t,n,s){let a=n.filter(r=>r.from!==void 0);for(let r of n.filter(o=>o.from===void 0))s.left(`auth settings ${r.name}: set in the target only, and a setting is not taken away (set it with auth:settings:set)`);if(a.length===0)return;let{etag:i}=await Ke(e,t,"/admin/auth-settings");await Q(s,`set the auth settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(a.map(r=>[r.name,r.from])),je(i))})}async function $0(e,t,n,s,a){for(let l of s){let d=l.from;d===void 0?a.left(`secret ${l.name}: only in the target, left as it is (delete it with palbase auth:providers:secret:delete ${l.name})`):a.left(`secret ${l.name} (${d.provider}): secrets are not copied \u2014 set it with palbase auth:providers:set ${d.provider} --secret-stdin --credential ${l.name}`)}if(n.length===0)return;let i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=new Set(i.body.credentials.filter(l=>l.configured).map(l=>l.key));for(let l of n){let d=l.from,p=[...new Set(d.browser_clients.map(u=>u.credential_ref).filter(u=>typeof u=="string"&&!o.has(u)))];if(p.length>0){a.left(`${l.name} sign-in: its clients use the secret ${p.join(", ")}, which the target does not hold \u2014 set it first (auth:providers:set ${l.name} --secret-stdin --credential ${p[0]})`);continue}await Q(a,`set ${l.name} sign-in (${d.enabled?"on":"off"}, ${d.browser_clients.length+d.native_clients.length} client(s))`,async()=>{r=(await qe(e,t,"PATCH",`/admin/social-auth/providers/${k(l.name)}`,d,je(r))).etag??r})}}async function P0(e,t,n,s){if(n.length===0)return;let{hooks:a}=await h(e,t,"GET","/admin/hooks");for(let i of n){let r=i.name.indexOf(" "),o=i.name.slice(0,r),l=i.name.slice(r+1),d=a.find(p=>p.event===o&&p.url===l);if(i.from===void 0)d&&await Q(s,`delete the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"DELETE",`/admin/hooks/${k(d.id)}`)});else if(d)await Q(s,`change the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"PUT",`/admin/hooks/${k(d.id)}`,{event:o,url:l,...i.from})});else{let p;await Q(s,`register the hook ${o} \u2192 ${l}`,async()=>{p=(await h(e,t,"POST","/admin/hooks",{event:o,url:l,...i.from},j())).secret}),p&&s.shown(`the hook ${o} \u2192 ${l} signs with`,p)}}}async function A0(e,t,n,s){if(n.length===0)return;let{clients:a}=await h(e,t,"GET","/admin/oauth-clients");for(let i of n){let r=a.find(l=>l.client_name===i.name),o=i.from;if(o===void 0)r&&await Q(s,`delete the OAuth client ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/oauth-clients/${k(r.id)}`)});else if(r)if(!We(o.is_public,r.is_public)||o.client_id!==void 0&&o.client_id!==r.client_id)s.left(`OAuth client ${i.name}: its client_id or kind (public or not) differs, which a client cannot change \u2014 delete it in the target and run the copy again`);else{let{client_id:l,is_public:d,...p}=o;await Q(s,`change the OAuth client ${i.name}`,async()=>{await h(e,t,"PATCH",`/admin/oauth-clients/${k(r.id)}`,p)})}else{let l;await Q(s,`register the OAuth client ${i.name}`,async()=>{l=await h(e,t,"POST","/admin/oauth-clients",{client_name:i.name,...o},j())}),l?.client_secret&&s.shown(`the OAuth client ${i.name} (${l.client_id}) has the secret`,l.client_secret)}}}var lu=["bool","number","string","object"];async function yn(e,t){return(await h(e,t,"GET","/flags/templates/capabilities")).publish_enabled}async function fn(e,t,n){let s=await Ke(e,t,"/flags/templates/draft");if(s.body.draft||!n)return{draft:s.body.draft,etag:s.etag};let a=await Ke(e,t,"/flags/templates/active"),i=await qe(e,t,"POST","/flags/templates/draft",{},je(a.etag));return{draft:i.body.draft,etag:i.etag}}function du(e){return{value_type:e.value_type,value:e.value,...e.description?{description:e.description}:{},...e.variants&&e.variants.length>0?{variants:e.variants}:{},...e.conditions&&e.conditions.length>0?{conditions:e.conditions}:{}}}function R0(e){return typeof e=="boolean"?"bool":typeof e=="number"?"number":typeof e=="string"?"string":"object"}function pu(e,t){switch(t){case"bool":if(e==="true"||e==="false")return e==="true";throw m(`a bool flag's value is true or false, not ${JSON.stringify(e)}`);case"number":{let n=Number(e);if(e.trim()===""||!Number.isFinite(n))throw m(`a number flag's value is a number, not ${JSON.stringify(e)}`);return n}case"string":{let n=jt(e);return typeof n=="string"?n:e}default:{let n=jt(e);if(typeof n!="object"||n===null)throw m(`an object flag's value is a JSON object or list, not ${JSON.stringify(e)}`);return n}}}function T0(e,t){let n=e.lastIndexOf("=>");if(n<=0)throw m(`a condition is "<expression> => <value>", not ${JSON.stringify(e)}`,`--condition "client.platform == 'ios' => true"`);return{when:e.slice(0,n).trim(),value:pu(e.slice(n+2).trim(),t)}}var uu={name:"flags:list",summary:"the environment's flags as they are live: type, default, targeting (and the draft's state when it publishes)",scope:"environment",async run(e){let t=await b(e),n=await yn(e,t),s,a,i;if(n){let[r,o]=await Promise.all([h(e,t,"GET","/flags/templates/active"),fn(e,t,!1)]);s=Object.entries(r.definitions).map(([l,d])=>({key:l,...d})),a=r.version,i=o.draft}else s=await h(e,t,"GET","/flags/system");s.sort((r,o)=>r.key<o.key?-1:1),e.out.result({publishing:n,...a?{version:a}:{},flags:s,...i?{draft:{revision:i.revision,base_version:i.base_version}}:{}},()=>{n&&e.out.line(`Version ${a} is live${i?`; a draft (from ${i.base_version}) is in progress: palbase flags:publish shows and publishes it`:""}.`),s.length===0&&e.out.line("No flag yet: palbase flags:set <key> <value> makes one."),e.out.table(s,[{header:"flag",value:r=>r.key},{header:"type",value:r=>r.value_type},{header:"value",value:r=>JSON.stringify(r.value)},{header:"targeting",value:r=>r.conditions?.length?`${r.conditions.length} condition(s)`:""},{header:"description",value:r=>r.description??""}])})}},cu={name:"flags:set",summary:"define a flag or change its default and targeting (into the draft when the environment publishes)",usage:'<key> <value> [--type bool|number|string|object] [--condition "<expression> => <value>"\u2026] [--description <text>]',details:["The value is read as the flag's type: true/false, a number, text, or a JSON object; a new flag's type is the value's unless --type says it.","--condition replaces the targeting (first match wins, 8 at most); --clear-conditions takes it away; without either it stays.","An environment that publishes takes the change into its shared draft (palbase flags:publish makes it live); one that does not, live at once."],args:{min:2,max:2},flags:{type:{type:"string",value:"type",description:"bool, number, string or object"},condition:{type:"string",multiple:!0,value:"rule",description:'"<expression> => <value>" (repeat it, in order)'},"clear-conditions":{type:"boolean",description:"take its targeting away"},variants:{type:"string",value:"list",description:"a string flag's allowed values, comma-separated"},description:{type:"string",value:"text",description:"what the flag is for"}},scope:"environment",async run(e){let t=await b(e),[n,s]=e.args,a=e.flags.type;if(a!==void 0&&!lu.includes(a))throw m(`--type is one of ${lu.join(", ")}`);if(e.flags.condition!==void 0&&e.flags["clear-conditions"]===!0)throw m("--condition and --clear-conditions are one or the other");let i=await yn(e,t),r,o;i?(o=await fn(e,t,!1),r=o.draft?.definitions[n]??(await h(e,t,"GET","/flags/templates/active")).definitions[n]):r=(await h(e,t,"GET","/flags/system")).find(u=>u.key===n);let l=a??r?.value_type??R0(jt(s)),d=e.flags["clear-conditions"]===!0?[]:e.flags.condition!==void 0?e.flags.condition.map(u=>T0(u,l)):r?.value_type===l?r.conditions??[]:[],p=du({value_type:l,value:pu(s,l),description:e.flags.description??r?.description,variants:oe(e.flags.variants)??(r?.value_type===l?r.variants:void 0),conditions:d});if(await v(e,t,i?`put ${n} = ${Oe(p.value)} into the flags draft`:`set the flag ${n} = ${Oe(p.value)}, live at once`),i){o?.draft||(o=await fn(e,t,!0));let u=await qe(e,t,"PUT",`/flags/templates/draft/parameters/${k(n)}`,p,je(o.etag));e.out.result({key:n,...p,draft:{revision:u.body.draft?.revision}},()=>e.out.line(`${n} = ${JSON.stringify(p.value)} is in the draft: palbase flags:publish makes it live.`))}else{let u=await h(e,t,"PUT",`/flags/system/${k(n)}`,p);e.out.result(u,()=>e.out.line(`${n} = ${JSON.stringify(u.value)} (${u.value_type}) is live.`))}}},hu={name:"flags:delete",summary:"delete a flag, with every user's own value of it (from the draft when the environment publishes)",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args[0],s=await yn(e,t);if(await v(e,t,s?`take ${n} out of the flags draft`:`delete the flag ${n} and every user's value of it, live at once`),s){let a=await fn(e,t,!0);await h(e,t,"DELETE",`/flags/templates/draft/parameters/${k(n)}`,void 0,je(a.etag)),e.out.result({deleted:n,draft:!0},()=>e.out.line(`${n} is out of the draft: palbase flags:publish makes it so.`))}else await h(e,t,"DELETE",`/flags/system/${k(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the flag ${n}.`))}};function To(){return new f("publishing_off","this environment's flags are not published through drafts: flags:set and flags:delete change them live",{hint:"versions, publishing and rollback are for an environment that publishes"})}function E0(e,t){t.changes.length===0&&e.out.line("The draft changes nothing.");for(let n of t.changes){let s=n.override_count>0?` (${n.override_count} users' own values)`:"";n.kind==="added"?e.out.line(` + ${n.key} = ${JSON.stringify(n.after?.value)}`):n.kind==="removed"?e.out.line(` - ${n.key}${s}`):e.out.line(` ~ ${n.key}: ${n.changed_fields.join(", ")}${n.changed_fields.includes("value")?` \u2192 ${JSON.stringify(n.after?.value)}`:""}${s}`)}for(let n of t.issues)e.out.line(` ! ${n.key?`${n.key}: `:""}${n.message}`)}async function Eo(e,t,n,s){return h(e,t,"POST","/flags/templates/publish",s===""?{}:{note:s},{...je(n),...j()})}var mu={name:"flags:publish",summary:"show the flags draft's changes against the live version, then publish it as the next version",usage:"[-m <note>]",flags:{note:{type:"string",short:"m",value:"note",description:"why: kept with the version"}},scope:"environment",async run(e){let t=await b(e);if(!await yn(e,t))throw To();if(!(await fn(e,t,!1)).draft)throw new f("no_draft","there is no draft to publish",{hint:"palbase flags:set puts a change into one"});let s=await Ke(e,t,"/flags/templates/draft/review");if(e.out.json||E0(e,s.body),!s.body.can_publish)throw new f("cannot_publish",`the draft cannot be published: ${s.body.issues.map(i=>i.message).join("; ")}`);if(s.body.changes.length===0){e.out.result({unchanged:!0,review:s.body},()=>e.out.line("Nothing to publish."));return}await v(e,t,`publish the flags draft (${s.body.changes.length} change(s)) as the version after ${s.body.active_version}`);let a=await Eo(e,t,s.etag,e.flags.note??"");e.out.result({...a,review:s.body},()=>e.out.line(a.unchanged?"The draft changed nothing; nothing was published.":`Published version ${a.template.version}.`))}},gu={name:"flags:publishing:enable",summary:"turn publishing on for the environment's flags: changes go into a shared draft, live once published \u2014 for good",details:["What is live now becomes version 1. From then on flags:set and flags:delete change the draft, flags:publish makes it live as the next version, and flags:rollback brings an earlier one back. It cannot be turned off."],scope:"environment",async run(e){let t=await b(e);if(await yn(e,t)){e.out.result({publishing:!0,changed:!1},()=>e.out.line("The environment's flags are published through drafts already."));return}await v(e,t,"turn publishing on for the flags \u2014 what is live becomes version 1, and it cannot be turned off");let n=await h(e,t,"POST","/flags/templates/activation",{});e.out.result({publishing:!0,changed:!0,version:n.version},()=>e.out.line(`Publishing is on: what was live is version ${n.version}; flags:set changes the draft, flags:publish makes it live.`))}},fu={name:"flags:versions",summary:"the published versions of the flags, newest first, and which one is live",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await b(e);if(!await yn(e,t))throw To();let n=Number(e.flags.limit??20);if(!Number.isInteger(n)||n<=0)throw m("--limit is a whole number");let s=await h(e,t,"GET",`/flags/templates/versions?limit=${n}`);e.out.result(s,()=>e.out.table(s.versions,[{header:"",value:a=>a.version===s.active_version?"*":""},{header:"version",value:a=>a.version},{header:"kind",value:a=>`${a.kind}${a.restored_from?` of ${a.restored_from}`:""}`},{header:"published",value:a=>a.created_at},{header:"by",value:a=>a.actor},{header:"note",value:a=>a.note}]))}},yu={name:"flags:rollback",summary:"make an earlier version of the flags live again (published as the next version)",usage:"<version> [-m <note>]",args:{min:1,max:1},flags:{note:{type:"string",short:"m",value:"note",description:"why (default: rollback to <version>)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];if(!await yn(e,t))throw To();if((await fn(e,t,!1)).draft)throw new f("draft_in_progress","a draft is in progress: publish it (flags:publish) before a rollback");let s=await Ke(e,t,"/flags/templates/active");await v(e,t,`make version ${n} of the flags live again (now ${s.body.version})`);let a=await qe(e,t,"POST",`/flags/templates/restore/${k(n)}`,{},je(s.etag)),i=await Eo(e,t,a.etag,e.flags.note??`rollback to ${n}`);e.out.result(i,()=>e.out.line(i.unchanged?`Version ${n} is what is live already.`:`Version ${n} is live again, as version ${i.template.version}.`))}},bu={name:"flags",async read(e,t){let n=await h(e,t,"GET","/flags/system"),s={};for(let a of n)s[`flags.${a.key}`]=du(a);return s},async copy(e,t,n,s){let a=fe(n,"flags.");if(a.length===0)return;if(!await yn(e,t)){for(let r of a)r.from===void 0?await Q(s,`delete the flag ${r.name}`,async()=>{await h(e,t,"DELETE",`/flags/system/${k(r.name)}`)}):await Q(s,`set the flag ${r.name}`,async()=>{await h(e,t,"PUT",`/flags/system/${k(r.name)}`,r.from)});return}if((await fn(e,t,!1)).draft){s.left("flags: the target has a draft in progress \u2014 publish it (flags:publish) and copy again");return}let i=(await fn(e,t,!0)).etag;for(let r of a)await Q(s,`${r.from===void 0?"take":"put"} the flag ${r.name} ${r.from===void 0?"out of":"into"} the draft`,async()=>{let o=`/flags/templates/draft/parameters/${k(r.name)}`;i=(r.from===void 0?await qe(e,t,"DELETE",o,void 0,je(i)):await qe(e,t,"PUT",o,r.from,je(i))).etag??i});await Q(s,"publish the flags draft",async()=>{await Eo(e,t,i,"config:copy")})}};var wu=["email","sms","verify","whatsapp","push"],Co=["email","sms","whatsapp"],vu={name:"notify:providers:list",summary:"the environment's own providers, by channel and the order they are tried (never their credentials)",scope:"environment",async run(e){let t=await b(e),{providers:n}=await h(e,t,"GET","/notify/providers");e.out.result({providers:n},()=>{n.length===0&&e.out.line("No provider of the environment's own: email goes through the platform's sender; texts need one (notify:providers:set)."),e.out.table(n,[{header:"channel",value:s=>s.channel},{header:"provider",value:s=>s.provider},{header:"on",value:s=>s.active?"yes":"no"},{header:"priority",value:s=>String(s.priority)},{header:"credentials",value:()=>"set"}])})}},_u={name:"notify:providers:set",summary:"bring a provider for a channel: its credentials are piped in as JSON, checked as the sender will use them, never shown",usage:"<channel> <provider> [--priority <n>] [--enable|--disable] < credentials.json",details:["email: acs {connection_string, from_email}, ses {region, access_key_id, secret_access_key, from_domain}, sendgrid {api_key, from_domain}, smtp {host, port, username, password, from_email, use_starttls}.","sms: twilio {account_sid, auth_token, from_number}, vonage {api_key, api_secret, from}, acs {connection_string, from_number}. verify: twilio_verify {account_sid, auth_token, service_sid}.","whatsapp: meta {phone_number_id, access_token, api_version, app_secret, verify_token}. push: fcm (the service account JSON), apns {private_key, team_id, key_id, bundle_id, is_production}, expo {access_token}.","The credentials are read from stdin only: never from the command line, where the shell would keep them."],args:{min:2,max:2},flags:{priority:{type:"string",value:"n",description:"lower is tried first"},...pa},scope:"environment",async run(e){let[t,n]=e.args;if(!wu.includes(t))throw m(`the channels: ${wu.join(", ")}`);let s=await b(e),a=me(await Me(e,`${n}'s credentials (JSON)`),"the credentials");if(typeof a!="object"||a===null||Array.isArray(a))throw m("the credentials are a JSON object");let i=fs(e),r=se(e.flags.priority,"priority");await v(e,s,`send ${t} through ${n}`);let o=await h(e,s,"PUT",`/notify/providers/${k(t)}/${k(n)}`,{credentials:a,...i!==void 0?{active:i}:{},...r!==void 0?{priority:r}:{}},j());e.out.result(o,()=>e.out.line(`${o.channel} goes through ${o.provider} (${o.active?"on":"off"}, priority ${o.priority}); its credentials are kept sealed.`))}},ku={name:"notify:providers:remove",summary:"forget a provider and its credentials",usage:"<channel> <provider>",args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=await b(e);await v(e,s,`forget the ${t} provider ${n} and its credentials`),await h(e,s,"DELETE",`/notify/providers/${k(t)}/${k(n)}`,void 0,j()),e.out.result({removed:{channel:t,provider:n}},()=>e.out.line(`${t} no longer goes through ${n}.`))}},Oo={channel:{type:"string",value:"channel",description:"email (default), sms or whatsapp"},locale:{type:"string",value:"locale",description:"the template's locale: en, tr, pt-BR"}};function va(e){let t=e.flags.channel??"email";if(!Co.includes(t))throw m(`--channel is one of ${Co.join(", ")}`);return t}function Mo(e,t){let n=e.flags.locale;if(n===void 0)throw m("which locale? pass --locale <locale>");return`/notify/templates/${va(e)}/${k(t)}/${k(n)}`}function C0(e,t){if(e==="sms"){let s=j0(t);return typeof s=="object"&&s!==null&&typeof s.body=="string"?{body:s.body}:{body:t.replace(/\n$/,"")}}let n=me(t,`the ${e} template`);if(e==="email"){for(let s of["subject","html_body","text_body"])if(typeof n[s]!="string")throw m(`an email template is {"subject", "html_body", "text_body"}: ${s} is missing`);return{subject:n.subject,html_body:n.html_body,text_body:n.text_body}}if(typeof n.name!="string"||typeof n.language!="string")throw m('a WhatsApp template is {"name", "language", "variables", "code_button"}: the template approved on your Meta account');return{name:n.name,language:n.language,...n.variables!==void 0?{variables:n.variables}:{},...n.code_button!==void 0?{code_button:n.code_button}:{}}}function j0(e){try{return JSON.parse(e)}catch{return e}}var Su={name:"notify:templates:list",summary:"the templates messages render from: the platform's defaults and the ones the environment overrides",usage:"[--channel email|sms|whatsapp]",flags:{channel:{type:"string",value:"channel",description:"only this channel's (default: all three)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.channel===void 0?Co:[va(e)],s=await Promise.all(n.map(i=>h(e,t,"GET",`/notify/templates/${i}`))),a=n.flatMap((i,r)=>s[r].templates.map(o=>({channel:i,...o})));e.out.result({templates:a},()=>e.out.table(a,[{header:"channel",value:i=>i.channel},{header:"slug",value:i=>i.slug},{header:"locale",value:i=>i.locale},{header:"yours",value:i=>"customized"in i?i.customized?"yes":"default":"yes"},{header:"subject / text / template",value:i=>"subject"in i?i.subject:"body"in i?i.body.split(`
|
|
30
|
+
`),"added"}var qp={name:"run",summary:"run a command with the environment's address and your own key in its environment, nothing written to disk",usage:"[--secrets development|production] -- <command> [args\u2026]",details:["palbase run -- bun dev, palbase run -- npm test: the app reads the project's secrets at boot (PALBASE_SECRETS)."],args:{min:1,max:1e3},flags:{secrets:Ti},scope:"environment",async run(e){let t=await b(e),n=Ai(e);(t.env_slug===Be||n==="production")&&await v(e,t,`run ${e.args[0]} with a key of ${t.env_slug}`,Ri(t,n));let s=await Pi(e,t);e.out.note(`${N(t)}: ${e.args.join(" ")}`);let a=await e.io.run(e.args[0],e.args.slice(1),{cwd:e.io.cwd,env:{PALBASE_URL:s.url,PALBASE_PROJECT_ID:s.projectId,PALBASE_SECRET_KEY:s.key.key,PALBASE_SECRETS:n},inherit:!0});if(a.code===127)throw new f("not_found",`${e.args[0]}: no such program`);return a.code}};var p0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,Kp=20;async function u0(e,t,n,s){if(n.length===0)return{};let a=n.map(r=>({email:`${r.toLowerCase()}.${s}@test.invalid`,password:Gp(18).toString("base64url")})),i=await h(e,t,"POST","/admin/test-users",{users:a,with_tokens:!0},j()).catch(r=>{throw r instanceof E&&r.code==="token_out_of_scope"&&Jt(e.io)?new f("token_out_of_scope",`PALBASE_TOKEN, an environment's token, may not make test users: its scopes do not name auth:test-users (${r.message})`,{hint:"a token's scopes are fixed when it is minted, and a person's yes does not widen them: mint one with --scope auth:test-users (palbase env:tokens:create, an admin)"}):r});if(i.users.length!==n.length)throw new f("unexpected_answer",`auth made ${i.users.length} test users of the ${n.length} asked for`);return Object.fromEntries(n.map((r,o)=>{let l=i.users[o];return[r,{id:l.user_id,email:l.email??a[o].email,password:a[o].password,...l.access_token?{accessToken:l.access_token}:{}}]}))}async function c0(e,t,n){let s=[];for(let a of Object.values(n))try{await h(e,t,"DELETE",`/admin/test-users/${k(a.id)}`)}catch(i){i.status!==404&&s.push(a.id)}return s}async function h0(e,t,n){if(e.out.note(`${t}'s test command, as the platform holds it: ${m0(n)}`),e.global.yes)return;if(!e.interactive)throw new f("confirmation_needed",`palbase test would run ${t}'s test command on this computer \u2014 a setting on the platform, not code of this checkout`,{hint:"read it above, then confirm with -y"});let s=(await e.io.prompt("Run it on this computer? [y/N] ")).trim().toLowerCase();if(s!=="y"&&s!=="yes")throw new f("cancelled","nothing was run")}function m0(e){return A(e).replace(/\p{Cf}/gu,t=>`\\u${t.codePointAt(0).toString(16).padStart(4,"0")}`)}function Ro(e){let t=[...new Set(oe(e)??[])];for(let s of t)if(!p0.test(s))throw m(`${JSON.stringify(s)} is no test user's name: letters, digits, _ and -, 64 at most`);let n=new Map;for(let s of t){let a=n.get(s.toLowerCase());if(a!==void 0)throw m(`${JSON.stringify(a)} and ${JSON.stringify(s)} are one test user (its address is in lower case): name it once`);n.set(s.toLowerCase(),s)}if(t.length>Kp)throw m(`--users names ${t.length}; a run makes ${Kp} at most`);return t}var Up={SIGHUP:1,SIGINT:2,SIGTERM:15};function g0(){let e,t=Object.keys(Up).map(n=>[n,()=>{e??=n}]);for(let[n,s]of t)process.on(n,s);return{got:()=>e,release:()=>{for(let[n,s]of t)process.off(n,s)}}}var Bp={name:"test",summary:"run the backend's tests as the platform does before a build goes out: test users made for the run and deleted after, PALBASE_TEST_* in the command's environment",usage:"[--machine <name>] [--users <names>] [--base-url <url>] [--secrets development|production] [-- <command> [args\u2026]]",details:["palbase test --machine backend --base-url http://localhost:8080: the machine's own test command and test users, as the platform runs them before each build of it rolls out.",'palbase test --users alice,bob --base-url http://localhost:8080 -- bun test: api.signInAs("alice") acts as a test user made for this run.',"The command gets what palbase run gives it, and PALBASE_TEST_AUTH_URL (the environment's address), PALBASE_TEST_IDENTITIES (the run's test users, each with its token) and, with --base-url, PALBASE_TEST_BASE_URL (where the app under test answers; without it HTTP tests skip themselves).","The test users are deleted when the command ends, however it ends \u2014 Ctrl-C too: the command is stopped, they are deleted, and palbase test ends as the signal would have.","With an environment's token (PALBASE_TOKEN, scope auth:test-users) the test users are made and deleted with the token, and no key is made: the command gets no PALBASE_SECRET_KEY, so test the app where it is deployed \u2014 palbase test --users alice,bob --base-url https://<ref>.app.palbase.studio -- bun test ./tests (the machine named backend; https://<name>-<ref>.app.palbase.studio for another, as machines:list shows)."],args:{min:0,max:1e3},flags:{machine:{type:"string",value:"name",description:"a machine whose test command (when no command is given) and test users (when --users is not) are run"},users:{type:"string",value:"names",description:"the test users to make for the run, comma-separated"},"base-url":{type:"string",value:"url",description:"where the app under test answers (http://localhost:8080)"},secrets:Ti},scope:"environment",async run(e){let t=Ro(e.flags.users),n=e.flags["base-url"];if(n!==void 0&&!/^https?:\/\/[^\s/]+/.test(n))throw m(`--base-url is an http(s) address, not ${JSON.stringify(n)}`);let s=e.flags.machine;if(e.args.length===0&&s===void 0)throw m("which tests? give their command after --, or --machine <name> to run its own","palbase test -- bun test");let a=await b(e),i=e.args.length>0?{cmd:e.args[0],args:e.args.slice(1)}:void 0;if(s!==void 0){let w=await h(e,a,"GET",`/machines/${k(s)}`);if(e.flags.users===void 0&&(t=w.test_users??[]),i===void 0){if(!w.test_command)throw m(`the machine ${s} runs no tests`,`give their command after --, or set it: palbase machines:update ${s} --test-command "bun test"`);await h0(e,s,w.test_command),i={cmd:"sh",args:["-c",w.test_command]}}}let r=i,o=Jt(e.io);if(o&&e.flags.secrets!==void 0)throw m("--secrets names the secrets an app started here reads with your key, and an environment's token makes no key: leave it out");let l=Ai(e);o?(a.env_slug===Be&&t.length>0&&await v(e,a,`make ${t.length} test user(s) there for ${r.cmd}, deleted when it ends`),e.out.note(`PALBASE_TOKEN is an environment's token: no key is made, and ${r.cmd} gets no PALBASE_SECRET_KEY \u2014 ${n!==void 0?`it tests the app at ${n}`:"with no --base-url the HTTP tests skip themselves: give the deployed machine's address (palbase machines:list shows it)"}`)):(a.env_slug===Be||l==="production")&&await v(e,a,`run ${r.cmd} with a key of ${a.env_slug}${t.length?` and ${t.length} test user(s) made there`:""}`,Ri(a,l));let d=o?{...await Ao(e,a),key:void 0}:await Pi(e,a),p=Gp(4).toString("hex"),u=t.length>0?g0():void 0,g=0;try{let w=await u0(e,a,t,p);t.length>0&&e.out.note(`${N(a)}: test users ${t.join(", ")} made for this run (${p})`);try{if(u?.got()===void 0){let _=await e.io.run(r.cmd,r.args,{cwd:e.io.cwd,env:{PALBASE_URL:d.url,PALBASE_PROJECT_ID:d.projectId,...d.key?{PALBASE_SECRET_KEY:d.key.key,PALBASE_SECRETS:l}:{},PALBASE_TEST_AUTH_URL:d.url,PALBASE_TEST_IDENTITIES:JSON.stringify(w),...n!==void 0?{PALBASE_TEST_BASE_URL:n}:{}},inherit:!0});if(_.code===127)throw new f("not_found",`${r.cmd}: no such program`);g=_.code}}finally{if(t.length>0){let _=await c0(e,a,w);_.length>0?e.out.warn(`test users not deleted: ${_.join(", ")} \u2014 palbase auth:test-users:delete <id> deletes one`):e.out.note(`the run's ${t.length} test user(s) deleted`)}}}finally{u?.release()}let y=u?.got();return y===void 0?g:128+Up[y]}};var zp={name:"auth:settings:get",summary:"the environment's auth settings: passwords, email confirmation, sessions, tokens, passkeys, risk",scope:"environment",async run(e){let t=await b(e),{body:n}=await Ke(e,t,"/admin/auth-settings");e.out.result(n,()=>gs(e,n))}},Wp={name:"auth:settings:set",summary:'change auth settings: key=value, a value read as JSON when it is JSON (12, true, ["https://\u2026"])',usage:"<key=value>\u2026",details:[`Text needs no quotes (site_url=https://shop.example); quote text that reads as JSON: from_name='"123"'.`,'app_name=Koz names your app in its invitations ("Koz invited you"); app_name= clears it.',"The change is made on the revision read: one made beside it in the meantime (Studio, another terminal) is refused, not overwritten.","palbase auth:settings:get lists the keys."],args:{min:1,max:50},scope:"environment",async run(e){let t=await b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/admin/auth-settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the auth settings",s);await v(e,t,`set the auth settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(r.map(l=>[l,i[l]])),je(a));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},_s=["google","apple","github","microsoft"],f0={google:"web_client_id",apple:"services_id",microsoft:"application_id",github:"oauth_client_id"},y0=new Set(["organizations","consumers","common"]),Fp={name:"auth:providers:list",summary:"the sign-in methods: email, phone and the social providers, whether each is on, their clients and stored secrets (by name)",scope:"environment",async run(e){let t=await b(e),[n,s]=await Promise.all([h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth")]),a=[...n.providers.map(i=>({provider:i.id,on:i.enabled,detail:i.settings?`codes by ${i.settings.sender??"sms"}, ${i.settings.otp_ttl_seconds}s, ${i.settings.otp_max_attempts} tries, sign-up ${i.settings.allow_signups?"on":"off"}`:"",secrets:""})),..._s.map(i=>{let r=s.providers[i]??{enabled:!1,browser_clients:[],native_clients:[]},o=[...r.browser_clients.map(l=>`${l.key} (${l.platform})`),...r.native_clients.map(l=>`${l.key} (${l.platform}, native)`)];return{provider:i,on:r.enabled,detail:o.length===0?"no client":o.join(", "),secrets:s.credentials.filter(l=>l.provider===i).map(l=>`${l.key} ${l.configured?"set":"not set"}`).join(", ")}})];e.out.result({providers:n.providers,social:s.providers,credentials:s.credentials},()=>e.out.table(a,[{header:"provider",value:i=>i.provider},{header:"on",value:i=>i.on?"yes":"no"},{header:"clients / settings",value:i=>i.detail},{header:"secrets",value:i=>i.secrets}]))}},Jp={name:"auth:providers:set",summary:"turn a sign-in provider on or off and set it up: its client, its secret (from stdin), phone codes",usage:"<provider> [--enable|--disable] [setting=value\u2026] [--client-id <id>] [--secret-stdin] \u2026",details:["email is always on. phone: --enable/--disable, and its code settings as setting=value (allow_signups, otp_ttl_seconds, otp_max_attempts, sender, sms_second_factor).","google, apple, github, microsoft: --client-id sets the browser client --client names (default web), made when the provider has none of that name.","--secret-stdin reads the client's secret from stdin (Apple: the .p8 signing key, with --team-id and --key-id) and keeps it under --credential (default: the provider's name). It is never taken from the command line and never printed.",`--clients-file replaces the provider's clients with the file's {"browser_clients": [\u2026], "native_clients": [\u2026]} (native apps, several clients).`],args:{min:1,max:20},flags:{...pa,client:{type:"string",value:"key",description:"the browser client --client-id, --return-uri and the secret go to (default web)"},"client-id":{type:"string",value:"id",description:"the provider's id of your app (Google web client id, Apple services id, Microsoft application id, GitHub client id)"},"return-uri":{type:"string",multiple:!0,value:"url",description:"where your app is sent back after sign-in (repeat it; replaces the list)"},application:{type:"string",value:"key",description:"the application the client is for (default app)"},variant:{type:"string",value:"name",description:"the build variant the client is for (default release)"},directory:{type:"string",value:"tenant",description:"microsoft: a tenant id, organizations, consumers or common (default common)"},"secret-stdin":{type:"boolean",description:"read the client's secret (Apple: the .p8 key) from stdin"},credential:{type:"string",value:"key",description:"the name the secret is kept under (default: the provider's)"},"team-id":{type:"string",value:"id",description:"apple: your team's id, with --secret-stdin"},"key-id":{type:"string",value:"id",description:"apple: the signing key's id, with --secret-stdin"},"clients-file":{type:"string",value:"path",description:"replace the provider's clients with the file's (JSON)"}},scope:"environment",async run(e){let t=e.args[0],n=await b(e);if(t==="email")throw new f("always_on","email sign-in is always on, and has no settings of its own here",{hint:"its policy is in palbase auth:settings:set"});if(t==="phone")return b0(e,n,e.args.slice(1));if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: email, phone, ${_s.join(", ")}`);if(e.args.length>1)throw m(`${t} takes flags, not settings: palbase help auth:providers:set`);await v0(e,n,t)}};async function b0(e,t,n){let s=fs(e),a=cn(n);if(s===void 0&&a.length===0)throw m("nothing to change: --enable, --disable or setting=value","palbase help auth:providers:set");let i=await h(e,t,"GET","/admin/providers/phone/settings"),r=hn(i,a),o=Vt(i,r);if(s===void 0&&o.length===0)return Fe(e,"the phone settings",i);await v(e,t,`phone sign-in: ${[...s===void 0?[]:[s?"turn it on":"turn it off"],...o.map(p=>`set ${p}`)].join(", ")}`);let l=o.length>0?await h(e,t,"PUT","/admin/providers/phone/settings",r):i,d=s===void 0?void 0:await h(e,t,"POST","/admin/providers/phone",{enabled:s});e.out.result({provider:"phone",...d?{enabled:d.enabled}:{},settings:l},()=>{d&&e.out.line(`phone sign-in is ${d.enabled?"on":"off"}.`);for(let p of o)e.out.line(`${p}: ${Oe(i[p])} \u2192 ${Oe(l[p])}`)})}function w0(e){if(y0.has(e))return{mode:e};if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return{mode:"tenant",tenant_id:e};throw m("--directory is a tenant id, organizations, consumers or common")}async function v0(e,t,n){let s=e.flags,a=fs(e),i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=i.body.providers[n]??{enabled:!1,browser_clients:[],native_clients:[]},l={},d=[],p=s.credential??n,u;if(s["secret-stdin"]===!0){if(n==="apple"&&(s["team-id"]===void 0||s["key-id"]===void 0))throw m("Apple's signing key goes with --team-id and --key-id");u=await Me(e,n==="apple"?"Apple's .p8 signing key":`${n}'s client secret`),d.push(`keep its secret as ${p}`)}let g=["client","client-id","return-uri","application","variant","directory","credential"].filter(P=>s[P]!==void 0);if(s["clients-file"]!==void 0){if(g.length>0)throw m(`--clients-file and --${g[0]} are one or the other`);let P=me(await ke(e,s["clients-file"],"the clients"),"the clients file");if(typeof P!="object"||P===null||P.browser_clients===void 0&&P.native_clients===void 0)throw m('the clients file is {"browser_clients": [\u2026], "native_clients": [\u2026]}');l.browser_clients=P.browser_clients??o.browser_clients,l.native_clients=P.native_clients??o.native_clients,d.push(`set its clients from ${s["clients-file"]}`)}else if(g.length>0||u!==void 0){let P=s.client??"web",S=[...o.browser_clients],$=S.findIndex(T=>T.key===P),R=u!==void 0&&g.every(T=>T==="credential");if($>=0||!R){let T=$>=0?{...S[$]}:{key:P,enabled:!0,application_key:"app",platform:"web",variant:"release",return_uris:[]},D=f0[n];if(s["client-id"]!==void 0&&(T[D]=s["client-id"]),!T[D])throw m(`the ${n} client ${P} is new: give it --client-id`);if(s["return-uri"]!==void 0&&(T.return_uris=s["return-uri"]),s.application!==void 0&&(T.application_key=s.application),s.variant!==void 0&&(T.variant=s.variant),n==="microsoft")T.directory=s.directory!==void 0?w0(s.directory):T.directory??{mode:"common"};else if(s.directory!==void 0)throw m("--directory is a Microsoft client's");(u!==void 0||s.credential!==void 0||!T.credential_ref)&&(T.credential_ref=p),S[$>=0?$:S.length]=T,l.browser_clients=S,d.push(`${$>=0?"change":"add"} its browser client ${P}`)}}if(a!==void 0&&(l.enabled=a,d.push(a?"turn it on":"turn it off")),d.length===0)throw m("nothing to change: give a flag","palbase help auth:providers:set");await v(e,t,`${n} sign-in: ${d.join(", ")}`);let y=i.body;if(u!==void 0){let P=n==="apple"?{provider:n,kind:"apple_signing_key",team_id:s["team-id"],key_id:s["key-id"],private_key:u}:{provider:n,kind:"oauth_client_secret",client_secret:u};r=(await qe(e,t,"PUT",`/admin/social-auth/credentials/${k(p)}`,P,je(r))).etag??r}Object.keys(l).length>0?y=await h(e,t,"PATCH",`/admin/social-auth/providers/${k(n)}`,l,je(r)):y=await h(e,t,"GET","/admin/social-auth");let w=y.providers[n],_=y.credentials.filter(P=>P.provider===n);e.out.result({provider:n,...w,credentials:_},()=>{e.out.line(`${n} sign-in is ${w.enabled?"on":"off"}: ${w.browser_clients.length} browser client(s), ${w.native_clients.length} native.`);for(let P of _)e.out.line(` secret ${P.key}: ${P.configured?"set":"not set"}`)})}var Vp={name:"auth:providers:secret:delete",summary:"delete a sign-in provider's stored secret by its name; one a client still uses is refused",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e),{body:s,etag:a}=await Ke(e,n,"/admin/social-auth");if(!s.credentials.some(i=>i.key===t))throw m(`the environment holds no provider secret ${JSON.stringify(t)}`,"palbase auth:providers:list names them");await v(e,n,`delete the provider secret ${t}`),await h(e,n,"DELETE",`/admin/social-auth/credentials/${k(t)}`,void 0,je(a)),e.out.result({deleted:t},()=>e.out.line(`Deleted the provider secret ${t}.`))}},Hp={name:"auth:providers:disable",summary:"turn a sign-in provider off (phone, google, apple, github, microsoft); its clients and secrets stay",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);if(t==="email")throw new f("always_on","email sign-in cannot be turned off");if(t==="phone"){await v(e,n,"turn phone sign-in off");let i=await h(e,n,"POST","/admin/providers/phone",{enabled:!1});e.out.result(i,()=>e.out.line("phone sign-in is off."));return}if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: phone, ${_s.join(", ")}`);let{etag:s}=await Ke(e,n,"/admin/social-auth");await v(e,n,`turn ${t} sign-in off`);let a=await h(e,n,"PATCH",`/admin/social-auth/providers/${k(t)}`,{enabled:!1},je(s));e.out.result({provider:t,...a.providers[t]},()=>e.out.line(`${t} sign-in is off; its clients and secrets stay.`))}},Yp={name:"auth:roles:list",summary:"the environment's roles: their permissions, which one new users get, how many users hold each",scope:"environment",async run(e){let t=await b(e),{roles:n}=await h(e,t,"GET","/admin/roles");e.out.result({roles:n},()=>{n.length===0&&e.out.line("No role yet: palbase auth:roles:set <name> --permissions \u2026 makes one."),e.out.table(n,[{header:"role",value:s=>`${s.name}${s.is_default?" (default)":""}`},{header:"permissions",value:s=>s.permissions.join(", ")},{header:"users",value:s=>String(s.user_count??0)},{header:"description",value:s=>s.description}])})}},Xp={name:"auth:roles:set",summary:"make a role, or change one: its permissions (the list is replaced), description, whether new users get it",usage:"<name> [--permissions <a.b,c.d>] [--description <text>] [--default yes|no]",args:{min:1,max:1},flags:{permissions:{type:"string",multiple:!0,value:"list",description:'resource.action permissions, comma-separated or repeated; replaces the list ("" for none)'},description:{type:"string",value:"text",description:"what the role is for"},default:{type:"string",value:"yes|no",description:"whether new users get it (one role at most)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0],{roles:s}=await h(e,t,"GET","/admin/roles"),a=s.find(p=>p.name===n),i=oe(e.flags.permissions),r=mn(e.flags.default,"default");if(a&&i===void 0&&e.flags.description===void 0&&r===void 0)throw m("nothing to change: give a flag","palbase help auth:roles:set");let o={permissions:i??a?.permissions??[],description:e.flags.description??a?.description??"",is_default:r??a?.is_default??!1};await v(e,t,`${a?"change":"make"} the role ${n}${a?.user_count?` (${a.user_count} users hold it)`:""}`);let l=await h(e,t,"PUT",`/admin/roles/${k(n)}`,o),d=l.roles.find(p=>p.name===n);e.out.result(d??l,()=>e.out.line(`${a?"Changed":"Made"} the role ${n}: ${(d?.permissions??o.permissions).join(", ")||"no permission"}${d?.is_default?", given to new users":""}.`))}},Zp={name:"auth:roles:delete",summary:"delete a role; one users hold is deleted only with --force, and is taken from them",usage:"<name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete it although users hold it"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];await v(e,t,`delete the role ${n}${e.flags.force===!0?", taking it from the users who hold it":""}`),await h(e,t,"DELETE",`/admin/roles/${k(n)}${e.flags.force===!0?"?confirm=true":""}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the role ${n}.`))}},Qp={event:{type:"string",value:"event",description:"before.user.create, before.login, before.token.issue, \u2026 (the module lists them)"},url:{type:"string",value:"url",description:"the https endpoint auth calls and waits for"},"failure-mode":{type:"string",value:"deny|allow",description:"what auth does when the hook does not answer in time (default deny)"},timeout:{type:"string",value:"ms",description:"how long auth waits, 100\u20135000 ms (default 5000)"}},eu={name:"auth:hooks:list",summary:"the blocking hooks: what auth calls, and waits for, before a sign-up, a sign-in, a token",scope:"environment",async run(e){let t=await b(e),{hooks:n}=await h(e,t,"GET","/admin/hooks");e.out.result({hooks:n},()=>{n.length===0&&e.out.line("No hook: palbase auth:hooks:create --event \u2026 --url \u2026 registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"event",value:s=>s.event},{header:"url",value:s=>s.url},{header:"on failure",value:s=>s.failure_mode},{header:"timeout",value:s=>`${s.timeout_ms} ms`},{header:"on",value:s=>s.enabled?"yes":"no"}])})}},tu={name:"auth:hooks:create",summary:"register a blocking hook; its signing secret is printed this once",usage:"--event <event> --url <url> [--failure-mode deny|allow] [--timeout <ms>] [--disable]",flags:{...Qp,disable:{type:"boolean",description:"register it turned off"}},scope:"environment",async run(e){let t=await b(e);if(e.flags.event===void 0||e.flags.url===void 0)throw m("a hook needs --event and --url");let n=uo({event:e.flags.event,url:e.flags.url,failure_mode:e.flags["failure-mode"],timeout_ms:se(e.flags.timeout,"timeout"),...e.flags.disable===!0?{enabled:!1}:{}});await v(e,t,`register a hook on ${String(n.event)} calling ${String(n.url)}`);let s=await h(e,t,"POST","/admin/hooks",n,j());e.out.result(s,()=>{e.out.line(`Registered ${s.id}: ${s.event} \u2192 ${s.url}.`),s.secret&&e.out.line(`signing secret (shown this once): ${s.secret}`)})}},nu={name:"auth:hooks:update",summary:"change a blocking hook: its event, endpoint, timeout, failure mode, on or off (its secret stays)",usage:"<id> [--event \u2026] [--url \u2026] [--failure-mode \u2026] [--timeout \u2026] [--enable|--disable]",args:{min:1,max:1},flags:{...Qp,...pa},scope:"environment",async run(e){let t=await b(e),{hooks:n}=await h(e,t,"GET","/admin/hooks"),s=n.find(o=>o.id===e.args[0]);if(!s)throw new f("no_such_hook",`no hook ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:hooks:list shows them"});let a={event:e.flags.event??s.event,url:e.flags.url??s.url,failure_mode:e.flags["failure-mode"]??s.failure_mode,timeout_ms:se(e.flags.timeout,"timeout")??s.timeout_ms,enabled:fs(e)??s.enabled},i=Vt(_0(s),a);if(i.length===0)throw m("nothing to change: give a flag","palbase help auth:hooks:update");await v(e,t,`change the hook ${s.id}: ${i.join(", ")}`);let r=await h(e,t,"PUT",`/admin/hooks/${k(s.id)}`,a);e.out.result(r,()=>e.out.line(`${r.id}: ${r.event} \u2192 ${r.url}, ${r.failure_mode} on failure, ${r.timeout_ms} ms, ${r.enabled?"on":"off"}.`))}};function _0(e){return{event:e.event,url:e.url,failure_mode:e.failure_mode,timeout_ms:e.timeout_ms,enabled:e.enabled}}var su={name:"auth:hooks:delete",summary:"delete a blocking hook; auth stops calling it",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`delete the hook ${e.args[0]}`),await h(e,t,"DELETE",`/admin/hooks/${k(e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the hook ${e.args[0]}.`))}},au={name:"auth:oauth-clients:list",summary:"the OAuth clients of the environment's OpenID provider (apps that sign in with your users' accounts)",scope:"environment",async run(e){let t=await b(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients");e.out.result({clients:n},()=>{n.length===0&&e.out.line("No OAuth client: palbase auth:oauth-clients:create <name> registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"client id",value:s=>s.client_id},{header:"name",value:s=>s.client_name},{header:"kind",value:s=>s.is_public?"public":s.token_endpoint_auth_method},{header:"grants",value:s=>s.grant_types.join(", ")},{header:"redirect uris",value:s=>s.redirect_uris.join(", ")}])})}},iu={name:"auth:oauth-clients:create",summary:"register an OAuth client; a confidential client's secret is printed this once",usage:"<name> [--public] [--redirect-uri <url>\u2026] [--grant <type>\u2026] [--scope <scope>\u2026] [--client-id <id>]",args:{min:1,max:1},flags:{public:{type:"boolean",description:"a public client (a CLI, a mobile app): it has no secret"},"redirect-uri":{type:"string",multiple:!0,value:"url",description:"where it may send the browser back (repeat it)"},grant:{type:"string",multiple:!0,value:"type",description:"authorization_code (default), refresh_token, client_credentials, urn:ietf:params:oauth:grant-type:device_code"},scope:{type:"string",multiple:!0,value:"scope",description:"what it may ask for (default openid, profile, email)"},"client-id":{type:"string",value:"id",description:"a client_id to use as it is (default: a random one)"}},scope:"environment",async run(e){let t=await b(e),n=uo({client_name:e.args[0],client_id:e.flags["client-id"],is_public:e.flags.public===!0?!0:void 0,redirect_uris:e.flags["redirect-uri"],grant_types:oe(e.flags.grant),scopes:oe(e.flags.scope)});await v(e,t,`register the OAuth client ${e.args[0]}`);let s=await h(e,t,"POST","/admin/oauth-clients",n,j());e.out.result(s,()=>{e.out.line(`Registered ${s.client_name}: client_id ${s.client_id} (${s.id}).`),s.client_secret&&e.out.line(`client secret (shown this once): ${s.client_secret}`)})}},ru={name:"auth:oauth-clients:delete",summary:"delete an OAuth client (by its id or its client_id)",usage:"<id|client-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients"),s=n.find(a=>a.id===e.args[0]||a.client_id===e.args[0]);if(!s)throw new f("no_such_client",`no OAuth client ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:oauth-clients:list shows them"});await v(e,t,`delete the OAuth client ${s.client_name} (${s.client_id})`),await h(e,t,"DELETE",`/admin/oauth-clients/${k(s.id)}`),e.out.result({deleted:s.id},()=>e.out.line(`Deleted the OAuth client ${s.client_name}.`))}};function k0(e){return{...e.client_id.startsWith("oidc_")?{}:{client_id:e.client_id},is_public:e.is_public,grant_types:[...e.grant_types].sort(),redirect_uris:e.redirect_uris,post_logout_redirect_uris:e.post_logout_redirect_uris,response_types:e.response_types,scopes:e.scopes,token_endpoint_auth_method:e.token_endpoint_auth_method,id_token_lifetime_secs:e.id_token_lifetime_secs,dpop_bound_access_tokens:e.dpop_bound_access_tokens,...e.jwks?{jwks:e.jwks}:{}}}var ou={name:"auth",async read(e,t){let[n,s,a,i,r,o]=await Promise.all([h(e,t,"GET","/admin/auth-settings"),h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth"),h(e,t,"GET","/admin/roles"),h(e,t,"GET","/admin/hooks"),h(e,t,"GET","/admin/oauth-clients")]),l={};for(let[p,u]of Object.entries(n))l[`settings.${p}`]=u;let d=s.providers.find(p=>p.id==="phone");d&&(l["phone.enabled"]=d.enabled,d.settings&&(l["phone.settings"]=d.settings));for(let p of _s){let u=a.providers[p];u&&(l[`social.${p}`]={enabled:u.enabled,browser_clients:u.browser_clients,native_clients:u.native_clients})}for(let p of a.credentials)l[`secrets.${p.key}`]={provider:p.provider,kind:p.kind,value:p.configured?"set":"not set"};for(let p of i.roles)l[`roles.${p.name}`]={description:p.description,is_default:p.is_default,permissions:[...p.permissions].sort()};for(let p of r.hooks)l[`hooks.${p.event} ${p.url}`]={failure_mode:p.failure_mode,timeout_ms:p.timeout_ms,enabled:p.enabled};for(let p of o.clients)l[`oauth_clients.${p.client_name}`]=k0(p);return l},async copy(e,t,n,s){await S0(e,t,fe(n,"settings."),s);for(let i of fe(n,"phone."))i.name==="enabled"&&await Q(s,`turn phone sign-in ${i.from?"on":"off"}`,async()=>{await h(e,t,"POST","/admin/providers/phone",{enabled:i.from===!0})}),i.name==="settings"&&i.from!==void 0&&await Q(s,"set the phone code settings",async()=>{await h(e,t,"PUT","/admin/providers/phone/settings",i.from)});await $0(e,t,fe(n,"social."),fe(n,"secrets."),s);let a=fe(n,"roles.").sort((i,r)=>+(i.from?.is_default===!0)-+(r.from?.is_default===!0));for(let i of a)i.from===void 0?await Q(s,`delete the role ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/roles/${k(i.name)}`)}):await Q(s,`set the role ${i.name}`,async()=>{await h(e,t,"PUT",`/admin/roles/${k(i.name)}`,i.from)});await P0(e,t,fe(n,"hooks."),s),await A0(e,t,fe(n,"oauth_clients."),s)}};async function S0(e,t,n,s){let a=n.filter(r=>r.from!==void 0);for(let r of n.filter(o=>o.from===void 0))s.left(`auth settings ${r.name}: set in the target only, and a setting is not taken away (set it with auth:settings:set)`);if(a.length===0)return;let{etag:i}=await Ke(e,t,"/admin/auth-settings");await Q(s,`set the auth settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(a.map(r=>[r.name,r.from])),je(i))})}async function $0(e,t,n,s,a){for(let l of s){let d=l.from;d===void 0?a.left(`secret ${l.name}: only in the target, left as it is (delete it with palbase auth:providers:secret:delete ${l.name})`):a.left(`secret ${l.name} (${d.provider}): secrets are not copied \u2014 set it with palbase auth:providers:set ${d.provider} --secret-stdin --credential ${l.name}`)}if(n.length===0)return;let i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=new Set(i.body.credentials.filter(l=>l.configured).map(l=>l.key));for(let l of n){let d=l.from,p=[...new Set(d.browser_clients.map(u=>u.credential_ref).filter(u=>typeof u=="string"&&!o.has(u)))];if(p.length>0){a.left(`${l.name} sign-in: its clients use the secret ${p.join(", ")}, which the target does not hold \u2014 set it first (auth:providers:set ${l.name} --secret-stdin --credential ${p[0]})`);continue}await Q(a,`set ${l.name} sign-in (${d.enabled?"on":"off"}, ${d.browser_clients.length+d.native_clients.length} client(s))`,async()=>{r=(await qe(e,t,"PATCH",`/admin/social-auth/providers/${k(l.name)}`,d,je(r))).etag??r})}}async function P0(e,t,n,s){if(n.length===0)return;let{hooks:a}=await h(e,t,"GET","/admin/hooks");for(let i of n){let r=i.name.indexOf(" "),o=i.name.slice(0,r),l=i.name.slice(r+1),d=a.find(p=>p.event===o&&p.url===l);if(i.from===void 0)d&&await Q(s,`delete the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"DELETE",`/admin/hooks/${k(d.id)}`)});else if(d)await Q(s,`change the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"PUT",`/admin/hooks/${k(d.id)}`,{event:o,url:l,...i.from})});else{let p;await Q(s,`register the hook ${o} \u2192 ${l}`,async()=>{p=(await h(e,t,"POST","/admin/hooks",{event:o,url:l,...i.from},j())).secret}),p&&s.shown(`the hook ${o} \u2192 ${l} signs with`,p)}}}async function A0(e,t,n,s){if(n.length===0)return;let{clients:a}=await h(e,t,"GET","/admin/oauth-clients");for(let i of n){let r=a.find(l=>l.client_name===i.name),o=i.from;if(o===void 0)r&&await Q(s,`delete the OAuth client ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/oauth-clients/${k(r.id)}`)});else if(r)if(!We(o.is_public,r.is_public)||o.client_id!==void 0&&o.client_id!==r.client_id)s.left(`OAuth client ${i.name}: its client_id or kind (public or not) differs, which a client cannot change \u2014 delete it in the target and run the copy again`);else{let{client_id:l,is_public:d,...p}=o;await Q(s,`change the OAuth client ${i.name}`,async()=>{await h(e,t,"PATCH",`/admin/oauth-clients/${k(r.id)}`,p)})}else{let l;await Q(s,`register the OAuth client ${i.name}`,async()=>{l=await h(e,t,"POST","/admin/oauth-clients",{client_name:i.name,...o},j())}),l?.client_secret&&s.shown(`the OAuth client ${i.name} (${l.client_id}) has the secret`,l.client_secret)}}}var lu=["bool","number","string","object"];async function yn(e,t){return(await h(e,t,"GET","/flags/templates/capabilities")).publish_enabled}async function fn(e,t,n){let s=await Ke(e,t,"/flags/templates/draft");if(s.body.draft||!n)return{draft:s.body.draft,etag:s.etag};let a=await Ke(e,t,"/flags/templates/active"),i=await qe(e,t,"POST","/flags/templates/draft",{},je(a.etag));return{draft:i.body.draft,etag:i.etag}}function du(e){return{value_type:e.value_type,value:e.value,...e.description?{description:e.description}:{},...e.variants&&e.variants.length>0?{variants:e.variants}:{},...e.conditions&&e.conditions.length>0?{conditions:e.conditions}:{}}}function R0(e){return typeof e=="boolean"?"bool":typeof e=="number"?"number":typeof e=="string"?"string":"object"}function pu(e,t){switch(t){case"bool":if(e==="true"||e==="false")return e==="true";throw m(`a bool flag's value is true or false, not ${JSON.stringify(e)}`);case"number":{let n=Number(e);if(e.trim()===""||!Number.isFinite(n))throw m(`a number flag's value is a number, not ${JSON.stringify(e)}`);return n}case"string":{let n=jt(e);return typeof n=="string"?n:e}default:{let n=jt(e);if(typeof n!="object"||n===null)throw m(`an object flag's value is a JSON object or list, not ${JSON.stringify(e)}`);return n}}}function T0(e,t){let n=e.lastIndexOf("=>");if(n<=0)throw m(`a condition is "<expression> => <value>", not ${JSON.stringify(e)}`,`--condition "client.platform == 'ios' => true"`);return{when:e.slice(0,n).trim(),value:pu(e.slice(n+2).trim(),t)}}var uu={name:"flags:list",summary:"the environment's flags as they are live: type, default, targeting (and the draft's state when it publishes)",scope:"environment",async run(e){let t=await b(e),n=await yn(e,t),s,a,i;if(n){let[r,o]=await Promise.all([h(e,t,"GET","/flags/templates/active"),fn(e,t,!1)]);s=Object.entries(r.definitions).map(([l,d])=>({key:l,...d})),a=r.version,i=o.draft}else s=await h(e,t,"GET","/flags/system");s.sort((r,o)=>r.key<o.key?-1:1),e.out.result({publishing:n,...a?{version:a}:{},flags:s,...i?{draft:{revision:i.revision,base_version:i.base_version}}:{}},()=>{n&&e.out.line(`Version ${a} is live${i?`; a draft (from ${i.base_version}) is in progress: palbase flags:publish shows and publishes it`:""}.`),s.length===0&&e.out.line("No flag yet: palbase flags:set <key> <value> makes one."),e.out.table(s,[{header:"flag",value:r=>r.key},{header:"type",value:r=>r.value_type},{header:"value",value:r=>JSON.stringify(r.value)},{header:"targeting",value:r=>r.conditions?.length?`${r.conditions.length} condition(s)`:""},{header:"description",value:r=>r.description??""}])})}},cu={name:"flags:set",summary:"define a flag or change its default and targeting (into the draft when the environment publishes)",usage:'<key> <value> [--type bool|number|string|object] [--condition "<expression> => <value>"\u2026] [--description <text>]',details:["The value is read as the flag's type: true/false, a number, text, or a JSON object; a new flag's type is the value's unless --type says it.","--condition replaces the targeting (first match wins, 8 at most); --clear-conditions takes it away; without either it stays.","An environment that publishes takes the change into its shared draft (palbase flags:publish makes it live); one that does not, live at once."],args:{min:2,max:2},flags:{type:{type:"string",value:"type",description:"bool, number, string or object"},condition:{type:"string",multiple:!0,value:"rule",description:'"<expression> => <value>" (repeat it, in order)'},"clear-conditions":{type:"boolean",description:"take its targeting away"},variants:{type:"string",value:"list",description:"a string flag's allowed values, comma-separated"},description:{type:"string",value:"text",description:"what the flag is for"}},scope:"environment",async run(e){let t=await b(e),[n,s]=e.args,a=e.flags.type;if(a!==void 0&&!lu.includes(a))throw m(`--type is one of ${lu.join(", ")}`);if(e.flags.condition!==void 0&&e.flags["clear-conditions"]===!0)throw m("--condition and --clear-conditions are one or the other");let i=await yn(e,t),r,o;i?(o=await fn(e,t,!1),r=o.draft?.definitions[n]??(await h(e,t,"GET","/flags/templates/active")).definitions[n]):r=(await h(e,t,"GET","/flags/system")).find(u=>u.key===n);let l=a??r?.value_type??R0(jt(s)),d=e.flags["clear-conditions"]===!0?[]:e.flags.condition!==void 0?e.flags.condition.map(u=>T0(u,l)):r?.value_type===l?r.conditions??[]:[],p=du({value_type:l,value:pu(s,l),description:e.flags.description??r?.description,variants:oe(e.flags.variants)??(r?.value_type===l?r.variants:void 0),conditions:d});if(await v(e,t,i?`put ${n} = ${Oe(p.value)} into the flags draft`:`set the flag ${n} = ${Oe(p.value)}, live at once`),i){o?.draft||(o=await fn(e,t,!0));let u=await qe(e,t,"PUT",`/flags/templates/draft/parameters/${k(n)}`,p,je(o.etag));e.out.result({key:n,...p,draft:{revision:u.body.draft?.revision}},()=>e.out.line(`${n} = ${JSON.stringify(p.value)} is in the draft: palbase flags:publish makes it live.`))}else{let u=await h(e,t,"PUT",`/flags/system/${k(n)}`,p);e.out.result(u,()=>e.out.line(`${n} = ${JSON.stringify(u.value)} (${u.value_type}) is live.`))}}},hu={name:"flags:delete",summary:"delete a flag, with every user's own value of it (from the draft when the environment publishes)",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args[0],s=await yn(e,t);if(await v(e,t,s?`take ${n} out of the flags draft`:`delete the flag ${n} and every user's value of it, live at once`),s){let a=await fn(e,t,!0);await h(e,t,"DELETE",`/flags/templates/draft/parameters/${k(n)}`,void 0,je(a.etag)),e.out.result({deleted:n,draft:!0},()=>e.out.line(`${n} is out of the draft: palbase flags:publish makes it so.`))}else await h(e,t,"DELETE",`/flags/system/${k(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the flag ${n}.`))}};function To(){return new f("publishing_off","this environment's flags are not published through drafts: flags:set and flags:delete change them live",{hint:"versions, publishing and rollback are for an environment that publishes"})}function E0(e,t){t.changes.length===0&&e.out.line("The draft changes nothing.");for(let n of t.changes){let s=n.override_count>0?` (${n.override_count} users' own values)`:"";n.kind==="added"?e.out.line(` + ${n.key} = ${JSON.stringify(n.after?.value)}`):n.kind==="removed"?e.out.line(` - ${n.key}${s}`):e.out.line(` ~ ${n.key}: ${n.changed_fields.join(", ")}${n.changed_fields.includes("value")?` \u2192 ${JSON.stringify(n.after?.value)}`:""}${s}`)}for(let n of t.issues)e.out.line(` ! ${n.key?`${n.key}: `:""}${n.message}`)}async function Eo(e,t,n,s){return h(e,t,"POST","/flags/templates/publish",s===""?{}:{note:s},{...je(n),...j()})}var mu={name:"flags:publish",summary:"show the flags draft's changes against the live version, then publish it as the next version",usage:"[-m <note>]",flags:{note:{type:"string",short:"m",value:"note",description:"why: kept with the version"}},scope:"environment",async run(e){let t=await b(e);if(!await yn(e,t))throw To();if(!(await fn(e,t,!1)).draft)throw new f("no_draft","there is no draft to publish",{hint:"palbase flags:set puts a change into one"});let s=await Ke(e,t,"/flags/templates/draft/review");if(e.out.json||E0(e,s.body),!s.body.can_publish)throw new f("cannot_publish",`the draft cannot be published: ${s.body.issues.map(i=>i.message).join("; ")}`);if(s.body.changes.length===0){e.out.result({unchanged:!0,review:s.body},()=>e.out.line("Nothing to publish."));return}await v(e,t,`publish the flags draft (${s.body.changes.length} change(s)) as the version after ${s.body.active_version}`);let a=await Eo(e,t,s.etag,e.flags.note??"");e.out.result({...a,review:s.body},()=>e.out.line(a.unchanged?"The draft changed nothing; nothing was published.":`Published version ${a.template.version}.`))}},gu={name:"flags:publishing:enable",summary:"turn publishing on for the environment's flags: changes go into a shared draft, live once published \u2014 for good",details:["What is live now becomes version 1. From then on flags:set and flags:delete change the draft, flags:publish makes it live as the next version, and flags:rollback brings an earlier one back. It cannot be turned off."],scope:"environment",async run(e){let t=await b(e);if(await yn(e,t)){e.out.result({publishing:!0,changed:!1},()=>e.out.line("The environment's flags are published through drafts already."));return}await v(e,t,"turn publishing on for the flags \u2014 what is live becomes version 1, and it cannot be turned off");let n=await h(e,t,"POST","/flags/templates/activation",{});e.out.result({publishing:!0,changed:!0,version:n.version},()=>e.out.line(`Publishing is on: what was live is version ${n.version}; flags:set changes the draft, flags:publish makes it live.`))}},fu={name:"flags:versions",summary:"the published versions of the flags, newest first, and which one is live",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await b(e);if(!await yn(e,t))throw To();let n=Number(e.flags.limit??20);if(!Number.isInteger(n)||n<=0)throw m("--limit is a whole number");let s=await h(e,t,"GET",`/flags/templates/versions?limit=${n}`);e.out.result(s,()=>e.out.table(s.versions,[{header:"",value:a=>a.version===s.active_version?"*":""},{header:"version",value:a=>a.version},{header:"kind",value:a=>`${a.kind}${a.restored_from?` of ${a.restored_from}`:""}`},{header:"published",value:a=>a.created_at},{header:"by",value:a=>a.actor},{header:"note",value:a=>a.note}]))}},yu={name:"flags:rollback",summary:"make an earlier version of the flags live again (published as the next version)",usage:"<version> [-m <note>]",args:{min:1,max:1},flags:{note:{type:"string",short:"m",value:"note",description:"why (default: rollback to <version>)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];if(!await yn(e,t))throw To();if((await fn(e,t,!1)).draft)throw new f("draft_in_progress","a draft is in progress: publish it (flags:publish) before a rollback");let s=await Ke(e,t,"/flags/templates/active");await v(e,t,`make version ${n} of the flags live again (now ${s.body.version})`);let a=await qe(e,t,"POST",`/flags/templates/restore/${k(n)}`,{},je(s.etag)),i=await Eo(e,t,a.etag,e.flags.note??`rollback to ${n}`);e.out.result(i,()=>e.out.line(i.unchanged?`Version ${n} is what is live already.`:`Version ${n} is live again, as version ${i.template.version}.`))}},bu={name:"flags",async read(e,t){let n=await h(e,t,"GET","/flags/system"),s={};for(let a of n)s[`flags.${a.key}`]=du(a);return s},async copy(e,t,n,s){let a=fe(n,"flags.");if(a.length===0)return;if(!await yn(e,t)){for(let r of a)r.from===void 0?await Q(s,`delete the flag ${r.name}`,async()=>{await h(e,t,"DELETE",`/flags/system/${k(r.name)}`)}):await Q(s,`set the flag ${r.name}`,async()=>{await h(e,t,"PUT",`/flags/system/${k(r.name)}`,r.from)});return}if((await fn(e,t,!1)).draft){s.left("flags: the target has a draft in progress \u2014 publish it (flags:publish) and copy again");return}let i=(await fn(e,t,!0)).etag;for(let r of a)await Q(s,`${r.from===void 0?"take":"put"} the flag ${r.name} ${r.from===void 0?"out of":"into"} the draft`,async()=>{let o=`/flags/templates/draft/parameters/${k(r.name)}`;i=(r.from===void 0?await qe(e,t,"DELETE",o,void 0,je(i)):await qe(e,t,"PUT",o,r.from,je(i))).etag??i});await Q(s,"publish the flags draft",async()=>{await Eo(e,t,i,"config:copy")})}};var wu=["email","sms","verify","whatsapp","push"],Co=["email","sms","whatsapp"],vu={name:"notify:providers:list",summary:"the environment's own providers, by channel and the order they are tried (never their credentials)",scope:"environment",async run(e){let t=await b(e),{providers:n}=await h(e,t,"GET","/notify/providers");e.out.result({providers:n},()=>{n.length===0&&e.out.line("No provider of the environment's own: email goes through the platform's sender; texts need one (notify:providers:set)."),e.out.table(n,[{header:"channel",value:s=>s.channel},{header:"provider",value:s=>s.provider},{header:"on",value:s=>s.active?"yes":"no"},{header:"priority",value:s=>String(s.priority)},{header:"credentials",value:()=>"set"}])})}},_u={name:"notify:providers:set",summary:"bring a provider for a channel: its credentials are piped in as JSON, checked as the sender will use them, never shown",usage:"<channel> <provider> [--priority <n>] [--enable|--disable] < credentials.json",details:["email: acs {connection_string, from_email}, ses {region, access_key_id, secret_access_key, from_domain}, sendgrid {api_key, from_domain}, smtp {host, port, username, password, from_email, use_starttls}.","sms: twilio {account_sid, auth_token, from_number}, vonage {api_key, api_secret, from}, acs {connection_string, from_number}. verify: twilio_verify {account_sid, auth_token, service_sid}.","whatsapp: meta {phone_number_id, access_token, api_version, app_secret, verify_token}. push: fcm (the service account JSON), apns {private_key, team_id, key_id, bundle_id, is_production}, expo {access_token}.","The credentials are read from stdin only: never from the command line, where the shell would keep them."],args:{min:2,max:2},flags:{priority:{type:"string",value:"n",description:"lower is tried first"},...pa},scope:"environment",async run(e){let[t,n]=e.args;if(!wu.includes(t))throw m(`the channels: ${wu.join(", ")}`);let s=await b(e),a=me(await Me(e,`${n}'s credentials (JSON)`),"the credentials");if(typeof a!="object"||a===null||Array.isArray(a))throw m("the credentials are a JSON object");let i=fs(e),r=se(e.flags.priority,"priority");await v(e,s,`send ${t} through ${n}`);let o=await h(e,s,"PUT",`/notify/providers/${k(t)}/${k(n)}`,{credentials:a,...i!==void 0?{active:i}:{},...r!==void 0?{priority:r}:{}},j());e.out.result(o,()=>e.out.line(`${o.channel} goes through ${o.provider} (${o.active?"on":"off"}, priority ${o.priority}); its credentials are kept sealed.`))}},ku={name:"notify:providers:remove",summary:"forget a provider and its credentials",usage:"<channel> <provider>",args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=await b(e);await v(e,s,`forget the ${t} provider ${n} and its credentials`),await h(e,s,"DELETE",`/notify/providers/${k(t)}/${k(n)}`,void 0,j()),e.out.result({removed:{channel:t,provider:n}},()=>e.out.line(`${t} no longer goes through ${n}.`))}},Oo={channel:{type:"string",value:"channel",description:"email (default), sms or whatsapp"},locale:{type:"string",value:"locale",description:"the template's locale: en, tr, pt-BR"}};function va(e){let t=e.flags.channel??"email";if(!Co.includes(t))throw m(`--channel is one of ${Co.join(", ")}`);return t}function Mo(e,t){let n=e.flags.locale;if(n===void 0)throw m("which locale? pass --locale <locale>");return`/notify/templates/${va(e)}/${k(t)}/${k(n)}`}function C0(e,t){if(e==="sms"){let s=j0(t);return typeof s=="object"&&s!==null&&typeof s.body=="string"?{body:s.body}:{body:t.replace(/\n$/,"")}}let n=me(t,`the ${e} template`);if(e==="email"){for(let s of["subject","html_body","text_body"])if(typeof n[s]!="string")throw m(`an email template is {"subject", "html_body", "text_body"}: ${s} is missing`);return{subject:n.subject,html_body:n.html_body,text_body:n.text_body}}if(typeof n.name!="string"||typeof n.language!="string")throw m('a WhatsApp template is {"name", "language", "variables", "code_button"}: the template approved on your Meta account');return{name:n.name,language:n.language,...n.variables!==void 0?{variables:n.variables}:{},...n.code_button!==void 0?{code_button:n.code_button}:{}}}function j0(e){try{return JSON.parse(e)}catch{return e}}var Su={name:"notify:templates:list",summary:"the templates messages render from: the platform's defaults and the ones the environment overrides",usage:"[--channel email|sms|whatsapp]",flags:{channel:{type:"string",value:"channel",description:"only this channel's (default: all three)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.channel===void 0?Co:[va(e)],s=await Promise.all(n.map(i=>h(e,t,"GET",`/notify/templates/${i}`))),a=n.flatMap((i,r)=>s[r].templates.map(o=>({channel:i,...o})));e.out.result({templates:a},()=>e.out.table(a,[{header:"channel",value:i=>i.channel},{header:"slug",value:i=>i.slug},{header:"locale",value:i=>i.locale},{header:"yours",value:i=>"customized"in i?i.customized?"yes":"default":"yes"},{header:"subject / text / template",value:i=>"subject"in i?i.subject:"body"in i?i.body.split(`
|
|
31
31
|
`)[0].slice(0,60):`${i.name} (${i.language})`}]))}},$u={name:"notify:templates:get",summary:"a template as it renders now in a locale (yours, or the platform's default); --json gives the document templates:set takes",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp]",args:{min:1,max:1},flags:Oo,scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",Mo(e,e.args[0]));e.out.result(n,()=>{e.out.line(`${String(n.slug)} (${String(n.locale)}) \u2014 ${n.customized===!1?"the platform's default":"yours"}`),Array.isArray(n.variables)&&n.variables.length>0&&e.out.line(`variables: ${n.variables.join(", ")}`);for(let s of["subject","name","language"])typeof n[s]=="string"&&e.out.line(`${s}: ${String(n[s])}`);for(let s of["text_body","body","html_body"])if(typeof n[s]=="string"){e.out.line(),e.out.line(`\u2500\u2500 ${s} \u2500\u2500`);for(let a of n[s].split(`
|
|
32
32
|
`))e.out.line(a)}})}},Pu={name:"notify:templates:set",summary:"override a template in a locale, from a file or stdin (email: {subject, html_body, text_body} as JSON)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp] [--file <path>]",details:['email: {"subject", "html_body", "text_body"}; sms: the text, or {"body"}; whatsapp: {"name", "language", "variables", "code_button"} of a template approved on your Meta account.',"notify:templates:get \u2026 --json > t.json gives a document to edit and set back. Handlebars: {{name}}, {{#if}}, {{#each}}."],args:{min:1,max:1},flags:{...Oo,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=va(e),s=Mo(e,e.args[0]),a=C0(n,await ke(e,e.flags.file,"the template"));await v(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let i=await h(e,t,"PUT",s,a,j());e.out.result(i,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof i.subject=="string"?`: "${i.subject}"`:""}.`))}},Au={name:"notify:templates:delete",summary:"remove an override: the platform's default renders again (a WhatsApp mapping is forgotten)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp]",args:{min:1,max:1},flags:Oo,scope:"environment",async run(e){let t=await b(e),n=Mo(e,e.args[0]);await v(e,t,`remove the ${va(e)} template ${e.args[0]} (${e.flags.locale})`),await h(e,t,"DELETE",n,void 0,j()),e.out.result({deleted:{channel:va(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function jo(e,t){let n=[],s;do{let a=await h(e,t,"GET",`/notify/topics?limit=100${s?`&cursor=${k(s)}`:""}`);n.push(...a.topics),s=a.next_cursor}while(s);return n}var Ru={name:"notify:topics:list",summary:"the topics users follow, how many follow each, whether they follow it from the app",scope:"environment",async run(e){let t=await b(e),n=await jo(e,t);e.out.result({topics:n},()=>{n.length===0&&e.out.line("No topic: palbase notify:topics:create <name> makes one."),e.out.table(n,[{header:"topic",value:s=>s.name},{header:"followers",value:s=>String(s.subscribers)},{header:"from the app",value:s=>s.self_subscribe?"yes":"no: the project adds them"}])})}},Tu={name:"notify:topics:create",summary:"make a topic users can follow; a push to it reaches its followers",usage:"<name> [--self-subscribe yes|no]",args:{min:1,max:1},flags:{"self-subscribe":{type:"string",value:"yes|no",description:"users follow it from the app (default no: the project adds them)"}},scope:"environment",async run(e){let t=await b(e),n=mn(e.flags["self-subscribe"],"self-subscribe");await v(e,t,`make the topic ${e.args[0]}`);let s=await h(e,t,"POST","/notify/topics",{name:e.args[0],...n!==void 0?{self_subscribe:n}:{}},j());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Eu={name:"notify:topics:delete",summary:"delete a topic and who follows it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`delete the topic ${e.args[0]} and who follows it`),await h(e,t,"DELETE",`/notify/topics/${k(e.args[0])}`,void 0,j()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Cu={name:"notify:settings:get",summary:"the environment's message settings: the default locale, who email is from, where texts may go",scope:"environment",async run(e){let t=await b(e),{body:n}=await Ke(e,t,"/notify/settings");e.out.result(n,()=>gs(e,n))}},ju={name:"notify:settings:set",summary:'change message settings: key=value (from_email=\u2026, sms_countries=["+90","+44"], mx_check=true)',usage:"<key=value>\u2026",details:["The change is made on the revision read: one made beside it in the meantime is refused, not overwritten."],args:{min:1,max:20},scope:"environment",async run(e){let t=await b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/notify/settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the message settings",s);await v(e,t,`set the message settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/notify/settings",i,{...je(a),...j()});e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},O0=new Set(["sms_countries","sms_blocked_countries"]);function M0(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Ou={name:"notify",async read(e,t){let[n,s,a,i,r,o]=await Promise.all([h(e,t,"GET","/notify/settings"),h(e,t,"GET","/notify/providers"),h(e,t,"GET","/notify/templates/email"),h(e,t,"GET","/notify/templates/sms"),h(e,t,"GET","/notify/templates/whatsapp"),jo(e,t)]),l={};for(let[u,g]of Object.entries(M0(n)))l[`settings.${u}`]=g;for(let u of s.providers)l[`providers.${u.channel}/${u.provider}`]={active:u.active,priority:u.priority,credentials:"set"};let d=a.templates.filter(u=>u.customized),p=await Promise.all(d.map(u=>h(e,t,"GET",`/notify/templates/email/${k(u.slug)}/${k(u.locale)}`)));for(let u of p)l[`templates.email/${u.slug}/${u.locale}`]={subject:u.subject,html_body:u.html_body,text_body:u.text_body};for(let u of i.templates.filter(g=>g.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of r.templates)l[`templates.whatsapp/${u.slug}/${u.locale}`]={name:u.name,language:u.language,variables:u.variables,code_button:u.code_button};for(let u of o)l[`topics.${u.name}`]={self_subscribe:u.self_subscribe};return l},async copy(e,t,n,s){let a=fe(n,"settings.");if(a.length>0){let{body:o,etag:l}=await Ke(e,t,"/notify/settings"),d={...o};for(let p of a)d[p.name]=O0.has(p.name)&&Array.isArray(p.from)&&p.from.length===0?null:p.from;await Q(s,`set the message settings ${a.map(p=>p.name).join(", ")}`,async()=>{await h(e,t,"PUT","/notify/settings",d,{...je(l),...j()})})}for(let o of fe(n,"providers.")){let[l,d]=o.name.split("/");o.from===void 0?s.left(`the ${l} provider ${d}: only in the target, left as it is (it holds credentials)`):s.left(`the ${l} provider ${d}: credentials are not copied \u2014 set them with palbase notify:providers:set ${l} ${d} < credentials.json`)}for(let o of fe(n,"templates.")){let l=`/notify/templates/${o.name.split("/").map(k).join("/")}`;o.from===void 0?await Q(s,`remove the template override ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())}):await Q(s,`override the template ${o.name}`,async()=>{await h(e,t,"PUT",l,o.from,j())})}let i=fe(n,"topics."),r=i.some(o=>o.from===void 0)?new Map((await jo(e,t)).map(o=>[o.name,o.subscribers])):new Map;for(let o of i){let l=`/notify/topics/${k(o.name)}`,d=o.from?.self_subscribe;if(o.from===void 0){let p=r.get(o.name)??0;p>0?s.left(`the topic ${o.name}: only in the target, and ${p} users follow it \u2014 delete it with notify:topics:delete`):await Q(s,`delete the topic ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())})}else o.change==="only_in_from"?await Q(s,`make the topic ${o.name}`,async()=>{await h(e,t,"POST","/notify/topics",{name:o.name,self_subscribe:d},j())}):await Q(s,`set the topic ${o.name} ${d?"followed from the app":"followed by the project's adding"}`,async()=>{await h(e,t,"PATCH",l,{self_subscribe:d},j())})}}};var ks=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function I0(e){if(e.kind==="owner")return"the user it names: everything";let t=[e.publish?"publish":"",e.state_read?"read state":"",e.state_write?"write state":""].filter(n=>n!=="");return`any signed-in user: subscribe${t.length>0?`, ${t.join(", ")}`:""}`}function Io(e){return Object.fromEntries(ks.map(t=>[t,e[t]??null]))}var Mu={name:"realtime:channels:get",summary:"the channel declaration, in the order patterns are matched: who may join each, publish, read and write its state",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/realtime/channels");e.out.result(n,()=>{n.channels.length===0&&e.out.line("No channel is declared: a channel no pattern matches belongs to no one."),e.out.table(n.channels,[{header:"pattern",value:s=>s.pattern},{header:"kind",value:s=>s.kind},{header:"who",value:s=>I0(s)}])})}},Iu={name:"realtime:channels:set",summary:'replace the channel declaration with a JSON file or stdin ({"channels": [\u2026]} or the list)',usage:"[--file <path>]",details:['Each channel: {"pattern": "room:{id}", "kind": "public", "publish": true, "state_read": true, "state_write": false}, or {"pattern": "user:{uid}", "kind": "owner"}.',"realtime:channels:get --json gives the document to edit. Open sockets are decided again within a heartbeat."],flags:{file:{type:"string",value:"path",description:"the declaration (default: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=me(await ke(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw m('the declaration is {"channels": [\u2026]} or a list of channels');let a=await h(e,t,"GET","/realtime/channels");if(We(a.channels,s))return Fe(e,"the channel declaration",a);await v(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let i=await h(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(i,()=>e.out.line(i.channels.length===0?"No channel is declared now.":`Declared ${i.channels.length} channel pattern(s): ${i.channels.map(r=>r.pattern).join(", ")}.`))}},Lu={name:"realtime:limits:get",summary:"the limits the environment holds its clients to (null: the platform's), and the platform's",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...ks.map(i=>i.length));for(let i of ks)e.out.line(`${i.padEnd(a)} ${n[i]===void 0||n[i]===null?"the platform's":Oe(n[i])}${s[i]!==void 0?` (platform ${s[i]===0?"no ceiling":Oe(s[i])})`:""}`)})}},Du={name:"realtime:limits:set",summary:"change realtime limits: key=value (max_connections=500), null for the platform's",usage:"<key=value>\u2026",details:[`The keys: ${ks.join(", ")}. A value above the platform's has no effect beyond it.`],args:{min:1,max:4},scope:"environment",async run(e){let t=await b(e),n=cn(e.args);for(let o of n)if(o.path.length!==1||!ks.includes(o.path[0]))throw m(`no limit ${JSON.stringify(o.path.join("."))}`,`the limits: ${ks.join(", ")}`);let s=Io(await h(e,t,"GET","/realtime/limits")),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the realtime limits",s);await v(e,t,`set the realtime limits ${i.join(", ")}`);let r=await h(e,t,"PUT","/realtime/limits",a);e.out.result({limits:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o]??"the platform's")} \u2192 ${Oe(r[o]??"the platform's")}`)})}},xu={name:"realtime",async read(e,t){let[n,s]=await Promise.all([h(e,t,"GET","/realtime/channels"),h(e,t,"GET","/realtime/limits")]),a={channels:n.channels};for(let[i,r]of Object.entries(Io(s)))a[`limits.${i}`]=r;return a},async copy(e,t,n,s){let a=n.find(r=>r.key==="channels");a&&await Q(s,"declare the channels",async()=>{await h(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let i=fe(n,"limits.");if(i.length>0){let r=Io(await h(e,t,"GET","/realtime/limits"));for(let o of i)r[o.name]=o.from??null;await Q(s,`set the realtime limits ${i.map(o=>o.name).join(", ")}`,async()=>{await h(e,t,"PUT","/realtime/limits",r)})}}},Nu={name:"analytics:settings:get",summary:"how long analytics keeps events and console records, the share of performance samples kept, whether bodies are kept",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/analytics/settings");e.out.result(n,()=>gs(e,n))}},qu={name:"analytics:settings:set",summary:"change analytics settings: key=value (retention_days=30, perf_sample_pct=10, console_bodies=false)",usage:"<key=value>\u2026",details:["A shorter retention removes what is older within minutes."],args:{min:1,max:4},scope:"environment",async run(e){let t=await b(e),n=cn(e.args),s=await h(e,t,"GET","/analytics/settings"),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the analytics settings",s);await v(e,t,`set the analytics settings ${i.join(", ")}`);let r=await h(e,t,"PUT","/analytics/settings",a);e.out.result({settings:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o])} \u2192 ${Oe(r[o])}`)})}},Ku={name:"analytics",async read(e,t){let n=await h(e,t,"GET","/analytics/settings");return Object.fromEntries(Object.entries(n).map(([s,a])=>[`settings.${s}`,a]))},async copy(e,t,n,s){let a=fe(n,"settings.");if(a.length===0)return;let i=await h(e,t,"GET","/analytics/settings");for(let r of a)r.from!==void 0&&(i[r.name]=r.from);await Q(s,`set the analytics settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/analytics/settings",i)})}};var at="/messaging/settings",L0=/^[A-Z][A-Z0-9_]{0,127}$/,Do=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function Ss(e,t){switch(e){case"retention_days":return t===null?"off: messages are kept for good":`${String(t)} days: older messages are removed`;case"push_preview":return t===!0?"on: a push says what the message says":"off: a push says only that a message came";case"deleted_user_messages":return t==="delete"?"delete: a deleted user's messages go with them":"keep: a deleted user's messages stay, their writer anonymous";case"search_by_meaning":return t===!0?"on: messages are found by what they mean too, each embedded by the AI module (billed as AI use)":"off: messages are found by their words alone";case"event_text":return t===!0?"on: messaging.message.created says what the message says":"off: messaging.message.created says who wrote to whom, not what (the backend reads it with the secret key)";case"hook":return t?Gu(t):"none: anyone may reach anyone"}}function Gu(e){return`${A(e.url)} (waited for ${e.timeout_ms} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the app is told to try again"})`}function D0(e,t){let n=[...Do.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${Ss(a,i)}`)}function Lo(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw m(`--${t} is on or off`)}}function x0(e){if(e===void 0)return;if(e==="off")return null;let t=Number(e);if(!/^[0-9]+$/.test(String(e))||t<1||t>36500)throw m("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var N0={name:"messaging:settings:get",summary:"how the environment runs its conversations: how long messages are kept, whether a push says what one says, what becomes of a deleted user's messages, whether they are found by what they mean, whether a message's event says what it says, the hook",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",at);e.out.result(n,()=>D0(e,n))}},q0={name:"messaging:settings:set",summary:"change how the environment runs its conversations: a setting left out is left as it is",usage:"[--retention-days <days>|off] [--push-preview on|off] [--deleted-user-messages keep|delete] [--search-by-meaning on|off] [--event-text on|off]",details:["A shorter retention removes the messages older than it, in every conversation. A deleted user's messages are kept or deleted as the setting is when the user is deleted.","Deleted, what of theirs had already gone from screens (seen once, its time up, vanish mode, taken back) stays its 14 days, sealed, for reports, then goes.","Search by meaning on: the app's search({ by: 'meaning' }) finds the messages nearest what a question means, no word of it needed. Each message's text (not a system message's, one seen a limited number of times, nor one of vanish mode) is embedded by the project's embedding model through the AI module and billed as the project's AI use; the messages written before are embedded in the background (seconds to minutes), a new one is found ~5 s after it is sent. Off: no message goes to a model, and the vectors are removed.","Event text on: messaging.message.created \u2014 told to the backend's webhooks and @On handlers that name it \u2014 carries the message's text (not a vanish-mode message's, one seen a limited number of times, nor one that goes after a time). The words leave the sealed store and stay on the event stream 7 days. Off: the backend reads the message with the secret key.","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"retention-days":{type:"string",value:"days|off",description:"messages older than this many days are removed (1\u201336500); off: kept for good"},"push-preview":{type:"string",value:"on|off",description:"a push says what the message says (on), or only that one came (off)"},"deleted-user-messages":{type:"string",value:"keep|delete",description:"a deleted user's messages: kept, their writer anonymous, or deleted (what went from screens before stays its 14 days for reports)"},"search-by-meaning":{type:"string",value:"on|off",description:"messages are found by what they mean too (on: each embedded through the AI module, billed as AI use), or by their words alone (off)"},"event-text":{type:"string",value:"on|off",description:"messaging.message.created says what the message says (on), or who wrote to whom alone (off)"}},scope:"environment",async run(e){let t={},n=x0(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=Lo(e.flags["push-preview"],"push-preview");s!==void 0&&(t.push_preview=s);let a=e.flags["deleted-user-messages"];if(a!==void 0){if(a!=="keep"&&a!=="delete")throw m("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let i=Lo(e.flags["search-by-meaning"],"search-by-meaning");i!==void 0&&(t.search_by_meaning=i);let r=Lo(e.flags["event-text"],"event-text");if(r!==void 0&&(t.event_text=r),Object.keys(t).length===0)throw m("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let o=await b(e),l=await h(e,o,"GET",at),d=Do.filter(u=>u in t&&!We(l[u],t[u]));if(d.length===0)return Fe(e,"the messaging settings",l);await v(e,o,`set the messaging settings ${d.join(", ")}`);let p=await h(e,o,"PUT",at,Object.fromEntries(d.map(u=>[u,t[u]])));e.out.result({settings:p,changed:d},()=>{for(let u of d)e.out.line(`${u}: ${Ss(u,l[u])} \u2192 ${Ss(u,p[u])}`)})}},Uu={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function Bu(e){let t=e.flags["secret-to"];if(t!==void 0&&!L0.test(t))throw m(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function zu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Ss("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var K0={name:"messaging:hook:get",summary:"the hook asked whom one may reach: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await b(e),{hook:n}=await h(e,t,"GET",at);e.out.result({hook:n},()=>e.out.line(n?Gu(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},G0={name:"messaging:hook:set",summary:"set the hook asked whom one may reach, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--secret-to <NAME> [--dev]]",details:[`Before a direct conversation opens, people are added to a group, someone makes or opens an open group, a space's open groups are listed or one is joined, the hook is POSTed {"event": "messaging.can_message", "action": "direct" | "group_add" | "open_group" | "list_open" | "join", "from_user_id", "to_user_ids", "conversation_id", "space"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: whom of to_user_ids from_user_id may reach \u2014 for open_group, list_open and join, to_user_ids is [from_user_id], and naming them lets them in. space is the conversation's (absent: none).`,"A new hook takes --url (an https URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase messaging:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the app is told to try again (a new hook: deny)"},...Uu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--url is where the hook is asked: an https URL");let n;if(e.flags["timeout-ms"]!==void 0&&(n=Number(e.flags["timeout-ms"]),!/^[0-9]+$/.test(String(e.flags["timeout-ms"]))||n<100||n>5e3))throw m("--timeout-ms is a whole number from 100 to 5000");let s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw m("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw m("nothing to change","pass --url, --timeout-ms or --on-error");let a=Bu(e),i=await b(e),r=await h(e,i,"GET",at),o=r.hook;if(!o&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(o&&a!==void 0)throw m("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase messaging:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let l={url:t??o.url},d=n??o?.timeout_ms;d!==void 0&&(l.timeout_ms=d);let p=s??o?.on_error;if(p!==void 0&&(l.on_error=p),o&&We(o,{...o,...l}))return Fe(e,"the hook",r);let u=o?["url","timeout_ms","on_error"].filter(y=>l[y]!==o[y]):[];await v(e,i,o?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let g=await h(e,i,"PUT",at,{hook:l});await zu(e,i,g,a,o?"Changed the hook":"Set the hook")}},U0={name:"messaging:hook:remove",summary:"remove the hook: anyone may reach anyone, and its signing secret is forgotten",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",at);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the messaging hook ${n.hook.url}: anyone may reach anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",at,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},B0={name:"messaging:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:Uu,scope:"environment",async run(e){let t=Bu(e),n=await b(e);await v(e,n,`make the messaging hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${at}/hook-secret`);await zu(e,n,s,t,"Made the signing secret anew for the hook")}},Wu={name:"messaging",async read(e,t){let n=await h(e,t,"GET",at),s={};for(let a of Do)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=fe(n,"settings.");a.length>0&&await Q(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",at,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",at,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",at,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Fu=[N0,q0,K0,G0,U0,B0];var it="/calls/settings",z0=/^[A-Z][A-Z0-9_]{0,127}$/,No=["max_participants","calls_per_hour"];function $s(e,t){switch(e){case"max_participants":return`${String(t)}: a call holds at most this many, people and bots together`;case"calls_per_hour":return`${String(t)}: one person may start at most this many calls in an hour`;case"hook":return t?Ju(t):"none: anyone may call anyone (blocks aside)"}}function Ju(e){return`${A(e.url)} (waited for ${e.timeout_ms??2e3} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the call is refused"})${e.places?"; asked of places too":""}`}function W0(e,t){let n=[...No.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${$s(a,i)}`)}function xo(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw m(`--${t} is a whole number from ${n} to ${s}`);return a}var F0={name:"calls:settings:get",summary:"how the environment runs its calls: how many a call holds, how many calls a person may start in an hour, the hook",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",it);e.out.result(n,()=>W0(e,n))}},J0={name:"calls:settings:set",summary:"change how the environment runs its calls: a setting left out is left as it is",usage:"[--max-participants <n>] [--calls-per-hour <n>]",details:["A call holds at most --max-participants, people and the project's bots together, as the setting was when the call was made: a change holds for the calls made after it.","Every call's media, one to one or in a group, goes through the platform's media server: no device learns another's address.","A person who has started --calls-per-hour calls in the last hour is refused another (too_many_calls).","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"max-participants":{type:"string",value:"n",description:"how many a call holds, people and bots together (2\u2013100)"},"calls-per-hour":{type:"string",value:"n",description:"how many calls one person may start in an hour (1\u20131000)"}},scope:"environment",async run(e){let t={},n=xo(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=xo(e.flags["calls-per-hour"],"calls-per-hour",1,1e3);if(s!==void 0&&(t.calls_per_hour=s),Object.keys(t).length===0)throw m("nothing to change","pass --max-participants or --calls-per-hour");let a=await b(e),i=await h(e,a,"GET",it),r=No.filter(l=>l in t&&!We(i[l],t[l]));if(r.length===0)return Fe(e,"the call settings",i);await v(e,a,`set the call settings ${r.join(", ")}`);let o=await h(e,a,"PUT",it,Object.fromEntries(r.map(l=>[l,t[l]])));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${$s(l,i[l])} \u2192 ${$s(l,o[l])}`)})}},Vu={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function Hu(e){let t=e.flags["secret-to"];if(t!==void 0&&!z0.test(t))throw m(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function Yu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${$s("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${$s("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${$s("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var V0={name:"calls:hook:get",summary:"the hook asked whom one may call: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await b(e),{hook:n}=await h(e,t,"GET",it);e.out.result({hook:n},()=>e.out.line(n?Ju(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},H0={name:"calls:hook:set",summary:"set the hook asked whom one may call, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--places on|off] [--secret-to <NAME> [--dev]]",details:['Before a call is made, or more people are asked into one, the hook is POSTed {"event": "calls.can_call", "action": "start" | "invite", "from_user_id", "to_user_ids", "video", "call_id", "conversation_id"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: only those are called, and with none the call is refused.',`With --places on, the hook is asked of places too ({"action": "place", "place", "from_user_id", "to_user_ids": [that person]}): it says who may see and join the meeting held at a place of the app (a channel). Off (a new hook), places are not asked of it, and a place's meeting is seen only by the people asked into it.`,"A new hook takes --url (a URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase calls:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the call is refused (a new hook: deny)"},places:{type:"string",value:"on|off",description:"the hook answers places too: who may see and join a channel's meeting (a new hook: off)"},...Vu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--url is where the hook is asked: a URL");let n=xo(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw m("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw m("--places is on or off");let i=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&i===void 0)throw m("nothing to change","pass --url, --timeout-ms, --on-error or --places");let r=Hu(e),o=await b(e),l=await h(e,o,"GET",it),d=l.hook;if(!d&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(d&&r!==void 0)throw m("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase calls:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let p={url:t??d.url},u=n??d?.timeout_ms;u!==void 0&&(p.timeout_ms=u);let g=s??d?.on_error;g!==void 0&&(p.on_error=g);let y=i??d?.places;if(y!==void 0&&(p.places=y),d&&We(d,{...d,...p}))return Fe(e,"the hook",l);let w=d?["url","timeout_ms","on_error","places"].filter(P=>(p[P]??!1)!==(d[P]??!1)):[];await v(e,o,d?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${p.url}${r?`, its secret kept in ${r.name} (${r.set})`:""}`);let _=await h(e,o,"PUT",it,{hook:p});await Yu(e,o,_,r,d?"Changed the hook":"Set the hook")}},Y0={name:"calls:hook:remove",summary:"remove the hook: anyone may call anyone (blocks aside), and its signing secret is forgotten",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",it);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the calls hook ${n.hook.url}: anyone may call anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",it,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},X0={name:"calls:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:Vu,scope:"environment",async run(e){let t=Hu(e),n=await b(e);await v(e,n,`make the calls hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${it}/hook-secret`);await Yu(e,n,s,t,"Made the signing secret anew for the hook")}},Xu={name:"calls",async read(e,t){let n=await h(e,t,"GET",it),s={};for(let a of No)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=fe(n,"settings.");a.length>0&&await Q(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",it,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",it,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",it,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Zu=[F0,J0,V0,H0,Y0,X0];var Z0=/^[a-z][a-z0-9-]{1,62}$/;function Ps(e){if(!Z0.test(e))throw m(`${JSON.stringify(e)} is not a bucket's name: lowercase letters, digits and dashes, starting with a letter (2\u201363)`);return`/storage/buckets/${k(e)}`}function Ko(e){if(e==null)return"platform (5 GiB)";for(let[t,n]of[["GiB",2**30],["MiB",2**20],["KiB",2**10]])if(e>=n&&e%n===0)return`${e/n} ${t}`;return`${e} B`}function Q0(e){if(e===""||e==="platform")return null;let t=/^(\d+(?:\.\d+)?)\s*(b|kb|kib|mb|mib|gb|gib)?$/i.exec(e.trim());if(!t)throw m(`--max-size ${JSON.stringify(e)} is not a size: 10MB, 512KiB, 1GB, a number of bytes, or platform`);let n=(t[2]??"b").toLowerCase(),s={b:1,kb:1e3,kib:2**10,mb:1e6,mib:2**20,gb:1e9,gib:2**30};return Math.round(Number(t[1])*s[n])}function qo(e){return{public:e.public,file_size_limit:e.file_size_limit??null,allowed_mime_types:e.allowed_mime_types??[],variants:e.variants??[]}}async function ek(e,t,n){try{return await h(e,t,"GET",Ps(n))}catch(s){if(s instanceof E&&s.status===404)return;throw s}}var Qu={name:"storage:buckets:list",summary:"the environment's buckets: who may read each, the largest file and the types it takes",scope:"environment",async run(e){let t=await b(e),{buckets:n}=await h(e,t,"GET","/storage/buckets");e.out.result({buckets:n},()=>{n.length===0&&e.out.line("No bucket yet: palbase storage:buckets:set <name> makes one."),e.out.table(n,[{header:"bucket",value:s=>s.name},{header:"read by",value:s=>s.public?"anyone":"signed URLs, rules"},{header:"largest file",value:s=>Ko(s.file_size_limit)},{header:"types",value:s=>s.allowed_mime_types.length===0?"any":s.allowed_mime_types.join(", ")},{header:"renditions",value:s=>s.variants.map(a=>a.name).join(", ")}])})}},ec={name:"storage:buckets:get",summary:"a bucket's declaration in full, with its renditions",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",Ps(e.args[0]));e.out.result(n,()=>{e.out.line(n.name),e.out.line(` read by ${n.public?"anyone, at /storage/public/":"signed URLs and the rules"}`),e.out.line(` largest file ${Ko(n.file_size_limit)}`),e.out.line(` types ${n.allowed_mime_types.length===0?"any":n.allowed_mime_types.join(", ")}`);for(let s of n.variants)e.out.line(` rendition ${s.name}: ${s.width}\xD7${s.height} ${s.fit}, ${s.format}${s.quality?` q${s.quality}`:""}`)})}},tc={name:"storage:buckets:set",summary:"make a bucket, or change one: public or private, the largest file, the content types, its renditions",usage:"<bucket> [--public|--private] [--max-size <size>] [--types <a/b,c/*>] [--variants-file <path>]",details:["What is not given is kept as it is (a new bucket: private, the platform's size, any type, no rendition)."],args:{min:1,max:1},flags:{public:{type:"boolean",description:"anyone may read its files at /storage/public/"},private:{type:"boolean",description:"its files are read with signed URLs and the rules"},"max-size":{type:"string",value:"size",description:"the largest file: 10MB, 512KiB, 1GB, bytes, or platform"},types:{type:"string",value:"list",description:'the content types it takes, comma-separated (image/* a family); "" for any'},"variants-file":{type:"string",value:"path",description:"its renditions, a JSON list of {name, width, height, fit, format, quality}"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw m("--public and --private are one or the other");let s=await ek(e,t,n),a=qo(s??{name:n,public:!1,allowed_mime_types:[],variants:[]});if(e.flags.public===!0&&(a.public=!0),e.flags.private===!0&&(a.public=!1),e.flags["max-size"]!==void 0&&(a.file_size_limit=Q0(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=oe(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let r=me(await ke(e,e.flags["variants-file"],"the renditions"),"the renditions file"),o=Array.isArray(r)?r:r.variants;if(!Array.isArray(o))throw m("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=o}if(s&&We(qo(s),a)){e.out.result(s,()=>e.out.line(`Nothing to change: ${n} already is so.`));return}await v(e,t,`${s?"change":"make"} the bucket ${n} (${a.public?"public":"private"})`);let i=await h(e,t,"PUT",Ps(n),a);e.out.result(i,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${i.name}: ${i.public?"public":"private"}, files up to ${Ko(i.file_size_limit)}, ${i.allowed_mime_types.length===0?"any type":i.allowed_mime_types.join(", ")}.`))}},nc={name:"storage:buckets:delete",summary:"delete an empty bucket (one that still holds files is refused)",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Ps(e.args[0]);await v(e,t,`delete the bucket ${e.args[0]}`),await h(e,t,"DELETE",n),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the bucket ${e.args[0]}.`))}},sc={name:"storage",async read(e,t){let{buckets:n}=await h(e,t,"GET","/storage/buckets"),s={};for(let a of n){let i=qo(a);s[`buckets.${a.name}`]={...i,allowed_mime_types:[...i.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of fe(n,"buckets."))a.from===void 0?await Q(s,`delete the bucket ${a.name}`,async()=>{await h(e,t,"DELETE",Ps(a.name))}):await Q(s,`declare the bucket ${a.name}`,async()=>{await h(e,t,"PUT",Ps(a.name),a.from)})}};var xn=[ou,sc,bu,Ou,xu,Ku,Wu,Xu];function zo(e="<env>"){return new f("not_copied","machines, databases and sites are the project's, each bound to one environment: only settings are compared and copied between environments",{hint:`make one bound to it with palbase machines:create -E ${e} (or databases:create -E ${e}), or move one there with palbase machines:move <name> --to ${e}`})}var ac={from:{type:"string",value:"env",description:"the environment compared from (slug or ref)"},to:{type:"string",value:"env",description:"the environment compared to (slug or ref)"},only:{type:"string",value:"modules",description:`only these, comma-separated: ${xn.map(e=>e.name).join(",")} (the default)`}};async function ic(e){if(e.global.env!==void 0)throw m("the two environments are named with --from and --to, not -E");let t=e.flags.from,n=e.flags.to;if(t===void 0||n===void 0)throw m("name both environments: --from <env> --to <env>");let s=await Pe(e.studio),a;if(e.global.project!==void 0)a=un(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new f("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});a=s.filter(d=>d.project_id===l.target.project_id)}let i=l=>{let d=a.find(p=>p.slug===l||p.ref===l);if(!d)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});return ie(d)},r=i(t),o=i(n);if(r.env_ref===o.env_ref)throw m("--from and --to name the same environment");return{from:r,to:o}}function rc(e,t){let n=oe(e.flags.only);if(n===void 0)return xn;if(n.some(s=>s==="machines"||s==="databases"||s==="sites"))throw zo(t.env_slug);for(let s of n)if(!xn.some(a=>a.name===s))throw m(`no module ${JSON.stringify(s)}`,`the modules: ${xn.map(a=>a.name).join(", ")}`);return xn.filter(s=>n.includes(s.name))}function tk(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let i=a in e,r=a in t;i&&!r?s.push({key:a,change:"only_in_from",from:e[a]}):!i&&r?s.push({key:a,change:"only_in_to",to:t[a]}):We(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function Go(e,t,n,s){let a=l=>Promise.all(t.map(d=>d.read(e,l))),[i,r]=await Promise.all([a(n),a(s)]),o=Object.fromEntries(t.map((l,d)=>[l.name,tk(i[d],r[d])]));return{from:n,to:s,modules:o,count:Object.values(o).reduce((l,d)=>l+d.length,0)}}function Uo(e){return{from:{env:e.from.env_slug,ref:e.from.env_ref},to:{env:e.to.env_slug,ref:e.to.env_ref},equal:e.count===0,differences:e.count,modules:e.modules}}function Ei(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function Bo(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[i,r]of Object.entries(t.modules))if(r.length!==0){e.out.line(`${i} (${r.length})`);for(let o of r)o.change==="differs"?e.out.line(` ~ ${o.key}: ${n} ${Ei(o.from)} \xB7 ${s} ${Ei(o.to)}`):o.change==="only_in_from"?e.out.line(` - ${o.key}: only in ${n}: ${Ei(o.from)}`):e.out.line(` + ${o.key}: only in ${s}: ${Ei(o.to)}`)}let a=Object.keys(t.modules).join(", ");e.out.line(t.count===0?`${n} and ${s} have the same settings (${a}).`:`${t.count} difference(s) between ${n} and ${s} (${a}).`)}var nk={name:"config:diff",summary:"how two environments' module settings differ (auth, storage, flags, notify, realtime, analytics, messaging, calls)",usage:"--from <env> --to <env> [--only <modules>]",details:["- a key only in --from, + only in --to, ~ in both with other values. Ids, times and versions are not compared; a secret is compared as set or not, never by its value.","Exit code 0 when they are the same, 1 when they differ. --json gives each difference with both values."],flags:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e),s=await Go(e,rc(e,n),t,n);return e.out.result(Uo(s),()=>Bo(e,s)),s.count===0?0:1}},sk={name:"config:copy",summary:"make one environment's module settings equal to another's (secrets excepted: their names are said)",usage:"--from <env> --to <env> [--only <modules>]",details:["It shows the differences, asks before changing a production environment (-y confirms), changes the target, and compares again.","A secret is never copied: a provider's credentials and a sign-in client's secret are listed by name for you to set. A new hook or OAuth client gets its own secret, printed this once.","What the target holds that its users depend on is not taken by a copy: a bucket with files, a role users hold, a topic users follow are left and said.","Machines, databases and sites are not settings: they are the project's, each bound to one environment (machines:create -E, machines:move --to).","Exit code 0 when the two are the same afterwards, 1 when a difference remains."],flags:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e);return Wo(e,rc(e,n),t,n)}};async function Wo(e,t,n,s,a={}){let i=await Go(e,t,n,s);if(i.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:Uo(i)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||Bo(e,i);let r=t.filter(u=>i.modules[u.name].length>0).map(u=>u.name);await v(e,s,`make its ${r.join(", ")} settings equal to ${n.env_slug}'s (${i.count} difference(s))`);let o=[],l=[],d=[];e.out.json||e.out.line();for(let u of t){let g=i.modules[u.name];if(g.length===0)continue;let y={done(w){o.push(`${u.name}: ${w}`),e.out.json||e.out.line(`copied ${u.name}: ${w}`)},left(w){l.push(`${u.name}: ${w}`),e.out.json||e.out.line(`left ${u.name}: ${w}`)},shown(w,_){d.push({what:`${u.name}: ${w}`,value:_}),e.out.json||e.out.line(` ${u.name}: ${w} ${_} (shown this once)`)}};await u.copy(e,s,g,y)}let p=await Go(e,t,n,s);return e.out.result({...a,copied:o,left:l,shown_once:d,after:Uo(p)},()=>{e.out.line(),e.out.line("Compared again:"),Bo(e,p)}),p.count===0?0:1}var oc=[zp,Wp,Fp,Jp,Hp,Vp,Yp,Xp,Zp,eu,tu,nu,su,au,iu,ru,Qu,ec,tc,nc,uu,cu,hu,mu,fu,yu,gu,vu,_u,ku,Su,$u,Pu,Au,Ru,Tu,Eu,Cu,ju,Mu,Iu,Lu,Du,Nu,qu,...Fu,...Zu,nk,sk];async function Fo(e){return(await e.studio.get("/orgs")).organizations}async function kt(e,t){let n=await Fo(e);if(t===void 0){if(n.length===1)return n[0];throw m(n.length===0?"you are in no organization yet: make one with palbase orgs:create <name>":"which organization? pass --org <name>",`yours: ${n.map(a=>a.name).join(", ")}`)}let s=n.filter(a=>a.id===t||a.name.localeCompare(t,void 0,{sensitivity:"accent"})===0);if(s.length===0)throw new f("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new f("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var lc={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await Fo(e);e.out.result({organizations:t},()=>{t.length===0&&e.out.line("You are in no organization yet: palbase orgs:create <name> makes one."),e.out.table(t,[{header:"name",value:n=>n.name},{header:"role",value:n=>n.role},{header:"id",value:n=>n.id}])})}},dc={name:"orgs:create",summary:"make an organization; you are its owner",usage:"<name>",details:["With an account token in PALBASE_TOKEN, the token's maker is its owner and the token its admin: one organization more the token reaches."],args:{min:1,max:1},scope:"account",async run(e){let t=await e.studio.post("/orgs",{name:e.args[0]});e.out.result(t,()=>e.out.line(`Made the organization ${q(t.name)} (${t.id}).`))}},pc={name:"orgs:members:list",summary:"an organization's members, and the invitations still open (for its admins)",flags:{org:{type:"string",value:"org",description:"the organization (name or id); needed when you are in more than one"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),n=await e.studio.get(`/orgs/${t.id}/members`);e.out.result(n,()=>{e.out.table(n.members,[{header:"email",value:s=>s.email??""},{header:"role",value:s=>s.role},{header:"user",value:s=>s.user_id}]),n.invitations.length>0&&(e.out.line(),e.out.line("Invited:"),e.out.table(n.invitations,[{header:"email",value:s=>s.email},{header:"role",value:s=>s.role},{header:"invitation",value:s=>s.id}]))})}},uc={name:"orgs:members:invite",summary:"invite someone to an organization by email; they accept in Studio",usage:"<email> [--role admin|member]",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"admin or member (default member)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--role is admin or member");let s=await e.studio.post(`/orgs/${t.id}/invitations`,{email:e.args[0],role:n});e.out.result(s,()=>e.out.line(`Invited ${q(s.email)} to ${q(t.name)} as ${s.role}.`))}},cc={name:"orgs:members:remove",summary:"take a member (by email or user id) or an open invitation out of an organization",usage:"<email|user-id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(r=>r.user_id===n||r.email!==null&&r.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/members/${x("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${q(a.email??a.user_id)} is no longer in ${q(t.name)}.`));return}let i=s.invitations.find(r=>r.id===n||r.email.toLowerCase()===n.toLowerCase());if(!i)throw new f("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/invitations/${x("the invitation's id",i.id)}`),e.out.result({withdrawn:i},()=>e.out.line(`The invitation of ${q(i.email)} is withdrawn.`))}},hc={name:"tokens:list",summary:"an organization's access tokens (PALBASE_TOKEN for CI and agents): name, role, when they end and were last used \u2014 never their values",flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`);e.out.result({tokens:n},()=>{n.length===0?e.out.line(`${q(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>q(s.name)},{header:"role",value:s=>s.role},{header:"token",value:s=>`pbo_\u2026${s.hint}`},{header:"ends",value:s=>s.expires_at.slice(0,10)},{header:"last used",value:s=>s.last_used_at?.slice(0,16).replace("T"," ")??"never"},{header:"id",value:s=>s.id}])})}},mc={name:"orgs:audit",summary:"who changed what at an organization's environments, through Studio or the CLI, newest first \u2014 its admins'",usage:"[--org <org>] [--limit <n>]",details:["A module keeps a change made through Studio as Studio's key's: this says whose it was. What was sent is not kept."],flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},limit:{type:"string",value:"n",description:"how many at most (default 50)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw m("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),r=await e.studio.get(`/orgs/${t.id}/audit?${i}`);s.push(...r.entries),a=r.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${q(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:i=>i.at.slice(0,16).replace("T"," ")},{header:"who",value:i=>q(i.actor_name??i.actor)},{header:"environment",value:i=>q(i.environment_ref)},{header:"what",value:i=>q(`${i.method} ${i.path}`)},{header:"answer",value:i=>String(i.status)}])})}},gc={name:"tokens:create",summary:"make an access token of an organization for CI or an agent; its value is shown this once",usage:"<name> [--role member|admin] [--days <n>]",details:["Give it to the CI as the secret PALBASE_TOKEN: the CLI acts with it in place of a sign-in. It reaches its organization's projects and environments at its role, and nothing of its people or tokens.","It ends after --days (default 90, at most 365), and goes when it is revoked or when the one who made it leaves the organization."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"member (default) or admin: what it may change"},days:{type:"string",value:"n",description:"how many days it is good for (default 90)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--role is member or admin");let s=e.flags.days===void 0?90:Number(e.flags.days);if(!Number.isInteger(s)||s<1||s>365)throw m("--days is a whole number from 1 to 365");let a=await e.studio.post(`/orgs/${t.id}/tokens`,{name:e.args[0],role:n,expires_in_days:s});e.out.result(a,()=>{e.out.line(`Made the access token ${q(a.name)} of ${q(t.name)} (${a.role}, until ${a.expires_at.slice(0,10)}).`),e.out.line(`token (shown this once \u2014 keep it as the CI's secret PALBASE_TOKEN): ${a.token}`)})}},fc={name:"tokens:revoke",summary:"revoke an organization's access token (by its name or id): refused from its next request on",usage:"<name|id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(r=>r.id===e.args[0]||r.name===e.args[0]);if(s.length===0)throw new f("no_such_token",`${q(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new f("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${x("the organization's id",t.id)}/tokens/${x("the token's id",s[0].id)}`,{endpoints:i}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:i},()=>{if(e.out.line(`Revoked the access token ${q(s[0].name)} of ${q(t.name)}.`),i.length>0){e.out.line("These webhook endpoints it made stay, and keep receiving events (palbase webhooks:delete <id> -E <env> removes one):");for(let r of i)e.out.line(` ${A(r.url)} \u2014 ${A(r.environment_ref)} (${A(r.id)})`)}})}},yc={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await Pe(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(i=>[i.organization_id,i.org_name]));for(let i of await Fo(e))a.set(i.id,i.name);e.out.result({projects:s.map(i=>({...i,organization_name:a.get(i.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let i=s.flatMap(r=>r.environments.length===0?[{org:a.get(r.organization_id)??"",project:r.name,env:"(none)",ref:"",here:""}]:r.environments.map(o=>({org:a.get(r.organization_id)??"",project:r.name,env:o.slug,ref:o.ref,here:n?.target.env_ref===o.ref?"*":""})));e.out.table(i,[{header:"",value:r=>r.here},{header:"organization",value:r=>r.org},{header:"project",value:r=>r.project},{header:"env",value:r=>r.env},{header:"ref",value:r=>r.ref}])})}},bc={name:"projects:create",summary:"make a project with its first environment (main), and print its keys",usage:"<name> [--org <org>] [--env-name <name>]",details:["The first environment is the project's production one: its slug is always main.","Its secret key is printed this once; keys:create makes more."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},"env-name":{type:"string",value:"name",description:"what the first environment is called on screen (default Production)"}},scope:"account",async run(e){let t=await kt(e,e.flags.org),{project:n}=await e.studio.post(`/orgs/${t.id}/projects`,{name:e.args[0]}),s=await e.studio.post(`/projects/${n.id}/environments`,{name:e.flags["env-name"]??"Production"});e.out.result({project:n,environment:s.environment,keys:s.keys},()=>{e.out.line(`Made ${q(t.name)} \u203A ${q(n.name)} with its environment ${s.environment.slug} (ref ${s.environment.ref}).`),s.keys&&(e.out.line(`publishable key: ${s.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${s.keys.secret.key}`)),e.out.line(`palbase use ${n.name}/${s.environment.slug} chooses it for this directory.`)})}},wc={name:"projects:delete",summary:"delete a project and every environment of it",usage:"<project> [-y]",details:["Its environments' data goes with them (the platform keeps it a week to bring back)."],args:{min:1,max:1},scope:"account",async run(e){let t=un(await Pe(e.studio),e.args[0]),n=t[0];if(e.out.note(`${n.org_name} \u203A ${n.project_name}: delete the project and its environments ${t.map(s=>s.slug).join(", ")}`),!e.global.yes){if(!e.interactive)throw new f("confirmation_needed","deleting a project is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the project's name to delete it: ")).trim()!==n.project_name)throw new f("cancelled","nothing was deleted")}await e.studio.request("DELETE",`/projects/${n.project_id}`),e.out.result({deleted:{project_id:n.project_id,environments:t.map(s=>s.ref)}},()=>e.out.line(`Deleted ${q(n.project_name)}.`))}},vc={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Yt(e);e.out.result({environments:t},()=>e.out.table(t,[{header:"slug",value:n=>n.slug},{header:"name",value:n=>n.name},{header:"ref",value:n=>n.ref},{header:"your role",value:n=>n.role}]))}},_c={name:"envs:create",summary:"add an environment to a project (staging, a developer's own)",usage:"<slug> [--name <name>] [--from <env>]",details:["Each environment is a project of its own on the platform: its users, data and keys are its own.","--from opens it with another environment's module settings (palbase config:copy: secrets are named, not copied).","Machines, databases and sites are the project's, each bound to one environment: a new environment opens with its settings alone, and one is made bound to it (machines:create -E <slug>) or moved there (machines:move <name> --to <slug>)."],args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"what it is called on screen (default: the slug)"},from:{type:"string",value:"env",description:"open it with this environment's settings (slug or ref)"},"with-cloud":{type:"boolean",description:"refused: machines, databases and sites are the project's, and no environment opens with copies of them"}},scope:"environment",async run(e){let t=e.args[0];if(e.flags["with-cloud"]===!0)throw zo(t);let n=await ak(e),s=e.flags.from,a=s===void 0?[]:(await Pe(e.studio)).filter(d=>d.project_id===n.project_id),i=s===void 0?void 0:a.find(d=>d.slug===s||d.ref===s);if(s!==void 0&&!i)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});let r=await e.studio.post(`/projects/${n.project_id}/environments`,{name:e.flags.name??t,slug:t}),o=()=>{e.out.line(`Made ${q(n.project_name)} \u203A ${r.environment.slug} (ref ${r.environment.ref}).`),r.keys&&(e.out.line(`publishable key: ${r.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${r.keys.secret.key}`))};if(!i){e.out.result(r,o);return}e.out.json||o();let l=ie({...i,ref:r.environment.ref,slug:r.environment.slug,name:r.environment.name});return e.out.json||e.out.line(),Wo(e,xn,ie(i),l,{made:r})}},kc={name:"envs:delete",summary:"delete an environment of a project, with its data",usage:"<slug> [--delete-bound | --move-to <env>]",details:["A project's machines, databases and sites are the project's, each bound to one environment. What is bound to the environment deleted is deleted with it (--delete-bound), or moved to another environment of the project first (--move-to <slug>); with neither and something bound to it, a person at the terminal is asked, and anything else is refused with what is bound.","Moved, they keep their data and answer throughout, and their old addresses keep working: the environment is deleted once each is up where it moved. The passwords this computer holds for its databases go with them."],args:{min:1,max:1},flags:{"delete-bound":{type:"boolean",description:"delete the machines, databases and sites bound to it with it"},"move-to":{type:"string",value:"env",description:"move its machines, databases and sites to this environment of the project (its slug) before it is deleted"}},scope:"environment",async run(e){let t=await Yt(e),n=t.find(d=>d.slug===e.args[0]||d.ref===e.args[0]);if(!n)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=ie(n);if(e.out.note(`${N(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new f("confirmation_needed","deleting an environment is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the environment's slug to delete it: ")).trim()!==n.slug)throw new f("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,i=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&i!==void 0)throw m("--delete-bound or --move-to: what is bound to it is deleted with it, or moved");let r=a?"?delete_bound=true":i!==void 0?`?move_to=${encodeURIComponent(i)}`:"",o=async()=>{let d=e.io.now()+6e5;for(;;)try{return await e.studio.request("DELETE",`/environments/${n.ref}${r}`)}catch(p){if(!(p instanceof E)||p.code!=="machines_still_moving"||e.io.now()>d)throw p;e.out.note(`still moving to ${decodeURIComponent(r.slice(9))}; asking again`),await e.io.sleep(5e3)}};try{await o()}catch(d){if(!(d instanceof E)||d.code!=="environment_has_resources"||r!=="")throw d;let p=d.body?.data??{},u=[p.machines?.length?`machines ${p.machines.join(", ")}`:"",p.databases?.length?`databases ${p.databases.join(", ")}`:"",p.sites?.length?`sites ${p.sites.join(", ")}`:""].filter(w=>w!=="").join("; "),g=t.filter(w=>w.ref!==n.ref).map(w=>w.slug);if(!e.interactive||e.global.yes)throw new f("environment_has_resources",`bound to ${n.slug}: ${u}`,{hint:`delete them with it (--delete-bound), or move them first (--move-to ${g[0]??"<env>"})`});e.out.line(`Bound to ${n.slug}: ${u}.`);let y=(await e.io.prompt(`Delete them with it (delete), move them to another environment (${g.join(", ")}), or keep it (keep)? `)).trim();if(y==="delete")r="?delete_bound=true";else if(g.includes(y))r=`?move_to=${encodeURIComponent(y)}`;else throw new f("cancelled","nothing was deleted");await o()}if(r.startsWith("?move_to=")){let d=t.find(p=>p.slug===decodeURIComponent(r.slice(9))||p.ref===decodeURIComponent(r.slice(9)));d&&await e.state.moveDatabasePasswords(n.ref,d.ref)}let l=await e.state.targetFor(e.io.cwd);l?.target.env_ref===n.ref&&await e.state.clearTarget(l.dir),e.out.result({deleted:n.ref},()=>e.out.line(`Deleted ${N(s)}.`))}},Sc={name:"use",summary:"choose the environment this directory acts on (kept on this computer)",usage:"[<project>[/<env>] | <org>/<project>/<env>] [--clear]",details:["Commands run in this directory, or a directory under it, then act on that environment unless -P/-E say otherwise.","Nothing is written into the project: two checkouts of it can each act on their own environment.","With no argument and a person at the terminal, it lists your environments to pick from."],args:{min:0,max:1},flags:{clear:{type:"boolean",description:"forget the choice made for this directory"}},scope:"account",async run(e){if(e.flags.clear===!0){let n=await e.state.clearTarget(e.io.cwd);e.out.result({cleared:n},()=>e.out.line(n?"This directory acts on no environment now.":"No environment was chosen for this directory."));return}let t;if(e.args.length===0)t=await b(e);else{let n=await Pe(e.studio);t=ie(ik(n,e.args[0]))}await e.state.setTarget(e.io.cwd,t),e.out.result({target:t,dir:e.io.cwd},()=>e.out.line(`This directory acts on ${N(t)}.`))}},$c={name:"status",summary:"the environment this directory acts on: who you are there, the machines and databases bound to it",scope:"environment",async run(e){let t=await b(e),n=await e.studio.get(`/environments/${t.env_ref}`),s=p=>_e(e.studio,t.env_ref,"GET",p).then(u=>u.body,u=>u instanceof E?null:Promise.reject(u)),a=`limit=100&environment=${encodeURIComponent(t.env_ref)}`,[i,r]=await Promise.all([s(`/machines?${a}`),s(`/databases?${a}`)]),o=i?.machines??[],l=r?.databases??[],d=await e.state.targetFor(e.io.cwd);e.out.result({target:t,role:n.role,address:`https://${t.env_ref}.${e.cloud.domain}`,machines:o,databases:l,chosen_for:d?.dir??null},()=>{e.out.line(N(t)),e.out.line(` ref ${t.env_ref} \xB7 your role ${n.role} \xB7 https://${t.env_ref}.${e.cloud.domain}`),d&&d.target.env_ref===t.env_ref&&e.out.line(` chosen for ${d.dir}`),e.out.line(` machines: ${o.length===0?"none":o.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`),e.out.line(` databases: ${l.length===0?"none":l.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`)})}},Pc={name:"open",summary:"open the environment in Studio (its overview, or a section: auth, storage, flags, \u2026)",usage:"[section]",args:{min:0,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args[0]?`/${e.args[0].replace(/^\/+/,"")}`:"",s=`${e.cloud.studioWeb}/projects/${t.project_id}/environments/${t.env_ref}${n}`,a=e.interactive&&await e.io.openBrowser(s);e.out.result({url:s,opened:a},()=>e.out.line(a?`Opened ${s}`:s))}},Ac={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await b(e),{keys:n}=await e.studio.get(`/environments/${t.env_ref}/keys`);e.out.result({keys:n},()=>e.out.table(n,[{header:"id",value:s=>s.id},{header:"kind",value:s=>s.kind},{header:"label",value:s=>s.label},{header:"ends",value:s=>s.hint?`\u2026${s.hint}`:""},{header:"state",value:s=>s.revoked_at?`revoked ${s.revoked_at}`:s.expires_at?`until ${s.expires_at}`:"active"},{header:"created",value:s=>s.created_at}]))}},Rc={name:"keys:create",summary:"make an API key of the environment; its value is shown this once",usage:"--kind publishable|secret [--label <label>]",flags:{kind:{type:"string",value:"kind",description:"publishable (ships in apps) or secret (servers only)"},label:{type:"string",value:"label",description:"what it is for, as Studio lists it"}},scope:"environment",async run(e){let t=e.flags.kind;if(t!=="publishable"&&t!=="secret")throw m("--kind is publishable or secret");let n=await b(e);await v(e,n,`make a ${t} key`);let s=await e.studio.post(`/environments/${n.env_ref}/keys`,{kind:t,label:e.flags.label??""});e.out.result(s,()=>{e.out.line(`${s.kind} key ${s.id}${s.kind==="secret"?" (shown this once)":""}:`),e.out.line(s.key)})}},Tc={name:"keys:revoke",summary:"revoke an API key of the environment; what holds it is refused from then on",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=`/environments/${x("the environment's ref",t.env_ref)}/keys/${x("the key's id",e.args[0])}`;await v(e,t,`revoke the key ${e.args[0]}`),await e.studio.request("DELETE",n),e.out.result({revoked:e.args[0]},()=>e.out.line(`Revoked ${e.args[0]}.`))}};async function ak(e){return(await Yt(e))[0]}async function Yt(e){if(Jt(e.io))return[await la(e)];let t=await Pe(e.studio);if(e.global.project!==void 0)return un(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new f("no_target","no project is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});let s=t.filter(a=>a.project_id===n.target.project_id);if(s.length===0)throw new f("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function ik(e,t){let n=t.split("/");if(n.length>3||n.some(i=>i===""))throw m(`${JSON.stringify(t)} is not project, project/env or org/project/env`);let s=n.length===3?[{project:`${n[0]}/${n[1]}`,env:n[2]}]:n.length===2?[{project:n[0],env:n[1]},{project:t}]:[{project:t}],a;for(let i of s){let r;try{r=un(e,i.project)}catch(o){a=o;continue}if(i.env!==void 0){let o=r.find(l=>l.slug===i.env||l.ref===i.env);if(o)return o;a=new f("no_such_environment",`${r[0].project_name} has no environment ${JSON.stringify(i.env)}`,{hint:`its environments: ${r.map(l=>l.slug).join(", ")}`});continue}if(r.length===1)return r[0];throw new f("which_environment",`${r[0].project_name} has more than one environment`,{hint:`name one: ${r.map(o=>`${o.project_name}/${o.slug}`).join(", ")}`})}throw a}import{mkdtemp as rk,rm as ok}from"node:fs/promises";import{tmpdir as lk}from"node:os";import{extname as dk,join as Ec}from"node:path";var Jo="Named by none, it is the only database of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one.";async function bn(e,t){let n=await pn(e),s=n.t,a=t??await Mc(e,s,hi(n,"/databases?limit=100"),n.by==="fallback"?"the project":`the environment ${s.env_slug}`),i=await Oc(e,s,a),r=()=>On(async o=>{let{body:l}=await _e(e.studio,s.env_ref,"GET",`/databases?limit=100${o?`&cursor=${encodeURIComponent(o)}`:""}`);return{items:l.databases,next:l.next_cursor}});return await Mn(e,n,i.d,r,`the database ${i.d.name}`),i}async function Oc(e,t,n){let{body:s}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}`);return{t:await Ln(e,t,s.environment,`the database ${s.name}`),d:s}}async function Mc(e,t,n,s){let{body:a}=await _e(e.studio,t.env_ref,"GET",n);if(a.databases.length===1)return a.databases[0].name;throw a.databases.length===0?new f("no_database",`${s} has no database`,{hint:"palbase databases:create opens one"}):m("which database? name it",`${s}'s databases: ${a.databases.map(i=>i.name).join(", ")}`)}async function Xt(e,t,n,s,a){let{body:i}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}/credentials`),r=(await e.state.databasePasswords(t.env_ref,n))[s];if(!r)throw new f("no_password",`this computer holds no ${s} password of ${n}: the platform showed it once, where the database was opened`,{hint:`palbase databases:password:reset ${n} --role ${s} makes a new one and keeps it here${s==="app"?" (the machines given it roll out with it)":""}`});let o=s==="owner"?i.owner:i.app,l=new URL(a?o.pooled_url:o.url);return l.password="",{url:l.toString(),password:r,role:s}}function pk(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Ic={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function Lc(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw m("--role is owner or app");return t}var Dc={PGSSLROOTCERT:"system"};async function Nn(e,t,n,s,a=!1){let i=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...Dc,PGAPPNAME:"palbase-cli"},inherit:a});if(i.code===127)throw new f("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return i}var xc={name:"db:url",summary:"a project database's connection address, for any tool (Prisma, Drizzle, pg_dump, a GUI)",usage:"[name] [--role owner|app] [--pooled] [--with-password]",details:[te("database"),Jo,"Without --with-password the address holds no password: give the tool PGPASSWORD, or pass --with-password and keep the line out of your history.","The address asks for a checked certificate (sslmode=verify-full). Node drivers check it against the system's roots by themselves; psql, pg_dump and other libpq tools do only with PGSSLROOTCERT=system (Postgres 16+). The address does not say so itself: a driver that sends what it does not know to the server (postgres.js) would be refused."],args:{min:0,max:1},flags:{role:Ic,pooled:{type:"boolean",description:"the pooled port (PgBouncer, transaction mode): for an app's many short connections"},"with-password":{type:"boolean",description:"put the password in the address"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,Lc(e),e.flags.pooled===!0),i=e.flags["with-password"]===!0?pk(a):a.url;e.out.result({database:s,role:a.role,url:i,libpq_env:Dc},()=>{e.io.stdout(`${i}
|
|
33
33
|
`),e.out.note("psql, pg_dump and other libpq tools: PGSSLROOTCERT=system (Postgres 16+), or they cannot check the certificate")})}},Nc={name:"db:shell",summary:"psql on a database of the project (it wakes if asleep); -c runs one statement and ends",usage:"[name] [--role owner|app] [--command <sql>]",details:[te("database"),Jo],args:{min:0,max:1},flags:{role:Ic,command:{type:"string",short:"c",value:"sql",description:"run this and end"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,Lc(e),!1),i=e.flags.command;if(i!==void 0){let o=await Nn(e,"psql",[a.url,"-v","ON_ERROR_STOP=1","-X","-c",i],a);if(o.stdout&&e.io.stdout(o.stdout),o.code!==0)throw new f("psql_failed",o.stderr.trim()||`psql ended with ${o.code}`);return}if(!e.interactive)throw m("db:shell with no person at the terminal needs --command <sql>");return e.out.note(`${N(t)} \u203A ${s} as ${a.role}`),(await Nn(e,"psql",[a.url],a,!0)).code}},qc={name:"db:dump",summary:"a copy of a database of the project (pg_dump's custom format), as its owner",usage:"[name] [--file <path>] [--schema-only]",details:[te("database"),Jo],args:{min:0,max:1},flags:{file:{type:"string",value:"path",description:"where to write it (default <database>-<time>.dump)"},"schema-only":{type:"boolean",description:"its structure, not its data"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,"owner",!1),i=e.flags.file??`${s}-${new Date(e.io.now()).toISOString().replaceAll(":","-").slice(0,19)}.dump`,r=await Nn(e,"pg_dump",["--format=custom","--no-owner","--no-acl",...e.flags["schema-only"]===!0?["--schema-only"]:[],"--file",i,a.url],a);if(r.code!==0)throw new f("pg_dump_failed",r.stderr.trim()||`pg_dump ended with ${r.code}`);e.out.result({database:s,file:i},()=>e.out.line(`Wrote ${i}.`))}},Kc={name:"db:restore",summary:"load a dump into a database of the project, as its owner: a custom-format dump (pg_restore) or a .sql file (psql)",usage:"<file> [--db <name>] [--clean]",details:["A database Palbase did not make is taken over by its first release: its tables stay as they are (palbase db:pull writes their schema files).",te("database"),"Named by no --db, it is the only database of the environment chosen for this directory or named by -E, else, when neither says, the project's only one."],args:{min:1,max:1},flags:{db:{type:"string",value:"name",description:"the database (default: the environment's only one \u2014 chosen here or -E's \u2014 else the project's)"},clean:{type:"boolean",description:"drop what the dump makes before making it again"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.flags.db),s=n.name,a=e.args[0];await v(e,t,`load ${a} into the database ${s}`);let i=await Xt(e,t,s,"owner",!1);await Gc(e,i,a,e.flags.clean===!0),e.out.result({database:s,loaded:a},()=>e.out.line(`Loaded ${a} into ${s}.`))}};async function Gc(e,t,n,s){let a=dk(n).toLowerCase()===".sql",i=a?await Nn(e,"psql",[t.url,"-v","ON_ERROR_STOP=1","-X","--single-transaction","-f",n],t):await Nn(e,"pg_restore",["--no-owner","--no-acl","--exit-on-error","--single-transaction",...s?["--clean","--if-exists"]:[],"--dbname",t.url,n],t);if(i.code!==0)throw new f("restore_failed",i.stderr.trim()||`${a?"psql":"pg_restore"} ended with ${i.code}`)}var Cc="\u2022\u2022\u2022";async function uk(e,t,n){let s=async l=>{let d=await Nn(e,"psql",[n.url,"-v","ON_ERROR_STOP=1","-X","-At","-F"," ","-c",l],n);if(d.code!==0)throw new f("redact_failed",d.stderr.trim()||`psql ended with ${d.code}`);return d.stdout.split(`
|