palbase 0.79.0 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{MLCAO5BP.js → 2NB7UENO.js} +2 -2
  9. package/dist/chunks/{6OSSTYNI.js → 5BQM5XTX.js} +2 -2
  10. package/dist/chunks/{H54MZKCJ.js → 6INSGN37.js} +1 -1
  11. package/dist/chunks/{Q5J5SAQN.js → 6PUARVHY.js} +1 -1
  12. package/dist/chunks/{OYYGUGM3.js → 7NOXAQOX.js} +2 -2
  13. package/dist/chunks/{7S3FQENY.js → 7QS5ABCT.js} +2 -2
  14. package/dist/chunks/{Z3MUYA3L.js → 7XQVUV65.js} +2 -2
  15. package/dist/chunks/{XKVQ4IQL.js → BQUNZH5E.js} +2 -2
  16. package/dist/chunks/{ZWTD6MI2.js → DP6WZPTF.js} +2 -2
  17. package/dist/chunks/{RH33COMI.js → FUNHIQCH.js} +2 -2
  18. package/dist/chunks/{L3CVM7BS.js → G4PGGIAO.js} +2 -2
  19. package/dist/chunks/{M64773TP.js → IK4MB3HQ.js} +2 -2
  20. package/dist/chunks/{M5R7OBNV.js → IS5HMTJX.js} +2 -2
  21. package/dist/chunks/{R3HD47TY.js → LZXD4SBY.js} +1 -1
  22. package/dist/chunks/{KXKIZ3ZM.js → N767RMLK.js} +2 -2
  23. package/dist/chunks/{V3FMVRBO.js → OY6JSD3B.js} +2 -2
  24. package/dist/chunks/{Y4V3NO2R.js → QV53HO4D.js} +1 -1
  25. package/dist/chunks/{NFCM74MS.js → RGCK6WN2.js} +2 -2
  26. package/dist/chunks/{H6J3ET7R.js → RU3A4ASQ.js} +1 -1
  27. package/dist/chunks/{PPZGWRCM.js → T2XBJBUC.js} +1 -1
  28. package/dist/chunks/TNNTPBI3.js +23 -0
  29. package/dist/chunks/{6ATOAAF5.js → TOGOOVTU.js} +1 -1
  30. package/dist/chunks/{IXCF3WHZ.js → UKM6LWJ3.js} +2 -2
  31. package/dist/chunks/{7Y5BCID4.js → VZQI2MW2.js} +2 -2
  32. package/dist/chunks/{JU5VP7GA.js → WUOSCBJ3.js} +2 -2
  33. package/dist/cli.js +3 -3
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
  51. package/types/web/src/iap.d.ts +6 -0
  52. package/dist/chunks/KZ2PTXAO.js +0 -23
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /*! palbase 0.79.0 — Palbase SDK License (see LICENSE) */
2
+ /*! palbase 0.80.0 — Palbase SDK License (see LICENSE) */
3
3
  var Q0=Object.defineProperty;var wt=(e,t)=>{for(var n in t)Q0(e,n,{get:t[n],enumerable:!0})};import{parseArgs as MS}from"node:util";var eS=Symbol.for("palbase.data"),tS=globalThis,Ou=tS[eS]??=new WeakSet;function nS(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Fi(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||Ou.has(n)||nS(n))){Ou.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var sS="X-PoW-Challenge-ID",aS="X-PoW-Nonce";function xu(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 oS(e){return 8*2**e}var Oa;async function iS(){if(Oa)return Oa;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 Oa=a=>new Uint8Array(s("sha256").update(a).digest()),Oa}catch{}let t=new TextEncoder;return Oa=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),Oa}function rS(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var lS=4096,pS=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function Lu(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 iS(),s=oS(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let o=0;o<s;o++){if(o%lS===0&&o>0){if(await pS(),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 ${o} attempts`)}let i=n(e.prefix+o),r=i instanceof Uint8Array?i:await i;if(rS(r)>=e.difficulty)return{[sS]:e.id,[aS]:String(o)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var G=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 G({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var dS=new Set(["apikey","authorization"]),cS=64*1024;function pp(e){let t=Bi(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(o,i)=>{let r=gS(t,o),l=new Headers;for(let[y,w]of Object.entries(o.headers??{}))w!=null&&!dS.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(i))l.set(y,w);await hS(o,e.credentials,l),l.has("accept")||l.set("accept","application/json");let p={method:o.method,headers:l,redirect:"manual",signal:o.signal,...o.keepalive?{keepalive:!0}:{}};o.body&&o.body.value!==void 0&&(l.set("content-type",o.body.contentType),p.body=yS(o.body.kind,o.body.value),xa(p.body)||(p.duplex="half"));let d;try{d=o.onUploadProgress&&e.xmlHttpRequest?await uS(e.xmlHttpRequest,o.op,r,p,o.onUploadProgress):await n(r,p)}catch(y){throw o.signal?.aborted||y instanceof G?y:new G({op:o.op,status:0,code:"network_error",message:`${o.op}: the request did not reach ${t.origin}`,cause:y})}let u=o.answers[d.status]??(o.ownResponse&&d.status>=200&&d.status<300?"raw":void 0);if(u===void 0)throw d.status>=200&&d.status<300?(await d.body?.cancel(),new G({op:o.op,status:d.status,code:"undeclared_answer",message:`${o.op}: the server answered ${d.status}, which its contract does not declare; the request may have taken effect`})):await bS(o.op,d);let m;switch(u){case"json":try{m=Fi(await d.json())}catch(y){throw new G({op:o.op,status:d.status,code:"invalid_json",message:`${o.op}: the answer is not JSON`,cause:y})}break;case"raw":m=d;break;default:await d.body?.cancel(),m=void 0}return{status:d.status,data:m,headers:d.headers}};return{async send(o){try{return await a(o,{})}catch(i){let r=s&&i instanceof G&&i.status===403?xu(i.body):null,l=o.body?.value;if(!r||o.body?.kind==="raw"&&!xa(l))throw i;let p=i,d;try{d=await Lu(r,{signal:o.signal})}catch(u){throw o.signal?.aborted?u:new G({op:o.op,status:403,code:"pow_unsolved",message:`${o.op}: ${u instanceof Error?u.message:String(u)}`,requestId:p.requestId,body:p.body,cause:u})}return a(o,d)}}}}function uS(e,t,n,s,a){return new Promise((o,i)=>{let r=s.signal;if(r?.aborted)return i(r.reason);let l=new e,p=()=>l.abort();r?.addEventListener("abort",p,{once:!0});let d=u=>{r?.removeEventListener("abort",p),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,m)=>l.setRequestHeader(m,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>d(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){i(new G({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 i(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;o(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:mS(l.getAllResponseHeaders())}))}),l.onerror=()=>d(()=>i(new TypeError(`${t}: the request failed`))),l.onabort=()=>d(()=>i(r?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function mS(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 Bi(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 gS(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new G({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+fS(t.query),e);if(n.origin!==e.origin)throw new G({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function hS(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(i=>i.includes("userJWT"))?await t.accessToken?.():void 0,a=i=>{switch(i){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}},o=e.auth.filter(i=>i.every(a)).reduce((i,r)=>i===void 0||r.length>i.length?r:i,void 0);if(!o)throw new G({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(i=>i.length===0?"nothing":i.join(" + ")).join(" | ")}`});for(let i of o)i==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(i==="SecretKeyAuth"||i==="AdminAuth"||i==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):i==="SecretKeyAuth"||i==="AdminAuth"?n.set("apikey",t.secretKey):i==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function yS(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))dp(n,s,a);return n}case"raw":return t}}function xa(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function fS(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))dp(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function dp(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)dp(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 bS(e,t){let n=await wS(t,cS).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=vS(s)?s:void 0,o=Number(t.headers.get("retry-after")),i=t.status>=300&&t.status<400;return new G({op:e,status:t.status,code:a?.error??(i?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(i?`${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(o)&&o>0?o:void 0),body:s})}async function wS(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:r,value:l}=await n.read();if(r)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let o=new Uint8Array(Math.min(a,t)),i=0;for(let r of s){let l=Math.min(r.byteLength,o.byteLength-i);if(o.set(r.subarray(0,l),i),i+=l,i>=o.byteLength)break}return new TextDecoder().decode(o)}function vS(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var Ji={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 b=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 h(e,t){return new b("usage",e,{hint:t,exitCode:2})}var Hi=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(`${le(t)}
5
5
  `)}note(t){this.io.stderr(`${le(t)}
@@ -9,7 +9,7 @@ var Q0=Object.defineProperty;var wt=(e,t)=>{for(var n in t)Q0(e,n,{get:t[n],enum
9
9
  `);let i;try{i=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 b("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
10
10
  `),i.status!==503||!s||o>=LS||!xS.has(await gp(i)??""))return i;await i.body?.cancel();let r=Number(i.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(r)&&r>0?Math.min(r,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),o=await this.send(t,n,s,a.value);if(o.status===401&&a.renewable){let i=await this.renew(await this.currentSession());o=await this.send(t,n,s,i.access_token)}return{res:o,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let o=await s.text(),i=o===""?void 0:IS(o);if(s.ok)return i;let r=i??{};throw s.status===401?r.error==="token_not_for_machines"?Vu(new URL(this.cloud.studioApi).host):a?La():this.tokenRefused("Studio"):new G({op:`${t} ${n}`,status:s.status,code:r.error??`http_${s.status}`,message:r.error_description??`Studio answered ${s.status}`,requestId:r.request_id??s.headers.get("x-request-id")??void 0,body:i})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new b("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 b("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 b("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 Fu(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let o=`${this.cloud.studioApi}${OS}${n}`;this.debug&&this.io.stderr(`> ${t} ${o}
11
11
  `);try{let i=await this.io.fetch(o,{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(`< ${i.status} ${i.headers.get("x-request-id")??""}
12
- `),i}catch(i){throw new b("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function Vu(e){return new b("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 gp(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 IS(e){try{return JSON.parse(e)}catch{return e}}var Xu={version:"0.79.0"};var Qi=Xu.version;async function tm(e,t,n,s){let a=new Map(n.map(r=>[r.name,r])),o=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:l}=DS(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${Qi}
12
+ `),i}catch(i){throw new b("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function Vu(e){return new b("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 gp(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 IS(e){try{return JSON.parse(e)}catch{return e}}var Xu={version:"0.80.0"};var Qi=Xu.version;async function tm(e,t,n,s){let a=new Map(n.map(r=>[r.name,r])),o=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:l}=DS(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${Qi}
13
13
  `),0):(t.stdout(em(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let E=e[l+1],C=E===void 0?void 0:a.get(E);if(E!==void 0&&!C)throw Yu(E,n);return t.stdout(C?Qu(C):em(n)),0}let p=a.get(r);if(!p)throw Yu(r,n);let d=[...e.slice(0,l),...e.slice(l+1)],u=d.includes("--")?d.slice(0,d.indexOf("--")):d;if(u.includes("--help")||u.includes("-h"))return t.stdout(Qu(p)),0;let{flags:m,positionals:y}=zS(p,d),w=p.args??{min:0,max:0};if(y.length<w.min)throw h(`${p.name} needs ${w.min===1?"an argument":`${w.min} arguments`}`,yp(p));if(y.length>w.max)throw h(`${p.name} takes ${w.max===0?"no argument":`at most ${w.max}`}: ${JSON.stringify(y.slice(w.max))} is left over`,yp(p));let v={project:m.project,env:m.env,json:m.json===!0,nonInteractive:m["non-interactive"]===!0,yes:m.yes===!0,debug:m.debug===!0},P=qu(t.env),A=new Xi(Ku(t.configDir,P)),T={io:t,state:A,out:new Hi(t,v.json),global:v,args:y,flags:m,interactive:t.interactive&&!v.nonInteractive,cloud:P,studio:new Zi(t,P,A,v.debug,s?.callPlatform)};return await p.run(T)??0}catch(r){return qS(r,t,o,i)}}function DS(e){let t=new Set;for(let[n,s]of Object.entries(Ji))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 zS(e,t){let n={...Ji,...e.flags??{}},s={};for(let[a,o]of Object.entries(n))s[a]={type:o.type,...o.short?{short:o.short}:{},...o.multiple?{multiple:!0}:{}};try{let{values:a,positionals:o}=MS({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:o}}catch(a){throw h(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function qS(e,t,n,s){let a="error",o,i,r=1,l;return e instanceof b?(a=e.code,o=e.message,i=e.hint,r=e.exitCode):e instanceof G?(a=e.code,o=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(o=`${e.op} refused PALBASE_TOKEN: ${e.message}`,i="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")):o=e instanceof Error?e.message:String(e),n&&e instanceof b&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:o,...i?{hint:i}:{},...l?{request_id:l}:{}},null,2)}
14
14
  `),t.stderr(`error: ${le(o)}${l?` (request ${le(l)})`:""}
15
15
  `),i&&t.stderr(` ${le(i)}
@@ -11196,7 +11196,7 @@ ${t}}`}var cs=e=>["",e.toUpperCase(),"-".repeat(e.length)],GO=[{title:"One packa
11196
11196
  `)}
11197
11197
  `}var xk={flow:"total",snapshot:"last",ratio:"overall"};function Lk(e){return(e.segments[0]?.points??[]).map(t=>t.period)}function EN(e,t,n){let s=t.segments[0];if(!s)return;let a=n?.measures??Object.keys(s.summary.measures).map(r=>({key:r,unit:t.unit,description:""})),o=[...s.points,{period:xk[t.kind]??"summary",value:s.summary.value,measures:s.summary.measures}],i=[{header:"period",value:r=>`${r.period}${r.incomplete?" *":""}`},{header:"value",value:r=>Pi(t.unit,r.value,t.currency)},...a.map(r=>({header:I(r.key),value:l=>r.key in l.measures?Pi(r.unit,l.measures[r.key],t.currency):"\u2014"}))];e.out.table(o,i)}function CN(e,t){let s=Lk(t).map((a,o)=>({period:a,values:t.segments.map(i=>i.points[o]?.value),incomplete:t.segments.some(i=>i.points[o]?.incomplete===!0)}));s.push({period:xk[t.kind]??"summary",values:t.segments.map(a=>a.summary.value),incomplete:!1}),e.out.table(s,[{header:"period",value:a=>`${a.period}${a.incomplete?" *":""}`},...t.segments.map((a,o)=>({header:I(a.label??a.key),value:i=>i.values[o]===void 0?"\u2014":Pi(t.unit,i.values[o],t.currency)}))])}function ON(e,t){for(let n of t.segments){let s=Math.max(0,...n.points.map(o=>o.ages?.length??0),n.summary.ages?.length??0),a=[...n.points.map(o=>({cohort:o.period,size:o.value,ages:o.ages??[],incomplete:o.incomplete})),{cohort:"all",size:n.summary.value,ages:n.summary.ages??[]}];t.segments.length>1&&e.out.line(`${I(n.label??n.key)}:`),e.out.table(a,[{header:"cohort",value:o=>`${o.cohort}${o.incomplete?" *":""}`},{header:"size",value:o=>Pi(t.unit,o.size,t.currency)},...Array.from({length:s},(o,i)=>({header:`+${i}`,value:r=>{let l=r.ages.find(p=>p.age===i);return l?`${Pi(t.age_unit,l.value,t.currency)}${l.incomplete?"*":""}`:""}}))])}}function xN(e){let t=[`${e.from} to ${e.to} (UTC) by ${e.resolution}`];return(e.unit==="currency"||e.age_unit==="currency"||e.revenue_type)&&t.push(`in ${e.currency}${e.revenue_type?`, ${Mc[e.revenue_type]??e.revenue_type}`:""}`),e.segment&&t.push(`by ${e.segment}`),e.filters.length>0&&t.push(`only ${e.filters.map(n=>`${n.dimension}:${n.value}`).join(", ")}`),e.window_days!==void 0&&t.push(`within ${e.window_days} day(s)`),e.cohort&&t.push(`cohorts of ${e.cohort==="new_paying_customers"?"new paying customers":"new customers"}`),t.push(`test purchases ${e.sandbox?"included":"left out"}`),`${e.name}: ${t.join(", ")}`}var LN={name:"iap:charts:get",summary:"one purchase chart, period by period \u2014 a table of its periods and segments, or the module's CSV",usage:"<chart> [--from <YYYY-MM-DD>] [--to <YYYY-MM-DD>] [--resolution day|week|month] [--segment <dimension>] [--filter <dimension:value>]\u2026 [--revenue-type <type>] [--currency <code>] [--window-days <n>] [--cohort new_customers|new_paying_customers] [--sandbox] [--csv [--out <palbase/\u2026.csv>]]",details:["Days are UTC; from and to are both included, at most two years apart (by default the last 30 days, 12 weeks or 12 months). A period marked * is not over: its value may still change.","Money is in the reporting currency (iap:charts:settings) at the European Central Bank's rate of the day it was paid; proceeds take off the store's commission and Stripe's fee, which the ledger does not hold: they are estimated, and so are taxes a store did not state.",`--csv prints the module's CSV (a row a segment and period) \u2014 on the terminal its control characters escaped \u2014; with --out it is written to that file, under ${ue}/. A cell that would start a spreadsheet formula (=, +, -, @) begins with a quote.`],args:{min:1,max:1},flags:{from:{type:"string",value:"YYYY-MM-DD",description:"the first day"},to:{type:"string",value:"YYYY-MM-DD",description:"the last day, included (default today)"},resolution:{type:"string",value:"resolution",description:"day (default), week or month"},segment:{type:"string",value:"dimension",description:"split by a dimension (iap:charts lists them)"},filter:{type:"string",multiple:!0,value:"dimension:value",description:"keep only this value, one each --filter: --filter store:app_store --filter country:TR"},"revenue-type":{type:"string",value:"type",description:"gross (default), net_of_taxes or proceeds"},currency:{type:"string",value:"code",description:"the currency to report money in (default: the reporting currency)"},"window-days":{type:"string",value:"n",description:"the conversion window or customer lifetime, in days from a customer's first day, 0 to 730 (default: to now)"},cohort:{type:"string",value:"cohort",description:"the cohort explorer's cohorts: new_customers (default) or new_paying_customers"},sandbox:{type:"boolean",description:"count the stores' test purchases too"},csv:{type:"boolean",description:"the module's CSV instead of a table"},out:{type:"string",value:"file",description:`with --csv, write it to this file, under ${ue}/`}},scope:"environment",async run(e){let t=e.args[0];if(!/^[a-z_]+$/.test(t))throw h(`${JSON.stringify(t)} is not a chart's key`,"palbase iap:charts lists them");for(let E of["from","to"]){let C=e.flags[E];if(C!==void 0&&(typeof C!="string"||!yN.test(C)))throw h(`--${E} is a day: 2026-10-01`)}let n=Ri(e,"resolution",bN),s=Ri(e,"revenue-type",Ek),a=Ri(e,"cohort",wN),o=Kl(e,"currency"),i=we(e.flags["window-days"],"window-days");if(i!==void 0&&i>730)throw h("--window-days is 0 to 730");let r=AN(e.flags.filter),l=e.flags.segment;if(l!==void 0&&!/^[a-z][a-z_]{0,31}$/.test(l))throw h(`--segment ${l}: a dimension (iap:charts lists them)`);let p=e.flags.csv===!0,d=e.flags.out;if(d!==void 0&&!p)throw h("--out writes the CSV: give --csv with it");if(p&&d===void 0&&e.global.json)throw h("--csv and --json are two forms of the answer: give one");let u=d!==void 0?Kt(e,"out",d,".csv",`${hN}/${t}.csv`):void 0,m=await f(e),y;try{y=await g(e,m,"GET","/iap/charts")}catch(E){ql(E,t)}let w=y.charts.find(E=>E.key===t);if(!w)throw new b("chart_not_found",`no chart ${JSON.stringify(t)}`,{hint:"palbase iap:charts lists them"});let v=y.dimensions.map(E=>E.key);if((l!==void 0||r.length>0)&&!w.segmentable)throw h(`${t} is not segmented or filtered by a dimension`);for(let E of[...l!==void 0?[l]:[],...r.map(C=>C.dimension)])if(!v.includes(E))throw h(`${E} is not a dimension the charts are cut by: ${v.map(I).join(", ")}`);let P=new URLSearchParams({...e.flags.from!==void 0?{from:e.flags.from}:{},...e.flags.to!==void 0?{to:e.flags.to}:{},...n?{resolution:n}:{},...e.flags.sandbox===!0?{sandbox:"true"}:{},...l?{segment:l}:{},...o?{currency:o}:{},...s?{revenue_type:s}:{},...i!==void 0?{window_days:String(i)}:{},...a?{cohort:a}:{}});for(let E of r)P.append("filter",`${E.dimension}:${E.value}`);let A=`/iap/charts/${R(t)}${P.size>0?`?${P}`:""}`;if(p){let E;try{E=await g(e,m,"GET",A,void 0,{accept:"text/csv"})}catch(K){ql(K,t)}if(typeof E!="string")throw new b("not_csv","the iap module did not answer the chart as CSV");let C=TN(E);if(u===void 0){e.io.stdout(le(C));return}let W=await Be(e.io.cwd,u);await uN(gN(W),{recursive:!0}),await Be(e.io.cwd,u),await mN(W,C);let z=Math.max(0,Ok(C).length-1);e.out.result({file:u,chart:t,rows:z},()=>e.out.line(`Wrote ${t} to ${u} (${z} row${z===1?"":"s"}).`));return}let T;try{T=await g(e,m,"GET",A)}catch(E){ql(E,t)}e.out.result(T,()=>{e.out.line(I(xN(T))),T.segments.length===0||Lk(T).length===0?e.out.line("Nothing in these days."):T.kind==="cohort"?(ON(e,T),e.out.line(T.chart==="subscription_retention"?"Ages are renewals: +0 is the first paid period; a value is the share that reached it.":`Ages are ${I(T.resolution)}s from each customer's first day; a value is realized LTV per customer.`)):T.segment===void 0&&T.segments.length===1?EN(e,T,w):CN(e,T),T.segments.some(E=>E.points.some(C=>C.incomplete||C.ages?.some(W=>W.incomplete)))&&e.out.line("* not over yet: the value may still change."),T.estimated&&e.out.line("Estimated: the money holds what the ledger does not state \u2014 taxes a store did not, the stores' commission and Stripe's fee, a Google Play offer's period at its plan's price \u2014 in any revenue type, gross too."),T.chart==="active_customers"&&e.out.line("Customers are counted from the day the module began keeping the days they were seen: days before it count none."),Ck(e,T.unconverted),e.out.line(`Counted ${I(Z(T.computed_at))}.`)})}};function IN(e){return`${Ik(e.web_fee_bps)} + ${Gl(e.web_fee_fixed_micros/1e6,e.web_fee_fixed_currency)}`}function Ik(e){return`${(e/100).toFixed(2).replace(/\.?0+$/,"")}%`}function NN(e){if(e===void 0)return;let t=Number(e);if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||t>20)throw h("--web-percent is a share of a payment, 0 to 20, with at most two decimals: 2.9");return Math.round(t*100)}function MN(e){if(e===void 0)return;if(typeof e!="string"||!/^\d+(\.\d{1,6})?$/.test(e)||Number(e)>1e5)throw h("--web-fixed is an amount, 0 to 100000, with at most six decimals: 0.30");let[t,n=""]=e.split(".");return Number(t)*1e6+Number(n.padEnd(6,"0"))}function DN(e){if(e===void 0)return;let t=Number(e);if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||t>30)throw h("--app-store-link-percent is a share of a web purchase, 0 to 30, with at most two decimals: 27");return Math.round(t*100)}function zN(e){if(e!==void 0){if(typeof e!="string"||!/^\d{1,2}$/.test(e)||Number(e)<1||Number(e)>90)throw h("--app-store-link-days is a number of days, 1 to 90: 7");return Number(e)}}var qN={name:"iap:charts:settings",summary:"the charts' settings \u2014 the reporting currency, the stores' commission, web payment processing fee and the App Store's fee on web purchases linked out of the app \u2014 read, or changed with the flags given",usage:"[--currency <code>] [--commission standard|small_business] [--web-percent <n>] [--web-fixed <amount>] [--web-fixed-currency <code>] [--app-store-link-percent <n>] [--app-store-link-days <n>]",details:["Every amount is converted to the reporting currency at the European Central Bank's rate of the day it was paid; the ledger keeps what was paid as it was paid, so a change redraws every chart from its first day.","The commission is what proceeds take off App Store and Google Play payments: standard (30%; 15% of a subscription's renewals after its first paid year in the App Store, and of every Google Play subscription) or small_business (15%). Web fee \u2014 its share and fixed part \u2014 is taken off web payments; the ledger does not hold it, so proceeds are estimated.","The App Store's link fee is what Apple takes of a web purchase bought through a link out of the iOS app in its United States storefront, within the days after the link: nothing today (App Review Guideline 3.1.1(a)), set here once Apple charges one."],flags:{currency:{type:"string",value:"code",description:"the reporting currency, one the European Central Bank published a rate for in the last ten days"},commission:{type:"string",value:"commission",description:"standard (30%) or small_business (15%)"},"web-percent":{type:"string",value:"n",description:"web payment provider share of a payment, in percent (2.9)"},"web-fixed":{type:"string",value:"amount",description:"web payment provider fixed fee per payment (0.30)"},"web-fixed-currency":{type:"string",value:"code",description:"currency of the web fixed fee (USD)"},"app-store-link-percent":{type:"string",value:"n",description:"the App Store's share of a web purchase linked out of the iOS app, in percent (0)"},"app-store-link-days":{type:"string",value:"n",description:"for how many days after the link a purchase owes it (7)"}},scope:"environment",async run(e){let t={},n=Kl(e,"currency");n!==void 0&&(t.reporting_currency=n);let s=Ri(e,"commission",vN);s!==void 0&&(t.store_commission=s);let a=NN(e.flags["web-percent"]);a!==void 0&&(t.web_fee_bps=a);let o=MN(e.flags["web-fixed"]);o!==void 0&&(t.web_fee_fixed_micros=o);let i=Kl(e,"web-fixed-currency");i!==void 0&&(t.web_fee_fixed_currency=i);let r=DN(e.flags["app-store-link-percent"]);r!==void 0&&(t.app_store_link_fee_bps=r);let l=zN(e.flags["app-store-link-days"]);l!==void 0&&(t.app_store_link_attribution_days=l);let p=await f(e),d;Object.keys(t).length===0?d=await g(e,p,"GET","/iap/settings"):d=await GN(e,p,t),e.out.result({reporting_currency:d.reporting_currency,store_commission:d.store_commission,web_fee_bps:d.web_fee_bps,web_fee_fixed_micros:d.web_fee_fixed_micros,web_fee_fixed_currency:d.web_fee_fixed_currency,app_store_link_fee_bps:d.app_store_link_fee_bps,app_store_link_attribution_days:d.app_store_link_attribution_days},()=>{e.out.table([["Reporting currency",d.reporting_currency],["Store commission",kN[d.store_commission]??d.store_commission],["Web payment fee",IN(d)],["App Store's link fee",`${Ik(d.app_store_link_fee_bps)} within ${d.app_store_link_attribution_days} day${d.app_store_link_attribution_days===1?"":"s"} of the link`]],[{header:"setting",value:u=>u[0]},{header:"value",value:u=>u[1]}])})}};async function GN(e,t,n){let s=[n.reporting_currency&&`report money in ${n.reporting_currency}`,n.store_commission&&`take the ${n.store_commission==="small_business"?"Small Business (15%)":"standard (30%)"} commission off store payments`,(n.web_fee_bps!==void 0||n.web_fee_fixed_micros!==void 0||n.web_fee_fixed_currency)&&"change the web payment fee",(n.app_store_link_fee_bps!==void 0||n.app_store_link_attribution_days!==void 0)&&"change the App Store's link fee"].filter(Boolean);return await k(e,t,`charts: ${s.join(", ")}`),g(e,t,"PUT","/iap/settings",n)}var Nk=[SN,$N,LN,qN];import{X509Certificate as KN}from"node:crypto";import{mkdir as UN,readFile as zc,stat as zk,writeFile as qc}from"node:fs/promises";import{basename as WN,dirname as FN,relative as BN,resolve as ji,sep as JN}from"node:path";var Mk={apple:"App Store",google:"Google Play"};function Je(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s}function qk(e){return`"${e}"`}async function Gk(e){let t=Ne(await ze(e,e.flags.file,"the catalog"),"the catalog");if(typeof t!="object"||t===null||Array.isArray(t))throw h("the catalog is a JSON object: { base_locale, products, entitlements, credits, limits }");if("catalog"in t&&"revision"in t)throw h('the file is a saved revision (catalog:get --json): give its "catalog" alone, as catalog:get --out writes it');return t}function Kk(e,t){for(let n of t)e.out.note(` ${n.warning?"warning":"problem"} ${n.path}: ${n.message} (${n.code}${n.channel?`, ${n.channel}`:""})`)}function Gc(e,t,n){if(t instanceof G&&t.code==="invalid_catalog"){let s=(t.body??{}).problems??[];throw s.length>0&&(e.out.note(`The catalog breaks ${s.filter(a=>!a.warning).length} rule(s):`),Kk(e,s)),new b("invalid_catalog",`${n}: ${t.message}`,{hint:"fix each problem in the file (palbase iap:catalog:validate checks it without saving)"})}throw t}function Uk(e,t){if(t.revision===0){e.out.line("No catalog yet (revision 0)."),e.out.line("Write one and save it: palbase iap:catalog:put --file catalog.json --revision 0");return}let n=t.catalog;e.out.line(`Catalog revision ${t.revision}${t.created_at?`, saved ${Z(t.created_at)}`:""}${t.created_by?` by ${t.created_by}`:""}`),e.out.line(`base language: ${n.base_locale}`),e.out.table(n.products,[{header:"product",value:s=>s.key},{header:"type",value:s=>s.type},{header:"plans",value:s=>s.plans.map(a=>a.key).join(", ")},{header:"channels",value:s=>Object.keys(s.channels).sort().join(", ")},{header:"gives",value:s=>[...s.entitlements??[],...s.credits?[`${s.credits.amount} ${s.credits.currency}`]:[]].join(", ")}]),n.products.length===0&&e.out.line("No product."),n.entitlements.length>0&&e.out.line(`entitlements: ${n.entitlements.map(s=>s.key).join(", ")}`),n.credits.length>0&&e.out.line(`credits: ${n.credits.map(s=>s.key).join(", ")}`),n.limits.length>0&&e.out.line(`limits: ${n.limits.map(s=>s.key).join(", ")}`)}var HN={name:"iap:catalog:get",summary:"the environment's catalog: its newest revision, the products it sells and what they give",usage:"[--out <catalog.json>]",details:["--out writes the catalog to a file to edit; catalog:put saves the edit with the revision it was edited from, which is printed."],flags:{out:{type:"string",value:"catalog.json",description:"write the catalog (the JSON catalog:put takes) to this file"}},scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/iap/catalog"),s=e.flags.out;if(s!==void 0){await qc(ji(e.io.cwd,s),`${JSON.stringify(n.catalog,null,2)}
11198
11198
  `),e.out.result({file:s,revision:n.revision},()=>{e.out.line(`Wrote revision ${n.revision} of the catalog to ${s}.`),e.out.line(`Save an edit of it: palbase iap:catalog:put --file ${s} --revision ${n.revision}`)});return}e.out.result(n,()=>Uk(e,n))}},VN={name:"iap:catalog:put",summary:"save a new revision of the whole catalog, on the revision it was edited from; nothing is written to a store",usage:"--file <catalog.json> --revision <n>",details:["The module checks it first: a catalog that breaks a rule is refused with every problem, and nothing is saved.","Of two people editing at once, the second is told \u2014 the catalog moved past the revision they edited \u2014 never overwritten.","The stores are brought to it by a plan: palbase iap:catalog:plan."],flags:{file:{type:"string",value:"catalog.json",description:"the catalog, as catalog:get --out wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the revision it was edited from (0 for the first), as catalog:get printed it"}},scope:"environment",async run(e){let t=await f(e),n=we(e.flags.revision,"revision");if(n===void 0)throw h("--revision is the revision the catalog was edited from (0 for the first): of two edits at once, the second is told, not saved over the first");let s=await Gk(e);await k(e,t,`save the catalog (${s.products?.length??0} products) over revision ${n}`);let a;try{a=await g(e,t,"PUT","/iap/catalog",s,{"if-match":qk(n),...D()})}catch(o){if(o instanceof G&&o.status===412)throw new b("catalog_changed",`the catalog is no longer at revision ${n}: someone saved a newer one since it was read \u2014 nothing was saved`,{hint:"read it again (palbase iap:catalog:get --out <file>), make the edit on it, and save it with that revision"});Gc(e,o,"the catalog was not saved")}e.out.result(a,()=>{e.out.line(`Saved revision ${a.revision} of the catalog.`),e.out.line("Bring the stores to it: palbase iap:catalog:plan")})}},XN={name:"iap:catalog:validate",summary:"check a catalog without saving it: every problem, with its path and the store whose rule it breaks",usage:"--file <catalog.json>",flags:{file:{type:"string",value:"catalog.json",description:"the catalog ('-' or none: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=await Gk(e),s;try{s=await g(e,t,"POST","/iap/catalog/validate",n,D())}catch(a){Gc(e,a,"the catalog cannot be read")}if(e.out.result(s,()=>{s.problems.length>0&&Kk(e,s.problems),e.out.line(s.valid?`The catalog can be saved${s.problems.length>0?`, with ${s.problems.length} warning(s)`:""}.`:"The catalog cannot be saved as it is.")}),!s.valid)throw new b("invalid_catalog",`the catalog breaks ${s.problems.filter(a=>!a.warning).length} rule(s)`)}};function Dk(e,t,n){e.out.line(`${t}${n.store_env?` (${n.store_env})`:""}: ${n.steps.length===0?"nothing to write":`${n.steps.length} step(s)`}`);for(let s of n.steps)e.out.line(` ${s.op} ${s.product}${s.plan?`/${s.plan}`:""}${s.store_id?` (${s.store_id})`:""}${s.irreversible?" \u2014 permanent":""}${s.note?`: ${s.note}`:""}`);n.note&&e.out.line(` ${n.note}`)}function Kc(e){let t=Je(e,0,"the plan's id");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw h(`${t} is no plan's id: it is the id iap:catalog:plan printed`);return t}function YN(e,t){if(e.out.line(`Plan ${t.id} for revision ${t.revision}: ${t.status}`),Dk(e,Mk.apple,t.apple),Dk(e,Mk.google,t.google),t.problems.length>0){e.out.line("Warnings of the revision:");for(let o of t.problems)e.out.line(` ${o.path}: ${o.message}${o.channel?` (${o.channel})`:""}`)}t.status==="failed"&&t.error&&e.out.line(`It failed: ${t.error}`);let n=t.apple_result;if(!n&&t.apple.steps.length>0&&(t.status==="applying"||t.status==="applied")&&e.out.line("App Store Connect: waiting for the stores module"),n){e.out.line(`App Store Connect (${n.bundle_id}): ${n.ok?"written":`not all written${n.error?`: ${n.error}`:""}`}`);for(let o of n.steps){let i=o.price?`, ${o.price.customer_price} ${o.price.currency}`:"",r=o.next_price?`, ${o.next_price.customer_price} ${o.next_price.currency} from ${o.next_price.from}`:"";e.out.line(` ${o.op} ${o.store_id}${o.state?`: ${o.state}`:""}${i}${r}${o.error?` \u2014 ${o.error}`:""}`)}}let s=t.google_result;if(s){e.out.line(`Google Play (${s.package_name}): ${s.pending?"waiting for the stores module":s.ok?"written":`not all written${s.error?`: ${s.error}`:""}`}`);for(let o of s.steps)e.out.line(` ${o.op} ${o.store_id}${o.state?`: ${o.state}`:""}${o.error?` \u2014 ${o.error}`:""}`)}let a=t.apple.hash||t.google.hash;t.status==="planned"&&a&&(e.out.line(` hash: ${a}`),e.out.line(t.apple.hash?"The App Store part is written only when confirmed (the stores module writes it to App Store Connect):":"The Google Play part is written only when confirmed (the stores module writes it to Google Play):"),e.out.line(` palbase iap:catalog:confirm ${t.id} --hash ${a}`))}var ZN={name:"iap:catalog:plan",summary:"plan bringing the stores to the catalog's newest revision, store by store, before anything is written",usage:"[<plan id>]",details:["A plan is confirmed with its hash (iap:catalog:confirm); the App Store and Google Play parts are written by the stores module once their accounts are connected.","With a plan's id it makes none: it shows that plan, and once confirmed what each store answered \u2014 the state of every product written, and a price that changes on a later day."],args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args.length===0?await g(e,t,"POST","/iap/catalog/plans",void 0,D()):await g(e,t,"GET",`/iap/catalog/plans/${R(Kc(e))}`);e.out.result(n,()=>YN(e,n))}},QN={name:"iap:catalog:confirm",summary:"write a plan to App Store Connect and Google Play through the stores module: it names the hash of the plan that was shown, and is asked about first",usage:"<plan id> --hash <hash>",details:["What it writes is shown, then asked about \u2014 in every environment: a product made in App Store Connect or Google Play never goes away. -y confirms without asking."],args:{min:1,max:1},flags:{hash:{type:"string",value:"hash",description:"the hash the plan printed"}},scope:"environment",async run(e){let t=await f(e),n=Kc(e),s=e.flags.hash;if(s===void 0||s.trim()==="")throw h("--hash is the hash iap:catalog:plan printed: a confirmation names the plan it saw");let a=await g(e,t,"GET",`/iap/catalog/plans/${R(n)}`);if(a.status!=="planned")throw new b("plan_not_open",`the plan ${n} is ${a.status}: only a planned one is confirmed`,{hint:"make a new one: palbase iap:catalog:plan"});let o=a.apple.steps.length,i=a.google.steps.length;if(a.apple.hash&&o>0)await k(e,t,`write ${o} step(s) of revision ${a.revision} to App Store Connect${i>0?`, and ${i} to Google Play`:""}`,"It makes the products in App Store Connect, where a product id never goes away");else if(a.google.hash&&i>0)await k(e,t,`write ${i} step(s) of revision ${a.revision} to Google Play`,"It makes the products in Google Play, where a product id never goes away");else throw new b("nothing_to_confirm",`the plan ${n} has nothing for App Store Connect or Google Play to confirm`);let r=await g(e,t,"POST",`/iap/catalog/plans/${R(n)}/confirm`,{hash:s},D());if(e.out.result(r,()=>{e.out.line(`Plan ${r.id}: ${r.status}${r.applied_at?` (${Z(r.applied_at)})`:""}.`),r.status==="failed"&&r.error&&e.out.line(`It failed: ${r.error}`);let l=[o>0&&!r.apple_result?"App Store Connect":"",i>0&&(!r.google_result||r.google_result.pending)?"Google Play":""].filter(Boolean);l.length>0&&e.out.line(`The stores module is writing to ${l.join(" and ")}: palbase iap:catalog:plan ${r.id} shows what it wrote.`)}),r.status==="failed")throw new b("plan_failed",`the plan ${r.id} failed: a new plan picks up where it stopped`)}},eM={name:"iap:catalog:decline",summary:"decline a plan: its Stripe part is never written",usage:"<plan id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Kc(e);await k(e,t,`decline the plan ${n}`);let s=await g(e,t,"POST",`/iap/catalog/plans/${R(n)}/decline`,void 0,D());e.out.result(s,()=>e.out.line(`Declined the plan ${s.id}.`))}};function Wk(e){let t=e.args[0],n=Number(t);if(t===void 0||!Number.isInteger(n)||n<1)throw h("the revision's number is required (iap:catalog:revisions lists them)");return n}var tM={name:"iap:catalog:revisions",summary:"every revision the catalog was saved as, the newest first: who saved it, when, and when a plan of it was written to the stores",usage:"[--limit <n>] [--cursor <next>]",details:["iap:catalog:revision <n> reads one; iap:catalog:restore <n> puts it back as the next revision."],flags:{limit:{type:"string",value:"n",description:"revisions a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams,s=we(e.flags.limit,"limit");s!==void 0&&n.set("limit",String(s)),e.flags.cursor!==void 0&&n.set("cursor",String(e.flags.cursor));let a=await g(e,t,"GET",`/iap/catalog/revisions${n.size?`?${n}`:""}`);e.out.result(a,()=>{if(a.revisions.length===0){e.out.line("No catalog yet: palbase iap:catalog:put --file catalog.json --revision 0");return}e.out.table(a.revisions,[{header:"revision",value:o=>`${o.revision}${o.current?" (now)":""}`},{header:"saved",value:o=>Z(o.created_at)},{header:"by",value:o=>o.created_by},{header:"products",value:o=>String(o.products)},{header:"entitlements",value:o=>String(o.entitlements)},{header:"offers",value:o=>String(o.offers)},{header:"written to stores",value:o=>Z(o.applied_at)}]),a.next_cursor&&e.out.line(`Older: palbase iap:catalog:revisions --cursor ${a.next_cursor}`)})}},nM={name:"iap:catalog:revision",summary:"the catalog as it was saved at a revision",usage:"<revision> [--out <catalog.json>]",details:["--out writes that revision's catalog to a file, as catalog:get --out writes the newest."],args:{min:1,max:1},flags:{out:{type:"string",value:"catalog.json",description:"write the revision's catalog to this file"}},scope:"environment",async run(e){let t=await f(e),n=Wk(e),s=await g(e,t,"GET",`/iap/catalog/revisions/${n}`),a=e.flags.out;if(a!==void 0){await qc(ji(e.io.cwd,a),`${JSON.stringify(s.catalog,null,2)}
11199
- `),e.out.result({file:a,revision:s.revision},()=>e.out.line(`Wrote revision ${s.revision} of the catalog to ${a}.`));return}e.out.result(s,()=>Uk(e,s))}},sM={name:"iap:catalog:restore",summary:"put an older revision of the catalog back, as its next revision; nothing is written to a store",usage:"<revision>",details:["It is saved as an edit is: checked against today's rules, what customers bought kept in it \u2014 a revision that breaks one is refused with every problem.","The stores are brought to it by a plan, confirmed: palbase iap:catalog:plan."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Wk(e),s=await g(e,t,"GET","/iap/catalog");await k(e,t,`put revision ${n} of the catalog back, over revision ${s.revision}`);let a;try{a=await g(e,t,"POST",`/iap/catalog/revisions/${n}/restore`,void 0,{"if-match":qk(s.revision),...D()})}catch(o){if(o instanceof G&&o.status===412)throw new b("catalog_changed",`the catalog moved past revision ${s.revision} while this ran \u2014 nothing was saved`,{hint:`run it again: palbase iap:catalog:restore ${n}`});Gc(e,o,`revision ${n} was not put back`)}e.out.result(a,()=>{e.out.line(`Saved revision ${n}'s catalog as revision ${a.revision}.`),e.out.line("Bring the stores to it: palbase iap:catalog:plan")})}};function Dc(e){return e===null?"for life":Z(e)}function aM(e,t){e.out.line(`Customer ${t.customer_id}${t.guest?" (guest)":""}: revision ${t.revision}, as of ${Z(t.requested_at)}`);let n=Object.entries(t.entitlements).sort(([s],[a])=>s<a?-1:s>a?1:0);e.out.line(n.length===0?"No entitlement.":"Entitlements:"),e.out.table(n,[{header:"entitlement",value:([s])=>s},{header:"active",value:([,s])=>s.active?"yes":"no"},{header:"until",value:([,s])=>Dc(s.expires_at)},{header:"store",value:([,s])=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"renews",value:([,s])=>s.will_renew?"yes":"no"},{header:"product",value:([,s])=>s.product??"\u2014"}]),t.subscriptions.length>0&&(e.out.line("Subscriptions:"),e.out.table(t.subscriptions,[{header:"product",value:s=>`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}`},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"until",value:s=>Dc(s.expires_at)},{header:"renews",value:s=>s.will_renew?"yes":"no"},{header:"id",value:s=>s.id}])),t.purchases.length>0&&(e.out.line("Purchases:"),e.out.table(t.purchases,[{header:"product",value:s=>s.product??"\u2014"},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"bought",value:s=>Z(s.purchased_at)}])),t.credits.length>0&&(e.out.line("Credits:"),e.out.table(t.credits,[{header:"credit",value:s=>s.currency},{header:"balance",value:s=>String(s.balance)},{header:"available",value:s=>String(s.available)},{header:"held",value:s=>String(s.reserved)},{header:"owed",value:s=>String(s.debt)},{header:"next expiry",value:s=>Z(s.next_expiry)}])),t.limits.length>0&&(e.out.line("Limits:"),e.out.table(t.limits,[{header:"limit",value:s=>s.limit},{header:"used",value:s=>`${s.used} of ${s.max}`},{header:"held",value:s=>String(s.reserved)},{header:"left",value:s=>String(s.remaining)},{header:"resets",value:s=>Z(s.resets_at)}]))}var oM={name:"iap:customer:get",summary:"what a customer has, whatever store they bought in: entitlements, subscriptions, purchases, credits and limits",usage:"<customer id>",details:["The customer is the user's id; a guest merged into an account answers as the account."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=await g(e,t,"GET",`/iap/customers/${R(n)}`);e.out.result(s,()=>aM(e,s))}};function Uc(e){let t=e.flags.until,n=e.flags.for;if(t!==void 0&&n!==void 0)throw h("--until or --for, not both");if(t!==void 0){let s=Date.parse(t);if(!Number.isFinite(s))throw h(`--until ${t}: a date or time (2026-12-31, 2026-12-31T18:00:00Z)`);if(s<=e.io.now())throw h(`--until ${t} is not in the future`);return new Date(s).toISOString()}if(n!==void 0){let s=/^([1-9][0-9]{0,4})([hdw])$/.exec(n.trim());if(!s)throw h(`--for ${n}: a number of hours, days or weeks (12h, 30d, 2w)`);let a=Number(s[1])*{h:1,d:24,w:168}[s[2]];return new Date(e.io.now()+a*36e5).toISOString()}}var iM={name:"iap:customer:grant",summary:"give a customer one of the catalog's entitlements, for a while or for life, saying why \u2014 a promotion, a support case, a tester",usage:"<customer id> <entitlement> --reason <why> [--for 30d | --until <date>]",details:["The reason is the record. Without --for or --until the grant is for life. It prints the grant's id: iap:customer:revoke ends it.","A customer not seen before is made; nothing is charged, in any store."],args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the entitlement"),a=e.flags.reason?.trim();if(!a)throw h("--reason says why it is given: the grant's record");if(a.length>500)throw h("--reason is 500 characters at most");let o=Uc(e);await k(e,t,`give ${n} ${s} ${o?`until ${Z(o)}`:"for life"}`);let i={entitlement:s,reason:a,...o?{expires_at:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/grants`,i,D());e.out.result(r,()=>{e.out.line(`Gave ${r.customer_id} ${r.entitlement} ${r.expires_at?`until ${Z(r.expires_at)}`:"for life"} (grant ${r.id}).`),e.out.line(`End it: palbase iap:customer:revoke ${r.customer_id} ${r.id}`)})}},rM={name:"iap:customer:revoke",summary:"end a granted entitlement now; what the customer bought is not touched",usage:"<customer id> <grant id>",details:["The grant's id is the one iap:customer:grant printed. The entitlement stays on while a purchase still gives it."],args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the grant's id");await k(e,t,`end the grant ${s} of ${n}`),await g(e,t,"DELETE",`/iap/customers/${R(n)}/grants/${R(s)}`,void 0,D()),e.out.result({revoked:s,customer_id:n},()=>e.out.line(`Ended the grant ${s} of ${n}.`))}};function lM(e,t){return e==null?"":`${(e/1e6).toFixed(2)}${t?` ${t}`:""}`}var pM={name:"iap:customers",summary:"find customers by what a person writing in has: their id, an id their store gave a purchase, or the email they bought with on the web",usage:"<query>",details:["The query is a customer's id; Apple's original transaction id or any transaction id; a Google order id (GPA.\u2026, a renewal's ..N or not); Stripe's subscription, payment intent, invoice or customer id; or an email address.","An email finds a buyer who had no account at checkout, matched whole (case aside): the address is never kept, an HMAC of it is."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"what to look for (an id, a store id, an email)"),s=await g(e,t,"GET",`/iap/customers?q=${encodeURIComponent(n)}`);e.out.result(s,()=>{if(s.customers.length===0){e.out.line(`No customer found by ${s.query}.`);return}e.out.table(s.customers,[{header:"customer",value:o=>o.customer_id??"\u2014 (not redeemed yet)"},{header:"found by",value:o=>o.matched_by},{header:"store",value:o=>o.store?`${o.store}${o.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:o=>o.product??""},{header:"since",value:o=>Z(o.at)}]);let a=s.customers.find(o=>o.customer_id);a&&e.out.line(`What happened to them: palbase iap:customer:history ${a.customer_id}`)})}},dM={name:"iap:customer:history",summary:"what happened to a customer, the newest first: payments, refunds, cancellations, grants, credits, moves \u2014 with who did each, and why",usage:"<customer id> [--limit <n>] [--cursor <next>]",details:["Credits spent are the credits' own entries; here are the credits given, taken back, expired and forgiven."],args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"events a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=new URLSearchParams,a=we(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let o=await g(e,t,"GET",`/iap/customers/${R(n)}/history${s.size?`?${s}`:""}`);e.out.result(o,()=>{e.out.line(`History of ${o.customer_id}, the newest first:`),o.events.length===0&&e.out.line("Nothing yet."),e.out.table(o.events,[{header:"when",value:i=>Z(i.at)},{header:"what",value:i=>i.kind},{header:"store",value:i=>i.store?`${i.store}${i.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:i=>[i.product,i.plan].filter(Boolean).join("/")||i.entitlement||""},{header:"amount",value:i=>i.credits?`${i.credits.delta>0?"+":""}${i.credits.delta} ${i.credits.currency}`:lM(i.amount_micros,i.currency)},{header:"why",value:i=>i.credits?[i.credits.kind,i.reason].filter(Boolean).join(": "):i.reason??""},{header:"by",value:i=>i.actor}]),o.next_cursor&&e.out.line(`Older: palbase iap:customer:history ${o.customer_id} --cursor ${o.next_cursor}`)})}},cM={name:"iap:customer:grants",summary:"the entitlements given a customer \u2014 active, ended and revoked \u2014 with each grant's id, reason and who gave it",usage:"<customer id>",details:["End one: palbase iap:customer:revoke <customer id> <grant id>."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=await g(e,t,"GET",`/iap/customers/${R(n)}/grants`);e.out.result(s,()=>{if(s.grants.length===0){e.out.line(`${s.customer_id} was given nothing.`);return}e.out.table(s.grants,[{header:"grant",value:a=>a.id},{header:"entitlement",value:a=>a.entitlement},{header:"active",value:a=>a.active?"yes":"no"},{header:"ends",value:a=>a.revoked_at?`revoked ${Z(a.revoked_at)}`:a.expires_at?Z(a.expires_at):"for life"},{header:"why",value:a=>a.reason},{header:"by",value:a=>a.revoked_by?`${a.granted_by}, revoked by ${a.revoked_by}`:a.granted_by}])})}};function Wc(e){let t=e.flags.note?.trim();if(t!==void 0&&t.length>500)throw h("--note is 500 characters at most");return t||void 0}function Fc(e,t,n){let s=t.subscription;e.out.line(`${n} (${t.action.store}, by ${t.action.actor}).`),e.out.line(`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}: ${s.state}, ${s.active?"on":"off"} until ${Dc(s.expires_at)}, ${s.will_renew?"renews":"does not renew"}.`)}var Bc={note:{type:"string",value:"why",description:"what support writes of it (500 characters at most): the record"}},uM={name:"iap:customer:extend",summary:"move a customer's subscription renewal days later, for free: the App Store's extension, Google Play's deferral, Stripe's next charge moved",usage:"<customer id> <subscription id> --days <1-90> --reason customer_satisfaction|service_issue|other [--note <why>]",details:["The subscription's id is the one iap:customer:get prints. The App Store extends a paid, active subscription, at most 90 days and twice a year.","The store is asked again after: the new expiry is printed, and the customer's history keeps it with who did it."],args:{min:2,max:2},flags:{days:{type:"string",value:"n",description:"how many days (1 to 90)"},reason:{type:"string",value:"why",description:"customer_satisfaction, service_issue or other: as the App Store asks it"},...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=we(e.flags.days,"days");if(a===void 0||a<1||a>90)throw h("--days is 1 to 90");let o=e.flags.reason;if(o!=="customer_satisfaction"&&o!=="service_issue"&&o!=="other")throw h("--reason is customer_satisfaction, service_issue or other");let i=Wc(e);await k(e,t,`extend ${n}'s subscription ${s} by ${a} day(s)`);let r={days:a,reason:o,...i?{note:i}:{}},l=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/extend`,r,D());e.out.result(l,()=>Fc(e,l,`Extended ${n}'s subscription by ${a} day(s)`))}},mM={name:"iap:customer:refund",summary:"refund a customer's subscription \u2014 its latest payment, or what is left of its period \u2014 and end it now: Google Play and Stripe",usage:"<customer id> <subscription id> --mode full|prorated [--note <why>]",details:["The customer's access ends as it answers. The App Store decides its own refunds: the customer asks Apple, which asks the app what they used \u2014 Palbase answers it when they consented in the app."],args:{min:2,max:2},flags:{mode:{type:"string",value:"kind",description:"full: the latest payment; prorated: what is left of its period"},...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=e.flags.mode;if(a!=="full"&&a!=="prorated")throw h("--mode is full (the latest payment) or prorated (what is left of its period)");let o=Wc(e);await k(e,t,`refund ${n}'s subscription ${s} (${a}) and end it now`);let i={mode:a,...o?{note:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/refund`,i,D());e.out.result(r,()=>Fc(e,r,`Refunded ${n}'s subscription (${a}); it ended`))}},gM={name:"iap:customer:cancel",summary:"turn a customer's subscription renewal off: it ends at its period's end, the customer keeping what they paid for \u2014 Google Play and Stripe",usage:"<customer id> <subscription id> [--note <why>]",details:["An App Store subscription's renewal is the customer's to turn off (Settings \u203A Apple ID \u203A Subscriptions)."],args:{min:2,max:2},flags:{...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=Wc(e);await k(e,t,`turn the renewal of ${n}'s subscription ${s} off`);let o=a?{note:a}:{},i=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/cancel`,o,D());e.out.result(i,()=>Fc(e,i,`Turned the renewal of ${n}'s subscription off`))}},Fk={source:{type:"string",value:"kind",description:"support (the default) or promotion"}};function Bk(e){let t=e.flags.source??"support";if(t!=="support"&&t!=="promotion")throw h("--source is support or promotion");return t}function Ul(e,t){let n=e.flags.reason?.trim();if(!n)throw h(`--reason says why ${t}: the record`);if(n.length>500)throw h("--reason is 500 characters at most");return n}function Jk(e,t,n){let s=Je(e,t,n),a=Number(s);if(!Number.isInteger(a)||a<1)throw h(`${n} is a whole number above 0: ${s}`);return a}var hM={name:"iap:customer:credits",summary:"a customer's credit entries, the newest first: given, spent, taken back, expired, forgiven \u2014 with who did each, and why",usage:"<customer id> [--credits <key>] [--limit <n>] [--cursor <next>]",args:{min:1,max:1},flags:{credits:{type:"string",value:"key",description:"one of the catalog's credits alone"},limit:{type:"string",value:"n",description:"entries a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=new URLSearchParams;e.flags.credits!==void 0&&s.set("credits",String(e.flags.credits));let a=we(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let o=await g(e,t,"GET",`/iap/customers/${R(n)}/credits/entries${s.size?`?${s}`:""}`);e.out.result(o,()=>{o.entries.length===0&&e.out.line(`${n} has no credit entry.`),e.out.table(o.entries,[{header:"when",value:i=>Z(i.created_at)},{header:"credit",value:i=>i.currency},{header:"what",value:i=>i.kind},{header:"amount",value:i=>`${i.delta>0?"+":""}${i.delta}`},{header:"owed",value:i=>i.debt_delta?`${i.debt_delta>0?"+":""}${i.debt_delta}`:""},{header:"why",value:i=>i.reason??""},{header:"by",value:i=>i.actor??""}]),o.next_cursor&&e.out.line(`Older: palbase iap:customer:credits ${n} --cursor ${o.next_cursor}`)})}},yM={name:"iap:customer:credits:give",summary:"give a customer credits, saying why \u2014 a support case, a promotion \u2014 for a while or until spent",usage:"<customer id> <credits> <amount> --reason <why> [--source support|promotion] [--for 30d | --until <date>]",details:["What they owe is paid first from what is given. Nothing is charged, in any store."],args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why they are given (500 characters at most): the record"},...Fk,for:{type:"string",value:"span",description:"how long they last: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when they expire (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the credits (the catalog's key)"),a=Jk(e,2,"the amount"),o=Ul(e,"they are given"),i=Bk(e),r=Uc(e);await k(e,t,`give ${n} ${a} ${s}${r?` until ${Z(r)}`:""}`);let l={credits:s,amount:a,source:i,reason:o,...r?{expires_at:r}:{}},p=await g(e,t,"POST",`/iap/customers/${R(n)}/credits`,l,D());e.out.result(p,()=>e.out.line(`Gave ${n} ${p.original} ${p.currency}${p.expires_at?` until ${Z(p.expires_at)}`:""}; ${p.remaining} left of it.`))}},fM={name:"iap:customer:credits:forgive",summary:"forgive what a customer owes of a credit \u2014 all of it, or an amount \u2014 saying why",usage:"<customer id> <credits> --reason <why> [--amount <n>]",args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is forgiven (500 characters at most): the record"},amount:{type:"string",value:"n",description:"how much of it (default: all they owe)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the credits (the catalog's key)"),a=Ul(e,"it is forgiven"),o=we(e.flags.amount,"amount");if(o===0)throw h("--amount is above 0");await k(e,t,`forgive ${o??"all"} of what ${n} owes of ${s}`);let i={credits:s,reason:a,...o!==void 0?{amount:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/credits/forgive`,i,D());e.out.result(r,()=>e.out.line(`Forgave ${r.forgiven} ${r.credits} ${n} owed; they owe ${r.debt}, ${r.available} available.`))}};function Jc(e,t,n){e.out.line(`${t}: ${n.used} of ${n.max} used, ${n.remaining} left, resets ${Z(n.resets_at)}.`)}var bM={name:"iap:customer:limit:set",summary:"set a customer's own maximum of a limit \u2014 above or below the catalog's \u2014 saying why, for a while or until cleared",usage:"<customer id> <limit> <max> --reason <why> [--for 30d | --until <date>]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)"),a=Je(e,2,"the maximum"),o=Number(a);if(!Number.isInteger(o)||o<0)throw h(`the maximum is a whole number: ${a}`);let i=Ul(e,"it is set"),r=Uc(e);await k(e,t,`set ${n}'s ${s} to ${o}${r?` until ${Z(r)}`:""}`);let l={max:o,reason:i,...r?{expires_at:r}:{}},p=await g(e,t,"PUT",`/iap/customers/${R(n)}/limits/${R(s)}`,l,D());e.out.result(p,()=>Jc(e,`Set ${n}'s ${p.limit} to ${p.max}`,p))}},wM={name:"iap:customer:limit:clear",summary:"clear a customer's own maximum of a limit: the catalog's counts again",usage:"<customer id> <limit>",args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)");await k(e,t,`clear ${n}'s own ${s}`);let a=await g(e,t,"DELETE",`/iap/customers/${R(n)}/limits/${R(s)}`,void 0,D());e.out.result(a,()=>Jc(e,`Cleared ${n}'s own ${a.limit}; the catalog's ${a.max} counts`,a))}},vM={name:"iap:customer:limit:give",summary:"give a customer more of a limit for its current period, saying why \u2014 a gift on top of their maximum",usage:"<customer id> <limit> <amount> --reason <why> [--source support|promotion]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},...Fk},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)"),a=Jk(e,2,"the amount"),o=Ul(e,"it is given"),i=Bk(e);await k(e,t,`give ${n} ${a} more ${s} this period`);let r={amount:a,source:i,reason:o},l=await g(e,t,"POST",`/iap/customers/${R(n)}/limits/${R(s)}/grants`,r,D());e.out.result(l,()=>Jc(e,`Gave ${n} ${a} more ${l.limit}`,l))}};function kM(e){let t=n=>/^[\w./@:-]+$/.test(n)?n:JSON.stringify(n);return`${e.global.project!==void 0?` -P ${t(e.global.project)}`:""}${e.global.env!==void 0?` -E ${t(e.global.env)}`:""}`}async function Hc(e,t){let n=(await Vt(e,t.project_id)).filter(r=>r.deleted_at===null),s=n.filter(r=>r.platform==="ios"),a=e.flags.app;if(a!==void 0){let r=un(n,a);if(r.platform!=="ios")throw h(`${r.slug} is a ${r.platform} app: a StoreKit configuration is an iOS app's`,`the project's iOS apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return r}let o=(await nl(e.io.cwd))?.apps.filter(r=>r.platform==="ios").map(r=>r.id)??[],i=s.filter(r=>o.includes(r.id));if(i.length===1)return i[0];if(s.length===1)return s[0];throw s.length===0?new b("no_ios_app",`${t.project_name} has no iOS app`,{hint:"register it: palbase apps:create ios <name> --team-id <team id>"}):h("name the iOS app the file is for: --app <app>",`the project's iOS apps: ${s.map(r=>r.slug).join(", ")}`)}function _M(e,t){let n=BN(e.io.cwd,ji(e.io.cwd,t)).split(JN).join("/");if(!n.startsWith(`${ue}/`)||n.split("/").includes(".."))throw h(`--out ${t}: the file goes under ${ue}/, as the CLI writes nothing else in the checkout`,`palbase iap:storekit --out ${ue}/<name>.storekit`);if(!n.endsWith(".storekit"))throw h(`--out ${t}: Xcode takes a StoreKit configuration by its .storekit extension`);return n}function SM(e){let t=new Map;for(let n of e.products)for(let s of n.channels.ios?.plans??[])t.set(s.price.currency.toUpperCase(),(t.get(s.price.currency.toUpperCase())??0)+1);return[...t].sort(([n,s],[a,o])=>o-s||(n<a?-1:1))[0]?.[0]}var $M={name:"iap:storekit",summary:"an Xcode StoreKit configuration of the environment's iOS products, under palbase/: a build Xcode runs buys them with no App Store",usage:"[--app <app>] [--out <palbase/\u2026.storekit>] [--storefront <code>]",details:["Each plan is the App Store product its store id names, with its text in every language the catalog has and its price; a subscription is in its group, at its tier's level, with its introductory offer and the catalog's offers on it as promotional offers (a grant has no store).","Prices are in the storefront's currency: the catalog's price, or the amount set by hand in that currency. The storefront is --storefront, else the one the file has, else the one the catalog's currency is the App Store's own price in (USD: USA, EUR: Germany, TRY: Turkey \u2026), else USA.","Made again, the file is made whole from the catalog \u2014 the same catalog, the same file \u2014 keeping the test settings Xcode's Editor menu wrote in it. Nothing outside palbase/ is written: Xcode is pointed at the file in the scheme."],flags:{app:{type:"string",value:"app",description:"the iOS app it is for (default: the one this checkout syncs, or the project's only one)"},out:{type:"string",value:"palbase/\u2026.storekit",description:"where under palbase/ (default: palbase/environments/<env>/<app>.storekit)"},storefront:{type:"string",value:"code",description:"the App Store storefront prices are in, by its three letters (USA, DEU, TUR, GBR, JPN \u2026)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.storefront?.trim().toUpperCase();if(n!==void 0&&!lo.has(n))throw h(`--storefront ${e.flags.storefront}: not an App Store storefront`,"a storefront is three letters, its country's ISO 3166-1 code: USA, DEU, TUR, GBR, JPN \u2026");let s=await Hc(e,t);if(!/^[A-Za-z][A-Za-z0-9-]{0,38}$/.test(t.env_slug))throw new b("unexpected_answer",`the environment's slug ${JSON.stringify(t.env_slug)} is not one`);if(!/^[a-z][a-z0-9-]{0,38}[a-z0-9]$/.test(s.slug))throw new b("unexpected_answer",`the project answered app ${JSON.stringify(s.slug)}, which is not one`);let a=e.flags.out!==void 0?_M(e,e.flags.out):`${ue}/environments/${t.env_slug}/${s.slug}.storekit`,o=await g(e,t,"GET","/iap/offerings?channel=ios");if(!o.products.some(E=>(E.channels.ios?.plans.length??0)>0))throw new b("nothing_on_ios",`${t.env_name}'s catalog sells nothing on iOS yet: there is no product for Xcode to sell`,{hint:"give a product channels.ios in the catalog (palbase iap:catalog:get --out catalog.json, then iap:catalog:put)"});let i=await Be(e.io.cwd,a),r,l;try{r=await zc(i,"utf8");let E=JSON.parse(r);typeof E.settings=="object"&&E.settings!==null&&!Array.isArray(E.settings)&&(l=E.settings)}catch{}let p=typeof l?._storefront=="string"&&lo.has(l._storefront)?l._storefront:void 0,d=SM(o);n??=p??(d!==void 0?Gw(d):void 0)??"USA";let{catalog:u}=await g(e,t,"GET","/iap/catalog"),m=Ww(o,{seed:`${t.env_ref}/${s.id}`,storefront:n,settings:l,offers:u.offers??[]}),y=r!==m.text;y&&(await UN(FN(i),{recursive:!0}),await Be(e.io.cwd,a),await qc(i,m.text));for(let E of m.notes)e.out.warn(E);let w=t.env_slug===Mt,v=kM(e),P=[`In Xcode: Product \u203A Scheme \u203A Edit Scheme\u2026 \u203A Run \u203A Options \u203A StoreKit Configuration \u2014 choose ${a} (not listed yet? add it from that menu).`,w?`${t.project_name} \u203A ${t.env_name} is the project's production environment: it never takes a purchase Xcode signs. Make the file for a test environment (-E <env>) to see a purchase reach the server.`:`Then select the file in Xcode, choose Editor \u203A Save Public Certificate, and let ${t.env_name} take the purchases Xcode signs: palbase iap:apple:xcode-certificate <the saved .cer file>${v}`,`Run the app and buy: Xcode sells the products itself, nothing goes to the App Store. After the catalog changes: palbase iap:storekit${e.flags.app!==void 0?` --app ${s.slug}`:""}${e.flags.out!==void 0?` --out ${a}`:""}${v}`],A=m.counts,T=[A.subscriptions>0?`${A.subscriptions} subscription${A.subscriptions===1?"":"s"} in ${A.groups} group${A.groups===1?"":"s"}`:"",A.products>0?`${A.products} in-app purchase${A.products===1?"":"s"}`:"",A.non_renewing>0?`${A.non_renewing} non-renewing subscription${A.non_renewing===1?"":"s"}`:""].filter(E=>E!=="").join(", ");e.out.result({file:a,app:s.slug,environment:t.env_slug,revision:o.revision,storefront:m.storefront,currency:m.currency,locale:m.locale,...A,written:y,next:P},()=>{e.out.line(`${y?"Wrote":"Up to date:"} ${a} \u2014 ${T}, priced in ${m.currency} (storefront ${m.storefront}), catalog revision ${o.revision}.`),e.out.line(""),P.forEach((E,C)=>e.out.line(`${C+1}. ${E}`))})}},AM=/^SubscriptionKey_([A-Z0-9]{10})\.p8$/,RM=/^AuthKey_[A-Z0-9]{10}\.p8$/,PM=8192,jM=16384;function Hk(e,t){if(!t.connected)e.out.line("No In-App Purchase key is connected: the App Store's purchases are not taken."),e.out.line("Connect one: palbase iap:apple:connect --key-file SubscriptionKey_<KEYID>.p8");else{e.out.line(`In-App Purchase key ${t.key_id??"?"} (issuer ${t.issuer_id??"?"}) for ${t.bundle_id??"?"}${t.app_apple_id?`, Apple ID ${t.app_apple_id}`:", its Apple ID not known yet"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${Z(t.checked_at)})`:""}`);let s=t.notifications;s&&e.out.line(`notifications: ${s.url} \u2014 ${s.bound?`bound ${Z(s.bound_at)}`:`not bound${s.error?`: ${s.error}`:""}`}; Apple's TEST notification ${s.verified_at?`arrived ${Z(s.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}let n=t.xcode_certificate;e.out.line(n?`Xcode's StoreKit Testing purchases: taken, signed with ${n.subject} until ${Z(n.not_after)} (sha256 ${n.fingerprint.slice(0,16)}\u2026)`:"Xcode's StoreKit Testing purchases: not taken (palbase iap:apple:xcode-certificate <file> takes them)")}var TM={name:"iap:apple",summary:"the environment's App Store connection: the In-App Purchase key, where the App Store reports, whether Xcode's purchases are taken",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/iap/apple");e.out.result(n,()=>Hk(e,n))}};function EM(e,t){let n=e.environments.find(s=>s.ref===t.env_ref)?.ios?.bundle;if(n===void 0)throw new b("app_not_in_environment",`${e.slug} is not set in ${t.env_name}: the key is connected for the app's bundle there`,{hint:`palbase apps:env:set ${e.slug} -E ${t.env_slug} --bundle <bundle id>`});return n}var CM={name:"iap:apple:connect",summary:"connect an In-App Purchase key for an iOS app: it goes from this computer straight to the environment, never through Studio",usage:"--key-file <SubscriptionKey_KEYID.p8> [--key-id <KEYID>] [--issuer-id <issuer id>] [--app <app>] | --print-link",details:["App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes the key (SubscriptionKey_<KEYID>.p8) and shows the Issuer ID \u2014 the team's, the same as its App Store Connect API keys': left out, the one stores:apple connected is taken.","The environment verifies the app's purchases and reads its subscriptions with it, and has the stores module point the App Store's notifications at the environment.","Studio is asked for a one-time grant alone; the key is posted with it to the environment's own address. --print-link prints a link that takes the key in a browser instead."],flags:{"key-file":{type:"string",value:"SubscriptionKey_KEYID.p8",description:"the .p8 file Apple gave when the key was made"},"key-id":{type:"string",value:"KEYID",description:"the key's id (default: from the file's name)"},"issuer-id":{type:"string",value:"issuer id",description:"the team's issuer id (default: the connected App Store Connect key's)"},app:{type:"string",value:"app",description:"the iOS app (default: the one this checkout syncs, or the project's only one)"},"print-link":{type:"boolean",description:"only print a link that takes the key in a browser (valid 30 minutes, once)"}},scope:"environment",async run(e){let t=await f(e);if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw h("--print-link or --key-file, not both");await k(e,t,"make a link that connects an In-App Purchase key");let y=await g(e,t,"POST","/iap/apple/grants",void 0,D());mn(e,t,y.connect_url,"the connect link"),e.out.result({connect_url:y.connect_url,expires_at:y.expires_at},()=>{e.out.line(y.connect_url),e.out.note(`Open it in a browser, pick the app and the .p8 file; it works once, until ${Z(y.expires_at)}.`)});return}let n=e.flags["key-file"];if(n===void 0)throw h("--key-file names the In-App Purchase key's .p8 file","or --print-link for a link a browser opens");let s=WN(n),a=e.flags["key-id"];if(a===void 0){if(RM.test(s))throw h(`${s} is an App Store Connect API key (palbase stores:apple:connect takes it): this is the In-App Purchase key, SubscriptionKey_<KEYID>.p8`,"App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes one");if(a=AM.exec(s)?.[1],a===void 0)throw h(`--key-id is needed: ${s} is not named SubscriptionKey_<KEYID>.p8`)}let o;try{let y=ji(e.io.cwd,n);if((await zk(y)).size>PM)throw new b("not_a_key",`${n} is larger than a .p8 key`);o=await zc(y,"utf8")}catch(y){throw y instanceof b?y:new b("unreadable_file",`${n} could not be read: ${y instanceof Error?y.message:String(y)}`)}if(!o.includes("-----BEGIN PRIVATE KEY-----"))throw new b("not_a_key",`${n} is not a .p8 key (no "BEGIN PRIVATE KEY")`);let i=e.flags["issuer-id"]?.trim();if(i===void 0||i===""){let y=await g(e,t,"GET","/stores/apple");if(i=y.connected?y.issuer_id:void 0,i===void 0)throw h("--issuer-id is the team's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations): no App Store Connect key is connected to read it from")}let r=await Hc(e,t),l=EM(r,t);await k(e,t,`connect the In-App Purchase key ${a} for ${l}`);let p=await g(e,t,"POST","/iap/apple/grants",void 0,D()),d=mn(e,t,p.connect_url,"the connect link"),u={grant:p.grant,issuer_id:i,key_id:a,private_key:o,bundle_id:l},m=await wi(e,`${d}/iap/apple/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(u)},"connecting the In-App Purchase key");e.out.result(m,()=>{e.out.line(`Connected key ${a} for ${l} to ${ee(t)}.`),Hk(e,m),e.out.line("Check what else the App Store needs: palbase iap:doctor")})}},OM={name:"iap:apple:disconnect",summary:"forget the environment's In-App Purchase key: the App Store's purchases and notifications are refused from then on (what was bought stays)",scope:"environment",async run(e){let t=await f(e);await k(e,t,"disconnect the In-App Purchase key"),await g(e,t,"DELETE","/iap/apple",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the In-App Purchase key from ${ee(t)}.`))}};function Vk(e,t){if(t.service_account===void 0){e.out.line("The project has no Google Play connection: Palbase reads the app's purchases as the account your Play Console invites."),e.out.line("Connect it first: palbase stores:google:connect");return}if(e.out.line(`Play connection: ${t.service_account} (${t.play_status??"not checked"})`),!t.connected){e.out.line("Google Play purchases are not connected: palbase iap:google:connect --app <android app>");return}e.out.line(`app: ${t.package_name??"?"}`),e.out.line(`topic: ${t.topic??"?"} (Play Console \u203A Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications)`),e.out.line(`notifications: ${t.notification_url??"?"} \u2014 Play's test notification ${t.verified_at?`arrived ${Z(t.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var xM={name:"iap:google",summary:"the environment's Google Play purchases: the app they are made in, the topic its Play Console names, whether Play's test notification arrived",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/iap/google");e.out.result(n,()=>Vk(e,n))}};async function LM(e,t){let n=(await Vt(e,t.project_id)).filter(r=>r.deleted_at===null),s=n.filter(r=>r.platform==="android"),a=e.flags.app;if(a!==void 0){let r=un(n,a);if(r.platform!=="android")throw h(`${r.slug} is a ${r.platform} app: Google Play purchases are an Android app's`,`the project's Android apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return r}let o=(await nl(e.io.cwd))?.apps.filter(r=>r.platform==="android").map(r=>r.id)??[],i=s.filter(r=>o.includes(r.id));if(i.length===1)return i[0];if(s.length===1)return s[0];throw s.length===0?new b("no_android_app",`${t.project_name} has no Android app`,{hint:"register it: palbase apps:create android <name>"}):h("name the Android app: --app <app>",`the project's Android apps: ${s.map(r=>r.slug).join(", ")}`)}var IM={name:"iap:google:connect",summary:"sell on Google Play in one of the project's Android apps: Palbase makes the app's notifications topic and has it pushed to this environment",usage:"[--app <app>]",details:["The project's Play connection (palbase stores:google:connect) is the account Palbase reads and acknowledges the app's purchases as: its Play Console invites it with View financial data and Manage orders and subscriptions.","Then, in Play Console: Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications, the topic this prints, Save, and Send test notification \u2014 palbase iap:google says when it arrived."],flags:{app:{type:"string",value:"app",description:"the Android app (default: the one this checkout syncs, or the project's only one)"}},scope:"environment",async run(e){let t=await f(e),n=await LM(e,t);await k(e,t,`connect Google Play purchases for ${n.slug}`);let s={app_id:n.id},a=await g(e,t,"POST","/iap/google",s,D());e.out.result(a,()=>{e.out.line(`Google Play purchases connected for ${a.package_name??n.slug} in ${ee(t)}.`),Vk(e,a)})}},NM={name:"iap:google:disconnect",summary:"stop taking the environment's Google Play purchases: Play's notifications stop reaching it, and the app's reports are refused (what was bought stays)",scope:"environment",async run(e){let t=await f(e);await k(e,t,"disconnect Google Play purchases"),await g(e,t,"DELETE","/iap/google",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play purchases from ${ee(t)}.`))}};async function MM(e,t){let n=(await Vt(e,t.project_id)).find(s=>s.deleted_at===null&&s.environments.some(a=>a.ref===t.env_ref));return n===void 0?t.env_slug===Mt:(await e.studio.get(`/environments/${t.env_ref}/apps/${n.id}/config`)).environment.production}async function DM(e,t){let n;try{let o=ji(t,e);if((await zk(o)).size>jM)throw new b("not_a_certificate",`${e} is larger than Xcode's certificate`);n=await zc(o)}catch(o){throw o instanceof b?o:new b("unreadable_file",`${e} could not be read: ${o instanceof Error?o.message:String(o)}`)}let s;try{s=new KN(n)}catch{throw new b("not_a_certificate",`${e} is not a certificate`,{hint:"the one Xcode saves: select the .storekit file, then Editor \u203A Save Public Certificate"})}let a=n.toString("latin1");return{certificate:a.includes("-----BEGIN CERTIFICATE-----")?a.trim():n.toString("base64"),x509:s}}var zM={name:"iap:apple:xcode-certificate",summary:"take the purchases Xcode's StoreKit Testing signs with this certificate, as test purchases \u2014 never on production; --remove stops",usage:"<certificate.cer> | --remove",details:["Xcode saves the certificate: select the .storekit file (palbase iap:storekit makes it), then Editor \u203A Save Public Certificate.","From then on what the app reports signed with it \u2014 Xcode's own purchases, on a developer's Mac \u2014 is a test purchase of the environment, with or without an In-App Purchase key; nothing of it is asked of Apple. Set again, it replaces the one before.","The production environment takes only what the App Store signed: it is refused there."],args:{min:0,max:1},flags:{remove:{type:"boolean",description:"stop taking Xcode's purchases (those taken stay)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.remove===!0,s=e.args[0];if(n===(s!==void 0))throw h("name the certificate file, or --remove","palbase iap:apple:xcode-certificate StoreKitTestCertificate.cer");if(n){await k(e,t,"stop taking Xcode's StoreKit Testing purchases"),await g(e,t,"DELETE","/iap/apple/xcode-certificate",void 0,D()),e.out.result({removed:!0},()=>e.out.line(`${ee(t)} no longer takes Xcode's purchases; those it took stay.`));return}let a=await DM(s,e.io.cwd);if(await MM(e,t))throw new b("production_environment",`${t.project_name} \u203A ${t.env_name} is the project's production environment: it takes only purchases the App Store signed, never Xcode's`,{hint:"set the certificate on a test environment: palbase iap:apple:xcode-certificate <file> -E <env>"});await k(e,t,`take the purchases Xcode signs with ${a.x509.subject.replaceAll(`
11199
+ `),e.out.result({file:a,revision:s.revision},()=>e.out.line(`Wrote revision ${s.revision} of the catalog to ${a}.`));return}e.out.result(s,()=>Uk(e,s))}},sM={name:"iap:catalog:restore",summary:"put an older revision of the catalog back, as its next revision; nothing is written to a store",usage:"<revision>",details:["It is saved as an edit is: checked against today's rules, what customers bought kept in it \u2014 a revision that breaks one is refused with every problem.","The stores are brought to it by a plan, confirmed: palbase iap:catalog:plan."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Wk(e),s=await g(e,t,"GET","/iap/catalog");await k(e,t,`put revision ${n} of the catalog back, over revision ${s.revision}`);let a;try{a=await g(e,t,"POST",`/iap/catalog/revisions/${n}/restore`,void 0,{"if-match":qk(s.revision),...D()})}catch(o){if(o instanceof G&&o.status===412)throw new b("catalog_changed",`the catalog moved past revision ${s.revision} while this ran \u2014 nothing was saved`,{hint:`run it again: palbase iap:catalog:restore ${n}`});Gc(e,o,`revision ${n} was not put back`)}e.out.result(a,()=>{e.out.line(`Saved revision ${n}'s catalog as revision ${a.revision}.`),e.out.line("Bring the stores to it: palbase iap:catalog:plan")})}};function Dc(e){return e===null?"for life":Z(e)}function aM(e,t){e.out.line(`Customer ${t.customer_id}${t.guest?" (guest)":""}: revision ${t.revision}, as of ${Z(t.requested_at)}`);let n=Object.entries(t.entitlements).sort(([s],[a])=>s<a?-1:s>a?1:0);e.out.line(n.length===0?"No entitlement.":"Entitlements:"),e.out.table(n,[{header:"entitlement",value:([s])=>s},{header:"active",value:([,s])=>s.active?"yes":"no"},{header:"until",value:([,s])=>Dc(s.expires_at)},{header:"store",value:([,s])=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"renews",value:([,s])=>s.will_renew?"yes":"no"},{header:"product",value:([,s])=>s.product??"\u2014"}]),t.subscriptions.length>0&&(e.out.line("Subscriptions:"),e.out.table(t.subscriptions,[{header:"product",value:s=>`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}`},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"until",value:s=>Dc(s.expires_at)},{header:"renews",value:s=>s.will_renew?"yes":"no"},{header:"seats",value:s=>s.quantity===void 0?"\u2014":s.renewal_quantity===void 0?String(s.quantity):`${s.quantity} (${s.renewal_quantity} at renewal)`},{header:"id",value:s=>s.id}])),t.purchases.length>0&&(e.out.line("Purchases:"),e.out.table(t.purchases,[{header:"product",value:s=>s.product??"\u2014"},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"bought",value:s=>Z(s.purchased_at)}])),t.credits.length>0&&(e.out.line("Credits:"),e.out.table(t.credits,[{header:"credit",value:s=>s.currency},{header:"balance",value:s=>String(s.balance)},{header:"available",value:s=>String(s.available)},{header:"held",value:s=>String(s.reserved)},{header:"owed",value:s=>String(s.debt)},{header:"next expiry",value:s=>Z(s.next_expiry)}])),t.limits.length>0&&(e.out.line("Limits:"),e.out.table(t.limits,[{header:"limit",value:s=>s.limit},{header:"used",value:s=>`${s.used} of ${s.max}`},{header:"held",value:s=>String(s.reserved)},{header:"left",value:s=>String(s.remaining)},{header:"resets",value:s=>Z(s.resets_at)}]))}var oM={name:"iap:customer:get",summary:"what a customer has, whatever store they bought in: entitlements, subscriptions, purchases, credits and limits",usage:"<customer id>",details:["The customer is the user's id; a guest merged into an account answers as the account."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=await g(e,t,"GET",`/iap/customers/${R(n)}`);e.out.result(s,()=>aM(e,s))}};function Uc(e){let t=e.flags.until,n=e.flags.for;if(t!==void 0&&n!==void 0)throw h("--until or --for, not both");if(t!==void 0){let s=Date.parse(t);if(!Number.isFinite(s))throw h(`--until ${t}: a date or time (2026-12-31, 2026-12-31T18:00:00Z)`);if(s<=e.io.now())throw h(`--until ${t} is not in the future`);return new Date(s).toISOString()}if(n!==void 0){let s=/^([1-9][0-9]{0,4})([hdw])$/.exec(n.trim());if(!s)throw h(`--for ${n}: a number of hours, days or weeks (12h, 30d, 2w)`);let a=Number(s[1])*{h:1,d:24,w:168}[s[2]];return new Date(e.io.now()+a*36e5).toISOString()}}var iM={name:"iap:customer:grant",summary:"give a customer one of the catalog's entitlements, for a while or for life, saying why \u2014 a promotion, a support case, a tester",usage:"<customer id> <entitlement> --reason <why> [--for 30d | --until <date>]",details:["The reason is the record. Without --for or --until the grant is for life. It prints the grant's id: iap:customer:revoke ends it.","A customer not seen before is made; nothing is charged, in any store."],args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the entitlement"),a=e.flags.reason?.trim();if(!a)throw h("--reason says why it is given: the grant's record");if(a.length>500)throw h("--reason is 500 characters at most");let o=Uc(e);await k(e,t,`give ${n} ${s} ${o?`until ${Z(o)}`:"for life"}`);let i={entitlement:s,reason:a,...o?{expires_at:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/grants`,i,D());e.out.result(r,()=>{e.out.line(`Gave ${r.customer_id} ${r.entitlement} ${r.expires_at?`until ${Z(r.expires_at)}`:"for life"} (grant ${r.id}).`),e.out.line(`End it: palbase iap:customer:revoke ${r.customer_id} ${r.id}`)})}},rM={name:"iap:customer:revoke",summary:"end a granted entitlement now; what the customer bought is not touched",usage:"<customer id> <grant id>",details:["The grant's id is the one iap:customer:grant printed. The entitlement stays on while a purchase still gives it."],args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the grant's id");await k(e,t,`end the grant ${s} of ${n}`),await g(e,t,"DELETE",`/iap/customers/${R(n)}/grants/${R(s)}`,void 0,D()),e.out.result({revoked:s,customer_id:n},()=>e.out.line(`Ended the grant ${s} of ${n}.`))}};function lM(e,t){return e==null?"":`${(e/1e6).toFixed(2)}${t?` ${t}`:""}`}var pM={name:"iap:customers",summary:"find customers by what a person writing in has: their id, an id their store gave a purchase, or the email they bought with on the web",usage:"<query>",details:["The query is a customer's id; Apple's original transaction id or any transaction id; a Google order id (GPA.\u2026, a renewal's ..N or not); Stripe's subscription, payment intent, invoice or customer id; or an email address.","An email finds a buyer who had no account at checkout, matched whole (case aside): the address is never kept, an HMAC of it is."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"what to look for (an id, a store id, an email)"),s=await g(e,t,"GET",`/iap/customers?q=${encodeURIComponent(n)}`);e.out.result(s,()=>{if(s.customers.length===0){e.out.line(`No customer found by ${s.query}.`);return}e.out.table(s.customers,[{header:"customer",value:o=>o.customer_id??"\u2014 (not redeemed yet)"},{header:"found by",value:o=>o.matched_by},{header:"store",value:o=>o.store?`${o.store}${o.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:o=>o.product??""},{header:"since",value:o=>Z(o.at)}]);let a=s.customers.find(o=>o.customer_id);a&&e.out.line(`What happened to them: palbase iap:customer:history ${a.customer_id}`)})}},dM={name:"iap:customer:history",summary:"what happened to a customer, the newest first: payments, refunds, cancellations, grants, credits, moves \u2014 with who did each, and why",usage:"<customer id> [--limit <n>] [--cursor <next>]",details:["Credits spent are the credits' own entries; here are the credits given, taken back, expired and forgiven."],args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"events a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=new URLSearchParams,a=we(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let o=await g(e,t,"GET",`/iap/customers/${R(n)}/history${s.size?`?${s}`:""}`);e.out.result(o,()=>{e.out.line(`History of ${o.customer_id}, the newest first:`),o.events.length===0&&e.out.line("Nothing yet."),e.out.table(o.events,[{header:"when",value:i=>Z(i.at)},{header:"what",value:i=>i.kind},{header:"store",value:i=>i.store?`${i.store}${i.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:i=>[i.product,i.plan].filter(Boolean).join("/")||i.entitlement||""},{header:"amount",value:i=>i.credits?`${i.credits.delta>0?"+":""}${i.credits.delta} ${i.credits.currency}`:lM(i.amount_micros,i.currency)},{header:"why",value:i=>i.credits?[i.credits.kind,i.reason].filter(Boolean).join(": "):i.reason??""},{header:"by",value:i=>i.actor}]),o.next_cursor&&e.out.line(`Older: palbase iap:customer:history ${o.customer_id} --cursor ${o.next_cursor}`)})}},cM={name:"iap:customer:grants",summary:"the entitlements given a customer \u2014 active, ended and revoked \u2014 with each grant's id, reason and who gave it",usage:"<customer id>",details:["End one: palbase iap:customer:revoke <customer id> <grant id>."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=await g(e,t,"GET",`/iap/customers/${R(n)}/grants`);e.out.result(s,()=>{if(s.grants.length===0){e.out.line(`${s.customer_id} was given nothing.`);return}e.out.table(s.grants,[{header:"grant",value:a=>a.id},{header:"entitlement",value:a=>a.entitlement},{header:"active",value:a=>a.active?"yes":"no"},{header:"ends",value:a=>a.revoked_at?`revoked ${Z(a.revoked_at)}`:a.expires_at?Z(a.expires_at):"for life"},{header:"why",value:a=>a.reason},{header:"by",value:a=>a.revoked_by?`${a.granted_by}, revoked by ${a.revoked_by}`:a.granted_by}])})}};function Wc(e){let t=e.flags.note?.trim();if(t!==void 0&&t.length>500)throw h("--note is 500 characters at most");return t||void 0}function Fc(e,t,n){let s=t.subscription;e.out.line(`${n} (${t.action.store}, by ${t.action.actor}).`),e.out.line(`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}: ${s.state}, ${s.active?"on":"off"} until ${Dc(s.expires_at)}, ${s.will_renew?"renews":"does not renew"}.`)}var Bc={note:{type:"string",value:"why",description:"what support writes of it (500 characters at most): the record"}},uM={name:"iap:customer:extend",summary:"move a customer's subscription renewal days later, for free: the App Store's extension, Google Play's deferral, Stripe's next charge moved",usage:"<customer id> <subscription id> --days <1-90> --reason customer_satisfaction|service_issue|other [--note <why>]",details:["The subscription's id is the one iap:customer:get prints. The App Store extends a paid, active subscription, at most 90 days and twice a year.","The store is asked again after: the new expiry is printed, and the customer's history keeps it with who did it."],args:{min:2,max:2},flags:{days:{type:"string",value:"n",description:"how many days (1 to 90)"},reason:{type:"string",value:"why",description:"customer_satisfaction, service_issue or other: as the App Store asks it"},...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=we(e.flags.days,"days");if(a===void 0||a<1||a>90)throw h("--days is 1 to 90");let o=e.flags.reason;if(o!=="customer_satisfaction"&&o!=="service_issue"&&o!=="other")throw h("--reason is customer_satisfaction, service_issue or other");let i=Wc(e);await k(e,t,`extend ${n}'s subscription ${s} by ${a} day(s)`);let r={days:a,reason:o,...i?{note:i}:{}},l=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/extend`,r,D());e.out.result(l,()=>Fc(e,l,`Extended ${n}'s subscription by ${a} day(s)`))}},mM={name:"iap:customer:refund",summary:"refund a customer's subscription \u2014 its latest payment, or what is left of its period \u2014 and end it now: Google Play and Stripe",usage:"<customer id> <subscription id> --mode full|prorated [--note <why>]",details:["The customer's access ends as it answers. The App Store decides its own refunds: the customer asks Apple, which asks the app what they used \u2014 Palbase answers it when they consented in the app."],args:{min:2,max:2},flags:{mode:{type:"string",value:"kind",description:"full: the latest payment; prorated: what is left of its period"},...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=e.flags.mode;if(a!=="full"&&a!=="prorated")throw h("--mode is full (the latest payment) or prorated (what is left of its period)");let o=Wc(e);await k(e,t,`refund ${n}'s subscription ${s} (${a}) and end it now`);let i={mode:a,...o?{note:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/refund`,i,D());e.out.result(r,()=>Fc(e,r,`Refunded ${n}'s subscription (${a}); it ended`))}},gM={name:"iap:customer:cancel",summary:"turn a customer's subscription renewal off: it ends at its period's end, the customer keeping what they paid for \u2014 Google Play and Stripe",usage:"<customer id> <subscription id> [--note <why>]",details:["An App Store subscription's renewal is the customer's to turn off (Settings \u203A Apple ID \u203A Subscriptions)."],args:{min:2,max:2},flags:{...Bc},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the subscription's id (iap:customer:get prints it)"),a=Wc(e);await k(e,t,`turn the renewal of ${n}'s subscription ${s} off`);let o=a?{note:a}:{},i=await g(e,t,"POST",`/iap/customers/${R(n)}/subscriptions/${R(s)}/cancel`,o,D());e.out.result(i,()=>Fc(e,i,`Turned the renewal of ${n}'s subscription off`))}},Fk={source:{type:"string",value:"kind",description:"support (the default) or promotion"}};function Bk(e){let t=e.flags.source??"support";if(t!=="support"&&t!=="promotion")throw h("--source is support or promotion");return t}function Ul(e,t){let n=e.flags.reason?.trim();if(!n)throw h(`--reason says why ${t}: the record`);if(n.length>500)throw h("--reason is 500 characters at most");return n}function Jk(e,t,n){let s=Je(e,t,n),a=Number(s);if(!Number.isInteger(a)||a<1)throw h(`${n} is a whole number above 0: ${s}`);return a}var hM={name:"iap:customer:credits",summary:"a customer's credit entries, the newest first: given, spent, taken back, expired, forgiven \u2014 with who did each, and why",usage:"<customer id> [--credits <key>] [--limit <n>] [--cursor <next>]",args:{min:1,max:1},flags:{credits:{type:"string",value:"key",description:"one of the catalog's credits alone"},limit:{type:"string",value:"n",description:"entries a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=new URLSearchParams;e.flags.credits!==void 0&&s.set("credits",String(e.flags.credits));let a=we(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let o=await g(e,t,"GET",`/iap/customers/${R(n)}/credits/entries${s.size?`?${s}`:""}`);e.out.result(o,()=>{o.entries.length===0&&e.out.line(`${n} has no credit entry.`),e.out.table(o.entries,[{header:"when",value:i=>Z(i.created_at)},{header:"credit",value:i=>i.currency},{header:"what",value:i=>i.kind},{header:"amount",value:i=>`${i.delta>0?"+":""}${i.delta}`},{header:"owed",value:i=>i.debt_delta?`${i.debt_delta>0?"+":""}${i.debt_delta}`:""},{header:"why",value:i=>i.reason??""},{header:"by",value:i=>i.actor??""}]),o.next_cursor&&e.out.line(`Older: palbase iap:customer:credits ${n} --cursor ${o.next_cursor}`)})}},yM={name:"iap:customer:credits:give",summary:"give a customer credits, saying why \u2014 a support case, a promotion \u2014 for a while or until spent",usage:"<customer id> <credits> <amount> --reason <why> [--source support|promotion] [--for 30d | --until <date>]",details:["What they owe is paid first from what is given. Nothing is charged, in any store."],args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why they are given (500 characters at most): the record"},...Fk,for:{type:"string",value:"span",description:"how long they last: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when they expire (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the credits (the catalog's key)"),a=Jk(e,2,"the amount"),o=Ul(e,"they are given"),i=Bk(e),r=Uc(e);await k(e,t,`give ${n} ${a} ${s}${r?` until ${Z(r)}`:""}`);let l={credits:s,amount:a,source:i,reason:o,...r?{expires_at:r}:{}},p=await g(e,t,"POST",`/iap/customers/${R(n)}/credits`,l,D());e.out.result(p,()=>e.out.line(`Gave ${n} ${p.original} ${p.currency}${p.expires_at?` until ${Z(p.expires_at)}`:""}; ${p.remaining} left of it.`))}},fM={name:"iap:customer:credits:forgive",summary:"forgive what a customer owes of a credit \u2014 all of it, or an amount \u2014 saying why",usage:"<customer id> <credits> --reason <why> [--amount <n>]",args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is forgiven (500 characters at most): the record"},amount:{type:"string",value:"n",description:"how much of it (default: all they owe)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the credits (the catalog's key)"),a=Ul(e,"it is forgiven"),o=we(e.flags.amount,"amount");if(o===0)throw h("--amount is above 0");await k(e,t,`forgive ${o??"all"} of what ${n} owes of ${s}`);let i={credits:s,reason:a,...o!==void 0?{amount:o}:{}},r=await g(e,t,"POST",`/iap/customers/${R(n)}/credits/forgive`,i,D());e.out.result(r,()=>e.out.line(`Forgave ${r.forgiven} ${r.credits} ${n} owed; they owe ${r.debt}, ${r.available} available.`))}};function Jc(e,t,n){e.out.line(`${t}: ${n.used} of ${n.max} used, ${n.remaining} left, resets ${Z(n.resets_at)}.`)}var bM={name:"iap:customer:limit:set",summary:"set a customer's own maximum of a limit \u2014 above or below the catalog's \u2014 saying why, for a while or until cleared",usage:"<customer id> <limit> <max> --reason <why> [--for 30d | --until <date>]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)"),a=Je(e,2,"the maximum"),o=Number(a);if(!Number.isInteger(o)||o<0)throw h(`the maximum is a whole number: ${a}`);let i=Ul(e,"it is set"),r=Uc(e);await k(e,t,`set ${n}'s ${s} to ${o}${r?` until ${Z(r)}`:""}`);let l={max:o,reason:i,...r?{expires_at:r}:{}},p=await g(e,t,"PUT",`/iap/customers/${R(n)}/limits/${R(s)}`,l,D());e.out.result(p,()=>Jc(e,`Set ${n}'s ${p.limit} to ${p.max}`,p))}},wM={name:"iap:customer:limit:clear",summary:"clear a customer's own maximum of a limit: the catalog's counts again",usage:"<customer id> <limit>",args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)");await k(e,t,`clear ${n}'s own ${s}`);let a=await g(e,t,"DELETE",`/iap/customers/${R(n)}/limits/${R(s)}`,void 0,D());e.out.result(a,()=>Jc(e,`Cleared ${n}'s own ${a.limit}; the catalog's ${a.max} counts`,a))}},vM={name:"iap:customer:limit:give",summary:"give a customer more of a limit for its current period, saying why \u2014 a gift on top of their maximum",usage:"<customer id> <limit> <amount> --reason <why> [--source support|promotion]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},...Fk},scope:"environment",async run(e){let t=await f(e),n=Je(e,0,"the customer's id (the user's id)"),s=Je(e,1,"the limit (the catalog's key)"),a=Jk(e,2,"the amount"),o=Ul(e,"it is given"),i=Bk(e);await k(e,t,`give ${n} ${a} more ${s} this period`);let r={amount:a,source:i,reason:o},l=await g(e,t,"POST",`/iap/customers/${R(n)}/limits/${R(s)}/grants`,r,D());e.out.result(l,()=>Jc(e,`Gave ${n} ${a} more ${l.limit}`,l))}};function kM(e){let t=n=>/^[\w./@:-]+$/.test(n)?n:JSON.stringify(n);return`${e.global.project!==void 0?` -P ${t(e.global.project)}`:""}${e.global.env!==void 0?` -E ${t(e.global.env)}`:""}`}async function Hc(e,t){let n=(await Vt(e,t.project_id)).filter(r=>r.deleted_at===null),s=n.filter(r=>r.platform==="ios"),a=e.flags.app;if(a!==void 0){let r=un(n,a);if(r.platform!=="ios")throw h(`${r.slug} is a ${r.platform} app: a StoreKit configuration is an iOS app's`,`the project's iOS apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return r}let o=(await nl(e.io.cwd))?.apps.filter(r=>r.platform==="ios").map(r=>r.id)??[],i=s.filter(r=>o.includes(r.id));if(i.length===1)return i[0];if(s.length===1)return s[0];throw s.length===0?new b("no_ios_app",`${t.project_name} has no iOS app`,{hint:"register it: palbase apps:create ios <name> --team-id <team id>"}):h("name the iOS app the file is for: --app <app>",`the project's iOS apps: ${s.map(r=>r.slug).join(", ")}`)}function _M(e,t){let n=BN(e.io.cwd,ji(e.io.cwd,t)).split(JN).join("/");if(!n.startsWith(`${ue}/`)||n.split("/").includes(".."))throw h(`--out ${t}: the file goes under ${ue}/, as the CLI writes nothing else in the checkout`,`palbase iap:storekit --out ${ue}/<name>.storekit`);if(!n.endsWith(".storekit"))throw h(`--out ${t}: Xcode takes a StoreKit configuration by its .storekit extension`);return n}function SM(e){let t=new Map;for(let n of e.products)for(let s of n.channels.ios?.plans??[])t.set(s.price.currency.toUpperCase(),(t.get(s.price.currency.toUpperCase())??0)+1);return[...t].sort(([n,s],[a,o])=>o-s||(n<a?-1:1))[0]?.[0]}var $M={name:"iap:storekit",summary:"an Xcode StoreKit configuration of the environment's iOS products, under palbase/: a build Xcode runs buys them with no App Store",usage:"[--app <app>] [--out <palbase/\u2026.storekit>] [--storefront <code>]",details:["Each plan is the App Store product its store id names, with its text in every language the catalog has and its price; a subscription is in its group, at its tier's level, with its introductory offer and the catalog's offers on it as promotional offers (a grant has no store).","Prices are in the storefront's currency: the catalog's price, or the amount set by hand in that currency. The storefront is --storefront, else the one the file has, else the one the catalog's currency is the App Store's own price in (USD: USA, EUR: Germany, TRY: Turkey \u2026), else USA.","Made again, the file is made whole from the catalog \u2014 the same catalog, the same file \u2014 keeping the test settings Xcode's Editor menu wrote in it. Nothing outside palbase/ is written: Xcode is pointed at the file in the scheme."],flags:{app:{type:"string",value:"app",description:"the iOS app it is for (default: the one this checkout syncs, or the project's only one)"},out:{type:"string",value:"palbase/\u2026.storekit",description:"where under palbase/ (default: palbase/environments/<env>/<app>.storekit)"},storefront:{type:"string",value:"code",description:"the App Store storefront prices are in, by its three letters (USA, DEU, TUR, GBR, JPN \u2026)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.storefront?.trim().toUpperCase();if(n!==void 0&&!lo.has(n))throw h(`--storefront ${e.flags.storefront}: not an App Store storefront`,"a storefront is three letters, its country's ISO 3166-1 code: USA, DEU, TUR, GBR, JPN \u2026");let s=await Hc(e,t);if(!/^[A-Za-z][A-Za-z0-9-]{0,38}$/.test(t.env_slug))throw new b("unexpected_answer",`the environment's slug ${JSON.stringify(t.env_slug)} is not one`);if(!/^[a-z][a-z0-9-]{0,38}[a-z0-9]$/.test(s.slug))throw new b("unexpected_answer",`the project answered app ${JSON.stringify(s.slug)}, which is not one`);let a=e.flags.out!==void 0?_M(e,e.flags.out):`${ue}/environments/${t.env_slug}/${s.slug}.storekit`,o=await g(e,t,"GET","/iap/offerings?channel=ios");if(!o.products.some(E=>(E.channels.ios?.plans.length??0)>0))throw new b("nothing_on_ios",`${t.env_name}'s catalog sells nothing on iOS yet: there is no product for Xcode to sell`,{hint:"give a product channels.ios in the catalog (palbase iap:catalog:get --out catalog.json, then iap:catalog:put)"});let i=await Be(e.io.cwd,a),r,l;try{r=await zc(i,"utf8");let E=JSON.parse(r);typeof E.settings=="object"&&E.settings!==null&&!Array.isArray(E.settings)&&(l=E.settings)}catch{}let p=typeof l?._storefront=="string"&&lo.has(l._storefront)?l._storefront:void 0,d=SM(o);n??=p??(d!==void 0?Gw(d):void 0)??"USA";let{catalog:u}=await g(e,t,"GET","/iap/catalog"),m=Ww(o,{seed:`${t.env_ref}/${s.id}`,storefront:n,settings:l,offers:u.offers??[]}),y=r!==m.text;y&&(await UN(FN(i),{recursive:!0}),await Be(e.io.cwd,a),await qc(i,m.text));for(let E of m.notes)e.out.warn(E);let w=t.env_slug===Mt,v=kM(e),P=[`In Xcode: Product \u203A Scheme \u203A Edit Scheme\u2026 \u203A Run \u203A Options \u203A StoreKit Configuration \u2014 choose ${a} (not listed yet? add it from that menu).`,w?`${t.project_name} \u203A ${t.env_name} is the project's production environment: it never takes a purchase Xcode signs. Make the file for a test environment (-E <env>) to see a purchase reach the server.`:`Then select the file in Xcode, choose Editor \u203A Save Public Certificate, and let ${t.env_name} take the purchases Xcode signs: palbase iap:apple:xcode-certificate <the saved .cer file>${v}`,`Run the app and buy: Xcode sells the products itself, nothing goes to the App Store. After the catalog changes: palbase iap:storekit${e.flags.app!==void 0?` --app ${s.slug}`:""}${e.flags.out!==void 0?` --out ${a}`:""}${v}`],A=m.counts,T=[A.subscriptions>0?`${A.subscriptions} subscription${A.subscriptions===1?"":"s"} in ${A.groups} group${A.groups===1?"":"s"}`:"",A.products>0?`${A.products} in-app purchase${A.products===1?"":"s"}`:"",A.non_renewing>0?`${A.non_renewing} non-renewing subscription${A.non_renewing===1?"":"s"}`:""].filter(E=>E!=="").join(", ");e.out.result({file:a,app:s.slug,environment:t.env_slug,revision:o.revision,storefront:m.storefront,currency:m.currency,locale:m.locale,...A,written:y,next:P},()=>{e.out.line(`${y?"Wrote":"Up to date:"} ${a} \u2014 ${T}, priced in ${m.currency} (storefront ${m.storefront}), catalog revision ${o.revision}.`),e.out.line(""),P.forEach((E,C)=>e.out.line(`${C+1}. ${E}`))})}},AM=/^SubscriptionKey_([A-Z0-9]{10})\.p8$/,RM=/^AuthKey_[A-Z0-9]{10}\.p8$/,PM=8192,jM=16384;function Hk(e,t){if(!t.connected)e.out.line("No In-App Purchase key is connected: the App Store's purchases are not taken."),e.out.line("Connect one: palbase iap:apple:connect --key-file SubscriptionKey_<KEYID>.p8");else{e.out.line(`In-App Purchase key ${t.key_id??"?"} (issuer ${t.issuer_id??"?"}) for ${t.bundle_id??"?"}${t.app_apple_id?`, Apple ID ${t.app_apple_id}`:", its Apple ID not known yet"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${Z(t.checked_at)})`:""}`);let s=t.notifications;s&&e.out.line(`notifications: ${s.url} \u2014 ${s.bound?`bound ${Z(s.bound_at)}`:`not bound${s.error?`: ${s.error}`:""}`}; Apple's TEST notification ${s.verified_at?`arrived ${Z(s.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}let n=t.xcode_certificate;e.out.line(n?`Xcode's StoreKit Testing purchases: taken, signed with ${n.subject} until ${Z(n.not_after)} (sha256 ${n.fingerprint.slice(0,16)}\u2026)`:"Xcode's StoreKit Testing purchases: not taken (palbase iap:apple:xcode-certificate <file> takes them)")}var TM={name:"iap:apple",summary:"the environment's App Store connection: the In-App Purchase key, where the App Store reports, whether Xcode's purchases are taken",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/iap/apple");e.out.result(n,()=>Hk(e,n))}};function EM(e,t){let n=e.environments.find(s=>s.ref===t.env_ref)?.ios?.bundle;if(n===void 0)throw new b("app_not_in_environment",`${e.slug} is not set in ${t.env_name}: the key is connected for the app's bundle there`,{hint:`palbase apps:env:set ${e.slug} -E ${t.env_slug} --bundle <bundle id>`});return n}var CM={name:"iap:apple:connect",summary:"connect an In-App Purchase key for an iOS app: it goes from this computer straight to the environment, never through Studio",usage:"--key-file <SubscriptionKey_KEYID.p8> [--key-id <KEYID>] [--issuer-id <issuer id>] [--app <app>] | --print-link",details:["App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes the key (SubscriptionKey_<KEYID>.p8) and shows the Issuer ID \u2014 the team's, the same as its App Store Connect API keys': left out, the one stores:apple connected is taken.","The environment verifies the app's purchases and reads its subscriptions with it, and has the stores module point the App Store's notifications at the environment.","Studio is asked for a one-time grant alone; the key is posted with it to the environment's own address. --print-link prints a link that takes the key in a browser instead."],flags:{"key-file":{type:"string",value:"SubscriptionKey_KEYID.p8",description:"the .p8 file Apple gave when the key was made"},"key-id":{type:"string",value:"KEYID",description:"the key's id (default: from the file's name)"},"issuer-id":{type:"string",value:"issuer id",description:"the team's issuer id (default: the connected App Store Connect key's)"},app:{type:"string",value:"app",description:"the iOS app (default: the one this checkout syncs, or the project's only one)"},"print-link":{type:"boolean",description:"only print a link that takes the key in a browser (valid 30 minutes, once)"}},scope:"environment",async run(e){let t=await f(e);if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw h("--print-link or --key-file, not both");await k(e,t,"make a link that connects an In-App Purchase key");let y=await g(e,t,"POST","/iap/apple/grants",void 0,D());mn(e,t,y.connect_url,"the connect link"),e.out.result({connect_url:y.connect_url,expires_at:y.expires_at},()=>{e.out.line(y.connect_url),e.out.note(`Open it in a browser, pick the app and the .p8 file; it works once, until ${Z(y.expires_at)}.`)});return}let n=e.flags["key-file"];if(n===void 0)throw h("--key-file names the In-App Purchase key's .p8 file","or --print-link for a link a browser opens");let s=WN(n),a=e.flags["key-id"];if(a===void 0){if(RM.test(s))throw h(`${s} is an App Store Connect API key (palbase stores:apple:connect takes it): this is the In-App Purchase key, SubscriptionKey_<KEYID>.p8`,"App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes one");if(a=AM.exec(s)?.[1],a===void 0)throw h(`--key-id is needed: ${s} is not named SubscriptionKey_<KEYID>.p8`)}let o;try{let y=ji(e.io.cwd,n);if((await zk(y)).size>PM)throw new b("not_a_key",`${n} is larger than a .p8 key`);o=await zc(y,"utf8")}catch(y){throw y instanceof b?y:new b("unreadable_file",`${n} could not be read: ${y instanceof Error?y.message:String(y)}`)}if(!o.includes("-----BEGIN PRIVATE KEY-----"))throw new b("not_a_key",`${n} is not a .p8 key (no "BEGIN PRIVATE KEY")`);let i=e.flags["issuer-id"]?.trim();if(i===void 0||i===""){let y=await g(e,t,"GET","/stores/apple");if(i=y.connected?y.issuer_id:void 0,i===void 0)throw h("--issuer-id is the team's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations): no App Store Connect key is connected to read it from")}let r=await Hc(e,t),l=EM(r,t);await k(e,t,`connect the In-App Purchase key ${a} for ${l}`);let p=await g(e,t,"POST","/iap/apple/grants",void 0,D()),d=mn(e,t,p.connect_url,"the connect link"),u={grant:p.grant,issuer_id:i,key_id:a,private_key:o,bundle_id:l},m=await wi(e,`${d}/iap/apple/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(u)},"connecting the In-App Purchase key");e.out.result(m,()=>{e.out.line(`Connected key ${a} for ${l} to ${ee(t)}.`),Hk(e,m),e.out.line("Check what else the App Store needs: palbase iap:doctor")})}},OM={name:"iap:apple:disconnect",summary:"forget the environment's In-App Purchase key: the App Store's purchases and notifications are refused from then on (what was bought stays)",scope:"environment",async run(e){let t=await f(e);await k(e,t,"disconnect the In-App Purchase key"),await g(e,t,"DELETE","/iap/apple",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the In-App Purchase key from ${ee(t)}.`))}};function Vk(e,t){if(t.service_account===void 0){e.out.line("The project has no Google Play connection: Palbase reads the app's purchases as the account your Play Console invites."),e.out.line("Connect it first: palbase stores:google:connect");return}if(e.out.line(`Play connection: ${t.service_account} (${t.play_status??"not checked"})`),!t.connected){e.out.line("Google Play purchases are not connected: palbase iap:google:connect --app <android app>");return}e.out.line(`app: ${t.package_name??"?"}`),e.out.line(`topic: ${t.topic??"?"} (Play Console \u203A Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications)`),e.out.line(`notifications: ${t.notification_url??"?"} \u2014 Play's test notification ${t.verified_at?`arrived ${Z(t.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var xM={name:"iap:google",summary:"the environment's Google Play purchases: the app they are made in, the topic its Play Console names, whether Play's test notification arrived",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/iap/google");e.out.result(n,()=>Vk(e,n))}};async function LM(e,t){let n=(await Vt(e,t.project_id)).filter(r=>r.deleted_at===null),s=n.filter(r=>r.platform==="android"),a=e.flags.app;if(a!==void 0){let r=un(n,a);if(r.platform!=="android")throw h(`${r.slug} is a ${r.platform} app: Google Play purchases are an Android app's`,`the project's Android apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return r}let o=(await nl(e.io.cwd))?.apps.filter(r=>r.platform==="android").map(r=>r.id)??[],i=s.filter(r=>o.includes(r.id));if(i.length===1)return i[0];if(s.length===1)return s[0];throw s.length===0?new b("no_android_app",`${t.project_name} has no Android app`,{hint:"register it: palbase apps:create android <name>"}):h("name the Android app: --app <app>",`the project's Android apps: ${s.map(r=>r.slug).join(", ")}`)}var IM={name:"iap:google:connect",summary:"sell on Google Play in one of the project's Android apps: Palbase makes the app's notifications topic and has it pushed to this environment",usage:"[--app <app>]",details:["The project's Play connection (palbase stores:google:connect) is the account Palbase reads and acknowledges the app's purchases as: its Play Console invites it with View financial data and Manage orders and subscriptions.","Then, in Play Console: Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications, the topic this prints, Save, and Send test notification \u2014 palbase iap:google says when it arrived."],flags:{app:{type:"string",value:"app",description:"the Android app (default: the one this checkout syncs, or the project's only one)"}},scope:"environment",async run(e){let t=await f(e),n=await LM(e,t);await k(e,t,`connect Google Play purchases for ${n.slug}`);let s={app_id:n.id},a=await g(e,t,"POST","/iap/google",s,D());e.out.result(a,()=>{e.out.line(`Google Play purchases connected for ${a.package_name??n.slug} in ${ee(t)}.`),Vk(e,a)})}},NM={name:"iap:google:disconnect",summary:"stop taking the environment's Google Play purchases: Play's notifications stop reaching it, and the app's reports are refused (what was bought stays)",scope:"environment",async run(e){let t=await f(e);await k(e,t,"disconnect Google Play purchases"),await g(e,t,"DELETE","/iap/google",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play purchases from ${ee(t)}.`))}};async function MM(e,t){let n=(await Vt(e,t.project_id)).find(s=>s.deleted_at===null&&s.environments.some(a=>a.ref===t.env_ref));return n===void 0?t.env_slug===Mt:(await e.studio.get(`/environments/${t.env_ref}/apps/${n.id}/config`)).environment.production}async function DM(e,t){let n;try{let o=ji(t,e);if((await zk(o)).size>jM)throw new b("not_a_certificate",`${e} is larger than Xcode's certificate`);n=await zc(o)}catch(o){throw o instanceof b?o:new b("unreadable_file",`${e} could not be read: ${o instanceof Error?o.message:String(o)}`)}let s;try{s=new KN(n)}catch{throw new b("not_a_certificate",`${e} is not a certificate`,{hint:"the one Xcode saves: select the .storekit file, then Editor \u203A Save Public Certificate"})}let a=n.toString("latin1");return{certificate:a.includes("-----BEGIN CERTIFICATE-----")?a.trim():n.toString("base64"),x509:s}}var zM={name:"iap:apple:xcode-certificate",summary:"take the purchases Xcode's StoreKit Testing signs with this certificate, as test purchases \u2014 never on production; --remove stops",usage:"<certificate.cer> | --remove",details:["Xcode saves the certificate: select the .storekit file (palbase iap:storekit makes it), then Editor \u203A Save Public Certificate.","From then on what the app reports signed with it \u2014 Xcode's own purchases, on a developer's Mac \u2014 is a test purchase of the environment, with or without an In-App Purchase key; nothing of it is asked of Apple. Set again, it replaces the one before.","The production environment takes only what the App Store signed: it is refused there."],args:{min:0,max:1},flags:{remove:{type:"boolean",description:"stop taking Xcode's purchases (those taken stay)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.remove===!0,s=e.args[0];if(n===(s!==void 0))throw h("name the certificate file, or --remove","palbase iap:apple:xcode-certificate StoreKitTestCertificate.cer");if(n){await k(e,t,"stop taking Xcode's StoreKit Testing purchases"),await g(e,t,"DELETE","/iap/apple/xcode-certificate",void 0,D()),e.out.result({removed:!0},()=>e.out.line(`${ee(t)} no longer takes Xcode's purchases; those it took stay.`));return}let a=await DM(s,e.io.cwd);if(await MM(e,t))throw new b("production_environment",`${t.project_name} \u203A ${t.env_name} is the project's production environment: it takes only purchases the App Store signed, never Xcode's`,{hint:"set the certificate on a test environment: palbase iap:apple:xcode-certificate <file> -E <env>"});await k(e,t,`take the purchases Xcode signs with ${a.x509.subject.replaceAll(`
11200
11200
  `,", ")}`);let o=await g(e,t,"PUT","/iap/apple/xcode-certificate",{certificate:a.certificate},D());e.out.result(o,()=>{e.out.line(`${ee(t)} takes the purchases Xcode signs with ${o.subject}, until ${Z(o.not_after)} (sha256 ${o.fingerprint.slice(0,16)}\u2026).`),e.out.line("Run the app from Xcode and buy: each purchase is a test purchase of this environment.")})}},qM=new Set(["sandbox_access","xcode_certificate"]),GM={name:"iap:doctor",summary:"whether the environment sells in the App Store now, check by check \u2014 the App Store Connect side and the iap side \u2014 with the fix of each that fails",usage:"[--app <app>]",details:["Apple is asked now: the keys, the agreements, the app's App Store Connect record, where the App Store reports, the sandbox testers, each product's state, the catalog's last confirmation; and whether Xcode's purchases are taken.","It exits 1 while a check that is not informational fails: run it again until every line is \u2713."],flags:{app:{type:"string",value:"app",description:"the iOS app (default: the environment's one linked app)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.app!==void 0?await Hc(e,t):void 0,s=n?`?${new URLSearchParams({app:n.id})}`:"",a=u=>u.then(m=>({value:m}),m=>({error:m})),[o,i]=await Promise.all([a(g(e,t,"GET",`/stores/apple/readiness${s}`)),a(g(e,t,"GET","/iap/apple/readiness"))]),r=(u,m)=>{if(!(m instanceof G))throw m;return{module:u,id:`${u}_unanswered`,ok:!1,informational:!1,message:`The ${u} module could not answer: ${m.message}`,fix:m.status===503||m.status===502?"palbase iap:doctor (again, in a moment)":""}},l=[..."value"in o?o.value.checks.map(u=>({module:"stores",id:u.id,ok:u.ok,informational:!1,message:u.message,fix:u.fix})):[r("stores",o.error)],..."value"in i?i.value.checks.map(u=>({module:"iap",id:u.id,ok:u.ok,informational:qM.has(u.id),message:u.message,fix:u.fix})):[r("iap",i.error)]],p=l.filter(u=>!u.ok&&!u.informational),d=p.length===0;return e.out.result({ready:d,checks:l,stores:"value"in o?o.value:null,iap:"value"in i?i.value:null},()=>{let u=(m,y)=>{e.out.line(y);for(let w of l.filter(v=>v.module===m))e.out.line(` ${w.informational?"i":w.ok?"\u2713":"\u2717"} ${w.message}`),(!w.ok||w.informational)&&w.fix&&e.out.line(` \u2192 ${w.fix}`)};u("stores","App Store Connect (stores)"),u("iap","In-App Purchases (iap)"),e.out.line(""),e.out.line(d?`Ready: ${ee(t)} sells in the App Store.`:`${p.length} of ${l.filter(m=>!m.informational).length} checks fail: fix each, then run palbase iap:doctor again.`)}),d?void 0:1}},Xk=[HN,VN,XN,ZN,QN,eM,tM,nM,sM,pM,oM,dM,cM,iM,rM,uM,mM,gM,hM,yM,fM,bM,wM,vM,$M,TM,CM,OM,zM,xM,IM,NM,GM];import{writeFile as KM}from"node:fs/promises";import{resolve as UM}from"node:path";function hs(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s.trim()}function WM(e,t){if(t.length===0){e.out.line("No payment channel is connected yet."),e.out.line("Connect Stripe with one click: palbase payments:stripe:install"),e.out.line("Or connect Stripe/iyzico via browser grant: palbase payments:stripe:grant / palbase payments:iyzico:connect");return}e.out.table(t,[{header:"channel",value:n=>`${n.key}${n.is_default?" (default)":""}`},{header:"provider",value:n=>n.provider},{header:"mode",value:n=>n.livemode?"live":"test"},{header:"status",value:n=>n.status},{header:"key",value:n=>n.via==="app"?"stripe app":n.key_hint??"\u2014"},{header:"masterpass",value:n=>n.has_masterpass?"yes":"no"},{header:"checked",value:n=>Z(n.checked_at)}])}var FM={name:"payments:channels",summary:"list the environment's connected payment channels (Stripe, iyzico, Masterpass status and health)",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/payments/channels");e.out.result(n,()=>WM(e,n.channels))}},BM={name:"payments:channels:check",summary:"probe a connected payment channel against its provider API to verify credentials and permissions",usage:"<channel key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the channel key"),s=await g(e,t,"POST",`/payments/channels/${R(n)}/check`,void 0,D());e.out.result(s,()=>{e.out.line(`Channel ${s.key} (${s.provider}, ${s.livemode?"live":"test"}): ${s.status} (checked ${Z(s.checked_at)}).`),s.permissions.length>0&&e.out.line(`permissions: ${s.permissions.join(", ")}`)})}},JM={name:"payments:channels:default",summary:"set an active payment channel as the default fallback when no routing rule matches",usage:"<channel key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the channel key");await k(e,t,`set ${n} as the default payment channel`);let s=await g(e,t,"POST",`/payments/channels/${R(n)}/default`,void 0,D());e.out.result(s,()=>e.out.line(`Set ${s.key} (${s.provider}) as the default payment channel for ${ee(t)}.`))}},HM={name:"payments:channels:disconnect",summary:"disable a payment channel and remove its managed provider webhook endpoint",usage:"<channel key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the channel key");await k(e,t,`disconnect payment channel ${n}`),await g(e,t,"DELETE",`/payments/channels/${R(n)}`,void 0,D()),e.out.result({disconnected:n},()=>e.out.line(`Disconnected payment channel ${n} from ${ee(t)}.`))}},VM={name:"payments:stripe:install",summary:"mint a one-time link to install Palbase's Stripe App with one click (no API key pasted)",usage:"[--channel <key>] [--live]",details:["Opens the one-click Stripe App installation flow; works once for 30 minutes.","Use --live to install in Stripe live mode (test mode otherwise)."],flags:{channel:{type:"string",value:"key",description:"target channel key (default: stripe)"},live:{type:"boolean",description:"install the Stripe App in live mode (test mode otherwise)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.live===!0,s=e.flags.channel?.trim();await k(e,t,`mint a link to install Palbase's Stripe App (${n?"live":"test"} mode)`);let a={livemode:n,...s?{channel_key:s}:{}},o=await g(e,t,"POST","/payments/stripe/app/grants",a,D()),i=Gu(e.cloud),r;try{r=new URL(o.connect_url)}catch{r=void 0}r?.origin===i&&r.pathname==="/payments/stripe/app/install"||mn(e,t,o.connect_url,"the Stripe App install link"),e.out.result({connect_url:o.connect_url,expires_at:o.expires_at},()=>{e.out.line(o.connect_url),e.out.note(`Open in a browser to connect Stripe with one click; expires ${Z(o.expires_at)}.`)})}},XM={name:"payments:stripe:grant",summary:"mint a one-time browser URL to connect a Stripe restricted key directly to the environment",usage:"[--channel <key>]",details:["The restricted key goes straight from your browser to the environment, never through this computer or an AI agent.","Works once, for 30 minutes."],flags:{channel:{type:"string",value:"key",description:"target channel key (default: stripe)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.channel?.trim();await k(e,t,"mint a one-time link to connect a Stripe restricted key");let s={kind:"stripe_key",...n?{channel_key:n}:{}},a=await g(e,t,"POST","/payments/channels/grants",s,D());mn(e,t,a.connect_url,"the Stripe connect link"),e.out.result({connect_url:a.connect_url,expires_at:a.expires_at},()=>{e.out.line(a.connect_url),e.out.note(`Open in a browser and paste your Stripe restricted key (rk_test_ / rk_live_); expires ${Z(a.expires_at)}.`)})}},YM={name:"payments:iyzico:connect",summary:"connect an iyzico payment channel (browser grant by default, or --stdin JSON for CI)",usage:"[--channel <key>] [--stdin [--live] [--default]]",details:["Without --stdin, mints a one-time browser URL where a human pastes iyzico credentials directly into the environment.",'With --stdin, reads JSON { "api_key", "secret_key", "masterpass"? } from stdin so secrets never appear in command-line arguments.'],flags:{channel:{type:"string",value:"key",description:"channel key (default: iyzico_tr)"},stdin:{type:"boolean",description:"read { api_key, secret_key, masterpass? } JSON from stdin instead of minting a browser link"},live:{type:"boolean",description:"with --stdin: mark credentials as live production mode (sandbox otherwise)"},default:{type:"boolean",description:"with --stdin: set this channel as the project default"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.channel?.trim()||"iyzico_tr";if(e.flags.stdin!==!0){await k(e,t,`mint a one-time link to connect iyzico channel ${n}`);let p=await g(e,t,"POST","/payments/channels/grants",{kind:"iyzico_key",channel_key:n},D());mn(e,t,p.connect_url,"the iyzico connect link"),e.out.result({connect_url:p.connect_url,expires_at:p.expires_at},()=>{e.out.line(p.connect_url),e.out.note(`Open in a browser and enter your iyzico API key & secret key; expires ${Z(p.expires_at)}.`)});return}let s=Ne(await ze(e,"-","iyzico credentials JSON"),"iyzico credentials");if(typeof s!="object"||s===null||Array.isArray(s))throw h("stdin must be a JSON object with api_key and secret_key");let a=s;if(!a.api_key?.trim()||!a.secret_key?.trim())throw h("stdin JSON must include non-empty api_key and secret_key");let o=e.flags.live===!0;await k(e,t,`connect iyzico channel ${n} (${o?"live":"sandbox"})`);let i={key:n,provider:"iyzico",api_key:a.api_key.trim(),secret_key:a.secret_key.trim(),livemode:o,...e.flags.default===!0?{set_default:!0}:{},...a.masterpass?{masterpass:a.masterpass}:{}},r=await g(e,t,"POST","/payments/channels",i,D());e.out.result(r,()=>{e.out.line(`Connected iyzico channel ${r.key} (${r.livemode?"live":"sandbox"}, status: ${r.status}).`)})}},ZM={name:"payments:routing",summary:"list deterministic payment channel routing rules ordered by priority",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/payments/routing-rules");e.out.result(n,()=>{if(n.rules.length===0){e.out.line("No routing rules configured: payments use the default active channel."),e.out.line("Configure rules: palbase payments:routing:put --file rules.json");return}e.out.table(n.rules,[{header:"priority",value:s=>String(s.priority)},{header:"channel",value:s=>s.channel_key},{header:"currency",value:s=>s.currency??"*"},{header:"country",value:s=>s.country??"*"},{header:"kind",value:s=>s.payment_kind??"*"},{header:"enabled",value:s=>s.enabled?"yes":"no"}])})}},QM={name:"payments:routing:put",summary:"replace all deterministic channel routing rules from a JSON file or stdin",usage:"--file <rules.json>",details:['Accepts either `{ "rules": [...] }` or a bare JSON array of routing rule objects.'],flags:{file:{type:"string",value:"rules.json",description:"JSON rules file ('-' or omitted: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Ne(await ze(e,e.flags.file,"routing rules"),"routing rules"),s=Array.isArray(n)?n:typeof n=="object"&&n!==null&&Array.isArray(n.rules)?n.rules:void 0;if(!s)throw h('routing rules must be a JSON array or `{ "rules": [...] }`');await k(e,t,`replace payment routing rules (${s.length} rule(s))`);let a=await g(e,t,"PUT","/payments/routing-rules",{rules:s},D());e.out.result(a,()=>e.out.line(`Saved ${a.rules.length} routing rule(s) for ${ee(t)}.`))}},eD={name:"payments:wallets",summary:"list configured closed-loop wallet definitions for the environment",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/payments/wallets");e.out.result(n,()=>{if(n.wallets.length===0){e.out.line("No closed-loop wallets configured yet."),e.out.line('Create one: palbase payments:wallets:put --key try --name "TRY Wallet" --currency TRY');return}e.out.table(n.wallets,[{header:"key",value:s=>s.key},{header:"name",value:s=>s.name},{header:"currency",value:s=>s.currency},{header:"kind",value:s=>s.kind},{header:"topup range",value:s=>`${s.topup_min}..${s.topup_max}`},{header:"expiry days",value:s=>s.expires_days?String(s.expires_days):"none"},{header:"active",value:s=>s.active?"yes":"no"}])})}},tD={name:"payments:wallets:put",summary:"create or update a closed-loop wallet definition (currency, top-up bounds, expiry)",usage:"--key <key> --name <name> --currency <ISO> [--kind fiat|points] [--min <minor>] [--max <minor>] [--expires-days <n>] [--inactive]",flags:{key:{type:"string",value:"key",description:"stable lowercase wallet key (e.g. try, usd, store_credit)"},name:{type:"string",value:"name",description:"human-readable wallet display name"},currency:{type:"string",value:"ISO",description:"3-letter ISO 4217 currency code (e.g. TRY, USD)"},kind:{type:"string",value:"fiat|points",description:"wallet kind (default: fiat)"},min:{type:"string",value:"minor",description:"minimum top-up in minor units (default: 100)"},max:{type:"string",value:"minor",description:"maximum top-up in minor units (default: 5000000)"},"expires-days":{type:"string",value:"n",description:"optional default lot expiry in days"},inactive:{type:"boolean",description:"create or mark the wallet inactive"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.key?.trim(),s=e.flags.name?.trim(),a=e.flags.currency?.trim().toUpperCase();if(!n)throw h("--key is required (e.g. --key try)");if(!s)throw h("--name is required");if(!a||!/^[A-Z]{3}$/.test(a))throw h("--currency must be a 3-letter ISO 4217 code (e.g. TRY, USD)");let o=(e.flags.kind??"fiat").trim();if(o!=="fiat"&&o!=="points")throw h("--kind must be fiat or points");let i=we(e.flags.min,"min")??100,r=we(e.flags.max,"max")??5e6,l=we(e.flags["expires-days"],"expires-days"),p={key:n,name:s,currency:a,kind:o,topup_min:i,topup_max:r,active:e.flags.inactive!==!0,...l!==void 0?{expires_days:l}:{}};await k(e,t,`save wallet definition ${n} (${a}, ${o})`);let d=await g(e,t,"POST","/payments/wallets",p,D());e.out.result(d,()=>{e.out.line(`Saved wallet ${d.key} (${d.name}, ${d.currency}, ${d.active?"active":"inactive"}).`)})}},nD={name:"payments:audit:drift",summary:"verify zero-drift double-entry accounting integrity across all ledger entries and wallets",details:["Exits 0 when every double-entry transaction balances and every wallet matches its ledger entries; exits 1 on any discrepancy."],scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/payments/audit/drift");return e.out.result(n,()=>{if(n.ok)e.out.line(`Zero drift verified: ${n.accounts_checked} wallet account(s) and ${n.transactions_checked} double-entry transaction(s) balanced.`);else{e.out.line(`Drift detected (${n.problems.length} problem(s)):`);for(let s of n.problems)e.out.line(` \u2717 ${s}`)}}),n.ok?void 0:1}},sD={name:"payments:audit:export",summary:"export immutable double-entry ledger entries as CSV (default) or JSON",usage:"[--customer <id>] [--wallet <key>] [--kind <kind>] [--from <iso>] [--to <iso>] [--out <file>]",flags:{customer:{type:"string",value:"id",description:"filter by customer UID"},wallet:{type:"string",value:"key",description:"filter by wallet key"},kind:{type:"string",value:"kind",description:"filter by ledger transaction kind"},from:{type:"string",value:"iso",description:"inclusive RFC 3339 start timestamp"},to:{type:"string",value:"iso",description:"exclusive RFC 3339 end timestamp"},out:{type:"string",value:"file",description:"write CSV export to this file path"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams;e.flags.customer!==void 0&&n.set("customer_id",String(e.flags.customer)),e.flags.wallet!==void 0&&n.set("wallet_key",String(e.flags.wallet)),e.flags.kind!==void 0&&n.set("kind",String(e.flags.kind)),e.flags.from!==void 0&&n.set("from",String(e.flags.from)),e.flags.to!==void 0&&n.set("to",String(e.flags.to));let s=n.size?`?${n}`:"";if(e.global.json&&e.flags.out===void 0){let i=await g(e,t,"GET",`/payments/audit/ledger${s}`);e.out.result(i,()=>{});return}let a=await g(e,t,"GET",`/payments/audit/ledger/export${s}`,void 0,{accept:"text/csv"}),o=e.flags.out;if(o!==void 0){await KM(UM(e.io.cwd,o),typeof a=="string"?a:String(a)),e.out.result({file:o},()=>e.out.line(`Wrote double-entry ledger CSV to ${o}.`));return}e.out.result({csv:a},()=>{typeof a=="string"&&e.io.stdout(a.endsWith(`
11201
11201
  `)?a:`${a}
11202
11202
  `)})}},aD={name:"payments:sandbox:verify",summary:"run live env-driven sandbox verification against iyzico Sandbox and/or Stripe Test Mode",usage:"[--use-connected] [--channel <key>] [--currency <ISO>] [--bin <digits>]",details:["Reads PALBASE_IYZICO_SANDBOX_API_KEY + PALBASE_IYZICO_SANDBOX_SECRET_KEY and/or PALBASE_STRIPE_TEST_KEY from the environment (always livemode: false).","Pass --use-connected to verify already-connected test/sandbox channels without connecting new credentials.","Skips gracefully with setup instructions when no sandbox credentials are present."],flags:{"use-connected":{type:"boolean",description:"verify already-connected test/sandbox channels on the environment"},channel:{type:"string",value:"key",description:"optional channel key filter when using --use-connected"},currency:{type:"string",value:"ISO",description:"currency for capabilities/installment probe (default: TRY for iyzico, USD for stripe)"},bin:{type:"string",value:"digits",description:"test card BIN prefix for installment lookup (default: 554960)"}},scope:"environment",async run(e){let t=await f(e),n=e.io.env.PALBASE_IYZICO_SANDBOX_API_KEY?.trim(),s=e.io.env.PALBASE_IYZICO_SANDBOX_SECRET_KEY?.trim(),a=e.io.env.PALBASE_STRIPE_TEST_KEY?.trim(),o=e.flags["use-connected"]===!0;if(!o&&!(n&&s)&&!a){let u={status:"skipped",reason:"no sandbox credentials provided in environment",env_vars:["PALBASE_IYZICO_SANDBOX_API_KEY","PALBASE_IYZICO_SANDBOX_SECRET_KEY","PALBASE_STRIPE_TEST_KEY"]};e.out.result(u,()=>{e.out.line("Skipped sandbox verification: no sandbox credentials set."),e.out.line("Set PALBASE_IYZICO_SANDBOX_API_KEY & PALBASE_IYZICO_SANDBOX_SECRET_KEY (and/or PALBASE_STRIPE_TEST_KEY), or pass --use-connected.")});return}let i=[],r=[];if(n&&s){let u=await g(e,t,"POST","/payments/channels",{key:"iyzico_sandbox",provider:"iyzico",api_key:n,secret_key:s,livemode:!1},D());i.push({name:"connect:iyzico_sandbox",ok:u.status==="active",detail:`status=${u.status}`}),r.push({key:u.key,provider:"iyzico"})}if(a){if(!a.startsWith("rk_test_"))throw new b("live_key_refused","PALBASE_STRIPE_TEST_KEY must be a Stripe test restricted key (rk_test_...)");let u=await g(e,t,"POST","/payments/channels",{key:"stripe_test",provider:"stripe",api_key:a,livemode:!1},D());i.push({name:"connect:stripe_test",ok:u.status==="active",detail:`status=${u.status}`}),r.push({key:u.key,provider:"stripe"})}if(o&&r.length===0){let u=e.flags.channel?.trim(),m=await g(e,t,"GET","/payments/channels");for(let y of m.channels)y.livemode||u&&y.key!==u||r.push({key:y.key,provider:y.provider});if(r.length===0)throw new b("no_sandbox_channel","no non-live payment channel found to verify")}let l=e.flags.bin?.trim()||"554960";for(let u of r){let m=await g(e,t,"POST",`/payments/channels/${R(u.key)}/check`,void 0,D());i.push({name:`health:${u.key}`,ok:m.status==="active",detail:`status=${m.status}`});let y=e.flags.currency?.trim().toUpperCase()||(u.provider==="iyzico"?"TRY":"USD"),w=await g(e,t,"GET",`/payments/capabilities?${new URLSearchParams({channel:u.key,currency:y})}`);if(i.push({name:`capabilities:${u.key}`,ok:w.available,detail:`currency=${w.currency} 3ds=${w.capabilities.three_ds} installments=${w.capabilities.installments}`}),w.available&&w.capabilities.installments){let v=await g(e,t,"POST","/payments/installments",{bin:l,amount:1e4,currency:y,channel:u.key});i.push({name:`installments:${u.key}`,ok:v.options.length>0,detail:`bin=${v.bin} family=${v.card_family??"n/a"} options=${v.options.length}`})}}let p=await g(e,t,"GET","/payments/audit/drift");i.push({name:"audit:drift",ok:p.ok,detail:p.ok?`${p.accounts_checked} accounts, ${p.transactions_checked} txs`:`${p.problems.length} problem(s)`});let d=i.every(u=>u.ok);return e.out.result({status:d?"passed":"failed",checks:i},()=>{for(let u of i)e.out.line(` ${u.ok?"\u2713":"\u2717"} ${u.name}: ${u.detail}`);e.out.line(d?"Sandbox verification passed.":"Sandbox verification failed.")}),d?void 0:1}},oD={name:"payments:sub-merchants",summary:"list marketplace sub-merchants registered across iyzico Pazaryeri and Stripe Connect channels",usage:"[--seller <ref>] [--channel <key>] [--status <status>] [--limit <n>] [--cursor <token>]",flags:{seller:{type:"string",value:"ref",description:"filter by seller_ref"},channel:{type:"string",value:"key",description:"filter by channel key"},status:{type:"string",value:"status",description:"filter by sub-merchant status"},limit:{type:"string",value:"n",description:"maximum rows to return (default 50)"},cursor:{type:"string",value:"token",description:"pagination cursor from previous page"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams;e.flags.seller!==void 0&&n.set("seller_ref",String(e.flags.seller)),e.flags.channel!==void 0&&n.set("channel",String(e.flags.channel)),e.flags.status!==void 0&&n.set("status",String(e.flags.status)),e.flags.limit!==void 0&&n.set("limit",String(we(e.flags.limit,"limit"))),e.flags.cursor!==void 0&&n.set("cursor",String(e.flags.cursor));let s=n.size?`?${n}`:"",a=await g(e,t,"GET",`/payments/sub-merchants${s}`);e.out.result(a,()=>{if(a.sub_merchants.length===0){e.out.line("No marketplace sub-merchants registered yet.");return}e.out.table(a.sub_merchants,[{header:"id",value:o=>o.id},{header:"seller",value:o=>o.seller_ref},{header:"channel",value:o=>`${o.channel_key} (${o.provider})`},{header:"external_id",value:o=>o.external_id},{header:"status",value:o=>o.status},{header:"payouts",value:o=>o.payouts_enabled?"yes":"no"}]),a.next_cursor&&e.out.note(`next cursor: ${a.next_cursor}`)})}},iD={name:"payments:sub-merchants:upsert",summary:"create or update a marketplace sub-merchant (iyzico Pazaryeri or Stripe Connect) from JSON file or stdin",usage:"--file <submerchant.json>",flags:{file:{type:"string",value:"submerchant.json",description:"JSON payload file ('-' or omitted: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Ne(await ze(e,e.flags.file,"sub-merchant JSON"),"sub-merchant JSON");if(typeof n!="object"||n===null||Array.isArray(n))throw h("sub-merchant payload must be a JSON object with seller_ref");let s=n;if(!s.seller_ref?.trim())throw h("seller_ref is required in sub-merchant JSON");await k(e,t,`upsert marketplace sub-merchant for seller ${s.seller_ref}`);let a=await g(e,t,"POST","/payments/sub-merchants",s,D());e.out.result(a,()=>{e.out.line(`Sub-merchant ${a.id} (${a.seller_ref} on ${a.channel_key}): ${a.status}, external_id=${a.external_id}.`)})}},rD={name:"payments:sub-merchants:sync",summary:"refresh a marketplace sub-merchant status and payout readiness directly from its PSP",usage:"<sub-merchant-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the sub-merchant id"),s=await g(e,t,"POST",`/payments/sub-merchants/${R(n)}/sync`,void 0,D());e.out.result(s,()=>{e.out.line(`Synced ${s.id} (${s.seller_ref}): status=${s.status}, charges=${s.charges_enabled}, payouts=${s.payouts_enabled}.`)})}},lD={name:"payments:splits",summary:"list marketplace payment splits and escrow settlement state",usage:"[--intent <id>] [--seller <ref>] [--status <escrow_status>] [--limit <n>] [--cursor <token>]",flags:{intent:{type:"string",value:"id",description:"filter by PaymentIntent UUID"},seller:{type:"string",value:"ref",description:"filter by seller_ref"},status:{type:"string",value:"escrow_status",description:"filter by escrow_status (pending, held, approved, transferred, disapproved, refunded)"},limit:{type:"string",value:"n",description:"maximum rows to return (default 50)"},cursor:{type:"string",value:"token",description:"pagination cursor from previous page"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams;e.flags.intent!==void 0&&n.set("intent_id",String(e.flags.intent)),e.flags.seller!==void 0&&n.set("seller_ref",String(e.flags.seller)),e.flags.status!==void 0&&n.set("escrow_status",String(e.flags.status)),e.flags.limit!==void 0&&n.set("limit",String(we(e.flags.limit,"limit"))),e.flags.cursor!==void 0&&n.set("cursor",String(e.flags.cursor));let s=n.size?`?${n}`:"",a=await g(e,t,"GET",`/payments/splits${s}`);e.out.result(a,()=>{if(a.splits.length===0){e.out.line("No marketplace payment splits found.");return}e.out.table(a.splits,[{header:"id",value:o=>o.id},{header:"seller",value:o=>o.seller_ref},{header:"item",value:o=>o.external_item_ref},{header:"net",value:o=>`${o.seller_net_amount} ${o.currency}`},{header:"escrow",value:o=>String(o.psp_escrow_amount)},{header:"fee",value:o=>String(o.platform_fee_amount)},{header:"status",value:o=>o.escrow_status}]),a.next_cursor&&e.out.note(`next cursor: ${a.next_cursor}`)})}},pD={name:"payments:splits:approve",summary:"approve a held marketplace payment split for seller payout (iyzico item/approve or Stripe Connect transfer)",usage:"<split-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the split id");await k(e,t,`approve marketplace payment split ${n} for payout`);let s=await g(e,t,"POST",`/payments/splits/${R(n)}/approve`,void 0,D());e.out.result(s,()=>{e.out.line(`Approved split ${s.id} (${s.seller_ref}): status=${s.escrow_status}, net=${s.seller_net_amount} ${s.currency}.`)})}},dD={name:"payments:splits:disapprove",summary:"reverse escrow approval on a marketplace payment split (iyzico item/disapprove or Stripe transfer reversal)",usage:"<split-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the split id");await k(e,t,`disapprove marketplace payment split ${n}`);let s=await g(e,t,"POST",`/payments/splits/${R(n)}/disapprove`,void 0,D());e.out.result(s,()=>{e.out.line(`Disapproved split ${s.id} (${s.seller_ref}): status=${s.escrow_status}.`)})}},cD={name:"payments:splits:refund",summary:"execute a partial or full item-level marketplace split refund with seller clawback",usage:"<split-id> --card <minor> --clawback <minor> [--wallet <minor>] [--fee-reversed <minor>] [--tax-reversed <minor>] [--reason <text>]",flags:{card:{type:"string",value:"minor",description:"card refund amount in minor units"},wallet:{type:"string",value:"minor",description:"wallet refund amount in minor units (default: 0)"},clawback:{type:"string",value:"minor",description:"seller clawback amount in minor units"},"fee-reversed":{type:"string",value:"minor",description:"platform commission reversed in minor units (default: 0)"},"tax-reversed":{type:"string",value:"minor",description:"withholding tax reversed in minor units (default: 0)"},reason:{type:"string",value:"text",description:"optional refund reason"}},args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the split id"),s=we(e.flags.card,"card"),a=we(e.flags.clawback,"clawback");if(s===void 0)throw h("--card is required (minor units)");if(a===void 0)throw h("--clawback is required (minor units)");let o={card_refund_amount:s,seller_clawback_amount:a,...e.flags.wallet!==void 0?{wallet_refund_amount:we(e.flags.wallet,"wallet")}:{},...e.flags["fee-reversed"]!==void 0?{platform_fee_reversed_amount:we(e.flags["fee-reversed"],"fee-reversed")}:{},...e.flags["tax-reversed"]!==void 0?{withholding_tax_reversed_amount:we(e.flags["tax-reversed"],"tax-reversed")}:{},...e.flags.reason!==void 0?{reason:String(e.flags.reason)}:{}};await k(e,t,`refund split ${n} (card=${s}, clawback=${a})`);let i=await g(e,t,"POST",`/payments/splits/${R(n)}/refund`,o,D());e.out.result(i,()=>{e.out.line(`Refunded split ${i.split_id}: refund_id=${i.refund_id}, status=${i.escrow_status}.`)})}},uD={name:"payments:seller-accounts",summary:"inspect channel-independent escrow, top-up escrow, payable, and debt balances for a marketplace seller",usage:"<seller-ref>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the seller ref"),s=await g(e,t,"GET",`/payments/seller-accounts/${R(n)}`);e.out.result(s,()=>{if(s.balances.length===0){e.out.line(`No balances recorded yet for seller ${s.seller_ref}.`);return}e.out.table(s.balances,[{header:"currency",value:a=>a.currency},{header:"escrow",value:a=>String(a.escrow_balance)},{header:"topup_escrow",value:a=>String(a.topup_escrow_balance)},{header:"payable",value:a=>String(a.payable_balance)},{header:"debt",value:a=>String(a.debt_balance)}])})}},mD={name:"payments:seller-accounts:ledger",summary:"list immutable double-entry ledger entries affecting a marketplace seller account",usage:"<seller-ref> [--limit <n>] [--cursor <seq>]",flags:{limit:{type:"string",value:"n",description:"maximum entries to return (default 100)"},cursor:{type:"string",value:"seq",description:"sequence cursor for older entries"}},args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=hs(e,0,"the seller ref"),s=new URLSearchParams;e.flags.limit!==void 0&&s.set("limit",String(we(e.flags.limit,"limit"))),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let a=s.size?`?${s}`:"",o=await g(e,t,"GET",`/payments/seller-accounts/${R(n)}/ledger${a}`);e.out.result(o,()=>{if(o.entries.length===0){e.out.line(`No ledger entries found for seller ${o.seller_ref}.`);return}e.out.table(o.entries,[{header:"seq",value:i=>String(i.seq)},{header:"kind",value:i=>i.kind},{header:"amount",value:i=>`${i.amount} ${i.currency}`},{header:"legs",value:i=>i.legs.map(r=>`${r.direction}:${r.account_id}=${r.amount}`).join(", ")},{header:"at",value:i=>Z(i.created_at)}]),o.next_cursor&&e.out.note(`next cursor: ${o.next_cursor}`)})}},gD={name:"payments:reconcile",summary:"run full payments & marketplace accounting reconciliation (zero-drift Checks 1-6 plus cash-flow summary)",usage:"[--from <iso>] [--to <iso>]",flags:{from:{type:"string",value:"iso",description:"inclusive RFC 3339 start timestamp for cash-flow window"},to:{type:"string",value:"iso",description:"exclusive RFC 3339 end timestamp for cash-flow window"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams;e.flags.from!==void 0&&n.set("from",String(e.flags.from)),e.flags.to!==void 0&&n.set("to",String(e.flags.to));let s=n.size?`?${n}`:"",[a,o]=await Promise.all([g(e,t,"GET","/payments/audit/drift"),g(e,t,"GET",`/payments/audit/cashflow${s}`)]);return e.out.result({drift:a,cashflow:o},()=>{if(a.ok)e.out.line(`Zero drift verified (Checks 1-6): ${a.accounts_checked} account(s), ${a.transactions_checked} double-entry tx(s).`);else{e.out.line(`Drift detected (${a.problems.length} problem(s)):`);for(let i of a.problems)e.out.line(` \u2717 ${i}`)}o.currencies.length>0&&e.out.table(o.currencies,[{header:"currency",value:i=>i.currency},{header:"gross",value:i=>String(i.payment_gross)},{header:"refunded",value:i=>String(i.payment_refunded)},{header:"escrow",value:i=>String(i.marketplace_escrow??0)},{header:"commission",value:i=>String(i.marketplace_commission??0)},{header:"withholding",value:i=>String(i.marketplace_withholding??0)}])}),a.ok?void 0:1}},Yk=[FM,BM,JM,HM,VM,XM,YM,ZM,QM,eD,tD,nD,sD,aD,oD,iD,rD,lD,pD,dD,cD,uD,mD,gD];function Zk(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s.trim()}async function Ti(e,t){let n=await ze(e,e.flags.file,t),s=Ne(n,t);if(typeof s!="object"||s===null||Array.isArray(s))throw h(`${t} must be a JSON object`);return s}var hD={name:"commerce:settings:get",summary:"show the environment's commerce settings (currency, commission, withholding, escrow)",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/commerce/settings");e.out.result(n,()=>{e.out.line(`Currency: ${n.default_currency??"TRY"}, commission: ${n.default_commission_bps??0} bps, withholding: ${n.default_withholding_bps??0} bps, escrow: ${n.escrow_release_days??0}d`)})}},yD={name:"commerce:settings:set",summary:"update the environment's commerce settings from JSON (--file or stdin)",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with commerce settings"}},scope:"environment",async run(e){let t=await f(e),n=await Ti(e,"commerce settings");await k(e,t,"update commerce settings");let s=await g(e,t,"PUT","/commerce/settings",n,D());e.out.result(s,()=>e.out.line(`Updated commerce settings for ${ee(t)}.`))}},fD={name:"commerce:stores",summary:"list the environment's first-party and marketplace seller stores",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/commerce/stores");e.out.result(n,()=>{if(n.stores.length===0){e.out.line("No stores yet.");return}e.out.table(n.stores,[{header:"id",value:s=>s.id??""},{header:"slug",value:s=>s.slug??""},{header:"name",value:s=>s.name??""},{header:"kind",value:s=>s.kind??""},{header:"status",value:s=>s.status??""}])})}},bD={name:"commerce:stores:create",summary:"create a first-party or marketplace seller store from JSON (--file or stdin)",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with store payload"}},scope:"environment",async run(e){let t=await f(e),n=await Ti(e,"store");await k(e,t,`create store ${String(n.slug??n.name??"")}`);let s=await g(e,t,"POST","/commerce/stores",n,D());e.out.result(s,()=>e.out.line(`Created store ${s.slug} (${s.id}).`))}},wD={name:"commerce:products",summary:"list catalog products (optionally filtered with --q)",usage:"[--q <query>]",flags:{q:{type:"string",value:"query",description:"search query"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.q?.trim(),s=n?`/commerce/products?q=${encodeURIComponent(n)}`:"/commerce/products",a=await g(e,t,"GET",s);e.out.result(a,()=>{if(a.products.length===0){e.out.line("No products yet.");return}e.out.table(a.products,[{header:"id",value:o=>o.id??""},{header:"handle",value:o=>o.handle??""},{header:"title",value:o=>o.title??""},{header:"status",value:o=>o.status??""},{header:"approval",value:o=>o.approval_status??""}])})}},vD={name:"commerce:products:quick",summary:"quick-create a product, default variant, listing, price, and initial stock from JSON",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with quick product payload"}},scope:"environment",async run(e){let t=await f(e),n=await Ti(e,"quick product"),s=await g(e,t,"POST","/commerce/products/quick",n,D());e.out.result(s,()=>e.out.line(`Created product ${s.product?.id??""} (listing ${s.listing?.id??""}).`))}},kD={name:"commerce:orders",summary:"list parent commerce orders (optionally filtered by --status)",usage:"[--status <status>]",flags:{status:{type:"string",value:"status",description:"filter by order status"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.status?.trim(),s=n?`/commerce/orders?status=${encodeURIComponent(n)}`:"/commerce/orders",a=await g(e,t,"GET",s);e.out.result(a,()=>{if(a.orders.length===0){e.out.line("No orders yet.");return}e.out.table(a.orders,[{header:"number",value:o=>o.order_number??""},{header:"status",value:o=>o.status??""},{header:"total",value:o=>`${o.total_amount??0} ${o.currency??""}`},{header:"customer",value:o=>o.customer_id??"guest"}])})}},_D={name:"commerce:orders:get",summary:"inspect a commerce order including its per-store splits and line items",usage:"<order id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Zk(e,0,"the order id"),s=await g(e,t,"GET",`/commerce/orders/${R(n)}`);e.out.result(s,()=>{e.out.line(`Order ${s.order?.order_number??n}: ${s.order?.status??""} (${s.store_orders?.length??0} store orders, ${s.lines?.length??0} lines)`)})}},SD={name:"commerce:store-orders",summary:"list per-seller split store orders",usage:"[--store <store id>] [--status <status>]",flags:{store:{type:"string",value:"id",description:"filter by store UUID"},status:{type:"string",value:"status",description:"filter by status"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams;e.flags.store&&n.set("store_id",String(e.flags.store)),e.flags.status&&n.set("status",String(e.flags.status));let s=n.size>0?`/commerce/store-orders?${n.toString()}`:"/commerce/store-orders",a=await g(e,t,"GET",s);e.out.result(a,()=>{if(a.store_orders.length===0){e.out.line("No store orders yet.");return}e.out.table(a.store_orders,[{header:"number",value:o=>o.store_order_number??""},{header:"store",value:o=>o.store_id??""},{header:"status",value:o=>o.status??""},{header:"seller_net",value:o=>`${o.seller_net_amount??0} ${o.currency??""}`},{header:"escrow",value:o=>o.escrow_status??""}])})}},$D={name:"commerce:returns",summary:"list RMA returns and partial-refund requests",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/commerce/returns");e.out.result(n,()=>{if(n.returns.length===0){e.out.line("No returns yet.");return}e.out.table(n.returns,[{header:"rma",value:s=>s.rma_number??""},{header:"status",value:s=>s.status??""},{header:"refund",value:s=>String(s.refund_total_amount??0)}])})}},AD={name:"commerce:settlements",summary:"list seller settlement statements",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/commerce/settlements");e.out.result(n,()=>{if(n.settlements.length===0){e.out.line("No settlements yet.");return}e.out.table(n.settlements,[{header:"id",value:s=>s.id??""},{header:"store",value:s=>s.store_id??""},{header:"status",value:s=>s.status??""},{header:"net",value:s=>`${s.net_payout_amount??0} ${s.currency??""}`}])})}},RD={name:"commerce:settlements:generate",summary:"generate a deduplicated seller settlement statement from JSON (--file or stdin)",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with store_id, currency, period_start_at, period_end_at"}},scope:"environment",async run(e){let t=await f(e),n=await Ti(e,"settlement request");await k(e,t,"generate seller settlement statement");let s=await g(e,t,"POST","/commerce/settlements/generate",n,D());e.out.result(s,()=>e.out.line(`Generated settlement ${s.id} (net ${s.net_payout_amount??0} ${s.currency??""}).`))}},PD={name:"commerce:hooks",summary:"list configured blocking commerce extension hooks",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/commerce/hooks");e.out.result(n,()=>{if(n.hooks.length===0){e.out.line("No commerce hooks configured.");return}e.out.table(n.hooks,[{header:"id",value:s=>s.id??""},{header:"point",value:s=>s.hook_point??""},{header:"url",value:s=>s.url??""},{header:"fail_mode",value:s=>s.fail_mode??""}])})}},jD={name:"commerce:hooks:set",summary:"register or rotate a blocking commerce hook endpoint (returns signing secret once)",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with hook_point, url, timeout_ms, fail_mode"}},scope:"environment",async run(e){let t=await f(e),n=await Ti(e,"commerce hook");await k(e,t,`set commerce hook ${String(n.hook_point??"")}`);let s=await g(e,t,"POST","/commerce/hooks",n,D());e.out.result(s,()=>{e.out.line(`Registered hook ${s.hook_point} (${s.id}).`),e.out.line(`Signing secret (shown once): ${s.signing_secret}`)})}},TD={name:"commerce:hooks:delete",summary:"delete a blocking commerce extension hook",usage:"<hook id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Zk(e,0,"the hook id");await k(e,t,`delete commerce hook ${n}`);let s=await g(e,t,"DELETE",`/commerce/hooks/${R(n)}`,void 0,D());e.out.result(s,()=>e.out.line(`Deleted commerce hook ${n}.`))}},Qk=[hD,yD,fD,bD,wD,vD,kD,_D,SD,$D,AD,RD,PD,jD,TD];function Vc(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s.trim()}async function Wl(e,t){let n=await ze(e,e.flags.file,t),s=Ne(n,t);if(typeof s!="object"||s===null||Array.isArray(s))throw h(`${t} must be a JSON object`);return s}var ED={name:"promotions:rules",summary:"list promotion rules (automatic, code, and referral campaigns)",usage:"[--status <status>]",flags:{status:{type:"string",value:"status",description:"filter by status"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.status?.trim(),s=n?`/promotions/rules?status=${encodeURIComponent(n)}`:"/promotions/rules",a=await g(e,t,"GET",s);e.out.result(a,()=>{if(a.rules.length===0){e.out.line("No promotion rules yet.");return}e.out.table(a.rules,[{header:"id",value:o=>o.id??""},{header:"key",value:o=>o.key??""},{header:"trigger",value:o=>o.trigger_kind??""},{header:"effect",value:o=>o.effect_kind??""},{header:"funded_by",value:o=>o.funded_by??""},{header:"status",value:o=>o.status??""}])})}},CD={name:"promotions:rules:create",summary:"create a promotion rule from JSON (--file or stdin)",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with rule definition"}},scope:"environment",async run(e){let t=await f(e),n=await Wl(e,"promotion rule");await k(e,t,`create promotion rule ${String(n.key??n.name??"")}`);let s=await g(e,t,"POST","/promotions/rules",n,D());e.out.result(s,()=>e.out.line(`Created promotion rule ${s.key} (${s.id}).`))}},OD={name:"promotions:rules:archive",summary:"archive a promotion rule",usage:"<rule id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Vc(e,0,"the rule id");await k(e,t,`archive promotion rule ${n}`);let s=await g(e,t,"DELETE",`/promotions/rules/${R(n)}`,void 0,D());e.out.result(s,()=>e.out.line(`Archived promotion rule ${n}.`))}},xD={name:"promotions:codes:create",summary:"create a single or referral promo code for a rule",usage:"<rule id> [--file <path>]",args:{min:1,max:1},flags:{file:{type:"string",value:"path",description:"JSON file with code payload"}},scope:"environment",async run(e){let t=await f(e),n=Vc(e,0,"the rule id"),s=await Wl(e,"promotion code"),a=await g(e,t,"POST",`/promotions/rules/${R(n)}/codes`,s,D());e.out.result(a,()=>e.out.line(`Created code ${a.code} (${a.id}).`))}},LD={name:"promotions:codes:batch",summary:"generate a batch of single-use promo codes for a rule",usage:"<rule id> [--file <path>]",args:{min:1,max:1},flags:{file:{type:"string",value:"path",description:"JSON file with count, prefix, expires_at"}},scope:"environment",async run(e){let t=await f(e),n=Vc(e,0,"the rule id"),s=await Wl(e,"code batch"),a=await g(e,t,"POST",`/promotions/rules/${R(n)}/codes/batch`,s,D());e.out.result(a,()=>e.out.line(`Generated ${a.count} promotion codes.`))}},ID={name:"promotions:evaluate",summary:"dry-run evaluate applicable promotions against a cart JSON payload",usage:"[--file <path>]",flags:{file:{type:"string",value:"path",description:"JSON file with evaluate request"}},scope:"environment",async run(e){let t=await f(e),n=await Wl(e,"evaluate payload"),s=await g(e,t,"POST","/promotions/evaluate",n);e.out.result(s,()=>{e.out.line(`Discount: ${s.total_discount_amount??0}, shipping discount: ${s.shipping_discount_amount??0}, cashback: ${s.wallet_cashback_amount??0}`)})}},ND={name:"promotions:redemptions",summary:"list committed and reversed promotion redemptions",scope:"environment",async run(e){let t=await f(e),n=await g(e,t,"GET","/promotions/redemptions");e.out.result(n,()=>{if(n.redemptions.length===0){e.out.line("No redemptions yet.");return}e.out.table(n.redemptions,[{header:"id",value:s=>s.id??""},{header:"rule",value:s=>s.rule_id??""},{header:"status",value:s=>s.status??""},{header:"discount",value:s=>`${s.discount_amount??0} ${s.currency??""}`}])})}},e_=[ED,CD,OD,xD,LD,ID,ND];import{readdir as MD,readFile as DD,stat as zD}from"node:fs/promises";import{join as qD,resolve as GD}from"node:path";var KD=1e3,t_=900*1024,UD="palbase-argon2id";function WD(e,t){let n=e.trim();if(n.startsWith("{"))try{let s=JSON.parse(n);if(Array.isArray(s.users)){if(s.hash?.pepper!==void 0)throw h(`${t} holds a pepper: it goes on stdin, not in a file`);let a=s.hash&&typeof s.hash.algorithm=="string"?{algorithm:s.hash.algorithm,...typeof s.hash.recovery_code_prefix=="string"?{recovery_code_prefix:s.hash.recovery_code_prefix}:{}}:void 0;return{users:s.users,hash:a}}}catch(s){if(s instanceof Error&&s.name==="CliError")throw s}return{users:BD(e,t)}}function FD(e){let t=[],n=[],s=0;for(let a of e){let o=Buffer.byteLength(JSON.stringify(a))+1;if(o>t_)throw new b("user_too_large",`the user ${String(a.id??"")} is larger than one call takes (${o} bytes)`);(n.length===KD||s+o>t_)&&(t.push(n),n=[],s=0),n.push(a),s+=o}return n.length>0&&t.push(n),t}function BD(e,t){let n=e.trim();if(n==="")return[];if(n.startsWith("["))try{let s=JSON.parse(n);if(Array.isArray(s)&&s.every(a=>typeof a=="object"&&a!==null&&!Array.isArray(a)))return s}catch{}return n.split(`