@sequenzy/cli 0.0.217 → 0.0.219
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -329,7 +329,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
329
329
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
330
330
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&t.sep&&!t.value){let o=[];for(let c=0;c<t.sep.length;++c){let l=t.sep[c];switch(l.type){case"newline":o.push(c);break;case"space":break;case"comment":if(l.indent>e.indent)o.length=0;break;default:o.length=0}}if(o.length>=2)i=t.sep.splice(o[1])}switch(this.type){case"anchor":case"tag":if(r||t.value)i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(r||t.value)i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Hl(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Rm(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Hl(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(X6(t.key)&&!Hl(t.sep,"newline")){let o=Rm(t.start),{key:c,sep:l}=t;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:c,sep:l}]})}else if(i.length>0)t.sep=t.sep.concat(i,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||r)e.items.push({start:i,key:null,sep:[this.sourceToken]});else if(Hl(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(r||t.value)e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0;return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Hl(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(n)e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Hl(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:r,sep:[]});else if(t.sep)this.stack.push(r);else Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);if(n)this.stack.push(n);else yield*this.pop(),yield*this.step()}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=jI(n),i=Rm(r);Z6(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let c={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=c}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
331
331
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
332
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=jI(e),n=Rm(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=jI(e),n=Rm(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((n)=>n.type==="newline"||n.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}LNe.Parser=e9});var o9=P(function(VNe){var t9=tR(),MNe=NA(),LA=$A(),jNe=dk(),zNe=nn(),GNe=dR(),n9=pR();function r9(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GNe.LineCounter||null,prettyErrors:t}}function HNe(e,t={}){let{lineCounter:n,prettyErrors:r}=r9(t),i=new n9.Parser(n?.addNewLine),o=new t9.Composer(t),c=Array.from(o.compose(i.parse(e)));if(r&&n)for(let l of c)l.errors.forEach(LA.prettifyError(e,n)),l.warnings.forEach(LA.prettifyError(e,n));if(c.length>0)return c;return Object.assign([],{empty:!0},o.streamInfo())}function i9(e,t={}){let{lineCounter:n,prettyErrors:r}=r9(t),i=new n9.Parser(n?.addNewLine),o=new t9.Composer(t),c=null;for(let l of o.compose(i.parse(e),!0,e.length))if(!c)c=l;else if(c.options.logLevel!=="silent"){c.errors.push(new LA.YAMLParseError(l.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(r&&n)c.errors.forEach(LA.prettifyError(e,n)),c.warnings.forEach(LA.prettifyError(e,n));return c}function JNe(e,t,n){let r=void 0;if(typeof t==="function")r=t;else if(n===void 0&&t&&typeof t==="object")n=t;let i=i9(e,n);if(!i)return null;if(i.warnings.forEach((o)=>jNe.warn(i.options.logLevel,o)),i.errors.length>0)if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[];return i.toJS(Object.assign({reviver:r},n))}function KNe(e,t,n){let r=null;if(typeof t==="function"||Array.isArray(t))r=t;else if(n===void 0&&t)n=t;if(typeof n==="string")n=n.length;if(typeof n==="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}if(zNe.isDocument(e)&&!r)return e.toString(n);return new MNe.Document(e,r,n).toString(n)}VNe.parse=JNe;VNe.parseAllDocuments=HNe;VNe.parseDocument=i9;VNe.stringify=KNe});var P0={};Vne(P0,{program:()=>oP,createCommand:()=>sP,createOption:()=>aP,createArgument:()=>cP,Command:()=>lP,Option:()=>uP,Argument:()=>dP,Help:()=>pP,CommanderError:()=>mP,InvalidArgumentError:()=>fP,InvalidOptionArgumentError:()=>gP},{program:(Qje)=>oP=Qje,createCommand:(Qje)=>sP=Qje,createOption:(Qje)=>aP=Qje,createArgument:(Qje)=>cP=Qje,Command:(Qje)=>lP=Qje,Option:(Qje)=>uP=Qje,Argument:(Qje)=>dP=Qje,Help:(Qje)=>pP=Qje,CommanderError:(Qje)=>mP=Qje,InvalidArgumentError:(Qje)=>fP=Qje,InvalidOptionArgumentError:(Qje)=>gP=Qje});var{Argument:nP}=Jy(),{Command:$0}=tP(),{CommanderError:Sre,InvalidArgumentError:rP}=Wf(),{Help:Dre}=R0(),{Option:iP}=T0();var oP=new $0,sP=(e)=>new $0(e),aP=(e,t)=>new iP(e,t),cP=(e,t)=>new nP(e,t),lP=$0,uP=iP,dP=nP,pP=Dre,mP=Sre,fP=rP,gP=rP;var{program:Fje,createCommand:Lje,createArgument:Uje,createOption:Mje,CommanderError:AP,InvalidArgumentError:jje,InvalidOptionArgumentError:zje,Command:hP,Argument:Gje,Option:Hje,Help:Jje}=P0;var Ky={name:"@sequenzy/cli",version:"0.0.217",description:"Sequenzy CLI for email marketing from the terminal",type:"module",bin:{sequenzy:"./dist/index.js"},main:"./src/index.tsx",types:"./src/index.tsx",exports:{".":"./src/index.tsx"},scripts:{dev:"bun --watch src/index.tsx",build:"bun ../../scripts/build-ink-cli.ts",start:"node dist/index.js",lint:"eslint src","type-check":"bun check",test:"sh ../../scripts/run-package-tests.sh src","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{commander:"^12.1.0",ink:"^5.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","ink-select-input":"^6.0.0","ink-table":"^3.1.0",open:"^10.1.0",react:"^18.3.1",conf:"^13.0.0",yaml:"^2.8.2"},devDependencies:{"@emailer/shared":"workspace:*","@types/bun":"latest","@types/node":"^22.0.0","@types/react":"^18.3.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist"],keywords:["sequenzy","email","cli","marketing"],license:"MIT",repository:{type:"git",url:"https://github.com/sequenzy/sequenzy"}};import{isDeepStrictEqual as Lge}from"node:util";import uj from"node:process";import Fu from"node:fs";import dj from"node:path";import Eg from"node:crypto";import Uge from"node:assert";var Tu=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var Q0=new Set(["__proto__","prototype","constructor"]),xre=new Set("0123456789");function Vy(e){let t=[],n="",r="start",i=!1;for(let o of e)switch(o){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(i)n+=o;r="property",i=!i;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(i){i=!1,n+=o;break}if(Q0.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(i){i=!1,n+=o;break}if(r==="property"){if(Q0.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!xre.has(o))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(i)i=!1,n+="\\";n+=o}}if(i)n+="\\";switch(r){case"property":{if(Q0.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function q0(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function yP(e,t){if(q0(e,t))throw Error("Cannot use string index")}function bP(e,t,n){if(!Tu(e)||typeof t!=="string")return n===void 0?e:n;let r=Vy(t);if(r.length===0)return n;for(let i=0;i<r.length;i++){let o=r[i];if(q0(e,o))e=i===r.length-1?void 0:null;else e=e[o];if(e===void 0||e===null){if(i!==r.length-1)return n;break}}return e===void 0?n:e}function F0(e,t,n){if(!Tu(e)||typeof t!=="string")return e;let r=e,i=Vy(t);for(let o=0;o<i.length;o++){let c=i[o];if(yP(e,c),o===i.length-1)e[c]=n;else if(!Tu(e[c]))e[c]=typeof i[o+1]==="number"?[]:{};e=e[c]}return r}function vP(e,t){if(!Tu(e)||typeof t!=="string")return!1;let n=Vy(t);for(let r=0;r<n.length;r++){let i=n[r];if(yP(e,i),r===n.length-1)return delete e[i],!0;if(e=e[i],!Tu(e))return!1}}function EP(e,t){if(!Tu(e)||typeof t!=="string")return!1;let n=Vy(t);if(n.length===0)return!1;for(let r of n){if(!Tu(e)||!(r in e)||q0(e,r))return!1;e=e[r]}return!0}import er from"node:path";import IP from"node:os";import L0 from"node:process";var tl=IP.homedir(),U0=IP.tmpdir(),{env:fp}=L0,Bre=(e)=>{let t=er.join(tl,"Library");return{data:er.join(t,"Application Support",e),config:er.join(t,"Preferences",e),cache:er.join(t,"Caches",e),log:er.join(t,"Logs",e),temp:er.join(U0,e)}},kre=(e)=>{let t=fp.APPDATA||er.join(tl,"AppData","Roaming"),n=fp.LOCALAPPDATA||er.join(tl,"AppData","Local");return{data:er.join(n,e,"Data"),config:er.join(t,e,"Config"),cache:er.join(n,e,"Cache"),log:er.join(n,e,"Log"),temp:er.join(U0,e)}},Rre=(e)=>{let t=er.basename(tl);return{data:er.join(fp.XDG_DATA_HOME||er.join(tl,".local","share"),e),config:er.join(fp.XDG_CONFIG_HOME||er.join(tl,".config"),e),cache:er.join(fp.XDG_CACHE_HOME||er.join(tl,".cache"),e),log:er.join(fp.XDG_STATE_HOME||er.join(tl,".local","state"),e),temp:er.join(U0,t,e)}};function M0(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(L0.platform==="darwin")return Bre(e);if(L0.platform==="win32")return kre(e);return Rre(e)}import Fre from"node:path";import an from"node:fs";import{promisify as Bi}from"node:util";var Tre=(e,t)=>{let{onError:n}=t;return function(...i){return e.apply(void 0,i).catch(n)}},ha=Tre;var Ore=(e,t)=>{let{onError:n}=t;return function(...i){try{return e.apply(void 0,i)}catch(o){return n(o)}}},ks=Ore;var CP=250;var Nre=(e,t)=>{let{isRetriable:n}=t;return function(i){let{timeout:o}=i,c=i.interval??CP,l=Date.now()+o;return function d(...m){return e.apply(void 0,m).catch((A)=>{if(!n(A))throw A;if(Date.now()>=l)throw A;let y=Math.round(c*Math.random());if(y>0)return new Promise((v)=>setTimeout(v,y)).then(()=>d.apply(void 0,m));else return d.apply(void 0,m)})}}},ya=Nre;var $re=(e,t)=>{let{isRetriable:n}=t;return function(i){let{timeout:o}=i,c=Date.now()+o;return function(...d){while(!0)try{return e.apply(void 0,d)}catch(m){if(!n(m))throw m;if(Date.now()>=c)throw m;continue}}}},ba=$re;import SP from"node:process";var Yf={isChangeErrorOk:(e)=>{if(!Yf.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!wP&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!Yf.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!Yf.isNodeError(e))throw e;if(Yf.isChangeErrorOk(e))return;throw e}},j0=Yf;var Zf={onError:j0.onChangeError},ao={onError:()=>{return}},wP=SP.getuid?!SP.getuid():!1,Ii={isRetriable:j0.isRetriableError};var Pre={attempt:{chmod:ha(Bi(an.chmod),Zf),chown:ha(Bi(an.chown),Zf),close:ha(Bi(an.close),ao),fsync:ha(Bi(an.fsync),ao),mkdir:ha(Bi(an.mkdir),ao),realpath:ha(Bi(an.realpath),ao),stat:ha(Bi(an.stat),ao),unlink:ha(Bi(an.unlink),ao),chmodSync:ks(an.chmodSync,Zf),chownSync:ks(an.chownSync,Zf),closeSync:ks(an.closeSync,ao),existsSync:ks(an.existsSync,ao),fsyncSync:ks(an.fsync,ao),mkdirSync:ks(an.mkdirSync,ao),realpathSync:ks(an.realpathSync,ao),statSync:ks(an.statSync,ao),unlinkSync:ks(an.unlinkSync,ao)},retry:{close:ya(Bi(an.close),Ii),fsync:ya(Bi(an.fsync),Ii),open:ya(Bi(an.open),Ii),readFile:ya(Bi(an.readFile),Ii),rename:ya(Bi(an.rename),Ii),stat:ya(Bi(an.stat),Ii),write:ya(Bi(an.write),Ii),writeFile:ya(Bi(an.writeFile),Ii),closeSync:ba(an.closeSync,Ii),fsyncSync:ba(an.fsyncSync,Ii),openSync:ba(an.openSync,Ii),readFileSync:ba(an.readFileSync,Ii),renameSync:ba(an.renameSync,Ii),statSync:ba(an.statSync,Ii),writeSync:ba(an.writeSync,Ii),writeFileSync:ba(an.writeFileSync,Ii)}},oi=Pre;import Ou from"node:process";var DP="utf8",z0=438,_P=511;var xP={},BP=Ou.geteuid?Ou.geteuid():-1,kP=Ou.getegid?Ou.getegid():-1;var RP=1000,TP=!!Ou.getuid,wze=Ou.getuid?!Ou.getuid():!1,G0=128;var OP=(e)=>e instanceof Error&&("code"in e);var H0=(e)=>typeof e==="string",Wy=(e)=>e===void 0;import qre from"node:path";import gp from"node:process";import NP from"node:process";var $P=NP.platform==="linux",Yy=NP.platform==="win32";var J0=["SIGHUP","SIGINT","SIGTERM"];if(!Yy)J0.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if($P)J0.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var PP=J0;class QP{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(Yy&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))gp.kill(gp.pid,"SIGTERM");else gp.kill(gp.pid,e)},this.hook=()=>{gp.once("exit",()=>this.exit());for(let e of PP)try{gp.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var qP=new QP;var Qre=qP.register,FP=Qre;var Oo={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",i=`.tmp-${n}${t}`;return`${e}${i}`},get:(e,t,n=!0)=>{let r=Oo.truncate(t(e));if(r in Oo.store)return Oo.get(e,t,n);return Oo.store[r]=n,[r,()=>delete Oo.store[r]]},purge:(e)=>{if(!Oo.store[e])return;delete Oo.store[e],oi.attempt.unlink(e)},purgeSync:(e)=>{if(!Oo.store[e])return;delete Oo.store[e],oi.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in Oo.store)Oo.purgeSync(e)},truncate:(e)=>{let t=qre.basename(e);if(t.length<=G0)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-G0;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};FP(Oo.purgeSyncAll);var Xf=Oo;function K0(e,t,n=xP){if(H0(n))return K0(e,t,{encoding:n});let i={timeout:n.timeout??RP},o=null,c=null,l=null;try{let d=oi.attempt.realpathSync(e),m=!!d;e=d||e,[c,o]=Xf.get(e,n.tmpCreate||Xf.create,n.tmpPurge!==!1);let A=TP&&Wy(n.chown),y=Wy(n.mode);if(m&&(A||y)){let b=oi.attempt.statSync(e);if(b){if(n={...n},A)n.chown={uid:b.uid,gid:b.gid};if(y)n.mode=b.mode}}if(!m){let b=Fre.dirname(e);oi.attempt.mkdirSync(b,{mode:_P,recursive:!0})}if(l=oi.retry.openSync(i)(c,"w",n.mode||z0),n.tmpCreated)n.tmpCreated(c);if(H0(t))oi.retry.writeSync(i)(l,t,0,n.encoding||DP);else if(!Wy(t))oi.retry.writeSync(i)(l,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)oi.retry.fsyncSync(i)(l);else oi.attempt.fsync(l);if(oi.retry.closeSync(i)(l),l=null,n.chown&&(n.chown.uid!==BP||n.chown.gid!==kP))oi.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==z0)oi.attempt.chmodSync(c,n.mode);try{oi.retry.renameSync(i)(c,e)}catch(b){if(!OP(b))throw b;if(b.code!=="ENAMETOOLONG")throw b;oi.retry.renameSync(i)(c,Xf.truncate(e))}o(),c=null}finally{if(l)oi.attempt.closeSync(l);if(c)Xf.purge(c)}}var mj=Et(WL(),1),fj=Et(yU(),1);var Ope=(e,t,n,r)=>{if(n==="length"||n==="prototype")return;if(n==="arguments"||n==="caller")return;let i=Object.getOwnPropertyDescriptor(e,n),o=Object.getOwnPropertyDescriptor(t,n);if(!Npe(i,o)&&r)return;Object.defineProperty(e,n,o)},Npe=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},$pe=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Ppe=(e,t)=>`/* Wrapped ${e}*/
|
|
332
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=jI(e),n=Rm(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=jI(e),n=Rm(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((n)=>n.type==="newline"||n.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}LNe.Parser=e9});var o9=P(function(VNe){var t9=tR(),MNe=NA(),LA=$A(),jNe=dk(),zNe=nn(),GNe=dR(),n9=pR();function r9(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GNe.LineCounter||null,prettyErrors:t}}function HNe(e,t={}){let{lineCounter:n,prettyErrors:r}=r9(t),i=new n9.Parser(n?.addNewLine),o=new t9.Composer(t),c=Array.from(o.compose(i.parse(e)));if(r&&n)for(let l of c)l.errors.forEach(LA.prettifyError(e,n)),l.warnings.forEach(LA.prettifyError(e,n));if(c.length>0)return c;return Object.assign([],{empty:!0},o.streamInfo())}function i9(e,t={}){let{lineCounter:n,prettyErrors:r}=r9(t),i=new n9.Parser(n?.addNewLine),o=new t9.Composer(t),c=null;for(let l of o.compose(i.parse(e),!0,e.length))if(!c)c=l;else if(c.options.logLevel!=="silent"){c.errors.push(new LA.YAMLParseError(l.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(r&&n)c.errors.forEach(LA.prettifyError(e,n)),c.warnings.forEach(LA.prettifyError(e,n));return c}function JNe(e,t,n){let r=void 0;if(typeof t==="function")r=t;else if(n===void 0&&t&&typeof t==="object")n=t;let i=i9(e,n);if(!i)return null;if(i.warnings.forEach((o)=>jNe.warn(i.options.logLevel,o)),i.errors.length>0)if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[];return i.toJS(Object.assign({reviver:r},n))}function KNe(e,t,n){let r=null;if(typeof t==="function"||Array.isArray(t))r=t;else if(n===void 0&&t)n=t;if(typeof n==="string")n=n.length;if(typeof n==="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}if(zNe.isDocument(e)&&!r)return e.toString(n);return new MNe.Document(e,r,n).toString(n)}VNe.parse=JNe;VNe.parseAllDocuments=HNe;VNe.parseDocument=i9;VNe.stringify=KNe});var P0={};Vne(P0,{program:()=>oP,createCommand:()=>sP,createOption:()=>aP,createArgument:()=>cP,Command:()=>lP,Option:()=>uP,Argument:()=>dP,Help:()=>pP,CommanderError:()=>mP,InvalidArgumentError:()=>fP,InvalidOptionArgumentError:()=>gP},{program:(Qje)=>oP=Qje,createCommand:(Qje)=>sP=Qje,createOption:(Qje)=>aP=Qje,createArgument:(Qje)=>cP=Qje,Command:(Qje)=>lP=Qje,Option:(Qje)=>uP=Qje,Argument:(Qje)=>dP=Qje,Help:(Qje)=>pP=Qje,CommanderError:(Qje)=>mP=Qje,InvalidArgumentError:(Qje)=>fP=Qje,InvalidOptionArgumentError:(Qje)=>gP=Qje});var{Argument:nP}=Jy(),{Command:$0}=tP(),{CommanderError:Sre,InvalidArgumentError:rP}=Wf(),{Help:Dre}=R0(),{Option:iP}=T0();var oP=new $0,sP=(e)=>new $0(e),aP=(e,t)=>new iP(e,t),cP=(e,t)=>new nP(e,t),lP=$0,uP=iP,dP=nP,pP=Dre,mP=Sre,fP=rP,gP=rP;var{program:Fje,createCommand:Lje,createArgument:Uje,createOption:Mje,CommanderError:AP,InvalidArgumentError:jje,InvalidOptionArgumentError:zje,Command:hP,Argument:Gje,Option:Hje,Help:Jje}=P0;var Ky={name:"@sequenzy/cli",version:"0.0.219",description:"Sequenzy CLI for email marketing from the terminal",type:"module",bin:{sequenzy:"./dist/index.js"},main:"./src/index.tsx",types:"./src/index.tsx",exports:{".":"./src/index.tsx"},scripts:{dev:"bun --watch src/index.tsx",build:"bun ../../scripts/build-ink-cli.ts",start:"node dist/index.js",lint:"eslint src","type-check":"bun check",test:"sh ../../scripts/run-package-tests.sh src","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{commander:"^12.1.0",ink:"^5.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","ink-select-input":"^6.0.0","ink-table":"^3.1.0",open:"^10.1.0",react:"^18.3.1",conf:"^13.0.0",yaml:"^2.8.2"},devDependencies:{"@emailer/shared":"workspace:*","@types/bun":"latest","@types/node":"^22.0.0","@types/react":"^18.3.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist"],keywords:["sequenzy","email","cli","marketing"],license:"MIT",repository:{type:"git",url:"https://github.com/sequenzy/sequenzy"}};import{isDeepStrictEqual as Lge}from"node:util";import uj from"node:process";import Fu from"node:fs";import dj from"node:path";import Eg from"node:crypto";import Uge from"node:assert";var Tu=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var Q0=new Set(["__proto__","prototype","constructor"]),xre=new Set("0123456789");function Vy(e){let t=[],n="",r="start",i=!1;for(let o of e)switch(o){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(i)n+=o;r="property",i=!i;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(i){i=!1,n+=o;break}if(Q0.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(i){i=!1,n+=o;break}if(r==="property"){if(Q0.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!xre.has(o))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(i)i=!1,n+="\\";n+=o}}if(i)n+="\\";switch(r){case"property":{if(Q0.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function q0(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function yP(e,t){if(q0(e,t))throw Error("Cannot use string index")}function bP(e,t,n){if(!Tu(e)||typeof t!=="string")return n===void 0?e:n;let r=Vy(t);if(r.length===0)return n;for(let i=0;i<r.length;i++){let o=r[i];if(q0(e,o))e=i===r.length-1?void 0:null;else e=e[o];if(e===void 0||e===null){if(i!==r.length-1)return n;break}}return e===void 0?n:e}function F0(e,t,n){if(!Tu(e)||typeof t!=="string")return e;let r=e,i=Vy(t);for(let o=0;o<i.length;o++){let c=i[o];if(yP(e,c),o===i.length-1)e[c]=n;else if(!Tu(e[c]))e[c]=typeof i[o+1]==="number"?[]:{};e=e[c]}return r}function vP(e,t){if(!Tu(e)||typeof t!=="string")return!1;let n=Vy(t);for(let r=0;r<n.length;r++){let i=n[r];if(yP(e,i),r===n.length-1)return delete e[i],!0;if(e=e[i],!Tu(e))return!1}}function EP(e,t){if(!Tu(e)||typeof t!=="string")return!1;let n=Vy(t);if(n.length===0)return!1;for(let r of n){if(!Tu(e)||!(r in e)||q0(e,r))return!1;e=e[r]}return!0}import er from"node:path";import IP from"node:os";import L0 from"node:process";var tl=IP.homedir(),U0=IP.tmpdir(),{env:fp}=L0,Bre=(e)=>{let t=er.join(tl,"Library");return{data:er.join(t,"Application Support",e),config:er.join(t,"Preferences",e),cache:er.join(t,"Caches",e),log:er.join(t,"Logs",e),temp:er.join(U0,e)}},kre=(e)=>{let t=fp.APPDATA||er.join(tl,"AppData","Roaming"),n=fp.LOCALAPPDATA||er.join(tl,"AppData","Local");return{data:er.join(n,e,"Data"),config:er.join(t,e,"Config"),cache:er.join(n,e,"Cache"),log:er.join(n,e,"Log"),temp:er.join(U0,e)}},Rre=(e)=>{let t=er.basename(tl);return{data:er.join(fp.XDG_DATA_HOME||er.join(tl,".local","share"),e),config:er.join(fp.XDG_CONFIG_HOME||er.join(tl,".config"),e),cache:er.join(fp.XDG_CACHE_HOME||er.join(tl,".cache"),e),log:er.join(fp.XDG_STATE_HOME||er.join(tl,".local","state"),e),temp:er.join(U0,t,e)}};function M0(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(L0.platform==="darwin")return Bre(e);if(L0.platform==="win32")return kre(e);return Rre(e)}import Fre from"node:path";import an from"node:fs";import{promisify as Bi}from"node:util";var Tre=(e,t)=>{let{onError:n}=t;return function(...i){return e.apply(void 0,i).catch(n)}},ha=Tre;var Ore=(e,t)=>{let{onError:n}=t;return function(...i){try{return e.apply(void 0,i)}catch(o){return n(o)}}},ks=Ore;var CP=250;var Nre=(e,t)=>{let{isRetriable:n}=t;return function(i){let{timeout:o}=i,c=i.interval??CP,l=Date.now()+o;return function d(...m){return e.apply(void 0,m).catch((A)=>{if(!n(A))throw A;if(Date.now()>=l)throw A;let y=Math.round(c*Math.random());if(y>0)return new Promise((v)=>setTimeout(v,y)).then(()=>d.apply(void 0,m));else return d.apply(void 0,m)})}}},ya=Nre;var $re=(e,t)=>{let{isRetriable:n}=t;return function(i){let{timeout:o}=i,c=Date.now()+o;return function(...d){while(!0)try{return e.apply(void 0,d)}catch(m){if(!n(m))throw m;if(Date.now()>=c)throw m;continue}}}},ba=$re;import SP from"node:process";var Yf={isChangeErrorOk:(e)=>{if(!Yf.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!wP&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!Yf.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!Yf.isNodeError(e))throw e;if(Yf.isChangeErrorOk(e))return;throw e}},j0=Yf;var Zf={onError:j0.onChangeError},ao={onError:()=>{return}},wP=SP.getuid?!SP.getuid():!1,Ii={isRetriable:j0.isRetriableError};var Pre={attempt:{chmod:ha(Bi(an.chmod),Zf),chown:ha(Bi(an.chown),Zf),close:ha(Bi(an.close),ao),fsync:ha(Bi(an.fsync),ao),mkdir:ha(Bi(an.mkdir),ao),realpath:ha(Bi(an.realpath),ao),stat:ha(Bi(an.stat),ao),unlink:ha(Bi(an.unlink),ao),chmodSync:ks(an.chmodSync,Zf),chownSync:ks(an.chownSync,Zf),closeSync:ks(an.closeSync,ao),existsSync:ks(an.existsSync,ao),fsyncSync:ks(an.fsync,ao),mkdirSync:ks(an.mkdirSync,ao),realpathSync:ks(an.realpathSync,ao),statSync:ks(an.statSync,ao),unlinkSync:ks(an.unlinkSync,ao)},retry:{close:ya(Bi(an.close),Ii),fsync:ya(Bi(an.fsync),Ii),open:ya(Bi(an.open),Ii),readFile:ya(Bi(an.readFile),Ii),rename:ya(Bi(an.rename),Ii),stat:ya(Bi(an.stat),Ii),write:ya(Bi(an.write),Ii),writeFile:ya(Bi(an.writeFile),Ii),closeSync:ba(an.closeSync,Ii),fsyncSync:ba(an.fsyncSync,Ii),openSync:ba(an.openSync,Ii),readFileSync:ba(an.readFileSync,Ii),renameSync:ba(an.renameSync,Ii),statSync:ba(an.statSync,Ii),writeSync:ba(an.writeSync,Ii),writeFileSync:ba(an.writeFileSync,Ii)}},oi=Pre;import Ou from"node:process";var DP="utf8",z0=438,_P=511;var xP={},BP=Ou.geteuid?Ou.geteuid():-1,kP=Ou.getegid?Ou.getegid():-1;var RP=1000,TP=!!Ou.getuid,wze=Ou.getuid?!Ou.getuid():!1,G0=128;var OP=(e)=>e instanceof Error&&("code"in e);var H0=(e)=>typeof e==="string",Wy=(e)=>e===void 0;import qre from"node:path";import gp from"node:process";import NP from"node:process";var $P=NP.platform==="linux",Yy=NP.platform==="win32";var J0=["SIGHUP","SIGINT","SIGTERM"];if(!Yy)J0.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if($P)J0.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var PP=J0;class QP{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(Yy&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))gp.kill(gp.pid,"SIGTERM");else gp.kill(gp.pid,e)},this.hook=()=>{gp.once("exit",()=>this.exit());for(let e of PP)try{gp.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var qP=new QP;var Qre=qP.register,FP=Qre;var Oo={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",i=`.tmp-${n}${t}`;return`${e}${i}`},get:(e,t,n=!0)=>{let r=Oo.truncate(t(e));if(r in Oo.store)return Oo.get(e,t,n);return Oo.store[r]=n,[r,()=>delete Oo.store[r]]},purge:(e)=>{if(!Oo.store[e])return;delete Oo.store[e],oi.attempt.unlink(e)},purgeSync:(e)=>{if(!Oo.store[e])return;delete Oo.store[e],oi.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in Oo.store)Oo.purgeSync(e)},truncate:(e)=>{let t=qre.basename(e);if(t.length<=G0)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-G0;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};FP(Oo.purgeSyncAll);var Xf=Oo;function K0(e,t,n=xP){if(H0(n))return K0(e,t,{encoding:n});let i={timeout:n.timeout??RP},o=null,c=null,l=null;try{let d=oi.attempt.realpathSync(e),m=!!d;e=d||e,[c,o]=Xf.get(e,n.tmpCreate||Xf.create,n.tmpPurge!==!1);let A=TP&&Wy(n.chown),y=Wy(n.mode);if(m&&(A||y)){let b=oi.attempt.statSync(e);if(b){if(n={...n},A)n.chown={uid:b.uid,gid:b.gid};if(y)n.mode=b.mode}}if(!m){let b=Fre.dirname(e);oi.attempt.mkdirSync(b,{mode:_P,recursive:!0})}if(l=oi.retry.openSync(i)(c,"w",n.mode||z0),n.tmpCreated)n.tmpCreated(c);if(H0(t))oi.retry.writeSync(i)(l,t,0,n.encoding||DP);else if(!Wy(t))oi.retry.writeSync(i)(l,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)oi.retry.fsyncSync(i)(l);else oi.attempt.fsync(l);if(oi.retry.closeSync(i)(l),l=null,n.chown&&(n.chown.uid!==BP||n.chown.gid!==kP))oi.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==z0)oi.attempt.chmodSync(c,n.mode);try{oi.retry.renameSync(i)(c,e)}catch(b){if(!OP(b))throw b;if(b.code!=="ENAMETOOLONG")throw b;oi.retry.renameSync(i)(c,Xf.truncate(e))}o(),c=null}finally{if(l)oi.attempt.closeSync(l);if(c)Xf.purge(c)}}var mj=Et(WL(),1),fj=Et(yU(),1);var Ope=(e,t,n,r)=>{if(n==="length"||n==="prototype")return;if(n==="arguments"||n==="caller")return;let i=Object.getOwnPropertyDescriptor(e,n),o=Object.getOwnPropertyDescriptor(t,n);if(!Npe(i,o)&&r)return;Object.defineProperty(e,n,o)},Npe=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},$pe=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Ppe=(e,t)=>`/* Wrapped ${e}*/
|
|
333
333
|
${t}`,Qpe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),qpe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Fpe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,i=Ppe.bind(null,r,t.toString());Object.defineProperty(i,"name",qpe);let{writable:o,enumerable:c,configurable:l}=Qpe;Object.defineProperty(e,"toString",{value:i,writable:o,enumerable:c,configurable:l})};function WD(e,t,{ignoreNonConfigurable:n=!1}={}){let{name:r}=e;for(let i of Reflect.ownKeys(t))Ope(e,t,i,n);return $pe(e,t),Fpe(e,t,r),e}var Lpe=(e,t={})=>{if(typeof e!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:n=0,maxWait:r=Number.POSITIVE_INFINITY,before:i=!1,after:o=!0}=t;if(n<0||r<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!i&&!o)throw Error("Both `before` and `after` are false, function wouldn't be called.");let c,l,d,m=function(...A){let y=this,b=()=>{if(c=void 0,l)clearTimeout(l),l=void 0;if(o)d=e.apply(y,A)},v=()=>{if(l=void 0,c)clearTimeout(c),c=void 0;if(o)d=e.apply(y,A)},k=i&&!c;if(clearTimeout(c),c=setTimeout(b,n),r>0&&r!==Number.POSITIVE_INFINITY&&!l)l=setTimeout(v,r);if(k)d=e.apply(y,A);return d};return WD(m,e),m.cancel=()=>{if(c)clearTimeout(c),c=void 0;if(l)clearTimeout(l),l=void 0},m},YD=Lpe;var Lu=Et(sj(),1);var Oge=Object.prototype.toString;function cj(e,t,n){if(!e)return!1;if(e.constructor===t)return!0;return Oge.call(e)===n}function lj(e){return cj(e,Uint8Array,"[object Uint8Array]")}function Nge(e){return cj(e,ArrayBuffer,"[object ArrayBuffer]")}function $ge(e){return lj(e)||Nge(e)}function Pge(e){if(!lj(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Qge(e){if(!$ge(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function d_(e,t){if(e.length===0)return new Uint8Array(0);t??=e.reduce((i,o)=>i+o.length,0);let n=new Uint8Array(t),r=0;for(let i of e)Pge(i),n.set(i,r),r+=i.length;return n}var aj={utf8:new globalThis.TextDecoder("utf8")};function p_(e,t="utf8"){return Qge(e),aj[t]??=new globalThis.TextDecoder(t),aj[t].decode(e)}function qge(e){if(typeof e!=="string")throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}var Fge=new globalThis.TextEncoder;function lv(e){return qge(e),Fge.encode(e)}var dJe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var Mge=fj.default.default,pj="aes-256-cbc",Mp=()=>Object.create(null),jge=(e)=>e!==void 0&&e!==null,zge=(e,t)=>{let n=new Set(["undefined","symbol","function"]),r=typeof t;if(n.has(r))throw TypeError(`Setting a value of type \`${r}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},uv="__internal__",m_=`${uv}.migrations.version`;class dv{path;events;#r;#t;#e;#n={};constructor(e={}){let t={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=M0(t.projectName,{suffix:t.projectSuffix}).config}if(this.#e=t,t.schema??t.ajvOptions??t.rootSchema){if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let o=new mj.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});Mge(o);let c={...t.rootSchema,type:"object",properties:t.schema};this.#r=o.compile(c);for(let[l,d]of Object.entries(t.schema??{}))if(d?.default)this.#n[l]=d.default}if(t.defaults)this.#n={...this.#n,...t.defaults};if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize;this.events=new EventTarget,this.#t=t.encryptionKey;let n=t.fileExtension?`.${t.fileExtension}`:"";this.path=dj.resolve(t.cwd,`${t.configName??"config"}${n}`);let r=this.store,i=Object.assign(Mp(),t.defaults,r);if(t.migrations){if(!t.projectVersion)throw Error("Please specify the `projectVersion` option.");this._migrate(t.migrations,t.projectVersion,t.beforeEachMigration)}this._validate(i);try{Uge.deepEqual(r,i)}catch{this.store=i}if(t.watch)this._watch()}get(e,t){if(this.#e.accessPropertiesByDotNotation)return this._get(e,t);let{store:n}=this;return e in n?n[e]:t}set(e,t){if(typeof e!=="string"&&typeof e!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=="object"&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${uv} key, as it's used to manage this module internal operations.`);let{store:n}=this,r=(i,o)=>{if(zge(i,o),this.#e.accessPropertiesByDotNotation)F0(n,i,o);else n[i]=o};if(typeof e==="object"){let i=e;for(let[o,c]of Object.entries(i))r(o,c)}else r(e,t);this.store=n}has(e){if(this.#e.accessPropertiesByDotNotation)return EP(this.store,e);return e in this.store}reset(...e){for(let t of e)if(jge(this.#n[t]))this.set(t,this.#n[t])}delete(e){let{store:t}=this;if(this.#e.accessPropertiesByDotNotation)vP(t,e);else delete t[e];this.store=t}clear(){this.store=Mp();for(let e of Object.keys(this.#n))this.reset(e)}onDidChange(e,t){if(typeof e!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleChange(()=>this.store,e)}get size(){return Object.keys(this.store).length}get store(){try{let e=Fu.readFileSync(this.path,this.#t?null:"utf8"),t=this._encryptData(e),n=this._deserialize(t);return this._validate(n),Object.assign(Mp(),n)}catch(e){if(e?.code==="ENOENT")return this._ensureDirectory(),Mp();if(this.#e.clearInvalidConfig&&e.name==="SyntaxError")return Mp();throw e}}set store(e){this._ensureDirectory(),this._validate(e),this._write(e),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))yield[e,t]}_encryptData(e){if(!this.#t)return typeof e==="string"?e:p_(e);try{let t=e.slice(0,16),n=Eg.pbkdf2Sync(this.#t,t.toString(),1e4,32,"sha512"),r=Eg.createDecipheriv(pj,n,t),i=e.slice(17),o=typeof i==="string"?lv(i):i;return p_(d_([r.update(o),r.final()]))}catch{}return e.toString()}_handleChange(e,t){let n=e(),r=()=>{let i=n,o=e();if(Lge(o,i))return;n=o,t.call(this,o,i)};return this.events.addEventListener("change",r),()=>{this.events.removeEventListener("change",r)}}_deserialize=(e)=>JSON.parse(e);_serialize=(e)=>JSON.stringify(e,void 0,"\t");_validate(e){if(!this.#r)return;if(this.#r(e)||!this.#r.errors)return;let n=this.#r.errors.map(({instancePath:r,message:i=""})=>`\`${r.slice(1)}\` ${i}`);throw Error("Config schema violation: "+n.join("; "))}_ensureDirectory(){Fu.mkdirSync(dj.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e);if(this.#t){let n=Eg.randomBytes(16),r=Eg.pbkdf2Sync(this.#t,n.toString(),1e4,32,"sha512"),i=Eg.createCipheriv(pj,r,n);t=d_([n,lv(":"),i.update(lv(t)),i.final()])}if(uj.env.SNAP)Fu.writeFileSync(this.path,t,{mode:this.#e.configFileMode});else try{K0(this.path,t,{mode:this.#e.configFileMode})}catch(n){if(n?.code==="EXDEV"){Fu.writeFileSync(this.path,t,{mode:this.#e.configFileMode});return}throw n}}_watch(){if(this._ensureDirectory(),!Fu.existsSync(this.path))this._write(Mp());if(uj.platform==="win32")Fu.watch(this.path,{persistent:!1},YD(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100}));else Fu.watchFile(this.path,{persistent:!1},YD(()=>{this.events.dispatchEvent(new Event("change"))},{wait:5000}))}_migrate(e,t,n){let r=this._get(m_,"0.0.0"),i=Object.keys(e).filter((c)=>this._shouldPerformMigration(c,r,t)),o={...this.store};for(let c of i)try{if(n)n(this,{fromVersion:r,toVersion:c,finalVersion:t,versions:i});let l=e[c];l?.(this),this._set(m_,c),r=c,o={...this.store}}catch(l){throw this.store=o,Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${l}`)}if(this._isVersionInRangeFormat(r)||!Lu.default.eq(r,t))this._set(m_,t)}_containsReservedKey(e){if(typeof e==="object"){if(Object.keys(e)[0]===uv)return!0}if(typeof e!=="string")return!1;if(this.#e.accessPropertiesByDotNotation){if(e.startsWith(`${uv}.`))return!0;return!1}return!1}_isVersionInRangeFormat(e){return Lu.default.clean(e)===null}_shouldPerformMigration(e,t,n){if(this._isVersionInRangeFormat(e)){if(t!=="0.0.0"&&Lu.default.satisfies(t,e))return!1;return Lu.default.satisfies(n,e)}if(Lu.default.lte(e,t))return!1;if(Lu.default.gt(e,n))return!1;return!0}_get(e,t){return bP(this.store,e,t)}_set(e,t){let{store:n}=this;F0(n,e,t),this.store=n}}var f_="com.sequenzy.cli",g_="api-key",A_=typeof globalThis.Bun<"u",Il=new dv({projectName:"sequenzy",schema:{userId:{type:"string"},userEmail:{type:"string"},_apiKey:{type:"string"}}});async function h_(){let e=process.env.SEQUENZY_API_KEY;if(e)return e;if(A_)try{let t=await globalThis.Bun.secrets.get({service:f_,name:g_});if(t)return t}catch{}return Il.get("_apiKey")}async function gj(e){if(A_)try{await globalThis.Bun.secrets.set({service:f_,name:g_,value:e,allowUnrestrictedAccess:!1});return}catch{}Il.set("_apiKey",e)}async function Aj(){if(A_)try{await globalThis.Bun.secrets.delete({service:f_,name:g_})}catch{}Il.delete("_apiKey")}async function j(){return!!await h_()}function pv(){return{userId:Il.get("userId"),userEmail:Il.get("userEmail")}}function hj(e){if(e.userId!==void 0)Il.set("userId",e.userId);if(e.userEmail!==void 0)Il.set("userEmail",e.userEmail)}function yj(){Il.clear()}function mv(e,t=Date.now()){if(!e?.trim())return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);if(!Number.isFinite(r)||new Date(r).toUTCString().slice(5)!==n.slice(5))return;return Math.max(0,Math.ceil((r-t)/1000))}function bj(e,t,n){if(e&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e))return e;switch(t){case 0:return"NETWORK_ERROR";case 400:case 422:return"VALIDATION_ERROR";case 401:return"UNAUTHORIZED";case 403:return"FORBIDDEN";case 404:return"NOT_FOUND";case 409:return"CONFLICT";case 429:return"RATE_LIMITED";default:return t!==void 0?t>=500?"SERVER_ERROR":"HTTP_ERROR":n}}var vj=!1;function y_(e){vj=e}function jp(){return vj}var Gge=new Set([502,503,504]),Hge=[250,1000,2000],Jge=5000,Kge=(e)=>new Promise((t)=>setTimeout(t,e));async function Ej(e,t,{delaysMs:n=Hge,sleep:r=Kge}={}){let i=e==="GET"?n.length:0;for(let o=0;o<i;o+=1){let c=n[o]??0,l;try{l=await t()}catch{await r(c);continue}if(!Gge.has(l.status))return l;let d=(mv(l.headers.get("Retry-After"))??0)*1000;if(d>Jge)return l;await l.body?.cancel().catch(()=>{return}),await r(Math.max(c,d))}return t()}var Vge=process.env.SEQUENZY_API_URL??"https://api.sequenzy.com";class g extends Error{statusCode;rawDetails;code;retryAfterSeconds;constructor(e,t,n,r,i){super(e);this.statusCode=t;this.rawDetails=n;this.code=r;this.retryAfterSeconds=i;this.name="ApiError"}}function Wge(e,t){if(typeof e!=="string")return;if(typeof t!=="string"||t==="root")return e;let n=t.slice(1).replaceAll("/",".");return e.includes(`'${n}'`)?e:`${n}: ${e}`}function Yge(e){if(!e.trim())return{message:"Request failed"};try{let t=JSON.parse(e);if(typeof t==="string")return{message:t};if(!t||typeof t!=="object"||Array.isArray(t))return{message:"Request failed"};let n=t,r=n.error&&typeof n.error==="object"?n.error:void 0,i=r?.code??n.code,o=n.type==="validation"?Wge(n.summary,n.property):void 0,c=typeof n.error==="string"?n.error:typeof o==="string"?o:r?.message??n.message;return{message:typeof c==="string"?c:"Request failed",...typeof i==="string"?{code:i}:{}}}catch{return{message:e}}}var Ij=!1;function Zge(e,t){if(t||Ij)return;if(e.headers.get("x-sequenzy-company-defaulted")!=="true")return;let n=e.headers.get("x-sequenzy-company-id");if(!n||jp())return;Ij=!0,console.error(`Note: no --company was given, so this account API key used its default company ${n}. Pass --company <id> to choose one (sequenzy companies list shows the options).`)}async function E(e,t,n,r,i){let o=await h_();if(!o)throw new g("Not logged in. Run `sequenzy login` first.",401);let c={"Content-Type":"application/json",Authorization:`Bearer ${o}`,"x-sequenzy-client":`cli/${Ky.version}`};if(r)c["x-company-id"]=r;Object.assign(c,i);let l;try{l=await Ej(e,()=>fetch(`${Vge}${t}`,{method:e,headers:c,body:n?JSON.stringify(n):void 0}))}catch(d){throw new g(d instanceof Error?d.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(Zge(l,r),!l.ok){let d=await l.text(),m=Yge(d);throw new g(m.message,l.status,d,m.code,mv(l.headers.get("Retry-After")))}return l.json()}var v_="https://docs.sequenzy.com",pc=`${v_}/concepts/cli`,b_=`${v_}/authentication`,Cj="https://sequenzy.com/dashboard";function wj(e){if(e instanceof g)return{message:e.message,statusCode:e.statusCode,code:e.code,rawDetails:e.rawDetails};if(e instanceof Error)return{message:e.message};return{message:String(e)}}function Xge(e){let t=e.match(/api key is missing required scopes?:\s*(.+)$/i);if(!t?.[1])return[];return[...new Set(t[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function Sj(e){let t=wj(e),n=t.message.trim()||"Unknown error",r=n.toLowerCase(),i=t.rawDetails?.trim()||n;if(t.code==="CLI_AUTH_REQUIRED"||r.includes("not logged in"))return{title:"Authentication required",description:"This command needs a Sequenzy API key, but the CLI could not find one in your local login state or environment.",howToFix:"Run `sequenzy login` and approve the session, or set `SEQUENZY_API_KEY` for non-interactive environments.",docsUrl:pc,details:i};if(r.includes("already logged in"))return{title:"CLI already authenticated",description:"The CLI already has a saved Sequenzy login for this machine.",howToFix:"Run `sequenzy logout` first if you want to switch accounts, then run `sequenzy login` again.",docsUrl:pc,details:i};if(t.statusCode===401||t.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The request reached Sequenzy, but the current API key was rejected.",howToFix:"Run `sequenzy login` again, or replace the key with a valid personal API key that still has access to your account.",docsUrl:b_,details:i};if(t.code==="COMPANY_CREATE_REQUIRES_PERSONAL_KEY")return{title:"Personal account key required",description:"Company creation is account-level and cannot be performed with a company/workspace-scoped API key.",howToFix:"Create or use a personal account key beginning with `seq_user_` from Account → API Keys, replace `SEQUENZY_API_KEY`, and retry the same command; alternatively, create the company in the Sequenzy dashboard. Widening the current company key or switching companies will not fix this restriction.",docsUrl:b_,details:i};let o=Xge(n);if(o.length>0){let c=o.map((m)=>`\`${m}\``).join(", "),l=o.every((m)=>m.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",d=o.includes("api_keys:manage")?` This command manages API keys, so the missing scope cannot be granted through the API by the key that is missing it. If the active key has \`account:read\`, run \`sequenzy api-keys handoff\` (add \`--replaces current\` when rotating) to get a dashboard link that opens the create-key form prefilled, then give it to the workspace owner. It creates nothing and never prints a key. If handoff is also denied because \`account:read\` is missing, open ${Cj} directly and choose the matching API Keys page.`:"";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${o.length===1?"scope":"scopes"}: ${c}.`,howToFix:`Permissions can be widened on the key you are already using - no new key and no re-login. Run \`sequenzy account\` to see the active key, its type, and its API Keys settings URL, then have the key owner enable ${c} there. Personal keys open Account → API Keys; company keys open workspace Settings → API Keys. If account metadata is unavailable, open ${Cj} directly and choose the matching API Keys page. When the active key type is \`company\` and it holds \`api_keys:manage\`, run \`sequenzy api-keys list --json\` and then \`sequenzy api-keys update <api-key-id> --scopes\` with the current scopes plus ${c}, or \`--preset\` covering all of them (${l}). Personal keys cannot be changed through \`sequenzy api-keys update\`. Both options replace the whole selection rather than merging. Retry the same command once the key is updated. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\` also works but is not required.${d}`,docsUrl:pc,details:i}}if(t.statusCode===403||r.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to perform this action or access the requested company.",howToFix:"Use an API key with access to the target company, or switch to a company you can access before retrying.",docsUrl:b_,details:i};if(t.statusCode===404||r.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the company, template, campaign, sequence, or subscriber you asked for.",howToFix:"Double-check the ID or email value and list the resource first before retrying the command.",docsUrl:pc,details:i};if(t.statusCode===429||r.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this request because too many requests were sent in a short period.",howToFix:"Wait a moment and retry. If an agent is looping, reduce the retry frequency before calling the CLI again.",docsUrl:pc,details:i};if(t.code==="AB_TEST_VARIANT_CONTENT_EDIT"||r.includes("update_ab_test_variant")&&(r.includes("a/b test")||r.includes("ab test")))return{title:"A/B variant copy cannot be edited here",description:n,howToFix:"Use `sequenzy ab-tests update-variant` with the `abTestId` and `variantId` from `sequenzy sequences get` or `sequenzy ab-tests get`. Repeat once per variant for a whole-step rewrite. If the sequence is live or the test has activity, pass `--confirm-live-change`. Do not retry with `sequenzy templates update` or `sequenzy sequences update-node`.",docsUrl:`${v_}/concepts/cli#editing-the-copy-of-a-sequence-ab-step`,details:i};if(r.includes("--subject")||r.includes("--template")||r.includes("is required"))return{title:"Invalid command input",description:"The CLI command arguments are incomplete or incompatible for this action.",howToFix:"Review the flags you passed, add the missing values, and run the command again.",docsUrl:pc,details:i};if(t.code==="NETWORK_ERROR"||r.includes("fetch failed")||r.includes("failed to initiate login"))return{title:"Network or configuration error",description:"The CLI could not reach the Sequenzy API or app URL from this environment.",howToFix:"Check your network connection and verify `SEQUENZY_API_URL` or `SEQUENZY_APP_URL` if you override them locally.",docsUrl:pc,details:i};if(t.statusCode&&t.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If the error persists, keep the details below and check the docs before escalating.",docsUrl:pc,details:i};return{title:"Command failed",description:"The CLI could not complete the requested operation.",howToFix:"Review the details below, adjust the command or credentials, and retry.",docsUrl:pc,details:i}}function z(){return new g("Not logged in. Run `sequenzy login` first.",401,void 0,"CLI_AUTH_REQUIRED")}function Ig(e){let t=Sj(e);return[`Sequenzy CLI error: ${t.title}`,`Description: ${t.description}`,`How to fix: ${t.howToFix}`,`Docs: ${t.docsUrl}`,`Details: ${t.details}`].join(`
|
|
334
334
|
`)}function eAe(e){let t=wj(e),n=Sj(e),r=(t.rawDetails===t.message?n.description:t.message.trim())||n.description;return{success:!1,error:{code:bj(t.code,t.statusCode,"CLI_ERROR"),message:r.replace(/\bBearer\s+[^\s]+/gi,"Bearer [redacted]").replace(/\bseq_(?:user_)?[A-Za-z0-9_-]{8,}\b/g,"[redacted key]"),...t.statusCode!==void 0?{statusCode:t.statusCode}:{},howToFix:n.howToFix,docsUrl:n.docsUrl,...e instanceof g&&e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}}}}function T(e,t={}){console.error(t.json??jp()?JSON.stringify(eAe(e)):Ig(e))}import{readFileSync as tAe}from"node:fs";import{isatty as Dj}from"node:tty";var Cl;function _j(){Cl=void 0}function E_(e){if(new Set(e).size>1)throw new g("Only one text input may read stdin (-) per command. Use regular files for the other inputs.",400,void 0,"CLI_INVALID_INPUT")}async function xj(){if(Dj(0))throw new g("Pipe text into stdin when using a text file '-'.",400,void 0,"CLI_INVALID_INPUT");try{process.stdin.setEncoding("utf8");let e="";for await(let t of process.stdin)e+=String(t);Cl={text:e}}catch(e){throw new g(`Failed to read stdin: ${e instanceof Error?e.message:"Unknown error"}`,400,void 0,"CLI_INPUT_READ_FAILED")}}function Bj(e,t){if(e==="-"){if(Cl){if(Cl.field)E_([Cl.field,t]);return Cl.field=t,Cl.text}if(Dj(0))throw new g(`Pipe text into stdin when using ${t} file '-'.`,400,void 0,"CLI_INVALID_INPUT")}try{let n=tAe(e==="-"?0:e,"utf8");if(e==="-")Cl={field:t,text:n};return n}catch(n){throw new g(`Failed to read ${t} file '${e}': ${n instanceof Error?n.message:"Unknown error"}`,400,void 0,"CLI_INPUT_READ_FAILED")}}function fv(e){return e.optsWithGlobals().json===!0||e.commands.some(fv)}async function nAe(e){y_(e.optsWithGlobals().json===!0),_j();let t=Object.entries(e.optsWithGlobals()).filter(([n,r])=>r==="-"&&n.endsWith("File")||n==="audienceJson"&&r==="@-").map(([n])=>n);if(e.parent?.name()==="subscribers"&&["import","events-import"].includes(e.name())&&e.args[0]==="-")t.push("subscriber import");if(E_(t),t.length>0)await xj()}function kj(e){let t=e.configureOutput().writeErr;e.configureOutput({writeErr:(n)=>{if(!fv(e))t?.(n)}}),e.exitOverride(),e.hook("preAction",(n,r)=>nAe(r))}async function Rj(e,t){y_(!1);try{await e.parseAsync(t)}catch(n){if(n instanceof AP){if(n.exitCode===0)return;if(fv(e))T(new g(n.message,400,void 0,"CLI_INVALID_INPUT"),{json:!0});process.exitCode=n.exitCode;return}T(n,{json:fv(e)}),process.exitCode=1}}var gv="Variant copy is edited with `sequenzy ab-tests update-variant`, not with `sequenzy sequences update-node`.";var Tj;function de(e,t,n){function r(l,d){if(!l._zod)Object.defineProperty(l,"_zod",{value:{def:d,constr:c,traits:new Set},enumerable:!1});if(l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,d);let m=c.prototype,A=Object.keys(m);for(let y=0;y<A.length;y++){let b=A[y];if(!(b in l))l[b]=m[b].bind(l)}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function c(l){var d;let m=n?.Parent?new o:this;r(m,l),(d=m._zod).deferred??(d.deferred=[]);for(let A of m._zod.deferred)A();return m}return Object.defineProperty(c,"init",{value:r}),Object.defineProperty(c,Symbol.hasInstance,{value:(l)=>{if(n?.Parent&&l instanceof n.Parent)return!0;return l?._zod?.traits?.has(e)}}),Object.defineProperty(c,"name",{value:e}),c}var ZJe=Symbol("zod_brand");class mc extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Cg extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Tj=globalThis).__zod_globalConfig??(Tj.__zod_globalConfig={});var zp=globalThis.__zod_globalConfig;function fc(e){if(e)Object.assign(zp,e);return zp}function hv(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Sg(e,t){if(typeof t==="bigint")return t.toString();return t}function yv(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function bv(e){return e===null||e===void 0}function vv(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var Oj=Symbol("evaluating");function Cn(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===Oj)return;if(r===void 0)r=Oj,r=n();return r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Uu(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function wl(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function C_(e){return JSON.stringify(e)}function Nj(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var w_="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function wg(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var $j=yv(()=>{if(zp.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Gp(e){if(wg(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(wg(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function S_(e){if(Gp(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Pj=new Set(["string","number","symbol"]);function Sl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Na(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function It(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Qj(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var rAe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function iAe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o=wl(e._zod.def,{get shape(){let c={};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;c[l]=n.shape[l]}return Uu(this,"shape",c),c},checks:[]});return Na(e,o)}function oAe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=wl(e._zod.def,{get shape(){let c={...e._zod.def.shape};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;delete c[l]}return Uu(this,"shape",c),c},checks:[]});return Na(e,o)}function sAe(e,t){if(!Gp(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let c in t)if(Object.getOwnPropertyDescriptor(o,c)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=wl(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Uu(this,"shape",o),o}});return Na(e,i)}function aAe(e,t){if(!Gp(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=wl(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return Uu(this,"shape",r),r}});return Na(e,n)}function cAe(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=wl(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Uu(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Na(e,n)}function lAe(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let c=wl(t._zod.def,{get shape(){let l=t._zod.def.shape,d={...l};if(n)for(let m in n){if(!(m in l))throw Error(`Unrecognized key: "${m}"`);if(!n[m])continue;d[m]=e?new e({type:"optional",innerType:l[m]}):l[m]}else for(let m in l)d[m]=e?new e({type:"optional",innerType:l[m]}):l[m];return Uu(this,"shape",d),d},checks:[]});return Na(t,c)}function uAe(e,t,n){let r=wl(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let c in n){if(!(c in o))throw Error(`Unrecognized key: "${c}"`);if(!n[c])continue;o[c]=new e({type:"nonoptional",innerType:i[c]})}else for(let c in i)o[c]=new e({type:"nonoptional",innerType:i[c]});return Uu(this,"shape",o),o}});return Na(t,r)}function Mu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qj(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ev(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Av(e){return typeof e==="string"?e:e?.message}function gc(e,t,n){let r=e.message?e.message:Av(e.inst?._zod.def?.error?.(e))??Av(t?.error?.(e))??Av(n.customError?.(e))??Av(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:c,...l}=e;if(l.path??(l.path=[]),l.message=r,t?.reportInput)l.input=c;return l}function Iv(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ju(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var Fj=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Sg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cv=de("$ZodError",Fj),D_=de("$ZodError",Fj,{Parent:Error});function Lj(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Uj(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((l)=>r({issues:l},[...o,...c.path]));else if(c.code==="invalid_key")r({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")r({issues:c.issues},[...o,...c.path]);else{let l=[...o,...c.path];if(l.length===0)n._errors.push(t(c));else{let d=n,m=0;while(m<l.length){let A=l[m];if(m!==l.length-1)d[A]=d[A]||{_errors:[]};else d[A]=d[A]||{_errors:[]},d[A]._errors.push(t(c));d=d[A],m++}}}};return r(e),n}var wv=(e)=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise)throw new mc;if(c.issues.length){let l=new(i?.Err??e)(c.issues.map((d)=>gc(d,o,fc())));throw w_(l,i?.callee),l}return c.value};var Sv=(e)=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise)c=await c;if(c.issues.length){let l=new(i?.Err??e)(c.issues.map((d)=>gc(d,o,fc())));throw w_(l,i?.callee),l}return c.value};var Dg=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new mc;return o.issues.length?{success:!1,error:new(e??Cv)(o.issues.map((c)=>gc(c,i,fc())))}:{success:!0,data:o.value}},Mj=Dg(D_),_g=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((c)=>gc(c,i,fc())))}:{success:!0,data:o.value}},jj=_g(D_),zj=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return wv(e)(t,n,i)};var Gj=(e)=>(t,n,r)=>wv(e)(t,n,r);var Hj=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Sv(e)(t,n,i)};var Jj=(e)=>async(t,n,r)=>Sv(e)(t,n,r);var Kj=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Dg(e)(t,n,i)};var Vj=(e)=>(t,n,r)=>Dg(e)(t,n,r);var Wj=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return _g(e)(t,n,i)};var Yj=(e)=>async(t,n,r)=>_g(e)(t,n,r);var Zj=/^[cC][0-9a-z]{6,}$/,Xj=/^[0-9a-z]+$/,ez=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tz=/^[0-9a-vA-V]{20}$/,nz=/^[A-Za-z0-9]{27}$/,rz=/^[a-zA-Z0-9_-]{21}$/,iz=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oz=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,__=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var sz=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var pAe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function az(){return new RegExp(pAe,"u")}var cz=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lz=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var uz=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,dz=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pz=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,x_=/^[A-Za-z0-9_-]*$/;var mz=/^https?$/,fz=/^\+[1-9]\d{6,14}$/,gz="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Az=new RegExp(`^${gz}$`);function hz(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function yz(e){return new RegExp(`^${hz(e)}$`)}function bz(e){let t=hz({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gz}T(?:${r})$`)}var vz=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ez=/^[^A-Z]*$/,Iz=/^[^a-z]*$/;var No=de("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var Cz=de("$ZodCheckMaxLength",(e,t)=>{var n;No.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!bv(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)r._zod.bag.maximum=t.maximum}),e._zod.check=(r)=>{let i=r.value;if(i.length<=t.maximum)return;let c=Iv(i);r.issues.push({origin:c,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wz=de("$ZodCheckMinLength",(e,t)=>{var n;No.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!bv(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)r._zod.bag.minimum=t.minimum}),e._zod.check=(r)=>{let i=r.value;if(i.length>=t.minimum)return;let c=Iv(i);r.issues.push({origin:c,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Sz=de("$ZodCheckLengthEquals",(e,t)=>{var n;No.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!bv(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(r)=>{let i=r.value,o=i.length;if(o===t.length)return;let c=Iv(i),l=o>t.length;r.issues.push({origin:c,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),xg=de("$ZodCheckStringFormat",(e,t)=>{var n,r;if(No.init(e,t),e._zod.onattach.push((i)=>{let o=i._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),Dz=de("$ZodCheckRegex",(e,t)=>{xg.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_z=de("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ez),xg.init(e,t)}),xz=de("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Iz),xg.init(e,t)}),Bz=de("$ZodCheckIncludes",(e,t)=>{No.init(e,t);let n=Sl(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((i)=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),kz=de("$ZodCheckStartsWith",(e,t)=>{No.init(e,t);let n=new RegExp(`^${Sl(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Rz=de("$ZodCheckEndsWith",(e,t)=>{No.init(e,t);let n=new RegExp(`.*${Sl(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var Tz=de("$ZodCheckOverwrite",(e,t)=>{No.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class B_{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
335
335
|
`).filter((o)=>o),r=Math.min(...n.map((o)=>o.length-o.trimStart().length)),i=n.map((o)=>o.slice(r)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,t=this?.args,r=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,r.join(`
|
|
@@ -503,7 +503,7 @@ steps:
|
|
|
503
503
|
`,"utf8"),console.log(`Exported ${n.enrollments.length} enrollments to ${t.csv}`);else console.log(o);return}if(t.json){w(n);return}let{pagination:r}=n;console.log(`Enrollments in ${n.sequenceName} (${r.count} of ${r.total}, statuses: ${n.statuses.join(", ")})`);let i=n.stopCondition;if(i&&i.type!=="none"){if(console.log(`Stop condition: ${i.type}${i.value?` = ${i.value}`:""}`),i.matchConfig)console.log(` match config: ${JSON.stringify(i.matchConfig)}`)}if(n.enrollments.length===0){console.log("No enrollments matched the filters.");return}for(let o of n.enrollments){console.log(""),console.log(`- ${o.email??o.subscriberId}${mPe(o)} [${o.status}]`),console.log(` at ${k9(o)}`),console.log(` enrolled ${te(o.enrollmentStartedAt)}${o.waitUntil?`, resumes ${te(o.waitUntil)}`:""}`);let c=o.enteredVia?.description;if(c&&o.enteredVia?.kind!=="unknown")console.log(` entered via ${c}`);let l=o.entryContext;if(l?.eventName){let m=l.eventPropertyKeys.length>0?` keys ${l.eventPropertyKeys.join(", ")}`:"";console.log(` entry event ${l.eventName}${m}`)}else if(l?.triggerType)console.log(` entry trigger ${l.triggerType}`);let d=o.branchDecisions?.at(-1);if(d){let m=vR(d);console.log(` branch ${d.selectedPath}${m?`: ${m}`:""}`)}if(o.branchDecisionsTruncated)console.log(` branch history truncated: showing ${o.branchDecisions?.length??0} of ${o.branchDecisionCount??"unknown"}`);if(o.failedReason)console.log(` failed: ${o.failedReason}`);if(o.stopConditionMatches===!0)console.log(` stop condition matches now: ${o.stopConditionMatchReason??"condition met"}`),console.log(" -> worker re-checks before a future step; a step already in progress may still finish");if(o.status==="paused")console.log(` paused${o.pausedAt?` since ${te(o.pausedAt)}`:""}${o.pauseReason?` (${o.pauseReason})`:""}; resume with sequenzy sequences resume-subscribers`);if(o.movedAt)console.log(` released from ${o.movedFromNodeId??"an earlier step"} on ${te(o.movedAt)}${o.moveReason?` (${o.moveReason})`:""}`);console.log(` subscriberId ${o.subscriberId}`)}if(console.log(""),t.stopConditionMatch)console.log(`Stop-condition match checked for ${n.stopConditionMatchEvaluatedCount??0} enrollment(s). A waiting enrollment whose stop condition already matches keeps reporting "waiting" until its delay expires, then is re-checked before continuing. This is a current-state snapshot; a step already in progress may still finish.`);if(r.hasMore)console.log(`More results: sequenzy sequences enrollments ${e} --offset ${r.offset+r.count}`);if(!t.all&&t.csv===void 0)console.log(`Export every match: sequenzy sequences enrollments ${e} --all --csv enrollments.csv`);console.log(`Node-level counts: sequenzy stats --sequence ${e} # enrollmentCounts.byCurrentNode`)}async function R9(e,t){if(!await j())T(z()),process.exit(1);try{await fPe(e,t)}catch(n){T(n instanceof g?n:n),process.exit(1)}}async function T9(e,t,n){if(!await j())T(z()),process.exit(1);try{let r=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){w(r);return}let i=r.enrollment;console.log(`Enrollment ${i.enrollmentId} in ${r.sequenceName} [${i.status}]`),console.log(` at ${k9(i)}`),console.log(` enrolled ${te(i.enrollmentStartedAt)}`);let o=i.enteredVia?.description;if(o)console.log(` entered via ${o}`);let c=i.entryContext;if(c?.eventName)console.log(` entry event ${c.eventName}${c.eventPropertyKeys.length>0?` keys ${c.eventPropertyKeys.join(", ")}`:""}`);if(console.log(` history from ${r.historySource}`),r.nodeHistoryTruncated)console.log(` node history truncated after ${r.nodeHistoryLimit} events`);if(i.branchDecisionsTruncated)console.log(` branch history truncated: showing ${i.branchDecisions?.length??0} of ${i.branchDecisionCount??"unknown"}`);if(r.nodeHistory.length===0)console.log(" no recorded node events");let l=new Set;for(let d of r.nodeHistory){let m=d.nodeLabel??d.nodeType??d.nodeId,A=d.branchDecision;if(A)l.add(_9(A));let y=A?vR(A):void 0,b=A?` branch ${A.selectedPath}${y?` (${y})`:""}`:"";console.log(` ${te(d.eventTime)} ${d.eventType} ${m}${b}`)}for(let d of i.branchDecisions??[]){if(l.has(_9(d)))continue;let m=vR(d);console.log(` ${te(d.decidedAt)} branch ${d.nodeId} ${d.selectedPath}${m?` (${m})`:""}`)}}catch(r){T(r instanceof g?r:r),process.exit(1)}}var O9=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function N9(e,t){if(e===void 0)return;let n=e.trim(),r=t==="--daily-limit"?0:1;if(!/^\d+$/.test(n))throw new g(`${t} must be a whole number`,400);let i=Number(n);if(!Number.isSafeInteger(i)||i<r)throw new g(`${t} must be at least ${r}`,400);return i}function $9(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function gPe(e){let t=e.fromNode?.trim();if(!t)throw new g("--from-node is required",400);if(e.sort!==void 0&&!O9.includes(e.sort))throw new g(`--sort must be one of: ${O9.join(", ")}`,400);let n=e.toNode?.trim(),r=$9(e.subscriberIds),i=$9(e.tag),o=N9(e.limit,"--limit"),c=N9(e.dailyLimit,"--daily-limit"),l=e.reason?.trim();return{fromNodeId:t,...n?{targetNodeId:n}:{},...o!==void 0&&{limit:o},...c!==void 0&&{dailyLimit:c},...e.sort!==void 0&&{sort:e.sort},...r.length>0&&{subscriberIds:r},...i.length>0&&{tags:i},...l?{reason:l}:{},dryRun:e.apply!==!0}}function APe(e){if(console.log(e.message),console.log(""),console.log(`From step ${e.fromNodeId}`),console.log(`To step ${e.targetNodeId}`),console.log(`Matched ${e.matchedCount}, moved ${e.movedCount}, remaining ${e.remainingCount} (sorted by ${e.sort})`),e.skippedCount>0)console.log(`Skipped ${e.skippedCount} enrollment(s) that are active, mid-step, or awaiting double opt-in.`);if(e.dailyLimit!==null)console.log(`Daily limit ${e.dailyLimit}: ${e.movedInWindow} already moved in the last 24h, ${e.dailyRemaining} left.`);if(e.tagResult)console.log(`Tagged ${e.tagResult.updated} contact(s) with ${e.tagResult.tags.join(", ")} (${e.tagResult.unchanged} already tagged, ${e.tagResult.failed} failed).`);if(e.enqueueErrors.length>0)console.log(`${e.enqueueErrors.length} enrollment(s) could not be queued; the stuck-enrollment sweeper will retry them.`);if(e.enrollments.length>0){console.log(""),console.log(e.dryRun?"Would move:":"Moved:");for(let t of e.enrollments)console.log(`- ${t.subscriberEmail??t.subscriberId} [${t.status}]`);if(e.hasMore)console.log(`... and more (showing the first ${e.enrollments.length})`)}if(console.log(""),e.dryRun)console.log("Re-run with --apply to move them.");else if(e.remainingCount>0)console.log("Re-run the same command to release the next batch.")}async function P9(e,t){if(!await j())T(z()),process.exit(1);try{let n=gPe(t),r=await E("POST",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/move`,n,t.company);if(t.json){w(r);return}APe(r)}catch(n){T(n instanceof g?n:n),process.exit(1)}}var Q9=500,hPe={paused:"paused",already_paused:"already paused",in_progress:"step running now, retry shortly",resumed:"resumed",not_paused:"was not paused"};function q9(e){return Array.from(new Set((e??[]).flatMap((t)=>t.split(",")).map((t)=>t.trim()).filter((t)=>t.length>0)))}function yPe(e,t){let n=q9(e.subscriberIds),r=q9(e.email);if(n.length===0&&r.length===0)throw new g("Provide --subscriber-ids, --email, or both",400);if(n.length+r.length>Q9)throw new g(`A maximum of ${Q9} subscriber IDs and emails combined can be targeted per command`,400);let i=e.reason?.trim();return{...n.length>0&&{subscriberIds:n},...r.length>0&&{emails:r},...t==="pause"&&i?{reason:i}:{}}}function bPe(e){if(console.log(e.message),e.enrollments.length>0){console.log("");for(let t of e.enrollments){let n=t.status==="paused"&&t.pausedAt?` since ${te(t.pausedAt)}`:t.waitUntil?`, next step ${te(t.waitUntil)}`:"";console.log(`- ${t.subscriberEmail??t.subscriberId}: ${hPe[t.outcome]??t.outcome} [${t.status}${n}] on step ${t.currentNodeId}`)}}for(let t of e.notEnrolled)console.log(`- ${t.email??t.subscriberId}: not enrolled in this sequence`);for(let t of e.notFound.subscriberIds)console.log(`- ${t}: subscriber not found`);for(let t of e.notFound.emails)console.log(`- ${t}: subscriber not found`)}async function F9(e,t,n){if(!await j())T(z()),process.exit(1);try{let r=yPe(n,e),i=await E("POST",`/api/v1/sequences/${encodeURIComponent(t)}/enrollments/${e}`,r,n.company);if(n.json){w(i);return}bPe(i)}catch(r){T(r),process.exit(1)}}function L9(e,t){return F9("pause",e,t)}function U9(e,t){return F9("resume",e,t)}var vPe={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};function M9(e){return e.split(",").map((t)=>t.trim().toLowerCase()).filter((t)=>t.length>0)}function EPe(e){let t=M9(e).map((n)=>{let r=vPe[n];if(r!==void 0)return r;if(/^[0-6]$/.test(n))return Number(n);throw new g(`Unknown weekday "${n}". Use names like mon,fri or numbers 0 (Sunday) to 6 (Saturday).`,400)});if(t.length===0)throw new g("--weekly needs at least one weekday, e.g. mon,fri",400);return t}function IPe(e){let t=M9(e).map((n)=>{if(n==="last")return"last";if(/^\d{1,2}$/.test(n)&&Number(n)>=1&&Number(n)<=31)return Number(n);throw new g(`Unknown day of the month "${n}". Use 1 to 31 or "last".`,400)});if(t.length===0)throw new g("--monthly needs at least one day, e.g. 1,last",400);return t}function CPe(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function wPe(e){let t=[e.daily?"--daily":null,e.weekly!==void 0?"--weekly":null,e.monthly!==void 0?"--monthly":null].filter((c)=>c!==null);if(t.length!==1)throw new g(t.length===0?"Choose how often: --daily, --weekly <days> or --monthly <days>":`Use exactly one of ${t.join(" and ")}`,400);let n=e.at?.trim();if(!n)throw new g("Choose a time with --at, e.g. --at 10:00",400);let r={frequency:e.daily?"daily":e.weekly!==void 0?"weekly":"monthly",time:n,timezone:e.timezone?.trim()||CPe()};if(e.weekly!==void 0)r.weekdays=EPe(e.weekly);if(e.monthly!==void 0)r.monthDays=IPe(e.monthly);let i=e.until?.trim();if(i&&i!=="none"&&Number.isNaN(Date.parse(i)))throw new g('--until must be an ISO 8601 date-time such as 2027-06-30T23:59:00Z, or "none"',400);let o=e.enrollmentMode?.trim();if(o!==void 0&&o!=="unlimited"&&o!=="one_time")throw new g('--enrollment-mode must be "unlimited" (everyone who matches at each run) or "one_time" (only people who never entered)',400);return{enabled:e.disable!==!0,audience:MA(e),schedule:r,...i?{endsAt:i==="none"?null:i}:{},...o?{enrollmentMode:o}:{}}}function SPe(e){let t=e.recurringEnrollment;if(!t){console.log("No recurring schedule.");return}if(console.log(`${e.description??"Recurring schedule"}${t.enabled?"":" (switched off)"}`),console.log(`Audience: ${Om(t.audience)}`),e.enrollmentMode)console.log(`Each run enrolls: ${e.enrollmentMode==="one_time"?"only people who never entered":"everyone who matches (people still inside are skipped)"}`);if(t.endsAt)console.log(`No runs after: ${te(t.endsAt)}`);if(t.enabled&&!t.nextRunAt&&t.endsAt)console.log("Finished: no runs left before the end date.");if(e.upcomingRuns.length>0){console.log("Next runs:");for(let n of e.upcomingRuns)console.log(` ${te(n)}`)}if(t.lastRunAt)console.log(`Last run: ${te(t.lastRunAt)}${t.lastRunId?` (${t.lastRunId})`:""}`);if(t.lastSkippedAt)console.log(`Last skipped: ${te(t.lastSkippedAt)} (${t.lastSkipReason==="missed"?"could not start in time":"sequence was not accepting entrants"})`)}async function j9(e,t){if(!await j())T(z()),process.exit(1);try{let n=`/api/v1/sequences/${encodeURIComponent(e)}/recurring-enrollment`,i=!t.daily&&t.weekly===void 0&&t.monthly===void 0?await E("GET",n,void 0,t.company):await E("PUT",n,wPe(t),t.company);if(t.json){w(i);return}if(i.message)console.log(i.message);SPe(i)}catch(n){T(n instanceof g?n:n),process.exit(1)}}async function z9(e,t){if(!await j())T(z()),process.exit(1);try{let n=await E("DELETE",`/api/v1/sequences/${encodeURIComponent(e)}/recurring-enrollment`,void 0,t.company);if(t.json){w(n);return}console.log(n.message??"Recurring schedule removed.")}catch(n){T(n instanceof g?n:n),process.exit(1)}}var X9="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file; omit sequence-level --from-email and --from-name.",eZ="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file or --emails-json/--emails-file; omit sequence-level --from-email and --from-name.";function DPe(e){let t=e.contactsInSequence;if(typeof t!=="number"||t<=0)return null;return`Removed ${t.toLocaleString("en-US")} ${t===1?"contact who was":"contacts who were"} still in it. They get none of its remaining steps.`}function _Pe(e){let t=[];if((e?.migratedRecipientCount??0)>0)t.push(`Recipients moved to the next step: ${e?.migratedRecipientCount}`);if((e?.completedRecipientCount??0)>0)t.push(`Recipients completed: ${e?.completedRecipientCount}`);return t}function xPe(e){let t=e.structuralStepNumber??e.stepNumber;return t!==null?`Step ${t}`:`Node ${e.nodeId}`}function BPe(e){if(!e?.addedBranchNodeId)return[];let t=[`Branch node: ${e.addedBranchNodeId}`];for(let[n,r]of Object.entries(e.addedBranchPathNodeIds??{}))t.push(` Path ${n}: ${r.length>0?r.join(" -> "):"wired to an existing node"}`);return t}var kPe=50,G9=10,H9=10,J9=500,RPe=new Set(["unlimited","one_time","matching_field"]);function TPe(e){if(!e.id)throw new g("Sequence ID is required",400);if(!e.nodeId?.trim())throw new g("--node is required",400);let t=e.to??[];if(t.length>H9)throw new g(`--to accepts no more than ${H9} email addresses`,400);let n=Array.from(new Set(t.map((o)=>o.trim().toLowerCase()).filter(Boolean)));if(n.length===0)throw new g("--to requires at least one email address",400);let r=n.find((o)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o));if(r)throw new g(`Invalid test recipient: ${r}`,400);let i={...Ku("--attrs-json",e.attrsJson),...Og("--attr",e.attr)};return{path:`/api/v1/sequences/${encodeURIComponent(e.id)}/nodes/${encodeURIComponent(e.nodeId.trim())}/test`,body:{recipients:n,...Object.keys(i).length>0&&{customAttributes:i}}}}var OPe={all:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],everyday:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],weekdays:["monday","tuesday","wednesday","thursday","friday"],"working-days":["monday","tuesday","wednesday","thursday","friday"],weekends:["saturday","sunday"]};function K9(e){if(e===void 0)return;if(!RPe.has(e))throw new g("--enrollment-mode must be one of: unlimited, one_time, matching_field",400);return e}function NPe(e){if(e===void 0)return;if(!MH(e))throw new g(`--list-scope must be one of: ${rx.join(", ")}`,400);return e}function V9(e,t){if(e===void 0&&t===void 0)return;let n=[],r=new Set;for(let i of[t,...e??[]]){let o=i?.trim();if(!o||r.has(o))continue;r.add(o),n.push(o)}if(n.length===0)throw new g("List and tag values must not be empty",400);return n}function $Pe(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(!r)continue;let i=OPe[r];if(i){for(let o of i)if(!t.includes(o))t.push(o);continue}if(!t.includes(r))t.push(r)}if(t.length===0)throw new g("--sending-window-days must include at least one day",400);return t}function PPe(e){let t=e.sendingWindowStart!==void 0||e.sendingWindowEnd!==void 0||e.sendingWindowTimezone!==void 0||e.sendingWindowDays!==void 0;if(e.clearSendingWindow&&t)throw new g("Use either --clear-sending-window or --sending-window-* options, not both",400);if(e.clearSendingWindow)return null;if(!t)return;let n=e.sendingWindowStart?.trim(),r=e.sendingWindowEnd?.trim(),i=e.sendingWindowTimezone?.trim();if(!n||!r||!i)throw new g("--sending-window-start, --sending-window-end, and --sending-window-timezone are required together",400);let o=$Pe(e.sendingWindowDays);return{enabled:!0,timezone:i,startTime:n,endTime:r,...o!==void 0&&{days:o}}}function QPe(e){if(e.sendSpreadHours===void 0)return;let t=e.sendSpreadHours.trim(),n=Number(t);if(t===""||!Number.isFinite(n)||n<0)throw new g("--send-spread-hours must be a number of hours",400);return{spreadOverHours:n}}async function qPe(e){if(e.sendSpreadHours===void 0||e.clearKeyDates===!0||(e.keyDate??[]).length>0||e.keyDatesJson!==void 0||e.keyDatesFile!==void 0)return e;let n=(await E("GET",`/api/v1/sequences/${e.id}`,void 0,e.company)).sequence?.keyDates;if(!n||n.dates.length===0)throw new g("This sequence has no key dates; add --key-date entries to set a spread",400);return{...e,keyDatesJson:JSON.stringify({timezone:n.timezone,dates:n.dates})}}function FPe(e){let t=LPe(e),n=QPe(e);if(n===void 0)return t;if(t===null)throw new g("--send-spread-hours cannot be combined with --clear-key-dates",400);if(t===void 0)throw new g("--send-spread-hours needs key dates: add --key-date entries (or --key-dates-json)",400);return{...t,sendWindow:n}}function LPe(e){let t=(e.keyDate??[]).map((c)=>c.trim()).filter((c)=>c.length>0),n=e.keyDatesJson!==void 0||e.keyDatesFile!==void 0,r=t.length>0||n||e.keyDatesTimezone!==void 0;if(e.clearKeyDates&&r)throw new g("Use either --clear-key-dates or --key-date/--key-dates-* options, not both",400);if(e.clearKeyDates)return null;if(!r)return;if(t.length>0&&n)throw new g("Use either --key-date entries or --key-dates-json/--key-dates-file, not both",400);if(n){let c=$e(e.keyDatesJson,e.keyDatesFile,"key dates");if(c===void 0)throw new g("Key dates JSON is empty",400);let l=Array.isArray(c)?{dates:c}:c;if(!Array.isArray(l.dates))throw new g('Key dates JSON must be an array of { label, at } or an object with "dates"',400);let d=e.keyDatesTimezone?.trim()||l.timezone;return{...d?{timezone:d}:{},dates:l.dates,...l.sendWindow!==void 0&&{sendWindow:l.sendWindow}}}let i=e.keyDatesTimezone?.trim();if(!i)throw new g("--key-dates-timezone is required with --key-date, e.g. --key-dates-timezone America/New_York",400);let o=t.map((c)=>{let l=c.lastIndexOf("=");if(l<=0||l===c.length-1)throw new g(`--key-date must look like "Label=2026-11-27T00:00:00" (got "${c}")`,400);let d=c.slice(0,l).trim(),m=c.slice(l+1).trim(),A=/^([a-z0-9_]+):(.+)$/.exec(d);return A?{key:A[1],label:A[2].trim(),at:m}:{label:d,at:m}});return{timezone:i,dates:o}}function UPe(e){let t=e.autoEnrollAll===!0||(e.autoEnrollListIds?.length??0)>0||e.autoEnrollSegmentId!==void 0||e.autoEnrollJson!==void 0;if(e.clearAutoEnroll&&t)throw new g("Use either --clear-auto-enroll or --auto-enroll-* options, not both",400);if(e.clearAutoEnroll)return null;if(!t){if(e.autoEnrollStartsAt!==void 0)throw new g("--auto-enroll-starts-at needs an audience: add --auto-enroll-all, --auto-enroll-list-ids, --auto-enroll-segment-id or --auto-enroll-json",400);return}let n=e.autoEnrollStartsAt?.trim();if(n&&Number.isNaN(Date.parse(n)))throw new g("--auto-enroll-starts-at must be an ISO 8601 date-time, e.g. 2026-11-15T09:00:00Z",400);return{...n?{startsAt:new Date(n).toISOString()}:{},audience:MA({...e.autoEnrollAll?{all:!0}:{},...e.autoEnrollListIds?{listIds:e.autoEnrollListIds}:{},...e.autoEnrollSegmentId?{segmentId:e.autoEnrollSegmentId}:{},...e.autoEnrollJson?{audienceJson:e.autoEnrollJson}:{}})}}function ER(e){if(!e)return"Off";let t=Om(e.audience);if(e.enabled){let n=e.startsAt&&Date.parse(e.startsAt)>Date.now()?` · starts ${te(e.startsAt)}`:"";return`On · ${t}${n} · new joiners are enrolled until the last key date`}return`Off (${e.endedReason==="countdown_ended"?"countdown ended":"switched off"}${e.endedAt?` ${te(e.endedAt)}`:""}) · was ${t}`}function IR(e){if(!e||e.dates.length===0)return"None";let t=e.timezone?` (${e.timezone})`:"",n=e.sendWindow?.spreadOverHours,r=n===void 0?"":n===0?" · sends at the exact moment":` · each email spread over ${n}h`;return e.dates.map((i)=>`${i.label}${i.key?` [${i.key}]`:""} = ${i.at}`).join("; ")+t+r}function MPe(e){if(e.respectFrequencyCap&&e.ignoreFrequencyCap)throw new g("Use either --respect-frequency-cap or --ignore-frequency-cap, not both",400);if(e.respectFrequencyCap)return!0;if(e.ignoreFrequencyCap)return!1;return}function jPe(e){if(e.activeSubscribersOnly&&e.includeSuppressedSubscribers)throw new g("Use either --active-subscribers-only or --include-suppressed-subscribers, not both",400);if(e.activeSubscribersOnly)return!0;if(e.includeSuppressedSubscribers)return!1;return}function zPe(e){let t=e.sendToNotSubscribed;if(t===void 0)return;if(t==="on")return!0;if(t==="off")return!1;if(t==="default")return null;throw new g("--send-to-not-subscribed must be on, off or default",400)}function CR(e){return e?"subscribers and not subscribed contacts":"subscribers only"}function HI(e){return e?"Respected":"Ignored"}function JI(e){if(!e)return"Not restricted";return`${e.startTime}-${e.endTime} ${e.timezone} (${(e.days??["every day"]).join(", ")})`}function GPe(e){if(e.clearBccEmails&&e.bccEmails!==void 0)throw new g("Use either --clear-bcc-emails or --bcc-emails, not both",400);if(e.clearBccEmails)return null;if(e.bccEmails===void 0)return;let t=Array.from(new Set(e.bccEmails.split(",").map((n)=>n.trim()).filter((n)=>n.length>0)));return t.length>0?t:null}var HPe={live:"running",enrollment_paused:"new enrollments paused, existing recipients continue",paused:"recipients frozen, nobody new enters",draft:"not running",archived:"not running"};function Nm(e){let t=e.status??"Unknown",n=e.effectiveStatus===void 0?void 0:HPe[e.effectiveStatus];if(n!==void 0)return`${t} (${n})`;return e.enrollmentPaused===!0?`${t} (new enrollments paused)`:t}function W9(e){if(e.effectiveStatusSummary!==void 0)console.log(`State: ${e.effectiveStatusSummary}`)}function JPe(e){let t=[],n=e.sequenceName??e.sequenceId??"Sequence";if(t.push(`Sequence: ${n}${e.sequenceId?` [${e.sequenceId}]`:""}`),t.push(`Status: ${Nm({status:e.status,enrollmentPaused:e.enrollmentPaused,effectiveStatus:e.effectiveStatus})}`),e.effectiveStatusSummary)t.push(`State: ${e.effectiveStatusSummary}`);t.push("Sends mail: no");let r=e.readiness;if(r){t.push(`Ready to activate: ${r.ready===!0?"yes":"no"}`);for(let c of r.errors??[])t.push(` Error: ${c}`);for(let c of r.warnings??[])t.push(` Warning: ${c}`)}let i=e.enrollment;if(i){if(t.push("Enrollment"),i.triggerType)t.push(` Trigger: ${i.triggerType}`);if(i.summary)t.push(` ${i.summary}`);if(i.note)t.push(` ${i.note}`);if(i.error)t.push(` Trigger error: ${i.error}`);if(i.autoEnrollOnActivateCount!==void 0)t.push(` Auto-enroll on activate: ${i.autoEnrollOnActivateCount}`);if(typeof i.currentlyMatchingCount==="number"){let c=i.currentlyMatchingEnrollsAutomatically?"enrolled on the first hourly check":"not enrolled automatically";t.push(` Currently matching: ${i.currentlyMatchingCount} (${c})`)}else if(i.currentlyMatchingAvailable===!1)t.push(" Currently matching: unavailable (evaluated by the hourly worker)");for(let c of i.currentlyMatchingSample??[]){let l=c.email??c.id??"unknown";t.push(c.name?` - ${c.name} <${l}>`:` - ${l}`)}}let o=e.path;if(o){let c=o.subscriber?.email??o.subscriber?.id??"subscriber";if(t.push(`Path for ${c}`),o.emailsOnPath!==void 0){let l=`${o.emailsOnPath} deliverable email${o.emailsOnPath===1?"":"s"}`;if(o.emailStepsOnPath!==void 0&&o.emailStepsOnPath!==o.emailsOnPath)t.push(` ${o.emailStepsOnPath} email step${o.emailStepsOnPath===1?"":"s"} on this path; ${l}`);else t.push(` ${l} on this path`)}for(let l of o.steps??[]){let d=l.label??l.nodeType??l.nodeId??"step",m=l.outcome;if(m){let A=m.assumed?" (assumed)":"",y=m.branchId?` [${m.branchId}]`:"";t.push(` ${d}: ${m.verdict??"unknown"}${y}${A} - ${m.reason??""}`)}else t.push(` ${d}`)}if(o.truncated)t.push(" Path truncated")}return t}function SR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!=="visual"&&t!=="plain")throw new g("--email-style must be 'visual' or 'plain'",400);return t}function Y9(e){if(e===void 0)return;if(e!=="sequence_created_at"&&e!=="subscriber_created_at")throw new g("--inactivity-baseline must be 'sequence_created_at' or 'subscriber_created_at'",400);return e}function Z9(e){let t=NPe(e.listScope),n=V9(e.listIds,e.listId),r=V9(e.tagNames,e.tagName);if(t!==void 0&&n!==void 0)throw new g("Provide either --list-id/--list-ids or --list-scope, not both",400);if(t!==void 0&&e.trigger!==void 0&&e.trigger!=="contact_added")throw new g("--list-scope only applies to a contact_added trigger",400);if(e.pauseNewEnrollments&&e.resumeNewEnrollments)throw new g("Provide either --pause-new-enrollments or --resume-new-enrollments, not both",400);if(e.userCancellable&&e.notUserCancellable)throw new g("Provide either --user-cancellable or --not-user-cancellable, not both",400);if(e.clearLabels&&e.label!==void 0)throw new g("Provide either --label or --clear-labels, not both",400);if((e.branchJson!==void 0||e.branchFile!==void 0)&&(e.insertStepsJson!==void 0||e.insertStepsFile!==void 0))throw new g("Provide either --branch-json/--branch-file or --insert-steps-json/--insert-steps-file, not both",400);let i=[e.branchJson!==void 0||e.branchFile!==void 0,e.insertStepsJson!==void 0||e.insertStepsFile!==void 0,e.graphEditJson!==void 0||e.graphEditFile!==void 0].filter(Boolean).length;if(i>1)throw new g("Provide only one of --branch-*, --insert-steps-*, or --graph-edit-*",400);if((e.nodeUpdatesJson!==void 0||e.nodeUpdatesFile!==void 0)&&(e.stepsJson!==void 0||e.stepsFile!==void 0||e.emailsJson!==void 0||e.emailsFile!==void 0||e.smsStepsJson!==void 0||e.smsStepsFile!==void 0||e.subscriberUpdateStepsJson!==void 0||e.subscriberUpdateStepsFile!==void 0||i>0))throw new g("--node-updates-* cannot be combined with legacy step updates or structural graph changes",400);let o=PPe(e),c=MPe(e),l=jPe(e),d=zPe(e),m=FPe(e),A=UPe(e),y=GPe(e);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.label!==void 0&&{labels:e.label},...e.clearLabels===!0&&{labels:[]},...e.userCancellable===!0&&{userCancellable:!0},...e.notUserCancellable===!0&&{userCancellable:!1},...e.trigger!==void 0&&{trigger:e.trigger},...e.goal!==void 0&&e.goal.trim().length>0&&{goal:e.goal.trim()},...nt(e.emailCount,"--email-count")!==void 0&&{emailCount:nt(e.emailCount,"--email-count")},...nt(e.durationDays,"--duration-days")!==void 0&&{durationDays:nt(e.durationDays,"--duration-days")},...SR(e.emailStyle)!==void 0&&{emailStyle:SR(e.emailStyle)},...e.pauseNewEnrollments===!0&&{enrollmentPaused:!0},...e.resumeNewEnrollments===!0&&{enrollmentPaused:!1},...e.confirmStructuralChange===!0&&{confirmStructuralChange:!0},...e.confirmLiveChange===!0&&{confirmLiveChange:!0},...A!==void 0&&{audienceAutoEnroll:A},...K9(e.enrollmentMode)!==void 0&&{enrollmentMode:K9(e.enrollmentMode)},...e.enrollmentFieldPath!==void 0&&{enrollmentFieldPath:e.enrollmentFieldPath},...o!==void 0&&{sendingWindow:o},...c!==void 0&&{frequencyCapEnabled:c},...l!==void 0&&{activeSubscribersOnly:l},...d!==void 0&&{sendToNotSubscribed:d},...m!==void 0&&{keyDates:m},...y!==void 0&&{bccEmails:y},...n!==void 0&&{listId:n[0],listIds:n},...t!==void 0&&{listScope:t},...r!==void 0&&{tagName:r[0],tagNames:r},...e.segmentId!==void 0&&{segmentId:e.segmentId},...e.stopOnSegmentExit!==void 0&&{stopOnSegmentExit:e.stopOnSegmentExit},...e.eventName!==void 0&&{eventName:e.eventName},...e.integrationSlug!==void 0&&{integrationSlug:e.integrationSlug},...e.integrationEventKey!==void 0&&{integrationEventKey:e.integrationEventKey},...$e(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")!==void 0&&{customIntegration:$e(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")},...$e(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")!==void 0&&{propertyFilters:$e(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")},...nt(e.inactiveDays,"--inactive-days")!==void 0&&{inactiveDays:nt(e.inactiveDays,"--inactive-days")},...Y9(e.inactivityBaseline)!==void 0&&{inactivityBaseline:Y9(e.inactivityBaseline)},...nt(e.minCount,"--min-count")!==void 0&&{minCount:nt(e.minCount,"--min-count")},...nt(e.timeWindowDays,"--time-window-days")!==void 0&&{timeWindowDays:nt(e.timeWindowDays,"--time-window-days")},...$e(e.stepsJson,e.stepsFile,"steps")!==void 0&&{steps:$e(e.stepsJson,e.stepsFile,"steps")},...$e(e.emailsJson,e.emailsFile,"emails")!==void 0&&{emails:$e(e.emailsJson,e.emailsFile,"emails")},...$e(e.smsStepsJson,e.smsStepsFile,"smsSteps")!==void 0&&{smsSteps:$e(e.smsStepsJson,e.smsStepsFile,"smsSteps")},...$e(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")!==void 0&&{subscriberUpdateSteps:$e(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")},...$e(e.branchJson,e.branchFile,"branch")!==void 0&&{branch:$e(e.branchJson,e.branchFile,"branch")},...$e(e.insertStepsJson,e.insertStepsFile,"insertSteps")!==void 0&&{insertSteps:$e(e.insertStepsJson,e.insertStepsFile,"insertSteps")},...$e(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")!==void 0&&{nodeUpdates:$e(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")},...$e(e.graphEditJson,e.graphEditFile,"graphEdit")!==void 0&&{graphEdit:$e(e.graphEditJson,e.graphEditFile,"graphEdit")},...$e(e.stopConditionJson,e.stopConditionFile,"stopCondition")!==void 0&&{stopCondition:$e(e.stopConditionJson,e.stopConditionFile,"stopCondition")},...e.fromEmail!==void 0&&{fromEmail:e.fromEmail},...e.fromName!==void 0&&{fromName:e.fromName},...e.senderProfileId!==void 0&&{senderProfileId:e.senderProfileId},...e.replyTo!==void 0&&{replyTo:e.replyTo},...e.replyToName!==void 0&&{replyToName:e.replyToName},...e.replyProfileId!==void 0&&{replyProfileId:e.replyProfileId}}}function KPe(e){return Array.from(new Set((e??"").split(",").map((t)=>t.trim()).filter((t)=>t.length>0)))}function VPe(e){let t=(o)=>Array.from(new Set((o??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),n=t(e.nodeIds),r=t(e.subscriberIds),i=e.cursor?.trim();return{...e.nodeIds!==void 0&&{nodeIds:n},...e.subscriberIds!==void 0&&{subscriberIds:r},...i&&{cursor:i},dryRun:e.apply!==!0}}function jA(e){if(/^[A-Za-z0-9_./:@+-]+$/.test(e))return e;return`'${e.replaceAll("'",`'"'"'`)}'`}function wR(e){let t=["sequenzy","sequences","realign-enrollments",jA(e.id)],n=(r,i)=>{let o=(i??[]).map((c)=>c.trim()).filter((c)=>c.length>0);if(o.length>0)t.push(r,...o.map(jA))};if(n("--node-ids",e.nodeIds),n("--subscriber-ids",e.subscriberIds),"jobId"in e&&e.jobId)t.push("--job-id",jA(e.jobId));else if("cursor"in e&&e.cursor){if(t.push("--cursor",jA(e.cursor)),e.apply)t.push("--apply")}if(e.company)t.push("--company",jA(e.company));return t.join(" ")}function WPe(e){let t=e.subscriberId?.trim(),n=Array.from(new Set((e.subscriberIds??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),r=KPe(e.fieldValues),i=e.all===!0;if((t!==void 0&&t.length>0?1:0)+(n.length>0?1:0)+(r.length>0?1:0)+(i?1:0)!==1)throw new g("Provide exactly one target: --all, --subscriber-id, --subscriber-ids, or --field-values",400);return{...i&&{cancelAll:!0},...t!==void 0&&t.length>0&&{subscriberId:t},...n.length>0&&{subscriberIds:n},...e.fieldPath!==void 0&&e.fieldPath.trim().length>0&&{fieldPath:e.fieldPath.trim()},...r.length>0&&{fieldValues:r},dryRun:e.apply!==!0,...e.reason!==void 0&&e.reason.trim().length>0&&{reason:e.reason.trim()}}}function YPe(e){let n=Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0?Yp(e):[],r=Array.from(new Set((e.subscriberIds??[]).map((i)=>i.trim()).filter((i)=>i.length>0)));if(n.length===0&&r.length===0)throw new g("Provide at least one email address or subscriber ID",400);return{...n.length>0&&{emails:n},...r.length>0&&{subscriberIds:r},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}}}function ZPe(e){let t=[],n=e.emails??[],r=e.subscriberIds??[],i=0,o=0;while(i<n.length||o<r.length){let c=n.slice(i,i+J9);i+=c.length;let l=J9-c.length,d=r.slice(o,o+l);o+=d.length,t.push({...c.length>0&&{emails:c},...d.length>0&&{subscriberIds:d},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}})}return t}function XPe(e){let t=e.goal?.trim(),n=!!t,r=!!e.stepsJson||!!e.stepsFile;if(n&&r)throw new g("Provide either --goal or --steps-json/--steps-file, not both",400);if(e.emailCount!==void 0&&!n)throw new g("--email-count requires --goal",400);if(e.durationDays!==void 0&&!n)throw new g("--duration-days requires --goal",400);if(e.emailStyle!==void 0&&!n)throw new g("--email-style requires --goal",400);SR(e.emailStyle);let i=nt(e.emailCount,"--email-count");if(i!==void 0&&i>G9)throw new g(`--email-count must be no more than ${G9}`,400);let o=nt(e.durationDays,"--duration-days");if(o!==void 0&&o<1)throw new g("--duration-days must be at least 1",400);return n?{mode:"goal",goal:t}:r?{mode:"steps"}:{mode:"blank"}}function eQe(e){if(e.isActive&&e.notActive)throw new g("Provide either --active or --inactive, not both",400);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.triggerType!==void 0&&{triggerType:e.triggerType},...e.triggerEventName!==void 0&&{triggerEventName:e.triggerEventName},...e.triggerTagName!==void 0&&{triggerTagName:e.triggerTagName},...e.attributePath!==void 0&&{attributePath:e.attributePath},...e.attributeCondition!==void 0&&{attributeCondition:e.attributeCondition},...e.attributeValue!==void 0&&{attributeValue:e.attributeValue},...e.attributePreviousValue!==void 0&&{attributePreviousValue:e.attributePreviousValue},...e.eventPropertyName!==void 0&&{eventPropertyName:e.eventPropertyName},...e.eventPropertyLabel!==void 0&&{eventPropertyLabel:e.eventPropertyLabel},...nt(e.attributionWindowHours,"--attribution-window-hours")!==void 0&&{attributionWindowHours:nt(e.attributionWindowHours,"--attribution-window-hours")},...e.isActive&&{isActive:!0},...e.notActive&&{isActive:!1}}}function tQe(e){if(!e||typeof e!=="object")return[];let{status:t,missingFields:n}=e,r=[];if(t==="ok")r.push("Mapping: ok");else if(t==="email_not_found")r.push("Mapping: email not found in last payload");else if(t==="no_sample")r.push("Mapping: no payload received yet");if(Array.isArray(n))for(let i of n){if(!i||typeof i!=="object")continue;let{field:o,path:c}=i;if(typeof o==="string"&&typeof c==="string")r.push(`Not found: ${o} (${c})`)}return r}function nQe(e){let t=$e(e.fieldMappingJson,e.fieldMappingFile,"fieldMapping"),n=$e(e.samplePayloadJson,e.samplePayloadFile,"samplePayload");if(e.clearFieldMapping&&t!==void 0)throw new g("Provide either --field-mapping-json/--field-mapping-file or --clear-field-mapping, not both",400);if(e.clearSamplePayload&&n!==void 0)throw new g("Provide either --sample-payload-json/--sample-payload-file or --clear-sample-payload, not both",400);if(t!==void 0&&(typeof t.email!=="string"||!t.email.trim()))throw new g("fieldMapping.email is required",400);return{...e.clearFieldMapping?{fieldMapping:null}:t!==void 0?{fieldMapping:t}:{},...e.clearSamplePayload?{samplePayload:null}:n!==void 0?{samplePayload:n}:{}}}async function Bn(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.status)c.set("status",t.status);if(t.search)c.set("search",t.search);if(t.label?.length)c.set("labels",t.label.join(","));if(t.limit)c.set("limit",t.limit);if(t.offset)c.set("offset",t.offset);let l=c.size>0?`?${c.toString()}`:"",d=await E("GET",`/api/v1/sequences${l}`,void 0,t.company),m=await jt(t.company),A=m!==void 0?ut({companyId:m}):void 0,y=d.sequences.map((v)=>m!==void 0?Qs(v,{sequenceId:v.id},"sequence",m):{...v,url:void 0});if(t.json){w({...d,sequences:y,...A!==void 0&&{appUrls:A.urls}});return}let b=d.pagination;console.log(b?`Sequences (${d.sequences.length} of ${b.total})`:`Sequences (${d.sequences.length})`);for(let v of y){if(console.log(`- ${v.name} [${v.id}]`),console.log(` Status: ${Nm(v)}`),console.log(` Trigger: ${v.trigger??"Unknown"}`),v.emailCount!==void 0)console.log(` Emails: ${v.emailCount}`);if(console.log(` Sending window: ${JI(v.sendingWindow)}`),v.frequencyCapEnabled!==void 0)console.log(` Frequency cap: ${HI(v.frequencyCapEnabled)}`);console.log(` Created: ${te(v.createdAt)}`),De(" URL",v.url)}if(b?.hasMore)console.log(`More sequences available. Re-run with --offset ${b.offset+b.count} to fetch the next page.`);return}if(e==="create"){if(!t.name)throw new g("Sequence name is required",400);let c=XPe(t),l=await E("POST","/api/v1/sequences",Z9({...t,...c.goal!==void 0&&{goal:c.goal}}),t.company),d=await jt(t.company),m=l.sequence?.id??l.sequenceId,A=d!==void 0&&m!==void 0?ut({companyId:d,sequenceId:m}):void 0;if(t.json){w({...l,...l.sequence!==void 0&&A?.urls.sequence!==void 0&&{sequence:{...l.sequence,url:A.urls.sequence}},...A!==void 0&&{appUrls:A.urls}});return}if($n(l),console.log(`Created sequence: ${l.sequence?.name??t.name}`),console.log(`ID: ${l.sequence?.id??"Unknown"}`),De("URL",A?.urls.sequence),console.log(`Status: ${Nm(l.sequence??{})}`),l.sequence?.emailCount!==void 0)console.log(`Emails: ${l.sequence.emailCount}`);if(l.sequence?.discountCount!==void 0)console.log(`Discount actions: ${l.sequence.discountCount}`);if("sendingWindow"in(l.sequence??{}))console.log(`Sending window: ${JI(l.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(l.sequence??{}))console.log(`Frequency cap: ${HI(l.sequence?.frequencyCapEnabled)}`);if(l.sequence?.sendToNotSubscribed!==void 0)console.log(`Marketing emails go to: ${CR(l.sequence.sendToNotSubscribed)}`);if("keyDates"in(l.sequence??{}))console.log(`Key dates: ${IR(l.sequence?.keyDates)}`);if("audienceAutoEnroll"in(l.sequence??{}))console.log(`Auto-enroll: ${ER(l.sequence?.audienceAutoEnroll)}`);if(c.mode==="goal")console.log("Mode: AI-generated");if(l.message)console.log(l.message);return}if(!t.id)throw new g("Sequence ID is required",400);if(e==="test"){let c=TPe(t),l=await E("POST",c.path,c.body,t.company),d=await jt(t.company),m=d!==void 0?ut({companyId:d,sequenceId:t.id}):void 0;if(t.json){w({...l,...m!==void 0&&{appUrls:m.urls}});return}console.log(l.message??`Queued ${l.results.length} sequence step test email${l.results.length===1?"":"s"}`);for(let A of l.results)console.log(`- ${A.recipientEmail}: email send ${A.emailSendId}`);De("URL",m?.urls.sequence);return}if(e==="goals"){let c=await E("GET",`/api/v1/sequences/${t.id}/goals`,void 0,t.company);if(t.json)return w(c);let l=Array.isArray(c.goals)?c.goals:[];console.log(`Sequence goals (${l.length})`);for(let d of l){if(typeof d!=="object"||d===null)continue;let m=d;console.log(`- ${String(m.name??"Unnamed goal")} [${String(m.id??"unknown")}]`)}return}if(e==="goal-create"||e==="goal-update"){if(e==="goal-create"&&!t.name)throw new g("Goal name is required",400);if(e==="goal-update"&&!t.goalId)throw new g("Goal ID is required",400);let c=await E(e==="goal-create"?"POST":"PATCH",`/api/v1/sequences/${t.id}/goals${t.goalId?`/${t.goalId}`:""}`,eQe(t),t.company);if(t.json)return w(c);let l=c.goal;if(console.log(`${e==="goal-create"?"Created":"Updated"} sequence goal: ${String(l?.name??t.name??t.goalId)}`),l?.id)console.log(`ID: ${String(l.id)}`);return}if(e==="goal-delete"){if(!t.goalId)throw new g("Goal ID is required",400);let c=await E("DELETE",`/api/v1/sequences/${t.id}/goals/${t.goalId}`,void 0,t.company);if(t.json)return w(c);console.log(`Deleted sequence goal: ${t.goalId}`);return}if(e==="webhook-get"||e==="webhook-configure"||e==="webhook-rotate"){let c=e==="webhook-configure",l=e==="webhook-rotate",d=await E(l?"POST":c?"PUT":"GET",`/api/v1/sequences/${t.id}/inbound-webhook${l?"/rotate-secret":""}`,c?nQe(t):void 0,t.company);if(t.json)return w(d);let m=d.webhook;if(console.log(`${l?"Rotated":c?"Configured":"Sequence"} inbound webhook: ${String(m?.status??"Unknown status")}`),m?.url)console.log(`URL: ${String(m.url)}`);for(let A of tQe(m?.mappingCheck))console.log(A);return}if(e==="update"){if(t.name===void 0&&t.description===void 0&&t.label===void 0&&t.clearLabels!==!0&&t.userCancellable!==!0&&t.notUserCancellable!==!0&&t.trigger===void 0&&t.fromEmail===void 0&&t.fromName===void 0&&t.senderProfileId===void 0&&t.replyTo===void 0&&t.replyToName===void 0&&t.replyProfileId===void 0&&t.enrollmentMode===void 0&&t.enrollmentFieldPath===void 0&&t.pauseNewEnrollments!==!0&&t.resumeNewEnrollments!==!0&&t.sendingWindowStart===void 0&&t.sendingWindowEnd===void 0&&t.sendingWindowTimezone===void 0&&t.sendingWindowDays===void 0&&t.clearSendingWindow!==!0&&t.respectFrequencyCap!==!0&&t.ignoreFrequencyCap!==!0&&t.activeSubscribersOnly!==!0&&t.includeSuppressedSubscribers!==!0&&t.sendToNotSubscribed===void 0&&t.keyDate===void 0&&t.keyDatesJson===void 0&&t.keyDatesFile===void 0&&t.keyDatesTimezone===void 0&&t.clearKeyDates!==!0&&t.sendSpreadHours===void 0&&t.autoEnrollAll!==!0&&t.autoEnrollListIds===void 0&&t.autoEnrollSegmentId===void 0&&t.autoEnrollJson===void 0&&t.autoEnrollStartsAt===void 0&&t.clearAutoEnroll!==!0&&t.bccEmails===void 0&&t.clearBccEmails!==!0&&!t.stepsJson&&!t.stepsFile&&!t.emailsJson&&!t.emailsFile&&!t.smsStepsJson&&!t.smsStepsFile&&!t.subscriberUpdateStepsJson&&!t.subscriberUpdateStepsFile&&!t.branchJson&&!t.branchFile&&!t.insertStepsJson&&!t.insertStepsFile&&!t.nodeUpdatesJson&&!t.nodeUpdatesFile&&!t.graphEditJson&&!t.graphEditFile&&!t.stopConditionJson&&!t.stopConditionFile)throw new g("Provide at least one sequence metadata, identity, settings, step, nodeUpdates, or graphEdit option",400);let c=await E("PUT",`/api/v1/sequences/${t.id}`,Z9(await qPe(t)),t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,sequenceId:t.id}):void 0;if(t.json){w({...c,...c.sequence!==void 0&&d?.urls.sequence!==void 0&&{sequence:{...c.sequence,url:d.urls.sequence}},...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(`Updated sequence: ${c.sequence?.name??t.id}`),console.log(`ID: ${c.sequence?.id??t.id}`),De("URL",d?.urls.sequence),console.log(`Status: ${Nm(c.sequence??{})}`);for(let m of _Pe(c.sequence))console.log(m);for(let m of BPe(c.sequence))console.log(m);if("sendingWindow"in(c.sequence??{}))console.log(`Sending window: ${JI(c.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(c.sequence??{}))console.log(`Frequency cap: ${HI(c.sequence?.frequencyCapEnabled)}`);if(c.sequence?.sendToNotSubscribed!==void 0)console.log(`Marketing emails go to: ${CR(c.sequence.sendToNotSubscribed)}`);if("keyDates"in(c.sequence??{}))console.log(`Key dates: ${IR(c.sequence?.keyDates)}`);if("audienceAutoEnroll"in(c.sequence??{}))console.log(`Auto-enroll: ${ER(c.sequence?.audienceAutoEnroll)}`);if("bccEmails"in(c.sequence??{}))console.log(`BCC: ${c.sequence?.bccEmails?.join(", ")||"None"}`);return}if(e==="pause-enrollments"||e==="resume-enrollments"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,sequenceId:t.id}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}console.log(c.message??`Updated sequence ${t.id}`),W9(c),De("URL",d?.urls.sequence);return}if(e==="duplicate"){let c=await E("POST",`/api/v1/sequences/${t.id}/duplicate`,t.name===void 0?void 0:{name:t.name},t.company),l=c.sequence?.id??c.sequenceId,d=await jt(t.company),m=d!==void 0&&l!==void 0?ut({companyId:d,sequenceId:l}):void 0;if(t.json){w({...c,...m!==void 0&&{appUrls:m.urls}});return}if(console.log(`Duplicated sequence: ${c.sequence?.name??l??t.id}`),l)console.log(`ID: ${l}`);console.log(`Status: ${Nm(c.sequence??{})}`),De("URL",m?.urls.sequence);return}if(e==="archive"||e==="unarchive"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company);if(t.json){w(c);return}console.log(`${e==="archive"?"Archived":"Restored"} sequence: ${c.sequence?.name??t.id}`);return}if(e==="test-run"||e==="test-run-get"){let c;if(e==="test-run"){if(!t.subscriber?.trim())throw new g("Pass --subscriber for a live sequence test",400);let d=$e(t.eventProperties,void 0,"event-properties");if(d!==void 0&&(d===null||typeof d!=="object"||Array.isArray(d)))throw new g("--event-properties must be a JSON object",400);let m=t.speedMultiplier===void 0?120:Number(t.speedMultiplier);if(!Number.isInteger(m)||m<60||m>1e4)throw new g("--speed-multiplier must be an integer between 60 and 10000",400);c={subscriberId:t.subscriber.trim(),speedMultiplier:m,...d!==void 0?{customVariables:d}:{}}}else if(!t.runId)throw new g("Pass a test run ID",400);let l=await E(e==="test-run"?"POST":"GET",`/api/v1/sequences/${encodeURIComponent(t.id??"")}/test-runs${e==="test-run-get"?`/${encodeURIComponent(t.runId??"")}`:""}`,c,t.company);if(t.json)w(l);else{if(console.log(`Sequence test ${l.run.id}: ${l.run.status}`),l.run.errorMessage)console.log(l.run.errorMessage);if(e==="test-run")console.log(`Inspect: sequenzy sequences test-run-get ${t.id} ${l.run.id}${t.company?` --company ${t.company}`:""} --json`)}return}if(e==="simulate"){let c=t.subscriber?.trim(),l=t.simulateEmail?.trim();if(c&&l)throw new g("Pass --subscriber or --email, not both",400);let d=new URLSearchParams;if(c)d.set("subscriberId",c);if(l)d.set("email",l);if(t.limit)d.set("limit",t.limit);let m=d.size>0?`?${d.toString()}`:"",A=await E("GET",`/api/v1/sequences/${t.id}/simulate${m}`,void 0,t.company),y=await jt(t.company),b=y!==void 0?ut({companyId:y,sequenceId:t.id}):void 0;if(t.json){w({...A,...b!==void 0&&{appUrls:b.urls}});return}for(let v of JPe(A))console.log(v);De("URL",b?.urls.sequence);return}if(e==="enable"||e==="disable"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,sequenceId:t.id}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(c.message??`${e}d sequence ${t.id}`),W9(c),De("URL",d?.urls.sequence);return}if(e==="enroll"){let c=YPe(t),l=ZPe(c),d=0,m=0,A=[],y,b;for(let v of l){let k=await E("POST",`/api/v1/sequences/${t.id}/enroll`,v,t.company);d+=k.enrolled,m+=k.skipped,A.push(...k.notFound),y??=k.targetNodeId,b??=k.scheduledFor}if(t.json){w({success:!0,sequenceId:t.id,enrolled:d,skipped:m,notFound:A,...y!==void 0&&{targetNodeId:y},...b!==void 0&&{scheduledFor:b}});return}if(console.log(`Enrolled ${d} subscriber(s) in sequence: ${t.id}`),console.log(`Skipped (already enrolled, inactive, or unavailable): ${m}`),A.length>0){console.log(`Not found: ${A.length}`);for(let v of A.slice(0,10))console.log(`- ${v}`);if(A.length>10)console.log(`...and ${A.length-10} more`)}if(y!==void 0)console.log(`Target node: ${y}`);if(b!==void 0)console.log(`Scheduled for: ${te(b)}`);return}if(e==="realign-enrollments"){let c=await jt(t.company),l=c!==void 0?ut({companyId:c,sequenceId:t.id}):void 0,d;if(t.jobId){let m=await E("GET",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window/jobs/${encodeURIComponent(t.jobId)}`,void 0,t.company);if(t.json){w({...m,...l!==void 0&&{appUrls:l.urls}});return}if(!m.result){if(console.log(m.message??`Enrollment realignment is ${m.status}.`),m.status!=="failed")console.log(`Check again: ${wR({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:m.jobId})}`);De("URL",l?.urls.sequence);return}d=m.result}else{let m=VPe(t),A=await E("POST",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window`,m,t.company);if("status"in A){if(t.json){w({...A,...l!==void 0&&{appUrls:l.urls}});return}console.log(A.message??"Enrollment realignment queued."),console.log(`Job ID: ${A.jobId}`),console.log(`Check status: ${wR({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:A.jobId})}`),De("URL",l?.urls.sequence);return}d=A}if(t.json){w({...d,...l!==void 0&&{appUrls:l.urls}});return}if(console.log(d.message??"Sequence enrollment realignment complete"),d.sendingWindow){let m=d.sendingWindow;console.log(`Sending window: ${m.days.join(", ")} ${m.startTime}-${m.endTime} ${m.timezone}`)}else console.log("Sending window: none set on the sequence (per-step weekday gates only)");console.log(`Checked: ${d.scannedCount}`),console.log(`${d.dryRun?"Would realign":"Realigned"}: ${d.realignedCount}`),console.log(`Left as-is: ${d.unchangedCount}`);for(let[m,A]of Object.entries(d.unchangedReasons??{}))console.log(` ${m}: ${A}`);if(console.log(`Dry run: ${d.dryRun?"yes":"no"}`),d.requeueFailedCount>0)console.log(`Re-queue deferred to the sweeper: ${d.requeueFailedCount}`);if(d.changes.length>0){console.log(`Enrollments (first ${d.changes.length} of ${d.realignedCount}):`);for(let m of d.changes)console.log(`- ${m.subscriberEmail??m.subscriberId} | ${te(m.waitUntil)} -> ${te(m.newWaitUntil)} (${m.movedEarlierMinutes} min earlier)`)}if(d.dryRun&&d.realignedCount>0)console.log("Re-run with --apply to move these enrollments.");if(d.hasMore)console.log(d.nextCursor?`More enrollments remain. Continue with: ${wR({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,cursor:d.nextCursor,apply:!d.dryRun})}`:"More enrollments remain. Re-run the command to continue.");De("URL",l?.urls.sequence);return}if(e==="cancel-enrollments"){let c=WPe(t),l=`/api/v1/sequences/${t.id}/enrollments/cancel`,d=await E("POST",l,c,t.company),m=d.matchedCount,A=d.cancelledCount,y=1;while(!d.dryRun&&(d.remainingCount??0)>0&&d.cancelledCount>0&&y<kPe){if(!t.json)console.log(`Cancelled ${A} so far, ${d.remainingCount} remaining...`);d=await E("POST",l,c,t.company),A+=d.cancelledCount,y+=1}let b=d.remainingCount??0,v=y===1?d.message??"Sequence enrollment cancellation done":`Cancelled ${A} sequence enrollment${A===1?"":"s"} across ${y} requests.${b>0?` ${b} still match; re-run the same command to continue.`:""}`,k=await jt(t.company),_=k!==void 0?ut({companyId:k,sequenceId:t.id}):void 0;if(t.json){w({...d,matchedCount:m,cancelledCount:A,message:v,requests:y,..._!==void 0&&{appUrls:_.urls}});return}if(console.log(v),console.log(`Matched: ${m}`),console.log(`Cancelled: ${A}`),console.log(`Remaining: ${b}`),console.log(`Dry run: ${d.dryRun?"yes":"no"}`),b>0&&!d.dryRun)console.log("Stopped before draining every enrollment. Re-run the same command to continue.");if((d.target?.notFoundSubscriberIds?.length??0)>0)console.log(`Subscriber IDs not found: ${d.target?.notFoundSubscriberIds?.join(", ")}`);if(d.hasMore)console.log("Only the first matching enrollments are shown.");if((d.enrollments?.length??0)>0){console.log("Enrollments:");for(let O of d.enrollments??[])console.log(`- ${O.tokenId} | ${O.subscriberEmail??O.subscriberId} [${O.status}]`)}De("URL",_?.urls.sequence);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/sequences/${t.id}`,void 0,t.company);if(t.json){w(c);return}console.log(c.message??`Deleted sequence ${t.id}`);let l=DPe(c);if(l)console.log(l);return}let n=await E("GET",`/api/v1/sequences/${t.id}`,void 0,t.company),r=await jt(t.company),i=r!==void 0?ut({companyId:r,sequenceId:t.id}):void 0;if(t.json){w({...n,...i?.urls.sequence!==void 0&&{sequence:{...n.sequence,url:i.urls.sequence}},...i!==void 0&&{appUrls:i.urls}});return}let o=n.sequence;if(console.log(o.name),console.log(`ID: ${o.id}`),De("URL",i?.urls.sequence),console.log(`Status: ${Nm(o)}`),console.log(`Trigger: ${o.trigger??"Unknown"}`),console.log(`Sending window: ${JI(o.sendingWindow)}`),o.frequencyCapEnabled!==void 0)console.log(`Frequency cap: ${HI(o.frequencyCapEnabled)}`);if(o.activeSubscribersOnly!==void 0)console.log(`Enrolls: ${o.activeSubscribersOnly?"active subscribers only":"all statuses (marketing emails skipped for unsubscribed and bounced)"}`);if(o.sendToNotSubscribed!==void 0)console.log(`Marketing emails go to: ${CR(o.sendToNotSubscribed)}`);if(console.log(`Key dates: ${IR(o.keyDates)}`),o.audienceAutoEnroll)console.log(`Auto-enroll: ${ER(o.audienceAutoEnroll)}`);if(console.log(`BCC: ${o.bccEmails?.join(", ")||"None"}`),console.log(`Created: ${te(o.createdAt)}`),console.log(`Enrichment: ${o.enrichmentStatus} (${o.enrichedCount}/${o.emailCount})`),o.emails.length>0){console.log("Emails:");for(let c of o.emails){if(console.log(`- ${xPe(c)}`),console.log(` Email ID: ${c.emailId??"None"}`),console.log(` Name: ${c.name??"None"}`),console.log(` Subject: ${c.subject??"None"}`),console.log(` Preview: ${c.previewText??"None"}`),console.log(` Format: ${Ns(c.emailPreset)}`),console.log(` Theme: ${YH(c.emailTheme)}`),c.attachments&&c.attachments.length>0)console.log(` Attachments: ${c.attachments.map((l)=>`${l.filename} (${l.path})`).join(", ")}`);if(console.log(` Blocks: ${c.blocks.length}`),c.abTest){console.log(` A/B test: ${c.abTest.id??"Unknown"}${c.abTest.status?` (${c.abTest.status})`:""}`);for(let l of c.abTest.variants??[])console.log(` Variant ${l.variantLabel}: ${l.subject??"None"}${l.isWinner?" (winner)":""}`),console.log(` Variant ID: ${l.variantId}`),console.log(` Blocks: ${l.blockCount??0}`);console.log(` ${gv}`)}}}}catch(n){T(n instanceof g?n:n),process.exit(1)}}function Kl(e,t,n){if(e===void 0)return;let r=Number(e);if(!Number.isFinite(r)||r<=0)throw new g(`${t} must be a positive number`,400);if(r>n)throw new g(`${t} must be at most ${n}`,400);return r}function rQe(e){let t={};if(e.resetBrowseAbandonment){if(e.browseAbandonment!==void 0||e.browseDelayHours!==void 0||e.browseCooldownHours!==void 0)throw new g("--reset-browse-abandonment cannot be combined with other browse flags",400);t.browseAbandonment=null}else{let n={},r=go(e.browseAbandonment,"--browse-abandonment");if(r!==void 0)n.enabled=r;let i=Kl(e.browseDelayHours,"--browse-delay-hours",fH);if(i!==void 0)n.delayHours=i;let o=Kl(e.browseCooldownHours,"--browse-cooldown-hours",gH);if(o!==void 0)n.cooldownHours=o;if(Object.keys(n).length>0)t.browseAbandonment=n}if(e.resetCartAbandonment){if(e.cartAbandonment!==void 0||e.cartDelayHours!==void 0||e.cartCooldownHours!==void 0||e.cartExpireAfterHours!==void 0)throw new g("--reset-cart-abandonment cannot be combined with other cart flags",400);t.cartAbandonment=null}else{let n={},r=go(e.cartAbandonment,"--cart-abandonment");if(r!==void 0)n.enabled=r;let i=Kl(e.cartDelayHours,"--cart-delay-hours",AH);if(i!==void 0)n.delayHours=i;let o=Kl(e.cartCooldownHours,"--cart-cooldown-hours",hH);if(o!==void 0)n.cooldownHours=o;let c=Kl(e.cartExpireAfterHours,"--cart-expire-after-hours",yH);if(c!==void 0)n.expireAfterHours=c;if(Object.keys(n).length>0)t.cartAbandonment=n}if(e.resetPriceDrop){if(e.priceDrop!==void 0||e.priceDropMinPercent!==void 0||e.priceDropLookbackDays!==void 0||e.priceDropCooldownDays!==void 0)throw new g("--reset-price-drop cannot be combined with other price-drop flags",400);t.priceDrop=null}else{let n={},r=go(e.priceDrop,"--price-drop");if(r!==void 0)n.enabled=r;let i=Kl(e.priceDropMinPercent,"--price-drop-min-percent",bH);if(i!==void 0)n.minPercent=i;let o=Kl(e.priceDropLookbackDays,"--price-drop-lookback-days",vH);if(o!==void 0)n.lookbackDays=o;let c=Kl(e.priceDropCooldownDays,"--price-drop-cooldown-days",EH);if(c!==void 0)n.cooldownDays=c;if(Object.keys(n).length>0)t.priceDrop=n}if(Object.keys(t).length===0)throw new g("Provide at least one settings flag (see --help for the full list)",400);return t}function tZ(e){let{browseAbandonment:t,cartAbandonment:n,priceDrop:r}=e;if(console.log(`Shopify automation settings (${e.shopDomain})`),console.log(""),console.log(`Browse abandonment: ${t.enabled?"on":"off"}`),console.log(" Emails shoppers who view a product but don't buy, add to cart, or start checkout."),console.log(` Waits ${t.delayHours}h after the view - at most one email per subscriber per ${t.cooldownHours}h`),n)console.log(""),console.log(`Cart abandonment: ${n.enabled?"on":"off"}`),console.log(" Fires ecommerce.cart_abandoned with the full cart after the cart sits untouched with no checkout or order."),console.log(` Waits ${n.delayHours}h of inactivity - at most one per subscriber per ${n.cooldownHours}h`),console.log(` Drops a cart untouched for ${n.expireAfterHours}h instead of emailing about it`);console.log(""),console.log(`Price drop alerts: ${r.enabled?"on":"off"}`),console.log(` Emails recent viewers when a product's price falls by ${r.minPercent}% or more.`),console.log(` Audience: viewers from the last ${r.lookbackDays} days - at most one email per product per subscriber per ${r.cooldownDays} days`)}async function DR(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="get"){let i=await E("GET","/api/v1/shopify/automation-settings",void 0,t.company);if(t.json){w(i);return}tZ(i);return}let n=rQe(t),r=await E("PUT","/api/v1/shopify/automation-settings",n,t.company);if(t.json){w(r);return}if(r.message)console.log(r.message),console.log("");tZ(r)}catch(n){T(n instanceof g?n:n),process.exit(1)}}function iQe(e){let{sms:t}=e;if(console.log(`SMS add-on: ${t.enabled?"enabled":"not enabled"}`),console.log(`Plan eligible: ${t.planEligible?"yes":"no"}`),console.log(`Credits balance: ${t.creditsBalance}`),console.log(`Brand prefix: ${t.brandPrefix??"(not set)"}`),t.numbers.length===0)console.log("Numbers: none");else{console.log("Numbers:");for(let n of t.numbers){let r=[n.label,n.brandPrefix?`prefix: ${n.brandPrefix}`:null,n.linkShorteningEnabled===!1?"links sent as written":null].filter(Boolean).join(", ");console.log(` ${n.e164} [${n.id}] (${n.status})${r?` - ${r}`:""}`)}}console.log(),console.log(e.message)}function oQe(e){if(e.usage.length===0){console.log("No SMS sends recorded yet.");return}for(let t of e.usage)console.log(t.fromNumber),console.log(` Sends: ${t.totalSends} (delivered: ${t.delivered}, failed: ${t.failed}, test: ${t.testSends})`),console.log(` Credits charged: ${t.creditsCharged}`),console.log(` Last sent: ${t.lastSentAt??"never"}`)}function sQe(e){return{to:Ct(e.phone??"","Phone number").trim(),text:Ct(e.text??"","--text").trim(),...e.imageUrl&&e.imageUrl.length>0?{imageUrls:e.imageUrl}:{},...e.fromNumber?.trim()?{fromNumberId:e.fromNumber.trim()}:{}}}function aQe(e){return{label:e.label?.trim()||null}}function cQe(e){let t=e.trim().toLowerCase();if(t==="on")return!0;if(t==="off")return!1;throw Error('--link-shortening must be "on" or "off".')}function lQe(e){if(e.label===void 0&&e.brandPrefix===void 0&&e.linkShortening===void 0)throw Error("Provide --label, --brand-prefix, and/or --link-shortening.");return{...e.label!==void 0?{label:e.label.trim()||null}:{},...e.brandPrefix!==void 0?{brandPrefix:e.brandPrefix.trim()||null}:{},...e.linkShortening!==void 0?{linkShorteningEnabled:cQe(e.linkShortening)}:{}}}async function Cd(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="settings"){let n=await E("GET","/api/v1/sms/settings",void 0,t.company);if(t.json){w(n);return}iQe(n);return}if(e==="send-test"){let n=await E("POST","/api/v1/sms/test",sQe(t),t.company);if(t.json){w(n);return}console.log(n.message);return}if(e==="usage"){let n=await E("GET","/api/v1/sms/usage",void 0,t.company);if(t.json){w(n);return}oQe(n);return}if(e==="release"){let n=Ct(t.numberId??"","SMS number ID").trim();if(!await rt(`Release SMS number ${n}? The number is handed back to the carrier and cannot be recovered.`,t)){console.log("Aborted.");return}let r=await E("DELETE",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,void 0,t.company);if(t.json){w(r);return}console.log(r.message);return}if(e==="label"||e==="update"){let n=Ct(t.numberId??"","SMS number ID").trim(),r=await E("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,e==="label"?aQe(t):lQe(t),t.company);if(t.json){w(r);return}console.log(r.message)}}catch(n){T(n instanceof g?n:n),process.exit(1)}}var wd=Et(xn(),1);var nZ=["email","sequence","email_type","mailbox_provider","recipient_domain"],uQe={permanent_bounce:"permanent bounces",temporary_bounce:"temporary bounces",blocked:"blocked sends",complaint:"sends with spam complaints"};function dQe(e){if(e.emails||e.clients||e.links)throw new g("--by cannot be combined with --emails, --clients or --links",400);if(e.campaign||e.sequence||e.transactional)throw new g("--by covers the account; narrow it with --source campaign:<id>, sequence:<id> or transactional:<id> instead",400);if(e.by&&!nZ.includes(e.by))throw new g(`--by must be one of: ${nZ.join(", ")}`,400);let t=new URLSearchParams;for(let[n,r]of[["by",e.by],["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["recipientDomain",e.recipientDomain],["source",e.source],["outcome",e.outcome],["limit",e.limit]])if(r)t.set(n,r);if(e.includeBots)t.set("includeMachineEngagement","true");return`/api/v1/metrics/breakdown?${t.toString()}`}function pQe(e){if(!e)return"";switch(e.kind){case"source":return`--source ${e.source.type}:${e.source.id}`;case"email_type":return`--email-type ${e.emailType}`;case"mailbox_provider":return`--mailbox-provider ${e.mailboxProvider}`;case"recipient_domain":return`--recipient-domain ${e.recipientDomain}`}}function _R(e){return`${e.toFixed(1)}%`}function mQe(e){let t=e.period&&e.period!=="custom"?e.period:`${e.start??""} - ${e.end??""}`,n=e.outcome?`, only ${uQe[e.outcome]??e.outcome}`:"",r=[`Breakdown by ${e.by.replace("_"," ")} (${t}${n})`];if(e.rows.length===0)return r.push("No emails were sent with these filters in this period."),r;let i=e.rows.some((c)=>c.revenue!==null),o=Math.max(4,...e.rows.map((c)=>c.sent.toLocaleString().length));r.push("",` ${"Sent".padStart(o)} Open Click Bounce${i?" Revenue":""} Name`);for(let c of e.rows){let l=i?` ${(c.revenue===null?"-":`$${Math.round(c.revenue).toLocaleString()}`).padStart(10)}`:"",d=c.detail?` (${c.detail})`:"";r.push(` ${c.sent.toLocaleString().padStart(o)} ${_R(c.openRate).padStart(5)} ${_R(c.clickRate).padStart(5)} ${_R(c.bounceRate).padStart(6)}${l} ${c.label}${d}`);let m=pQe(c.filter);if(m)r.push(` ${"".padStart(o)} drill in: ${m}`)}return r}async function rZ(e){let t=await E("GET",dQe(e),void 0,e.company);if(e.json){w(t);return}for(let n of mQe(t))console.log(n)}function fQe(e){if(e.emails)throw new g("--clients cannot be combined with --emails",400);if(e.sequence||e.transactional)throw new g("--clients supports account-level stats and --campaign only",400);if(e.campaign&&(e.period||e.start||e.end||e.emailType))throw new g("--clients with --campaign covers the whole campaign; --period, --start, --end, and --email-type apply to account-level stats only",400);let t=new URLSearchParams;if(!e.campaign){for(let[i,o]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType]])if(o)t.set(i,o)}if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString(),r=e.campaign?`/api/v1/metrics/campaigns/${encodeURIComponent(e.campaign)}/clients`:"/api/v1/metrics/clients";return n?`${r}?${n}`:r}function gQe(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function AQe(e){let n=[`Email clients (${e.campaignId?`campaign ${e.campaignId}`:e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalOpens===0)return n.push("No opens recorded yet."),n;let r=Math.max(...[...e.clients,...e.devices].map((i)=>i.label.length));for(let[i,o]of[["Clients",e.clients],["Devices",e.devices]]){n.push("",`${i}:`);for(let c of o)n.push(` ${c.label.padEnd(r)} ${gQe(c.share).padStart(4)} ${c.opens.toLocaleString()} ${c.opens===1?"open":"opens"}`)}return n.push("",`Based on ${e.totalOpens.toLocaleString()} unique ${e.totalOpens===1?"open":"opens"}; ${e.privacyProxyOpens.toLocaleString()} came through Gmail, Yahoo, or Apple Mail privacy proxies, which hide the device.`),n}async function iZ(e){let t=await E("GET",fQe(e),void 0,e.company);if(e.json){w(t);return}for(let n of AQe(t))console.log(n)}var oZ=["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"],hQe=["step","sort","order","page","limit"];function sZ(e){if(e.emails)return;let t=hQe.find((n)=>e[n]!==void 0&&!(n==="limit"&&(e.links||e.by)));if(t)throw new g(`--${t} requires --emails`,400)}function yQe(e){if(e.transactional)throw new g("--emails covers campaigns and sequence steps; --transactional is not supported",400);if(e.emailType!==void 0&&!["campaign","sequence"].includes(e.emailType))throw new g("--email-type must be 'campaign' or 'sequence' with --emails",400);if(e.sort!==void 0&&!oZ.includes(e.sort))throw new g(`--sort must be one of: ${oZ.join(", ")}`,400);if(e.order!==void 0&&!["asc","desc"].includes(e.order))throw new g("--order must be 'asc' or 'desc'",400);if(e.mailboxProvider)throw new g("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign&&(e.sequence||e.step))throw new g("--campaign cannot be combined with --sequence or --step when using --emails",400);let t=new URLSearchParams,n=[["emailType",e.emailType],["sequenceId",e.sequence],["campaignId",e.campaign],["step",e.step],["sort",e.sort],["order",e.order],["page",e.page],["limit",e.limit]];for(let[i,o]of n)if(o!==void 0&&o.trim()!=="")t.set(i,o.trim());if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(e.period)t.set("period",e.period);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function bQe(e){return E("GET",`/api/v1/metrics/emails${yQe(e)}`,void 0,e.company)}function vQe(e){let t=e.emailType==="sequence"?`${e.sequenceName??"Unknown sequence"}${e.step!==null?` · Step ${e.step}`:""}`:"Campaign",n=`${e.stats.opened.toLocaleString()} opened (${e.stats.openRate.toFixed(1)}%), ${e.stats.clicked.toLocaleString()} clicked (${e.stats.clickRate.toFixed(1)}%)`;return`${e.name} — ${e.stats.sent.toLocaleString()} sent, ${n} [${t}, ${e.emailId}]`}function EQe(e){let{totals:t,pagination:n}=e,r=e.period?e.period==="custom"?`${e.start??"?"} to ${e.end??"?"}`:e.period:"all time";if(console.log(`Per-email metrics (${r}${e.step!==void 0?`, step ${e.step}`:""})`),console.log(`Totals: ${t.emails.toLocaleString()} emails, ${t.sent.toLocaleString()} sent, ${t.delivered.toLocaleString()} delivered, ${t.opened.toLocaleString()} opened (${t.openRate.toFixed(1)}%), ${t.clicked.toLocaleString()} clicked (${t.clickRate.toFixed(1)}%)`),console.log(`Page: ${n.page}/${n.totalPages||1} (${n.total.toLocaleString()} matching emails)`),e.emails.length===0){console.log("No emails found.");return}console.log("");for(let i of e.emails)console.log(`- ${vQe(i)}`)}async function aZ(e){let t=await bQe(e);if(e.json){w(t);return}EQe(t)}function IQe(e){if(e.emails||e.clients)throw new g("--links cannot be combined with --emails or --clients",400);if(e.campaign||e.sequence||e.transactional)throw new g("--links covers the whole account; for one campaign's links use 'sequenzy stats --campaign <id> --json' and read clickedLinks",400);let t=new URLSearchParams;for(let[r,i]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["limit",e.limit]])if(i)t.set(r,i);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString();return n?`/api/v1/metrics/links?${n}`:"/api/v1/metrics/links"}function CQe(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function wQe(e){let n=[`Link clicks (${e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalClicks===0)return n.push("No link clicks in this period."),n;let r=Math.max(...e.links.map((i)=>i.uniqueClicks.toLocaleString().length));n.push("");for(let i of e.links)n.push(` ${i.uniqueClicks.toLocaleString().padStart(r)} ${CQe(i.share).padStart(4)} ${i.clicks.toLocaleString()} ${i.clicks===1?"click":"clicks"} ${i.url}`);return n.push("",`${e.totalUniqueClicks.toLocaleString()} unique ${e.totalUniqueClicks===1?"click":"clicks"} (${e.totalClicks.toLocaleString()} total) across ${e.totalLinks.toLocaleString()} ${e.totalLinks===1?"link":"links"}${e.links.length<e.totalLinks?`; showing the top ${e.links.length}`:""}. Each subscriber counts once per link, and query strings are ignored, so UTM-tagged variants of a page count together.`),n}async function cZ(e){let t=await E("GET",IQe(e),void 0,e.company);if(e.json){w(t);return}for(let n of wQe(t))console.log(n)}var Z=Et(AA(),1);function SQe(e,t){if(e===void 0||t===void 0)return null;return`${t.toLocaleString()} active (${e.toLocaleString()} total)`}function DQe(e){let t=e.recipients===1?"recipient":"recipients",n=e.clickers===1?"clicker":"clickers";return{impressions:`${e.impressions.toLocaleString()} (${e.recipients.toLocaleString()} ${t})`,clicks:`${e.clicks.toLocaleString()} (${e.clickers.toLocaleString()} ${n})`,orders:e.orders.toLocaleString(),revenue:(e.revenueByCurrency?.length??0)>0?(e.revenueByCurrency??[]).map(({currency:r,revenueCents:i})=>{let o=(i/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});return r==="UNKNOWN"?`${o} (currency unknown)`:`${r} ${o}`}).join(" + "):e.revenueCents>0?`${e.revenueCents.toLocaleString()} minor units (currency unavailable)`:"—",topProducts:e.topProducts.map((r)=>`${r.provider}:${r.providerProductId}: ${r.impressions.toLocaleString()} shown, ${r.clicks.toLocaleString()} clicked`)}}function _Qe(e){let t=e.blocked??0;return[`Permanent: ${e.permanent.toLocaleString()}`,`Soft: ${Math.max(0,e.transient-t).toLocaleString()}`,`Blocked: ${t.toLocaleString()}`,`Undetermined: ${e.undetermined.toLocaleString()}`].join(" · ")}function xQe(e){let t=e.allowMultiple?e.totalResponses===1?"respondent · multiple answers":"respondents · multiple answers":e.totalResponses===1?"response":"responses";return{heading:`${e.question||"Poll"} (${e.totalResponses.toLocaleString()} ${t})`,details:[...e.nps?[`NPS: ${e.nps.score>0?"+":""}${e.nps.score} · Average: ${e.nps.average.toFixed(1)} · ${e.nps.promoters} promoters · ${e.nps.passives} passives · ${e.nps.detractors} detractors`]:[],...e.answers.map((n)=>`- ${n.answer}: ${n.responses.toLocaleString()} (${n.percentage}%)`)]}}function lZ({polls:e,indent:t=0}){return Z.jsxDEV(Z.Fragment,{children:e.map((n)=>{let{heading:r,details:i}=xQe(n);return Z.jsxDEV(Pe,{flexDirection:"column",marginBottom:1,marginLeft:t,children:[Z.jsxDEV(Ae,{children:r},void 0,!1,void 0,this),i.map((o)=>Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:o},void 0,!1,void 0,this)},o,!1,void 0,this))]},n.blockId,!0,void 0,this)})},void 0,!1,void 0,this)}function BQe(e){let t=e.stats;return{subscriberCount:e.subscriberCount,activeSubscriberCount:e.activeSubscriberCount,sent:t.sent,delivered:t.delivered,opened:t.opened,clicked:t.clicked,replies:t.replies??0,unsubscribed:t.unsubscribed,openRate:t.openRate,clickRate:t.clickRate,replyRate:t.replyRate??0,complaints:t.complaints,complaintRate:t.complaintRate,conversions:t.conversions,revenueCents:t.revenueCents,enrollmentSkipped:e.enrollmentSkipped,enrollmentCounts:e.enrollmentCounts,pausedEnrollments:e.pausedEnrollments,steps:e.steps,clickedLinks:e.clickedLinks,bounceBreakdown:e.bounceBreakdown,engagementBreakdown:e.engagementBreakdown,polls:e.polls,commerceForecast:e.commerceForecast,recommendations:e.recommendations}}function xR(e,t){try{return new Intl.NumberFormat(void 0,{style:"currency",currency:t??"USD",maximumFractionDigits:0}).format(e/100)}catch{return`${t??"USD"} ${Math.round(e/100).toLocaleString()}`}}function KI(e){let t=new URLSearchParams,n=Boolean(e.campaign||e.sequence||e.transactional);if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(!n)t.set("period",e.period??"7d");else if(e.period)t.set("period",e.period);if(!n&&e.emailType)t.set("emailType",e.emailType);if(!n&&e.recipientDomain)t.set("recipientDomain",e.recipientDomain);if(!n&&e.source)t.set("source",e.source);if(!n&&e.outcome)t.set("outcome",e.outcome);if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function uZ(e){let t=[e.campaign,e.sequence,e.transactional].filter((n)=>n!==void 0);if(t.length>1)throw new g("Use only one of --campaign, --sequence, or --transactional",400);if(e.emailType!==void 0&&!["campaign","transactional","sequence"].includes(e.emailType))throw new g("--email-type must be 'campaign', 'transactional', or 'sequence'",400);if(e.emailType&&t.length>0)throw new g("--email-type filters account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if((e.recipientDomain||e.source||e.outcome)&&t.length>0)throw new g("--recipient-domain, --source and --outcome filter account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if(e.mailboxProvider&&(e.sequence||e.transactional))throw new g("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign)return E("GET",`/api/v1/metrics/campaigns/${e.campaign}${KI(e)}`,void 0,e.company);if(e.sequence)return E("GET",`/api/v1/metrics/sequences/${e.sequence}${KI(e)}`,void 0,e.company);if(e.transactional)return E("GET",`/api/v1/metrics/transactional/${encodeURIComponent(e.transactional)}${KI(e)}`,void 0,e.company);return E("GET",`/api/v1/metrics${KI(e)}`,void 0,e.company)}function kQe({options:e}){let[t,n]=wd.useState(!0),[r,i]=wd.useState(""),[o,c]=wd.useState(null);if(wd.useEffect(()=>{async function b(){try{let v=await uZ(e);c(BQe(v))}catch(v){i(Ig(v instanceof g?v:v))}finally{n(!1)}}b()},[e]),wd.useEffect(()=>{if(!t)setTimeout(()=>process.exit(r?1:0),100)},[t,r]),t)return Z.jsxDEV(Pe,{padding:1,children:[Z.jsxDEV(Ae,{color:"cyan",children:Z.jsxDEV(nI,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:" Loading stats..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(r)return Z.jsxDEV(Pe,{padding:1,children:Z.jsxDEV(Ae,{color:"red",children:[" ",r]},void 0,!0,void 0,this)},void 0,!1,void 0,this);if(!o)return Z.jsxDEV(Pe,{padding:1,children:Z.jsxDEV(Ae,{dimColor:!0,children:"No stats available"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let l=e.period??"7d",d=e.campaign?"Campaign Stats":e.sequence?"Sequence Stats":e.transactional?"Transactional Email Stats":`Stats (${e.emailType?`${e.emailType}, `:""}${l})`,m=e.sequence&&o.steps?o.steps.filter((b)=>(b.failedCount??0)>0):[],A=o.recommendations?DQe(o.recommendations):null,y=SQe(o.subscriberCount,o.activeSubscriberCount);return Z.jsxDEV(Pe,{flexDirection:"column",padding:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:[Z.jsxDEV(Ae,{bold:!0,color:"green",children:d},void 0,!1,void 0,this),e.mailboxProvider&&Z.jsxDEV(Ae,{dimColor:!0,children:[" for ",e.mailboxProvider," recipients"]},void 0,!0,void 0,this),e.outcome&&Z.jsxDEV(Ae,{dimColor:!0,children:[" ","only sends with ",e.outcome.replace("_"," ")]},void 0,!0,void 0,this),e.includeBots&&Z.jsxDEV(Ae,{dimColor:!0,children:" including bot/scanner engagement"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{flexDirection:"column",children:[y&&Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Subscribers: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:y},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Sent: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.sent.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.complaints!==void 0&&Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Complaints: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.complaints.toLocaleString()},void 0,!1,void 0,this),o.complaintRate!==void 0&&Z.jsxDEV(Ae,{dimColor:!0,children:[" (",o.complaintRate.toFixed(2),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Delivered: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.delivered.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Opened: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.opened.toLocaleString()},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:[" (",o.openRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Clicked: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.clicked.toLocaleString()},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:[" (",o.clickRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Replies: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.replies.toLocaleString()},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:[" (",o.replyRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Unsubscribed: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.unsubscribed.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.conversions!==void 0&&Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Conversions: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:o.conversions.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.revenueCents!==void 0&&Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:["$",(o.revenueCents/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(o.enrollmentSkipped?.count??0)>0&&Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Skipped: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{color:"yellow",children:o.enrollmentSkipped?.count.toLocaleString()},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:[" ","(",Object.entries(o.enrollmentSkipped?.byReason??{}).map(([b,v])=>`${v} ${b}`).join(", ")||"couldn't be enrolled","; contacts that triggered the sequence but can't receive emails)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e.sequence&&(o.steps?.length??0)>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Steps"},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:" · sent per email step, in graph order"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(o.steps??[]).map((b)=>Z.jsxDEV(Pe,{marginLeft:2,children:[Z.jsxDEV(Ae,{children:[`${b.step}. ${b.subject??b.nodeId}: `,b.stats.sent.toLocaleString()," sent"]},void 0,!0,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:` · ${b.stats.delivered.toLocaleString()} delivered · ${b.stats.opened.toLocaleString()} opened · ${b.stats.clicked.toLocaleString()} clicked · ${b.nodeId}`},void 0,!1,void 0,this)]},b.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&(o.steps??[]).some((b)=>(b.polls?.length??0)>0)&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:" · per email step, all time"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(o.steps??[]).filter((b)=>(b.polls?.length??0)>0).map((b)=>Z.jsxDEV(Pe,{flexDirection:"column",marginLeft:2,children:[Z.jsxDEV(Ae,{bold:!0,children:`${b.step}. ${b.subject??b.nodeId}`},void 0,!1,void 0,this),Z.jsxDEV(lZ,{polls:b.polls??[],indent:2},void 0,!1,void 0,this)]},b.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&o.enrollmentCounts&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Current Enrollments"},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:[` · ${o.enrollmentCounts.total.toLocaleString()} total, ${o.enrollmentCounts.active.toLocaleString()} active, ${o.enrollmentCounts.waiting.toLocaleString()} waiting`,o.pausedEnrollments&&o.pausedEnrollments.total>0?` · ${o.pausedEnrollments.total.toLocaleString()} paused (not in total)`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o.enrollmentCounts.byCurrentNode.map((b)=>Z.jsxDEV(Pe,{marginLeft:2,children:[Z.jsxDEV(Ae,{children:["-"," ",b.currentNodeLabel??b.currentNodeType??b.currentNodeId,": ",b.total.toLocaleString()," (",b.active.toLocaleString()," ","active, ",b.waiting.toLocaleString()," waiting)"]},void 0,!0,void 0,this),b.currentNodeMissing&&Z.jsxDEV(Ae,{color:"yellow",children:" · node missing from sequence graph"},void 0,!1,void 0,this)]},b.currentNodeId,!0,void 0,this))]},void 0,!0,void 0,this),!e.campaign&&!e.sequence&&!e.transactional&&!e.emailType&&o.commerceForecast&&o.commerceForecast.history.orderCount>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Commerce Forecast"},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:` · ${o.commerceForecast.history.orderCount.toLocaleString()} paid orders`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.commerceForecast.status==="ready"&&o.commerceForecast.forecast?Z.jsxDEV(Z.Fragment,{children:[Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Predicted AOV: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:xR(o.commerceForecast.forecast.predictedAverageOrderValueCents,o.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"12-month LTV: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:xR(o.commerceForecast.forecast.predictedCustomerValue365DaysCents,o.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"90-day revenue: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:xR(o.commerceForecast.forecast.expectedRevenue90DaysCents,o.commerceForecast.currency)},void 0,!1,void 0,this),Z.jsxDEV(Ae,{dimColor:!0,children:` (${o.commerceForecast.forecast.expectedOrders90Days.toLocaleString()} orders, ${o.commerceForecast.confidence} confidence)`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):Z.jsxDEV(Ae,{dimColor:!0,children:o.commerceForecast.eligibility.reasons.map((b)=>b.message).join(" · ")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:Z.jsxDEV(Ae,{bold:!0,children:"Product Recommendations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Impressions: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:A.impressions},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Clicks: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:A.clicks},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Orders: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:A.orders},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.jsxDEV(Pe,{children:[Z.jsxDEV(Ae,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),Z.jsxDEV(Ae,{children:A.revenue},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.topProducts.length>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Top Products"},void 0,!1,void 0,this),A.topProducts.map((b)=>Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["- ",b]},void 0,!0,void 0,this)},b,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m.length>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:Z.jsxDEV(Ae,{bold:!0,children:"Step Failures"},void 0,!1,void 0,this)},void 0,!1,void 0,this),m.map((b)=>Z.jsxDEV(Pe,{flexDirection:"column",marginBottom:1,children:[Z.jsxDEV(Ae,{children:["Step ",b.step,": ",b.subject??b.nodeId," (",b.failedCount," failed",")"]},void 0,!0,void 0,this),(b.failedSubscribers??[]).map((v)=>Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["- ",v.email??v.subscriberId,":"," ",v.failedReason??"Reason unavailable"]},void 0,!0,void 0,this)},`${b.nodeId}-${v.subscriberId}`,!1,void 0,this)),(b.failedCount??0)>(b.failedSubscribers?.length??0)&&Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{dimColor:!0,children:["Showing first ",b.failedSubscribers?.length??0," of"," ",b.failedCount," failed subscribers"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},b.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),o.clickedLinks&&o.clickedLinks.length>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:Z.jsxDEV(Ae,{bold:!0,children:"Clicked Links"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o.clickedLinks.map((b)=>Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["- ",b.url,": ",b.clicks.toLocaleString()," (",b.percentage.toFixed(1),"%)"]},void 0,!0,void 0,this)},b.url,!1,void 0,this))]},void 0,!0,void 0,this),o.bounceBreakdown&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Bounce Breakdown"},void 0,!1,void 0,this),Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:_Qe(o.bounceBreakdown)},void 0,!1,void 0,this)},void 0,!1,void 0,this),o.bounceBreakdown.subtypes.map((b)=>Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["- ",b.type," / ",b.subType??"Unknown",": ",b.count]},void 0,!0,void 0,this)},`${b.type}-${b.subType??"unknown"}`,!1,void 0,this))]},void 0,!0,void 0,this),o.engagementBreakdown&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Ae,{bold:!0,children:"Human vs Machine Engagement"},void 0,!1,void 0,this),Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["Human: ",o.engagementBreakdown.human.opens," opens ·"," ",o.engagementBreakdown.human.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z.jsxDEV(Pe,{marginLeft:2,children:Z.jsxDEV(Ae,{children:["Machine: ",o.engagementBreakdown.machine.opens," opens ·"," ",o.engagementBreakdown.machine.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.polls&&o.polls.length>0&&Z.jsxDEV(Pe,{flexDirection:"column",marginTop:1,children:[Z.jsxDEV(Pe,{marginBottom:1,children:Z.jsxDEV(Ae,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Z.jsxDEV(lZ,{polls:o.polls},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function RQe(e){return e.outcome&&(e.links||e.clients||e.emails)?new g("--outcome filters account stats and --by only, not --links, --clients or --emails",400):null}async function dZ(e){try{sZ(e)}catch(r){T(r),process.exitCode=1;return}if(!await j())T(z()),process.exit(1);if(e.by){try{await rZ(e)}catch(r){T(r),process.exitCode=1}return}let t=RQe(e);if(t){T(t),process.exitCode=1;return}if(e.links){try{await cZ(e)}catch(r){T(r),process.exitCode=1}return}if(e.clients){try{await iZ(e)}catch(r){T(r),process.exitCode=1}return}if(e.emails){try{await aZ(e)}catch(r){T(r),process.exitCode=1}return}if(e.json){try{w(await uZ(e))}catch(r){T(r),process.exitCode=1}return}await gA(Z.jsxDEV(kQe,{options:e},void 0,!1,void 0,this)).waitUntilExit()}var pZ=500;function VI(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function TQe(e){return Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0}function OQe(e,t){let n=VI(e.tag);if(n.length===0)throw new g("Provide at least one --tag",400);let r=TQe(e)?VI(Yp(e)):[],i=VI(e.externalId),o=VI(e.subscriberId);if(r.length+i.length+o.length===0)throw new g("Provide at least one target: --email, --emails-file, --emails-json, --external-id, or --subscriber-id",400);let c=[...r.map((d)=>({kind:"emails",value:d})),...i.map((d)=>({kind:"externalIds",value:d})),...o.map((d)=>({kind:"subscriberIds",value:d}))],l=[];for(let d=0;d<c.length;d+=pZ){let m=c.slice(d,d+pZ),A=m.filter((v)=>v.kind==="emails").map((v)=>v.value),y=m.filter((v)=>v.kind==="externalIds").map((v)=>v.value),b=m.filter((v)=>v.kind==="subscriberIds").map((v)=>v.value);l.push({tags:n,...A.length>0&&{emails:A},...y.length>0&&{externalIds:y},...b.length>0&&{subscriberIds:b},...t==="add"&&e.triggerAutomations===!0?{triggerAutomations:!0}:{}})}return l}function NQe(e){let t=e[0];if(!t)throw new g("No bulk tag responses to combine",500);return e.reduce((n,r)=>({success:n.success&&r.success,tags:r.tags,requested:n.requested+r.requested,matched:n.matched+r.matched,updated:n.updated+r.updated,unchanged:n.unchanged+r.unchanged,failed:n.failed+r.failed,notFound:{emails:[...n.notFound.emails,...r.notFound.emails],externalIds:[...n.notFound.externalIds,...r.notFound.externalIds],subscriberIds:[...n.notFound.subscriberIds,...r.notFound.subscriberIds]},failures:[...n.failures,...r.failures],triggeredAutomations:n.triggeredAutomations===!0||r.triggeredAutomations===!0}),{success:!0,tags:t.tags,requested:0,matched:0,updated:0,unchanged:0,failed:0,notFound:{emails:[],externalIds:[],subscriberIds:[]},failures:[],triggeredAutomations:!1})}function $Qe(e,t){if(console.log(`${t==="add"?"Added":"Removed"} tags: ${e.tags.join(", ")}`),console.log(`Requested: ${e.requested}`),console.log(`Matched existing subscribers: ${e.matched}`),console.log(`Changed: ${e.updated}`),console.log(`Already in target state: ${e.unchanged}`),console.log(`Failed: ${e.failed}`),t==="add")console.log(`Tag automations: ${e.triggeredAutomations?"enabled":"skipped"}`);let n=[...e.notFound.emails,...e.notFound.externalIds,...e.notFound.subscriberIds];if(n.length>0){console.log(`Not found (not created): ${n.length}`);for(let r of n.slice(0,10))console.log(`- ${r}`);if(n.length>10)console.log(`...and ${n.length-10} more`)}for(let r of e.failures.slice(0,10))console.log(`- ${r.email??r.subscriberId}: ${r.error}`);if(e.failures.length>10)console.log(`...and ${e.failures.length-10} more failures`)}async function BR(e,t){if(!await j())T(z()),process.exit(1);try{let n=OQe(t,e),r=[];for(let o of n)r.push(await E("POST",`/api/v1/subscribers/bulk/tags/${e}`,o,t.company));let i=NQe(r);if(t.json){w({...i,requests:n.length});return}$Qe(i,e)}catch(n){T(n instanceof g?n:n),process.exit(1)}}import{randomUUID as PQe}from"node:crypto";var kR="/api/v1/subscribers/operations";async function WI(e,t){if(e!=="start"&&e!=="list"&&!t.id)throw Error("Operation ID is required");let n=t.id?`${kR}/${encodeURIComponent(t.id)}`:kR;if(e==="list"){let o=await E("GET",kR,void 0,t.company);if(t.json)w(o);else for(let c of o.operations)mZ(c);return}let r;if(e==="start"){if(t.kind!=="add_tags")throw Error("--kind must be add_tags");let o=t.audienceJson?JSON.parse(Dn(t.audienceJson.startsWith("@")?void 0:t.audienceJson,t.audienceJson.startsWith("@")?t.audienceJson.slice(1):void 0,"audience-json")??"{}"):{},c=t.requestKey??PQe();kl(`Request key: ${c}. If the request is interrupted, retry with --request-key ${c}.`,{json:t.json,type:"recovery",requestKey:c}),r={kind:t.kind,requestKey:c,audience:o,...t.tag!==void 0&&{tags:t.tag},...t.triggerAutomations!==void 0&&{triggerAutomations:t.triggerAutomations}}}let i=await E(e==="get"?"GET":"POST",e==="cancel"?`${n}/cancel`:n,r,t.company);if(t.json)w(i);else mZ(i.operation)}function mZ(e){console.log(`${e.id} ${e.kind} ${e.status} ${e.processed}/${e.total} processed, ${e.failed} failed`);for(let t of e.failures)console.log(`${t.subscriberId}: ${t.error}`);if(e.error)console.log(e.error)}function QQe(e){if(typeof e!=="object"||e===null)return null;let t=e;if(t.sequenceTriggersRan!==!1||t.sequenceTriggersSkippedReason!=="missing_scope")return null;return(Array.isArray(t.warnings)?t.warnings.find((r)=>typeof r==="string"&&r.trim()!==""):void 0)??"No sequences were started: this API key is missing the automations:trigger scope."}function $m(e,t={}){if(t.json)return;let n=QQe(e);if(n)kl(`Warning: ${n}`,{warn:!0})}function RR(e,t){let n={...Ku("--attrs-json",t),...e};return Object.keys(n).length>0?n:void 0}function qQe(e){let t=e.isArray?`${e.valueType} list`:e.valueType,n=e.mixedTypes?`${t}, mixed types`:t,r=e.sampleValue===null?"":` e.g. ${e.sampleValue}`;return`${e.key} (${n})${r}`}async function fZ(e){let t=e.includeNested?"?includeNested=true":"",n=await E("GET",`/api/v1/subscribers/attributes${t}`,void 0,e.company);if(e.json){w(n);return}if(n.attributes.length===0){console.log("No custom attributes yet.");return}for(let i of n.attributes)console.log(qQe(i));let r=n.sampledContacts>0?`Types and examples come from ${n.sampledContacts} recent contacts.`:"Types and examples come from the account's attribute index.";console.log(`
|
|
504
504
|
${r} Set typed values with --attrs-json, e.g. --attrs-json '{"zip":"02134","seats":5}'.`)}var gZ=25;function YI(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function FQe(e){let t=e.trim();if(!t)throw new g("Events import file is empty",400);let n;try{n=JSON.parse(t)}catch(l){throw new g(`Invalid events import JSON: ${l instanceof Error?l.message:"Unknown error"}`,400)}let r=Array.isArray(n)?n:YI(n)&&Array.isArray(n.events)?n.events:null;if(!r||r.length===0)throw new g("Events import JSON must be a non-empty array or an object with an events array",400);if(r.length>gZ)throw new g(`Events import accepts at most ${gZ} events per request - split the file and send multiple requests`,400);let i=new Set(["email","externalId","name","properties","occurredAt","eventId"]),o=new Set,c=r.map((l,d)=>{if(!YI(l))throw new g(`Event ${d+1} must be an object`,400);if(!(typeof l.name==="string"&&l.name.trim()!==""))throw new g(`Event ${d+1} must include a name`,400);let A=typeof l.email==="string"&&l.email.trim()!=="",y=typeof l.externalId==="string"&&l.externalId.trim()!=="";if(!A&&!y)throw new g(`Event ${d+1} must include an email or an externalId`,400);if(!(typeof l.eventId==="string"&&l.eventId.trim()!==""))throw new g(`Event ${d+1} must include a non-empty eventId so retries are safe`,400);if(l.properties!==void 0&&l.properties!==null&&!YI(l.properties))throw new g(`Event ${d+1} properties must be an object`,400);for(let v of["email","externalId","occurredAt","eventId"]){let k=l[v];if(k!==void 0&&k!==null&&typeof k!=="string")throw new g(`Event ${d+1} ${v} must be a string`,400)}for(let v of Object.keys(l))if(!i.has(v))o.add(v);return{...A?{email:l.email}:{},...y?{externalId:l.externalId}:{},name:l.name,...YI(l.properties)?{properties:l.properties}:{},...typeof l.occurredAt==="string"&&l.occurredAt.trim()?{occurredAt:l.occurredAt}:{},eventId:l.eventId.trim()}});if(o.size>0)kl(`Ignoring unrecognized event field(s): ${[...o].sort().join(", ")}. Put row data inside "properties" to keep it.`,{warn:!0});return c}async function AZ(e){if(e.eventsJson&&e.file)throw new g("Provide either the positional JSON file or --events-json, not both",400);let t=e.file?Dn(void 0,e.file,"events import"):e.eventsJson;if(t===void 0)throw new g("Provide a JSON file or --events-json",400);let n=FQe(t),r=await E("POST","/api/v1/subscribers/events/imports",{events:n},e.company);if(!r.success)process.exitCode=1;if(e.json){w(r);return}console.log(`Events: ${r.total}`),console.log(`Recorded: ${r.recorded}`),console.log(`Duplicates: ${r.duplicates}`),console.log(`Failed: ${r.failed}`),console.log(`Side-effect failures: ${r.sideEffectFailed??0}`),console.log(`Subscribers: ${r.subscribers}`),$m(r);for(let i of r.failures??[])console.log(` events[${i.index}]: ${i.error}`);for(let i of r.sideEffectFailures??[])console.log(` events[${i.index}] recorded, but ${i.stages.join(", ")} failed${i.error?`: ${i.error}`:""}`);if(!r.success)console.log("Some receipts or downstream stages still need recovery. Fix request-level row errors, then retry the same file: eventId prevents a second receipt and downstream work is re-attempted idempotently.")}import{basename as LQe}from"node:path";var UQe=new Set(["skip","merge","overwrite"]),MQe=new Set(["default","confirmed","double_opt_in"]);function bZ(e){if(!e)return[];let t=[`List check: ${e.status.replaceAll("_"," ")}`];if(e.message)t.push(` ${e.message}`);if(e.cleaningUrl)t.push(` Clean the list: ${e.cleaningUrl}`);return t}function hZ(e){return Object.entries(e??{}).filter(([,n])=>n>0).sort(([,n],[,r])=>r-n).map(([n,r])=>`${n}=${r}`).join(", ")}function TR(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jQe(e){let t=e.trim();if(/^(true|false)$/i.test(t))return t.toLowerCase()==="true";if(/^-?(?:\d+|\d*\.\d+)$/.test(t)){let n=Number(t);if(!/^-?0\d/.test(t)&&Number.isFinite(n)&&Math.abs(n)<=Number.MAX_SAFE_INTEGER)return n}return t}function yZ(e){return e.trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function OR(e,t){let n=new Set(t.map(yZ)),r=e.findIndex((i)=>n.has(yZ(i)));return r===-1?void 0:r}function ds(e,t){return t===void 0?"":e[t]?.trim()??""}function zQe(e){let t=Array.isArray(e)?e:TR(e)&&Array.isArray(e.subscribers)?e.subscribers:null;if(!t||t.length===0)throw new g("Subscriber import JSON must be a non-empty array or an object with a subscribers array",400);return t.map((n,r)=>{let i=TR(n)&&typeof n.email==="string"&&n.email.trim()!=="",o=TR(n)&&typeof n.phone==="string"&&n.phone.trim()!=="";if(!i&&!o)throw new g(`Subscriber import record ${r+1} must include an email or a phone number`,400);return n})}function GQe(e){let t=e.trim();if(!t)throw new g("Subscriber import file is empty",400);if(t.startsWith("[")||t.startsWith("{"))try{return{subscribers:zQe(JSON.parse(t))}}catch(V){if(V instanceof g)throw V;throw new g(`Invalid subscriber import JSON: ${V instanceof Error?V.message:"Unknown error"}`,400)}let{headers:n,data:r}=xH(e),i=Ju(n,"email"),o=Ju(n,"externalId"),c=Ju(n,"firstName"),l=Ju(n,"lastName"),d=Ju(n,"fullName"),m=Ju(n,"timezone"),A=OR(n,["phone","phone number","mobile"]),y=OR(n,["status","email status"])??$H(n,r),b=PH(n),v=OR(n,["tags","tag"]),k=new Set([i,o,c,l,d,m,A,y,b,v].filter((V)=>V!==void 0));if(i===void 0&&A===void 0)throw new g("CSV must include an email or phone column",400);let _=y!==void 0||b!==void 0,O=[],U=new Set,re=r.map((V,G)=>{let H=ds(V,i);if(!H&&!ds(V,A))throw new g(`CSV row ${G+2} is missing an email and a phone number`,400);let be=BH(ds(V,d)),ve=ds(V,c)||be.firstName,ae=ds(V,l)||be.lastName,me=ds(V,y),He=TH({...y!==void 0&&{status:me},...b!==void 0&&{unsubscribeDate:ds(V,b)}});if(O.push(He),!He.recognized&&me)U.add(me);let gn=OH(He.status),et={};n.forEach((Bt,on)=>{let Qt=ds(V,on);if(!k.has(on)&&Bt.trim()&&Qt)et[Bt.trim()]=jQe(Qt)});let lt=ds(V,v).split(/[|;,]/).map((Bt)=>Bt.trim()).filter(Boolean),Wt=ds(V,o),xe=ds(V,A),rn=ds(V,m);return{...H&&{email:H},...Wt&&{externalId:Wt},...ve&&{firstName:ve},...ae&&{lastName:ae},...xe&&{phone:xe},...rn&&{timezone:rn},...gn&&{status:gn},...lt.length>0&&{tags:lt},...Object.keys(et).length>0&&{customAttributes:et}}});if(!_)return{subscribers:re};return{subscribers:re,statusSummary:NH(O),unrecognizedStatusValues:[...U].slice(0,5)}}function HQe(e){return[`${e.active} active`,`${e.unsubscribed} unsubscribed`,`${e.bounced} bounced`,...e.unrecognized>0?[`${e.unrecognized} unknown imported as active`]:[]].join(", ")}function JQe(e){let t=e.duplicateStrategy??"skip";if(!UQe.has(t))throw new g("--duplicate-strategy must be one of: skip, merge, overwrite",400);let n=e.optInMode??"default";if(!MQe.has(n))throw new g("--opt-in-mode must be one of: default, confirmed, double_opt_in",400);if(e.defaultPhoneCountry!==void 0&&!/^[a-z]{2}$/i.test(e.defaultPhoneCountry))throw new g("--default-phone-country must be a two-letter code",400)}async function vZ(e){if(JQe(e),e.recordsJson&&e.file)throw new g("Provide either the positional CSV/JSON file or --records-json, not both",400);let t=e.file?Dn(void 0,e.file,"subscriber import"):e.recordsJson;if(t===void 0)throw new g("Provide a CSV/JSON file or --records-json",400);let{subscribers:n,statusSummary:r,unrecognizedStatusValues:i}=GQe(t),o=Array.isArray(e.list)?e.list:e.list?[e.list]:[],c=await E("POST","/api/v1/subscribers/imports",{subscribers:n,duplicateStrategy:e.duplicateStrategy??"skip",fileName:e.fileName??(e.file?LQe(e.file):"CLI import"),...o.length>0&&{listIds:o},enrollInSequences:e.enrollSequences===!0,...e.defaultPhoneCountry&&{defaultPhoneCountry:e.defaultPhoneCountry.toUpperCase()},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...e.idempotencyKey!==void 0&&{idempotencyKey:e.idempotencyKey},optInMode:e.optInMode??"default"},e.company);if(e.json){w(r?{...c,statusSummary:r,...i?.length?{unrecognizedStatusValues:i}:{}}:c);return}if(r){if(console.log(`Statuses: ${HQe(r)}`),i?.length)console.log(` Unrecognized status values: ${i.join(", ")}`)}if(c.deduplicated){console.log(`Import already queued for this idempotency key: ${c.import.id}`),console.log(`Status: ${c.import.status}`),console.log(`Check progress: sequenzy subscribers import-status ${c.import.id}`);return}console.log(`Queued subscriber import: ${c.import.id}`),console.log(`Rows: ${c.import.totalRows}`),console.log(`Status: ${c.import.status}`);for(let l of bZ(c.import.listQuality))console.log(l);console.log(`Check progress: sequenzy subscribers import-status ${c.import.id}`)}async function EZ(e){let t=e.importId?.trim();if(!t)throw new g("Provide an import ID",400);let n=await E("GET",`/api/v1/subscribers/imports/${encodeURIComponent(t)}`,void 0,e.company);if(e.json){w(n);return}let r=n.import;console.log(`Subscriber import: ${r.id}`),console.log(`Status: ${r.status}`);for(let c of bZ(r.listQuality))console.log(c);console.log(`Processed: ${r.processedCount} of ${r.totalRows}`),console.log(`Added: ${r.addedCount}`),console.log(`Updated: ${r.updatedCount}`),console.log(`Skipped: ${r.skippedCount}`);let i=hZ(r.skippedReasons);if(i)console.log(` Skipped reasons: ${i}`);console.log(`Failed: ${r.failedCount}`);let o=hZ(r.failedReasons);if(o)console.log(` Failed reasons: ${o}`);if(r.status==="completed"&&r.failedCount>0)console.log("Completed with row failures; inspect --json for reason counts.")}function KQe(e){if(typeof e!=="object"||e===null)return null;let t=e;if(t.historical!==!0)return null;return{duplicates:typeof t.duplicates==="number"?t.duplicates:0}}function VQe(e){if(typeof e!=="object"||e===null)return!1;return e.duplicate===!0}function WQe(e){if(typeof e!=="object"||e===null)return null;let t=e.accountIgnored;if(typeof t!=="object"||t===null)return null;let n=t.message;return typeof n==="string"?n:null}function YQe(e){if(typeof e!=="object"||e===null)return[];let t=e.sideEffectFailures;return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function QR(e){if(!e)return[];return Array.isArray(e)?e:[e]}function wZ(e){if(!e)return[];return Array.isArray(e)?e:[e]}function ZI(e){let t={};for(let n of e??[]){let[r,...i]=n.split("="),o=i.join("=");if(r&&o)t[r]=o}return Object.keys(t).length>0?t:void 0}function SZ(e){let t=e.email?.trim()||void 0,n=e.externalId?.trim()||void 0;return{...t?{email:t}:{},...n?{externalId:n}:{}}}function Sd(e){let t=SZ(e);if(!t.email&&!t.externalId)throw Error("Provide an email or --external-id.");return t}function qR(e,t){let n=new URLSearchParams;if(t?.includeBots)n.set("includeMachineEngagement","true");let r=n.toString(),i=r?`?${r}`:"";if(e.email)return`/api/v1/subscribers/${encodeURIComponent(e.email)}${i}`;return n.set("externalId",String(e.externalId)),`/api/v1/subscribers/external?${n.toString()}`}function DZ(e){if(e.email)return`/api/v1/subscribers/${encodeURIComponent(e.email)}/notes`;let t=new URLSearchParams;return t.set("externalId",String(e.externalId)),`/api/v1/subscribers/external/notes?${t.toString()}`}var IZ=["is","contains","gt","gte","lt","lte","is_not_empty"];function ZQe(e){let t=e.attribute?.trim(),n=e.attributeValue,r=e.attributeOperator?.trim().toLowerCase();if(!t){if(n!==void 0||r)throw new g("--attribute-value and --attribute-operator require --attribute",400);return{}}if(r&&!IZ.includes(r))throw new g(`--attribute-operator must be one of ${IZ.join(", ")}. Create a segment for is_not, not_contains, or is_empty filters.`,400);let i=r||"is",o;if(n!==void 0)o=`${t}:${n}`;else if(t.includes(":"))o=t;else if(i==="is_not_empty")o=`${t}:`;else throw new g(`Provide --attribute-value (or --attribute "name:value") when --attribute-operator is ${i}. Only is_not_empty may omit a value.`,400);return{attribute:o,attributeOperator:i}}function XQe(e){let t=new URLSearchParams;if(e.segment)t.set("segmentId",e.segment);if(e.status?.trim())t.set("status",e.status.trim());if(e.unsubscribedAfter?.trim())t.set("unsubscribedAfter",e.unsubscribedAfter.trim());if(e.unsubscribedBefore?.trim())t.set("unsubscribedBefore",e.unsubscribedBefore.trim());if(e.attribute?.trim())t.set("attribute",e.attribute.trim());if(e.attributeOperator?.trim())t.set("attributeOperator",e.attributeOperator.trim());let n=QR(e.tag);if(n.length>0)t.set("tags",n.join(","));let r=wZ(e.list);if(r.length>0&&r[0])t.set("list",r[0]);if(e.attribute){if(t.set("attribute",e.attribute),e.attributeOperator)t.set("attributeOperator",e.attributeOperator)}if(e.cursor)t.set("cursor",e.cursor);else t.set("page",String(e.page));return t.set("limit",String(e.pageSize)),t}var NR=1000,$R=1000,PR=NR*$R-1;function CZ(e){if(e>PR)throw new g(`--offset must be ${PR} or less. Use --cursor to continue beyond that point.`,400);return e}function eqe(e){let t=nt(e.offset,"--offset"),n=nt(e.page,"--page");if(e.cursor?.trim()){if(t!==void 0||n!==void 0)throw new g("--cursor cannot be combined with --offset or --page. Keep following pagination.nextCursor instead.",400);return 0}if(t!==void 0&&n!==void 0)throw new g("Provide either --offset or --page, not both",400);if(t!==void 0&&t<0)throw new g("--offset must be zero or greater",400);if(n!==void 0){if(n<1)throw new g("--page must be 1 or greater",400);let r=_Z(e.limit);if(r===void 0)throw new g("--page requires --limit so the page size is defined. Omit both to fetch every match.",400);return CZ((n-1)*r)}return CZ(t??0)}function _Z(e){let t=nt(e,"--limit");if(t!==void 0&&t<1)throw new g("--limit must be 1 or greater",400);return t}async function tqe(e){let t=_Z(e.limit),n=eqe(e),r=t===void 0?void 0:n+t,i=Math.min(NR,Math.max(1,r??NR)),o=ZQe(e),c=[],l=1,d=e.cursor?.trim()||void 0,m,A=null,y=0,b=!1,v=!1;while(!0){let V=r===void 0?void 0:r-c.length,G=d?Math.min(i,Math.max(1,V??i)):i,H=XQe({segment:e.segment,tag:e.tag,list:e.list,status:e.status,unsubscribedAfter:e.unsubscribedAfter,unsubscribedBefore:e.unsubscribedBefore,attribute:o.attribute,attributeOperator:o.attributeOperator,page:l,pageSize:G,cursor:d}),be=await E("GET",`/api/v1/subscribers?${H.toString()}`,void 0,e.company);if(y===0)A=be.pagination?.total??null;y+=1,c.push(...be.subscribers??[]);let ve=(be.subscribers??[]).length,ae=be.pagination?.nextCursor??void 0;m=ae;let me=r!==void 0&&c.length>=r,He;if(ae)He=!1;else if(be.pagination?.hasMore!==void 0)He=!be.pagination.hasMore;else if(be.pagination?.totalPages!==void 0&&be.pagination.totalPages!==null)He=l>=be.pagination.totalPages;else He=ve<G;if(He||ve===0&&!ae){b=!0;break}if(me)break;if(y>=$R){v=!0;break}if(ae)d=ae;else if(d)break;else l+=1}let k=Boolean(e.cursor?.trim());if(v&&(c.length<n||c.length===n&&m===void 0))throw new g(`Could not reach offset ${n} within ${$R} requests because too few matches were returned per page. Start without --offset and follow pagination.nextCursor instead.`,400);if(A===null&&b&&!k)A=c.length;let _=c.slice(n,r),O=b?!1:A!==null?n+_.length<A:!b||c.length>n+_.length,U=m!==void 0&&c.length===n+_.length,re=n+_.length;return{success:!0,subscribers:_,pagination:{page:t===void 0?1:Math.floor(n/t)+1,limit:t??i,offset:n,total:A,totalPages:A===null?null:Math.ceil(A/(t??i)),fetchedPages:y,hasMore:O,nextOffset:O&&!k&&re<=PR?re:null,nextCursor:O&&U?m??null:null},returned:_.length,truncated:O}}function xZ(e){let t=[e.firstName,e.lastName].map((n)=>n?.trim()).filter((n)=>!!n);return t.length>0?t.join(" "):null}function nqe(e){let t=e.machine===!0?` [bot:${e.engagementQuality??"machine"}]`:"",n=`${te(e.eventTime)} ${e.eventType}${t}`;if(e.eventType==="custom"){let r=e.eventName??"unknown",i=e.properties&&Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:"";return`${n} ${r}${i}`}if(e.eventType.startsWith("sms_")){let r=[e.smsErrorCode?`error:${e.smsErrorCode}`:null,e.clickedUrl,e.campaignId?`campaign:${e.campaignId}`:null].filter((i)=>Boolean(i));return r.length>0?`${n} ${r.join(" ")}`:n}if(e.clickedUrl)return`${n} ${e.clickedUrl}`;if(e.bounceType)return`${n} ${e.bounceType}`;if(e.campaignId)return`${n} campaign:${e.campaignId}`;return n}function rqe(e){if(e.subscribers.length===0){console.log("No subscribers found");return}console.log(`Subscribers (${e.returned})`);let{offset:t,total:n,nextOffset:r,nextCursor:i}=e.pagination,o=t>0?`Showing ${e.returned} matching subscribers starting at offset ${t}`:`Showing ${e.returned} matching subscribers`;if(e.truncated){let c=n===null?"":` of ${n}`,l=i?`--cursor ${i}`:`--offset ${r}`;console.log(`${o}${c}. Re-run with ${l} for the next page.`)}else console.log(`${o}. Fetched across ${e.pagination.fetchedPages} page(s).`);for(let c of e.subscribers){if(console.log(`- ${kZ(c)} [${c.status}]`),c.externalId)console.log(` External ID: ${c.externalId}`);let l=xZ(c);if(l)console.log(` Name: ${l}`);if(c.tags.length>0)console.log(` Tags: ${c.tags.join(", ")}`);if(c.emailProvider)console.log(` Email provider: ${c.emailProvider}`);if(console.log(` Created: ${te(c.createdAt)}`),c.unsubscribedAt)console.log(` Unsubscribed: ${te(c.unsubscribedAt)}`)}}function BZ(e){if(console.log(`Notes (${e.length})`),e.length===0){console.log(" None");return}for(let t of e){let n=t.author?.name??t.author?.email??t.authorId??"Unknown";console.log(` - ${t.id} by ${n} at ${te(t.createdAt)}`);for(let r of t.body.split(`
|
|
505
505
|
`))console.log(` ${r}`)}}function kZ(e){return e.email||e.phone||(e.externalId?`external:${e.externalId}`:e.id)}function iqe(e){if(console.log(`Subscriber: ${kZ(e)}`),console.log(`Status: ${e.status}`),e.unsubscribedAt)console.log(`Unsubscribed: ${te(e.unsubscribedAt)}`);if(e.externalId)console.log(`External ID: ${e.externalId}`);let t=xZ(e);if(t)console.log(`Name: ${t}`);if(e.timezone)console.log(`Timezone: ${e.timezone}`);if(console.log(`ID: ${e.id}`),console.log(`Created: ${te(e.createdAt)}`),console.log(`Updated: ${te(e.updatedAt)}`),console.log(`Email provider: ${e.emailProvider??"None"}`),console.log(`Tags: ${e.tags.length>0?e.tags.join(", "):"None"}`),BZ(e.notes??[]),console.log("Lists:"),(e.lists?.length??0)===0)console.log(" None");else for(let n of e.lists??[])console.log(` - ${n.name}${n.unsubscribedAt?" [inactive]":" [active]"}`),console.log(` Joined: ${te(n.subscribedAt)}${n.unsubscribedAt?` | Unsubscribed: ${te(n.unsubscribedAt)}`:""}`);if(console.log("Sequence Enrollments:"),(e.sequenceEnrollments?.length??0)===0)console.log(" None");else for(let n of e.sequenceEnrollments??[])if(console.log(` - ${n.sequenceName} [${n.enrollmentStatus}]`),console.log(` Sequence ID: ${n.sequenceId} | Status: ${n.sequenceStatus}`),console.log(` Current node: ${n.currentNodeLabel??n.currentNodeType??"Unknown"}`),console.log(` Entered: ${te(n.enteredAt)} | Updated: ${te(n.updatedAt)}`),n.scheduledFor)console.log(` Scheduled: ${te(n.scheduledFor)}`);if(console.log("Email Stats:"),!e.emailStats)console.log(" None");else console.log(` Sent ${e.emailStats.sent}, delivered ${e.emailStats.delivered}, opened ${e.emailStats.opened}, clicked ${e.emailStats.clicked}, bounced ${e.emailStats.bounced}, unsubscribed ${e.emailStats.unsubscribed}, complained ${e.emailStats.complained}`);if(console.log("Recent Activity:"),(e.activity?.length??0)===0)console.log(" None");else for(let n of e.activity??[])console.log(` - ${nqe(n)}`);if(console.log("Custom Attributes:"),!e.customAttributes||Object.keys(e.customAttributes).length===0)console.log(" None");else console.log(JSON.stringify(e.customAttributes,null,2))}async function oqe(e){let t=await tqe(e);if(e.json){w(t);return}rqe(t)}async function sqe(e){if(e.enrollSequences&&e.skipSequences)throw Error("Provide either --enroll-sequences or --skip-sequences, not both.");let t=e.phone?.trim();if(e.phoneCountry!==void 0&&!t)throw Error("--phone-country only says how to read a national-format number. Pass it together with --phone.");let n=t?SZ(e):Sd(e),r=wZ(e.list),i=await E("POST","/api/v1/subscribers",{...n,...t?{phone:t}:{},...e.phoneCountry!==void 0?{phoneCountry:e.phoneCountry}:{},...e.smsConsent?{smsConsent:!0}:{},firstName:e.firstName,lastName:e.lastName,...e.timezone!==void 0?{timezone:e.timezone.trim()||null}:{},tags:QR(e.tag),...e.noLists?{lists:[]}:r.length>0?{lists:r}:{},...e.enrollSequences?{enrollInSequences:!0}:e.skipSequences?{enrollInSequences:!1}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{},customAttributes:RR(ZI(e.attr),e.attrsJson)},e.company);if(e.json){w(i);return}if(console.log(`Added subscriber: ${n.email??(n.externalId?`external:${n.externalId}`:`phone:${t}`)}`),$m(i),e.createdAt!==void 0)console.log(e.enrollSequences?`Signup date recorded as ${e.createdAt}; matching sequence enrollment was enabled.`:`Signup date recorded as ${e.createdAt}; sequences were not enrolled.`)}async function aqe(e){let t=Sd(e),n=QR(e.tag),r=RR(ZI(e.attr),e.attrsJson);if(!(e.status!==void 0||e.firstName!==void 0||e.lastName!==void 0||e.timezone!==void 0||e.phone!==void 0||e.smsConsent!==void 0||n.length>0||r!==void 0))throw Error("Provide at least one of --status, --first-name, --last-name, --timezone, --phone, --sms-consent/--no-sms-consent, --tag, --attr, or --attrs-json.");if(e.phoneCountry!==void 0&&e.phone===void 0)throw Error("--phone-country only says how to read a national-format number. Pass it together with --phone.");let o=await E("PATCH",qR(t),{...e.status!==void 0&&{status:e.status},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.timezone!==void 0&&{timezone:e.timezone.trim()||null},...e.phone!==void 0&&{phone:e.phone},...e.phoneCountry!==void 0&&{phoneCountry:e.phoneCountry},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...n.length>0&&{tags:n},...r!==void 0&&{customAttributes:r},...e.merge&&r!==void 0?{customAttributesStrategy:"merge"}:{}},e.company);if(e.json){w(o);return}console.log(`Updated subscriber: ${t.email??`external:${t.externalId}`}`),$m(o)}async function cqe(e){let t=Sd(e),n=await E("GET",qR(t,{includeBots:e.includeBots}),void 0,e.company);if(e.json){w(n);return}iqe(n.subscriber)}async function lqe(e){let t=Sd(e),n=await E("GET",DZ(t),void 0,e.company);if(e.json){w(n);return}BZ(n.notes)}async function uqe(e){let t=Sd(e),n=e.body?.trim();if(!n)throw Error("--body is required.");let r=await E("POST",DZ(t),{body:n},e.company);if(e.json){w(r);return}console.log(`Added note: ${r.note.id}`)}async function dqe(e){let t=e.noteId?.trim();if(!t)throw Error("Provide a note ID.");let n=await E("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(t)}`,void 0,e.company);if(e.json){w(n);return}console.log(`Deleted note: ${t}`)}async function pqe(e){let t=Sd(e),n=qR(t),r=t.email??`external:${t.externalId}`;if(e.hard){let o=await E("DELETE",n,void 0,e.company);if(e.json){w(o);return}console.log(`Deleted subscriber: ${r}`);return}let i=await E("PATCH",n,{status:"unsubscribed"},e.company);if(e.json){w(i);return}console.log(`Unsubscribed: ${r}`)}async function mqe(e){let t=Sd(e),n=e.name?.trim();if(!n)throw Error("--name is required.");if(e.account!==void 0&&e.organization!==void 0)throw Error("Provide either --account or --organization, not both.");let r=e.account??e.organization;if(r!==void 0&&e.accountJson!==void 0)throw Error(e.organization!==void 0?"Provide either --organization or --account-json, not both.":"Provide either --account or --account-json, not both.");let i=r;if(e.accountJson!==void 0){try{i=JSON.parse(e.accountJson)}catch{throw Error("--account-json must be a JSON object with externalId.")}if(typeof i!=="object"||i===null||Array.isArray(i)||!("externalId"in i)||typeof i.externalId!=="string"||!i.externalId.trim())throw Error("--account-json must be a JSON object with externalId.")}else if(typeof i==="string"&&!i.trim())throw Error("--account must be a non-empty account external ID.");let o=await E("POST","/api/v1/subscribers/events",{...t,event:n,...i!==void 0?{account:i}:{},properties:ZI(e.property),customAttributes:ZI(e.attr),...e.occurredAt!==void 0?{occurredAt:e.occurredAt}:{},...e.eventId!==void 0?{eventId:e.eventId}:{}},e.company);if(e.json){w(o);return}let c=t.email??`external:${t.externalId}`,l=WQe(o);if(l)console.warn(`Warning: ${l}`);$m(o);let d=KQe(o);if(d){console.log(d.duplicates>0?`Already recorded: ${n} for ${c} (no duplicate written)`:`Recorded historical event: ${n} for ${c} (no sequences enrolled)`);return}if(VQe(o)){console.log(`Already recorded: ${n} for ${c} (no duplicate written)`);return}let m=YQe(o);if(m.length>0){console.log(`Event recorded with side-effect failures: ${m.join(", ")}`);return}console.log(`Triggered event: ${n} for ${c}`)}async function yo(e,t){if(!await j())T(z()),process.exit(1);try{switch(e){case"list":await oqe(t);return;case"add":await sqe(t);return;case"update":await aqe(t);return;case"attributes":await fZ(t);return;case"get":await cqe(t);return;case"notes:list":await lqe(t);return;case"notes:add":await uqe(t);return;case"notes:delete":await dqe(t);return;case"import":await vZ(t);return;case"import:get":await EZ(t);return;case"events:import":await AZ(t);return;case"event":await mqe(t);return;case"remove":await pqe(t);return}}catch(n){let r=n instanceof g?n:new g(n instanceof Error?n.message:"Unknown error",500);T(r),process.exit(1)}}function fqe(e){let t=new URLSearchParams;if(e.search)t.set("search",e.search);if(e.page)t.set("page",e.page);if(e.limit)t.set("limit",e.limit);if(e.sort)t.set("sort",e.sort);if(e.order)t.set("order",e.order);return`/api/v1/suppressions${t.size>0?`?${t}`:""}`}function gqe(e){if(e.suppressions.length===0)return["No suppressed recipients found."];let t=e.suppressions.map((r)=>{let i=r.reason==="complaint"?"complaint":r.scope==="global"?"global":"workspace",o=r.reason==="complaint"?"reported as spam":r.bounceSubType??r.bounceType??"bounced",c=r.delistable?"":" (protected)";return`${r.email} [${i}] ${o} ${te(r.suppressedAt)}${c}`}),n=e.sortBy?` Sorted by ${e.sortBy} ${e.sortOrder??"desc"}.`:"";if(t.push(`
|
|
506
|
-
Showing ${e.suppressions.length} of ${e.total} (page ${e.page}).${n}`),e.hasMore)t.push(`Use --page ${e.page+1} for more.`);return t}function Aqe(e,t){let n=new URLSearchParams;if(t)n.set("region",t);return`/api/v1/suppressions/${encodeURIComponent(e)}${n.size>0?`?${n}`:""}`}function hqe(e){return[`Recipient: ${e.email}`,`Suppressed: ${e.suppressed?"Yes":"No"}`,`Associated with company: ${e.knownRecipient?"Yes":"No"}`,`Local suppression: ${e.local.suppressed?`${e.local.suppressionType??e.local.reason??"unknown"} (${e.local.scope??"unknown scope"}, ${e.local.delistable?"removable":"protected"})`:"None"}`]}async function XI(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let i=await E("GET",fqe(t),void 0,t.company);if(t.json){w(i);return}for(let o of gqe(i))console.log(o);return}if(!t.email)throw new g("Recipient email is required",400);let n=Aqe(t.email,t.region);if(e==="get"){let i=await E("GET",n,void 0,t.company);if(t.json){w(i);return}for(let o of hqe(i.suppression))console.log(o);return}if(!await rt(`Remove the workspace soft-bounce escalation for ${t.email}? Global, complaint, and unsubscribe protections will be kept.`,t)){console.log("Aborted.");return}let r=await E("DELETE",n,void 0,t.company);if(t.json){w(r);return}if(console.log(r.removed?`Removed workspace soft-bounce escalation for ${r.email}.`:`No removable workspace soft-bounce escalation found for ${r.email}.`),r.reactivatedSubscriberIds.length>0)console.log(`Reactivated subscribers: ${r.reactivatedSubscriberIds.length}`);if(r.remainingSuppression.suppressed)console.log("The recipient remains suppressed by a protected global, complaint, or unsubscribe source.")}catch(n){T(n instanceof g?n:n),process.exit(1)}}function yqe(e){if(e.reset){if(e.rulesJson!==void 0||e.rulesFile!==void 0)throw new g("--reset cannot be combined with --rules",400);return{syncRules:null}}let t=$e(e.rulesJson,e.rulesFile,"rules");if(t===void 0)throw new g("Provide --rules-json, --rules-file, or --reset",400);if(!Array.isArray(t))throw new g("rules JSON must be an array of sync rules",400);return{syncRules:t}}function bqe(e){let t=[],n=e.conditions;if(!n)return t;if(n.requiresTags?.length)t.push(` Requires tags: ${n.requiresTags.join(", ")}`);if(n.requiresNotTags?.length)t.push(` Excluded tags: ${n.requiresNotTags.join(", ")}`);let r=n.purchasedProduct;if(r){let i=[];if(r.tags?.length)i.push(`tags ${r.tags.join("|")}`);if(r.collectionIds?.length)i.push(`collections ${r.collectionIds.join("|")}`);if(r.productTypes?.length)i.push(`types ${r.productTypes.join("|")}`);if(r.vendors?.length)i.push(`vendors ${r.vendors.join("|")}`);if(i.length>0)t.push(` Product match: ${i.join("; ")}`)}return t}function RZ(e){console.log(`Sync rules (${e.syncRules.length})${e.isDefault?" - platform defaults":""}`);for(let t of e.syncRules){let n=t.actions.addTags.length?`+${t.actions.addTags.join(", +")}`:"",r=t.actions.removeTags.length?`-${t.actions.removeTags.join(", -")}`:"",i=[n,r].filter(Boolean).join(" ")||"(no-op)";console.log(`- ${t.triggerEvent}: ${i}`);for(let o of bqe(t))console.log(o)}}async function FR(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="get"){let i=await E("GET","/api/v1/sync-rules",void 0,t.company);if(t.json){w(i);return}RZ(i);return}let n=yqe(t),r=await E("PUT","/api/v1/sync-rules",n,t.company);if(t.json){w(r);return}if(r.message)console.log(r.message);RZ(r)}catch(n){T(n instanceof g?n:n),process.exit(1)}}function vqe(e){let t=e.isSystem?" [system]":"";console.log(`- ${e.name} [${e.id}]${t}`),console.log(` Color: ${e.color??"Default"}`)}function Eqe(e){if(!e.name||e.name.trim()==="")throw new g("Tag name is required",400);return{name:e.name,...e.color!==void 0&&{color:e.color}}}async function Pm(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/tags",void 0,t.company);if(t.json){w(r);return}console.log(`Tags (${r.tags.length})`);for(let i of r.tags)vqe(i);return}if(e==="create"){let r=Eqe(t),i=await E("POST","/api/v1/tags",r,t.company);if(t.json){w(i);return}if(console.log(`Created tag: ${i.tag?.name??r.name}`),i.tag)console.log(`ID: ${i.tag.id}`),console.log(`Color: ${i.tag.color??"Default"}`);return}if(!t.tagId)throw new g("Tag ID is required",400);if(e==="update"){if(!t.color||t.color.trim()==="")throw new g("--color is required",400);let r=await E("PATCH",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,{color:t.color},t.company);if(t.json){w(r);return}if(console.log(`Updated tag: ${r.tag?.name??t.tagId}`),r.tag)console.log(`ID: ${r.tag.id}`),console.log(`Color: ${r.tag.color??"Default"}`);return}if(!await rt(`Delete tag ${t.tagId}? It will be removed from all subscribers.`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,void 0,t.company);if(t.json){w(n);return}console.log(`Deleted tag: ${t.tagId}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}var Iqe=new Set(["admin","marketer","viewer","restricted"]);function Cqe(e){if(!e.email||e.email.trim()==="")throw new g("Email is required",400);if(!e.role||!Iqe.has(e.role))throw new g("--role must be admin, marketer, viewer, or restricted",400);return{email:e.email.trim(),role:e.role,...e.billingAccess===!0&&{canManageBilling:!0}}}function wqe(e){let t=e.user.name?`${e.user.name} <${e.user.email}>`:e.user.email;if(console.log(`- ${t} [${e.id}]`),console.log(` Kind: ${e.kind}`),console.log(` Role: ${e.role}`),console.log(` Status: ${e.status}`),console.log(` Billing access: ${e.canManageBilling?"yes":"no"}`),e.invitedAt)console.log(` Invited: ${te(e.invitedAt)}`);if(e.expiresAt)console.log(` Expires: ${te(e.expiresAt)}`);if(e.invitedBy)console.log(` Invited by: ${e.invitedBy.name??e.invitedBy.email}`)}async function eC(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/team",void 0,t.company);if(t.json){w(r);return}console.log(`Team members (${r.members.length})`);for(let i of r.members)wqe(i);return}if(e==="invite"){let r=Cqe(t),i=await E("POST","/api/v1/team/invitations",r,t.company);if(t.json){w(i);return}if(i.invitation){console.log(`Invitation sent to ${i.invitation.email}`),console.log(`ID: ${i.invitation.id}`),console.log(`Role: ${i.invitation.role}`),console.log(`Billing access: ${i.invitation.canManageBilling?"yes":"no"}`),console.log(`Status: ${i.invitation.status}`),console.log(`Expires: ${te(i.invitation.expiresAt)}`);return}console.log(`Added team member: ${i.member?.email??r.email}`),console.log(`Role: ${i.member?.role??r.role}`),console.log(`Billing access: ${i.member?.canManageBilling?"yes":"no"}`);return}if(!t.invitationId)throw new g("Invitation ID is required",400);if(!await rt(`Cancel invitation ${t.invitationId}?`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/team/invitations/${encodeURIComponent(t.invitationId)}`,void 0,t.company);if(t.json){w(n);return}console.log(`Cancelled invitation: ${t.invitationId}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}function Qm(e,t,n){return`${e} ${e===1?t:n}`}function TZ(e){let t=e.upToDate+e.edited+e.outdated,n=[e.translating>0?`${e.translating} translating`:null,e.missing>0?`${e.missing} missing`:null,(e.failed??0)>0?`${e.failed} failed`:null,e.outdated>0?`${e.outdated} outdated`:null,e.edited>0?`${e.edited} edited`:null].filter((r)=>r!==null);return`${e.locale}: ${t}/${e.total} translated${n.length>0?` (${n.join(", ")})`:""}`}function Sqe(e){let t=e.queuedPushes??0;if(e.queuedEmails===0&&t===0)return"Nothing new to translate: every email and push is translated or already translating";return`Queued ${[e.queuedEmails>0?`${Qm(e.queuedTranslations,"translation","translations")} for ${Qm(e.queuedEmails,"email","emails")}`:null,t>0?`${Qm(e.queuedPushTranslations??t,"translation","translations")} for ${Qm(t,"push","pushes")}`:null].filter(Boolean).join(" and ")}: ${e.locales.join(", ")}`}async function LR(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="coverage"){let r=await E("GET","/api/v1/templates/localizations/coverage",void 0,t.company);if(t.json){w(r);return}if(console.log(`Emails: ${r.totalEmails} (${Qm(r.sequenceEmails,"sequence email","sequence emails")}, ${Qm(r.transactionalEmails,"transactional email","transactional emails")})`),console.log(`Primary locale: ${r.primaryLocale}`),r.locales.length===0){console.log("No translated languages configured");return}for(let i of r.locales)console.log(`- ${TZ(i)}`);if(r.push&&r.push.totalPushes>0){console.log(`Sequence pushes: ${r.push.totalPushes}`);for(let i of r.push.locales)console.log(`- ${TZ(i)}`)}return}let n=await E("POST","/api/v1/templates/localizations/translate-missing",{...t.locales!==void 0&&{locales:t.locales}},t.company);if(t.json){w(n);return}console.log(Sqe(n))}catch(n){T(n),process.exit(1)}}function OZ(e){if(e.length===0)return"none";return e.map((t)=>`${t.locale}:${t.status}${t.editedAt?" (edited)":""}`).join(", ")}function tC(e){return e&&e.length>0?e.join(", "):"None"}function nC(e){return e?"yes":"no"}function Dqe(e,t){if(e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&e.label===void 0&&e.template===void 0&&t.html===void 0&&t.blocks===void 0)throw new g("Provide at least one of: --name, --subject, --preview-text, --label, --template/--no-template, --html, --html-file, --blocks-json, --blocks-file",400);return{name:e.name,subject:e.subject,previewText:e.previewText,html:t.html,blocks:t.blocks,labels:e.label,...e.template!==void 0&&{isTemplate:e.template}}}function _qe(e,t){let n=e.subject?.trim();if(!n)throw new g("Localization subject is required",400);if(t.html===void 0&&t.blocks===void 0)throw new g("Provide localized content with --html, --html-file, --blocks-json, or --blocks-file",400);return{subject:n,previewText:e.previewText,html:t.html,blocks:t.blocks,...e.keepEdits===!0&&{keepEdits:!0}}}async function Ha(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.label)for(let v of t.label)c.append("label",v);if(t.templatesOnly)c.set("isTemplate","true");let l=nt(t.limit,"--limit");if(l!==void 0)c.set("limit",String(l));let d=nt(t.offset,"--offset");if(d!==void 0){if(d<0)throw new g("--offset must be zero or greater",400);c.set("offset",String(d))}let m=await E("GET",`/api/v1/templates${c.size>0?`?${c.toString()}`:""}`,void 0,t.company),A=ut({companyId:m.companyId}),y=m.templates.map((v)=>Qs(v,{emailId:v.id},"email",m.companyId));if(t.json){w({...m,templates:y,appUrls:A.urls});return}console.log(`Templates (${m.templates.length})`);let b=m.pagination;if(b?.hasMore){let v=b.offset+b.count;console.log(`Showing ${b.count} of ${b.total}. Re-run with --offset ${v} for the next page.`)}if(m.emailLocalizationConfig)console.log(`Primary locale: ${m.emailLocalizationConfig.primaryLocale}`);for(let v of y)console.log(`- ${v.name} [${v.id}]`),console.log(` Subject: ${v.subject}`),console.log(` Format: ${Ns(v.emailPreset)}`),console.log(` Labels: ${tC(v.labels)}`),console.log(` Reusable template: ${nC(v.isTemplate)}`),De(" URL",v.url),console.log(` Localizations: ${OZ(v.localizations)}`);return}let n=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile});if(e==="create"){if(!t.name)throw new g("Template name is required",400);let c=t.prompt?.trim()||void 0;if([c,n.html,n.blocks].filter((b)=>b!==void 0).length!==1)throw new g("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!c&&(t.style!==void 0||t.tone!==void 0))throw new g("--style and --tone require --prompt",400);if(!t.subject&&!c)throw new g("Template subject is required unless --prompt is provided",400);let d=await E("POST","/api/v1/templates",{name:t.name,subject:t.subject,previewText:t.previewText,prompt:c,style:t.style,tone:t.tone,html:n.html,blocks:n.blocks,labels:t.label,...t.template!==void 0&&{isTemplate:t.template}},t.company),m=await jt(t.company),A=d.template?.id??d.templateId,y=m!==void 0&&A!==void 0?ut({companyId:m,emailId:A}):void 0;if(t.json){w({...d,...d.template!==void 0&&y?.urls.email!==void 0&&{template:{...d.template,url:y.urls.email}},...y!==void 0&&{appUrls:y.urls}});return}$n(d),console.log(`Created template: ${d.template?.name??t.name}`),console.log(`ID: ${d.template?.id??"Unknown"}`),De("URL",y?.urls.email),console.log(`Labels: ${tC(d.template?.labels)}`),console.log(`Reusable template: ${nC(d.template?.isTemplate)}`),console.log(`Subject: ${d.template?.subject??t.subject??"Unknown"}`);return}if(!t.id)throw new g("Template ID is required",400);if(e==="set-localization"){if(!t.locale)throw new g("Localization locale is required",400);let c=await E("PUT",`/api/v1/templates/${t.id}/localizations/${encodeURIComponent(t.locale)}`,_qe(t,n),t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:c.templateId}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(`Set ${c.localization.locale} localization for template ${c.templateId}`),console.log(`Status: ${c.localization.status}`),console.log(`Subject: ${c.localization.subject}`),De("URL",d?.urls.email);return}if(e==="sync-localizations"){let c=await E("POST",`/api/v1/templates/${t.id}/localizations/sync`,{...t.locales!==void 0&&{locales:t.locales},...t.skipEdited===!0&&{skipEdited:!0}},t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:c.templateId}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}console.log(c.queuedLocales.length>0?`Queued ${c.queuedVariantCount} localization${c.queuedVariantCount===1?"":"s"}: ${c.queuedLocales.join(", ")}`:"Queued 0 localizations");let m=c.skippedLocales??[];if(m.length>0)console.log(`Kept ${m.length} edited localization${m.length===1?"":"s"}: ${m.join(", ")}`);De("URL",d?.urls.email);return}if(e==="update"){let c=await E("PUT",`/api/v1/templates/${t.id}`,Dqe(t,n),t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:t.id}):void 0;if(t.json){w({...c,...c.template!==void 0&&d?.urls.email!==void 0&&{template:{...c.template,url:d.urls.email}},...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(`Updated template: ${c.template?.name??t.id}`),console.log(`ID: ${c.template?.id??t.id}`),De("URL",d?.urls.email),console.log(`Labels: ${tC(c.template?.labels)}`),console.log(`Reusable template: ${nC(c.template?.isTemplate)}`),console.log(`Subject: ${c.template?.subject??"Unchanged"}`);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/templates/${t.id}`,void 0,t.company);if(t.json){w(c);return}console.log(c.message??`Deleted template: ${t.id}`);return}if(e==="share"){let c=await E("POST",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){w(c);return}console.log(c.created?"Public link created.":"Public link already active."),De("Share URL",c.shareUrl),console.log("Anyone with the link sees an anonymized copy - no subscriber data, no tracking.");return}if(e==="unshare"){let c=await E("DELETE",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){w(c);return}console.log(c.revoked?"Public link revoked. The old URL now returns 404.":"No public link to revoke.");return}let r=await E("GET",`/api/v1/templates/${t.id}`,void 0,t.company),i=ut({companyId:r.template.companyId,emailId:t.id});if(t.json){w({...r,template:{...r.template,url:i.urls.email},appUrls:i.urls});return}let o=r.template;if(console.log(o.name),console.log(`ID: ${o.id}`),console.log(`Company: ${o.companyId}`),De("URL",i.urls.email),o.shareUrl)De("Share URL",o.shareUrl);console.log(`Subject: ${o.subject}`),console.log(`Labels: ${tC(o.labels)}`),console.log(`Reusable template: ${nC(o.isTemplate)}`),console.log(`Preview: ${o.previewText??"None"}`),console.log(`Blocks: ${o.blocks.length}`),console.log(`Format: ${Ns(o.emailPreset)}`),console.log(`Font: ${o.fontFamily??"Default"}`),console.log(`Created: ${te(o.createdAt)}`),console.log(`Updated: ${te(o.updatedAt)}`),console.log(`Localizations: ${OZ(o.localizations)}`);for(let c of o.localizations){let l=c.lastError?` | error: ${c.lastError}`:"";console.log(`- ${c.locale} [${c.status}${c.editedAt?", edited":""}] blocks=${c.blocks.length}${l}`)}}catch(n){T(n instanceof g?n:n),process.exit(1)}}function xqe(e){if(!e){console.log("Tracking domain: none (links use the shared Sequenzy domain)");return}if(console.log(`Tracking domain: ${e.domain}`),console.log(` Status: ${e.status}`),console.log(` Links: ${e.active?e.domain:"shared Sequenzy domain until it verifies"}`),e.sslStatus)console.log(` SSL: ${e.sslStatus}`);if(e.error)console.log(` Error: ${e.error}`);if(!e.active)console.log(` DNS: ${e.cnameRecord.name} CNAME ${e.cnameRecord.value}`)}async function Bqe(e,t){if(!await j())T(z()),process.exit(1);try{let n;if(e==="show")n=await E("GET","/api/v1/tracking-domain",void 0,t.company);else if(e==="set"){let r=t.domain?.trim();if(!r)throw new g("Provide a tracking domain, like links.acme.com",400);n=await E("PUT","/api/v1/tracking-domain",{domain:r},t.company)}else if(e==="verify")n=await E("POST","/api/v1/tracking-domain/verify",void 0,t.company);else{if(!await rt("Remove the tracking domain? Links and images in emails already sent through it will stop working.",t)){console.log("Cancelled.");return}n=await E("DELETE","/api/v1/tracking-domain",void 0,t.company)}if(t.json){w(n);return}if(e==="remove"){console.log(n.removed?"Tracking domain removed. Links use the shared Sequenzy domain.":"No tracking domain was set.");return}if(n.message)console.log(n.message),console.log("");xqe(n.trackingDomain)}catch(n){T(n),process.exit(1)}}function NZ(e,t=Bqe){let n=(l)=>l.optsWithGlobals(),r=e.command("domain").description("Show the company tracking domain used by every sending domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").allowExcessArguments(!1).action((l,d)=>t("show",n(d)));S(r,{notes:["Every sending domain uses the company tracking domain for tracked links and opens. It never blocks sending: until it verifies, or when it breaks or is removed, links use the shared Sequenzy domain."],examples:["sequenzy tracking domain","sequenzy tracking domain set links.example.com","sequenzy tracking domain verify"]});let i=r.command("set <hostname>").description("Set or change the company tracking domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d,m)=>t("set",{...n(m),domain:l}));S(i,{notes:["Any subdomain you control works (it does not have to match a sending domain), for example links.example.com. Add the returned CNAME record.","Changing it keeps the previous hostname serving links in emails already sent, as long as its old CNAME stays in place."],examples:["sequenzy tracking domain set links.example.com"]});let o=r.command("verify").description("Check the company tracking domain's DNS and HTTPS now").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t("verify",n(d)));S(o,{examples:["sequenzy tracking domain verify"]});let c=r.command("remove").description("Remove the company tracking domain").option("-y, --yes","Skip the confirmation prompt").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t("remove",n(d)));return S(c,{notes:["Links and images in emails already sent through the tracking domain stop working. New emails use the shared Sequenzy domain."],examples:["sequenzy tracking domain remove --yes"]}),r}function UR(e,t,n){if(e!==void 0&&!n.includes(e))throw new g(`${t} must be one of: ${n.join(", ")}`,400)}function kqe(e){UR(e.status,"--status",["all","active","disabled"]),UR(e.sort,"--sort",["date","sends","opens","open-rate","clicks","ctr"]),UR(e.order,"--order",["asc","desc"]);let t=new URLSearchParams;for(let n of e.label??[])t.append("label",n);if(e.search?.trim())t.set("search",e.search.trim());if(e.status)t.set("status",e.status);if(e.sort)t.set("sort",e.sort);if(e.order)t.set("order",e.order);if(e.includeBots)t.set("includeMachineEngagement","true");return t.size>0?`?${t.toString()}`:""}function Rqe(e,t){if(e.previewText!==void 0&&e.clearPreviewText===!0)throw new g("Use either --preview-text or --clear-preview-text, not both",400);if(e.label!==void 0&&e.clearLabels)throw new g("Use either --label or --clear-labels, not both",400);let n=e.clearPreviewText===!0?null:void 0;if(e.label===void 0&&!e.clearLabels&&e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&n===void 0&&e.enabled===void 0&&t.html===void 0&&t.blocks===void 0)throw new g("Provide at least one of: --name, --subject, --preview-text, --clear-preview-text, --enabled/--no-enabled, --label, --clear-labels, --html, --html-file, --blocks-json, --blocks-file",400);return{...e.label!==void 0&&{labels:e.label},...e.clearLabels&&{labels:[]},...e.name!==void 0&&{name:e.name},...e.subject!==void 0&&{subject:e.subject},...e.previewText!==void 0&&{previewText:e.previewText},...n===null&&{previewText:null},...e.enabled!==void 0&&{enabled:e.enabled},...t.html!==void 0&&{html:t.html},...t.blocks!==void 0&&{blocks:t.blocks}}}async function qm(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="create"){if(!t.name)throw new g("Transactional name is required",400);let i=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),o=t.prompt?.trim()||void 0;if([o,i.html,i.blocks].filter((A)=>A!==void 0).length!==1)throw new g("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!o&&!t.subject)throw new g("Transactional subject is required unless --prompt is provided",400);if(!o&&(t.style!==void 0||t.tone!==void 0))throw new g("--style and --tone require --prompt",400);let l=await E("POST","/api/v1/transactional",{name:t.name,...t.label!==void 0&&{labels:t.label},...t.slug!==void 0&&{slug:t.slug},...t.subject!==void 0&&{subject:t.subject},...t.previewText!==void 0&&{previewText:t.previewText},...o!==void 0&&{prompt:o},...t.style!==void 0&&{style:t.style},...t.tone!==void 0&&{tone:t.tone},...i.html!==void 0&&{html:i.html},...i.blocks!==void 0&&{blocks:i.blocks},...t.enabled!==void 0&&{enabled:t.enabled}},t.company),d=await jt(t.company),m=d?ut({companyId:d,transactionalId:l.transactional.id}).urls.transactionalEmail:void 0;if(t.json){w({...l,transactional:{...l.transactional,url:m},...m&&{appUrls:{transactionalEmail:m}}});return}$n(l),console.log(`Created transactional template: ${l.transactional.name}`),console.log(`ID: ${l.transactional.id}`),console.log(`Slug: ${l.transactional.slug}`),console.log(`Enabled: ${l.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${l.transactional.labels?.join(", ")||"None"}`),De("URL",m);return}if(e==="list"){let i=await E("GET",`/api/v1/transactional${kqe(t)}`,void 0,t.company),o=await jt(t.company),c=i.transactional.map((d)=>Qs(d,{transactionalId:d.id},"transactionalEmail",o)),l=ut({companyId:o});if(t.json){w({...i,transactional:c,appUrls:l.urls});return}console.log(`Transactional templates (${i.transactional.length})`);for(let d of c)console.log(`- ${d.name} [${d.slug}] ${d.enabled?"enabled":"disabled"}${d.managedBy==="code"?" · managed in code":""}`),console.log(` Subject: ${d.subject??"Unknown"}`),console.log(` Labels: ${d.labels?.join(", ")||"None"}`),console.log(` Format: ${Ns(d.emailPreset)}`),console.log(` Sends: ${d.stats.sends} · Opens: ${d.stats.opens} (${d.stats.openRate.toFixed(2)}%) · Clicks: ${d.stats.clicks} (${d.stats.clickRate.toFixed(2)}%)`),De(" URL",d.url);return}if(!t.slug)throw new g("Transactional template slug is required",400);if(e==="update"){let i=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),o=await E("PATCH",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,Rqe(t,i),t.company),c=await jt(t.company),l=c?ut({companyId:c,transactionalId:o.transactional.id}).urls.transactionalEmail:void 0;if(t.json){w({...o,transactional:{...o.transactional,url:l},...l&&{appUrls:{transactionalEmail:l}}});return}if($n(o),console.log(`Updated transactional template: ${o.transactional.name}`),console.log(`ID: ${o.transactional.id}`),console.log(`Slug: ${o.transactional.slug}`),console.log(`Enabled: ${o.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${o.transactional.labels?.join(", ")||"None"}`),o.transactional.subject)console.log(`Subject: ${o.transactional.subject}`);De("URL",l);return}if(e==="delete"){if(!await rt(`Delete transactional template ${t.slug}?`,t)){console.log("Aborted.");return}let i=await E("DELETE",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){w(i);return}if(console.log(`Deleted transactional template: ${i.deleted?.name??t.slug}`),console.log(`Slug: ${i.deleted?.slug??t.slug}`),i.deleted?.emailDeleted)console.log("Code-managed content snapshot deleted with it");else if(i.deleted?.emailId)console.log(`Email content kept as a template: ${i.deleted.emailId}`);return}let n=await E("GET",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){w(n);return}let r=n.transactional;if(console.log(r.name),console.log(`ID: ${r.id}`),console.log(`Slug: ${r.slug}`),console.log(`Enabled: ${r.enabled?"yes":"no"}`),r.managedBy==="code")console.log(`Managed in code: sends with --track-as ${r.slug}; content is a snapshot of a recent send`);if(r.subject)console.log(`Subject: ${r.subject}`);if(console.log(`Labels: ${r.labels?.join(", ")||"None"}`),console.log(`Format: ${Ns(r.emailPreset)}`),(r.variables?.length??0)>0)console.log(`Variables: ${r.variables?.join(", ")}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}import{readFileSync as Tqe}from"node:fs";var $Z=["snowflake","bigquery","redshift","postgres"],Oqe=["subscribers","events"],PZ=["every_15_minutes","hourly","daily","weekly","manual"],QZ=["confirmed","double_opt_in"],Vl="SEQUENZY_WAREHOUSE_PASSWORD";function Ni(e){T(new g(e,400)),process.exit(1)}function zA(e,t){if(!e||e.trim().length===0)Ni(`${t} is required.`);return e.trim()}function Fm(e,t,n){if(e===void 0)return;if(!t.includes(e))Ni(`Invalid ${n} "${e}". Use one of: ${t.join(", ")}.`);return e}function GA(e,t){try{return Tqe(e,"utf8")}catch{Ni(`Could not read ${t} file "${e}".`)}}function rC(e,t){let n;try{n=JSON.parse(e)}catch{Ni(`${t} must be valid JSON.`)}if(!n||typeof n!=="object"||Array.isArray(n))Ni(`${t} must be a JSON object.`);return n}function qZ(e){let t=e.configJson?rC(e.configJson,"--config-json"):{},n=[["account","account"],["username","username"],["warehouse","warehouse"],["database","database"],["schema","schema"],["role","role"],["projectId","projectId"],["location","location"],["host","host"],["sslMode","sslMode"]];for(let[r,i]of n){let o=e[r];if(typeof o==="string")t[i]=o}if(e.port!==void 0){let r=Number(e.port);if(!Number.isInteger(r))Ni("--port must be a number.");t.port=r}return t}function FZ(e,t="create"){let n=e.credentialsFile?rC(GA(e.credentialsFile,"--credentials-file"),"--credentials-file"):{};if(e.privateKeyFile)n.privateKey=GA(e.privateKeyFile,"--private-key-file");if(e.privateKeyPassphrase)n.privateKeyPassphrase=e.privateKeyPassphrase;if(e.serviceAccountFile)n.serviceAccountJson=GA(e.serviceAccountFile,"--service-account-file");let r=t==="create"||e.passwordFromEnv?process.env[Vl]:void 0;if(t==="update"&&e.passwordFromEnv&&!r)Ni(`--password-from-env needs ${Vl} to be set.`);let i=e.password??r;if(i)n.password=i;return Object.keys(n).length>0?n:void 0}function zR(e,t){if(e.query&&e.queryFile)Ni("Use either --query or --query-file, not both.");let n=e.queryFile?GA(e.queryFile,"--query-file"):e.query;if(t&&!n?.trim())Ni("--query or --query-file is required.");return n}function LZ(e){if(e.mappingJson&&e.mappingFile)Ni("Use either --mapping-json or --mapping-file, not both.");if(e.mappingFile)return rC(GA(e.mappingFile,"--mapping-file"),"--mapping-file");return e.mappingJson?rC(e.mappingJson,"--mapping-json"):void 0}function UZ(e){if(e===void 0)return;return e.split(",").map((t)=>t.trim()).filter(Boolean)}function MR(e){let t=e.config.host??e.config.account??e.config.projectId??"";if(console.log(`- ${e.name} (${e.provider}) ${String(t)}`),console.log(` id: ${e.id} | status: ${e.status} | syncs: ${e.syncCount??0} | tested: ${e.lastTestedAt??"never"}`),e.lastError)console.log(` last error: ${e.lastError}`)}function MZ(e){if(e.status==="running")return`running, ${e.rowsRead} rows read so far`;return`${e.status}: ${e.rowsRead} read, ${e.rowsSynced} synced, ${e.rowsUnchanged} unchanged, ${e.rowsSkipped} skipped, ${e.rowsFailed} failed`}function jR(e){let t=!e.isEnabled?"paused":e.status;if(console.log(`- ${e.name} (${e.kind})`),console.log(` id: ${e.id} | connection: ${e.connectionId} | ${e.frequency} | status: ${t}${e.cursorColumn?` | cursor: ${e.cursorColumn} >= ${e.cursorValue??"start"}`:""}`),console.log(` last success: ${e.lastSuccessAt??"never"} | next run: ${e.nextRunAt??"not scheduled"}`),e.latestRun)console.log(` latest run ${MZ(e.latestRun)}`);if(e.lastError)console.log(` last error: ${e.lastError}`)}async function jZ(){if(!await j())T(z()),process.exit(1)}function zZ(e){return(t,n)=>{if(e.json){console.log(JSON.stringify(t,null,2));return}n()}}async function Wl(e,t){await jZ();let n=zZ(t);try{if(e==="list"){let o=await E("GET","/api/v1/warehouse-connections",void 0,t.company);n(o,()=>{console.log(`Warehouse connections (${o.connections.length})`),o.connections.forEach(MR)});return}if(e==="create"){let o=Fm(t.provider,$Z,"--provider");if(!o)Ni(`--provider is required (${$Z.join(", ")}).`);let c=FZ(t);if(!c)Ni(`Provide credentials: --private-key-file (Snowflake), --service-account-file (BigQuery), ${Vl} or --password (Redshift/Postgres), or --credentials-file.`);let l=await E("POST","/api/v1/warehouse-connections",{name:zA(t.name,"--name"),provider:o,config:qZ(t),credentials:c},t.company);n(l,()=>{console.log(`Connected ${l.connection.name} (${l.connection.id}).`),console.log("The test query succeeded. Create a sync with `sequenzy warehouse syncs create`.")});return}let r=encodeURIComponent(zA(t.id,"<id>"));if(e==="get"){let o=await E("GET",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(o,()=>MR(o.connection));return}if(e==="update"){let o=qZ(t),c=FZ(t,"update"),l={...t.name!==void 0?{name:t.name}:{},...Object.keys(o).length>0?{config:o}:{},...c?{credentials:c}:{}};if(Object.keys(l).length===0)Ni("Nothing to update. Pass --name, connection settings or new credentials.");let d=await E("PATCH",`/api/v1/warehouse-connections/${r}`,l,t.company);n(d,()=>{console.log(`Updated ${d.connection.name}.`),MR(d.connection)});return}if(e==="delete"){if(!await rt(`Delete warehouse connection ${decodeURIComponent(r)}?`,t)){console.log("Cancelled.");return}let c=await E("DELETE",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(c,()=>console.log(`Deleted connection ${c.connectionId}.`));return}if(e==="test"){let o=await E("POST",`/api/v1/warehouse-connections/${r}/test`,void 0,t.company);n(o,()=>console.log(`Connection works (${o.connection.name}).`));return}let i=await E("POST",`/api/v1/warehouse-connections/${r}/preview`,{query:zR(t,!0)},t.company);n(i,()=>{console.log(`Columns: ${i.columns.map((o)=>`${o.name} (${o.type})`).join(", ")}`),console.log(`First ${i.rows.length} row(s):`);for(let o of i.rows)console.log(` ${JSON.stringify(o)}`)})}catch(r){T(r),process.exit(1)}}async function Yl(e,t){await jZ();let n=zZ(t);try{if(e==="list"){let c=t.connection?`?connectionId=${encodeURIComponent(t.connection)}`:"",l=await E("GET",`/api/v1/warehouse-syncs${c}`,void 0,t.company);n(l,()=>{console.log(`Warehouse syncs (${l.syncs.length})`),l.syncs.forEach(jR)});return}if(e==="create"){let c=LZ(t);if(!c)Ni("--mapping-json or --mapping-file is required.");let l=Fm(t.frequency,PZ,"--frequency"),d=Fm(t.optInMode,QZ,"--opt-in-mode"),m=UZ(t.lists),A=await E("POST","/api/v1/warehouse-syncs",{connectionId:zA(t.connection,"--connection"),name:zA(t.name,"--name"),kind:Fm(t.kind,Oqe,"--kind")??"subscribers",query:zR(t,!0),mapping:c,...t.cursorColumn?{cursorColumn:t.cursorColumn}:{},...l?{frequency:l}:{},...m?{listIds:m}:{},...d?{optInMode:d}:{},...t.triggerAutomations?{triggerAutomations:!0}:{}},t.company);n(A,()=>{console.log(`Created sync ${A.sync.name} (${A.sync.id}).`),console.log(`The first run is starting. Follow it with \`sequenzy warehouse syncs runs ${A.sync.id}\`.`)});return}let r=encodeURIComponent(zA(t.id,"<id>"));if(e==="get"){let c=await E("GET",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(c,()=>jR(c.sync));return}if(e==="update"){let c={};if(t.name!==void 0)c.name=t.name;let l=zR(t,!1);if(l!==void 0)c.query=l;let d=LZ(t);if(d)c.mapping=d;if(t.cursorColumn!==void 0)c.cursorColumn=t.cursorColumn===""?null:t.cursorColumn;let m=Fm(t.frequency,PZ,"--frequency");if(m)c.frequency=m;let A=UZ(t.lists);if(A)c.listIds=A;let y=Fm(t.optInMode,QZ,"--opt-in-mode");if(y)c.optInMode=y;if(t.triggerAutomations!==void 0)c.triggerAutomations=t.triggerAutomations;if(t.enabled!==void 0){if(t.enabled!=="true"&&t.enabled!=="false")Ni('--enabled must be "true" or "false".');c.isEnabled=t.enabled==="true"}if(Object.keys(c).length===0)Ni("Nothing to update.");let b=await E("PATCH",`/api/v1/warehouse-syncs/${r}`,c,t.company);n(b,()=>{console.log(`Updated ${b.sync.name}.`),jR(b.sync)});return}if(e==="delete"){if(!await rt(`Delete warehouse sync ${decodeURIComponent(r)}? Imported contacts and events stay.`,t)){console.log("Cancelled.");return}let l=await E("DELETE",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(l,()=>console.log(`Deleted sync ${l.syncId}.`));return}if(e==="run"){let c=await E("POST",`/api/v1/warehouse-syncs/${r}/run`,t.fullResync?{fullResync:!0}:{},t.company);n(c,()=>console.log(`${t.fullResync?"Full resync":"Run"} queued for ${c.sync.name}. Follow it with \`sequenzy warehouse syncs runs ${c.sync.id}\`.`));return}let i=t.limit?`?limit=${encodeURIComponent(t.limit)}`:"",o=await E("GET",`/api/v1/warehouse-syncs/${r}/runs${i}`,void 0,t.company);n(o,()=>{console.log(`Recent runs (${o.runs.length})`);for(let c of o.runs){let l=c.isFullResync?" (full resync)":c.isManual?" (manual)":"";console.log(`- ${c.startedAt}${l} ${MZ(c)}`);for(let d of c.imports)console.log(` import ${d.status}: ${d.processedCount}/${d.totalRows}`);for(let d of c.errorSamples.slice(0,5))console.log(` row ${d.row}: ${d.reason}`);if(c.error)console.log(` error: ${c.error}`)}})}catch(r){T(r),process.exit(1)}}var Nqe={requested:"Waiting to be added",collecting:"Collecting emails",available:"Watching",declined:"Not added"};function GZ(e){return e.slice(0,16).replace("T"," ")}function HZ(e){let t=e.status==="available"?`${e.emailCount} ${e.emailCount===1?"email":"emails"}${e.latestEmailAt?`, latest ${GZ(e.latestEmailAt)} UTC`:""}`:null,n=e.status==="declined"?e.declineReason:e.note;return[`${e.brand?.name??e.domain} (${e.domain}) · ${Nqe[e.status]}${t?` · ${t}`:""}`,n?` ${n}`:null,` ID: ${e.id}`].filter(Boolean).join(`
|
|
506
|
+
Showing ${e.suppressions.length} of ${e.total} (page ${e.page}).${n}`),e.hasMore)t.push(`Use --page ${e.page+1} for more.`);return t}function Aqe(e,t){let n=new URLSearchParams;if(t)n.set("region",t);return`/api/v1/suppressions/${encodeURIComponent(e)}${n.size>0?`?${n}`:""}`}function hqe(e){return[`Recipient: ${e.email}`,`Suppressed: ${e.suppressed?"Yes":"No"}`,`Associated with company: ${e.knownRecipient?"Yes":"No"}`,`Local suppression: ${e.local.suppressed?`${e.local.suppressionType??e.local.reason??"unknown"} (${e.local.scope??"unknown scope"}, ${e.local.delistable?"removable":"protected"})`:"None"}`]}async function XI(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let i=await E("GET",fqe(t),void 0,t.company);if(t.json){w(i);return}for(let o of gqe(i))console.log(o);return}if(!t.email)throw new g("Recipient email is required",400);let n=Aqe(t.email,t.region);if(e==="get"){let i=await E("GET",n,void 0,t.company);if(t.json){w(i);return}for(let o of hqe(i.suppression))console.log(o);return}if(!await rt(`Remove the workspace soft-bounce escalation for ${t.email}? Global, complaint, and unsubscribe protections will be kept.`,t)){console.log("Aborted.");return}let r=await E("DELETE",n,void 0,t.company);if(t.json){w(r);return}if(console.log(r.removed?`Removed workspace soft-bounce escalation for ${r.email}.`:`No removable workspace soft-bounce escalation found for ${r.email}.`),r.reactivatedSubscriberIds.length>0)console.log(`Reactivated subscribers: ${r.reactivatedSubscriberIds.length}`);if(r.remainingSuppression.suppressed)console.log("The recipient remains suppressed by a protected global, complaint, or unsubscribe source.")}catch(n){T(n instanceof g?n:n),process.exit(1)}}function yqe(e){if(e.reset){if(e.rulesJson!==void 0||e.rulesFile!==void 0)throw new g("--reset cannot be combined with --rules",400);return{syncRules:null}}let t=$e(e.rulesJson,e.rulesFile,"rules");if(t===void 0)throw new g("Provide --rules-json, --rules-file, or --reset",400);if(!Array.isArray(t))throw new g("rules JSON must be an array of sync rules",400);return{syncRules:t}}function bqe(e){let t=[],n=e.conditions;if(!n)return t;if(n.requiresTags?.length)t.push(` Requires tags: ${n.requiresTags.join(", ")}`);if(n.requiresNotTags?.length)t.push(` Excluded tags: ${n.requiresNotTags.join(", ")}`);let r=n.purchasedProduct;if(r){let i=[];if(r.tags?.length)i.push(`tags ${r.tags.join("|")}`);if(r.collectionIds?.length)i.push(`collections ${r.collectionIds.join("|")}`);if(r.productTypes?.length)i.push(`types ${r.productTypes.join("|")}`);if(r.vendors?.length)i.push(`vendors ${r.vendors.join("|")}`);if(i.length>0)t.push(` Product match: ${i.join("; ")}`)}return t}function RZ(e){console.log(`Sync rules (${e.syncRules.length})${e.isDefault?" - platform defaults":""}`);for(let t of e.syncRules){let n=t.actions.addTags.length?`+${t.actions.addTags.join(", +")}`:"",r=t.actions.removeTags.length?`-${t.actions.removeTags.join(", -")}`:"",i=[n,r].filter(Boolean).join(" ")||"(no-op)";console.log(`- ${t.triggerEvent}: ${i}`);for(let o of bqe(t))console.log(o)}}async function FR(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="get"){let i=await E("GET","/api/v1/sync-rules",void 0,t.company);if(t.json){w(i);return}RZ(i);return}let n=yqe(t),r=await E("PUT","/api/v1/sync-rules",n,t.company);if(t.json){w(r);return}if(r.message)console.log(r.message);RZ(r)}catch(n){T(n instanceof g?n:n),process.exit(1)}}function vqe(e){let t=e.isSystem?" [system]":"";console.log(`- ${e.name} [${e.id}]${t}`),console.log(` Color: ${e.color??"Default"}`)}function Eqe(e){if(!e.name||e.name.trim()==="")throw new g("Tag name is required",400);return{name:e.name,...e.color!==void 0&&{color:e.color}}}async function Pm(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/tags",void 0,t.company);if(t.json){w(r);return}console.log(`Tags (${r.tags.length})`);for(let i of r.tags)vqe(i);return}if(e==="create"){let r=Eqe(t),i=await E("POST","/api/v1/tags",r,t.company);if(t.json){w(i);return}if(console.log(`Created tag: ${i.tag?.name??r.name}`),i.tag)console.log(`ID: ${i.tag.id}`),console.log(`Color: ${i.tag.color??"Default"}`);return}if(!t.tagId)throw new g("Tag ID is required",400);if(e==="update"){if(!t.color||t.color.trim()==="")throw new g("--color is required",400);let r=await E("PATCH",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,{color:t.color},t.company);if(t.json){w(r);return}if(console.log(`Updated tag: ${r.tag?.name??t.tagId}`),r.tag)console.log(`ID: ${r.tag.id}`),console.log(`Color: ${r.tag.color??"Default"}`);return}if(!await rt(`Delete tag ${t.tagId}? It will be removed from all subscribers.`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,void 0,t.company);if(t.json){w(n);return}console.log(`Deleted tag: ${t.tagId}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}var Iqe=new Set(["admin","marketer","viewer","restricted"]);function Cqe(e){if(!e.email||e.email.trim()==="")throw new g("Email is required",400);if(!e.role||!Iqe.has(e.role))throw new g("--role must be admin, marketer, viewer, or restricted",400);return{email:e.email.trim(),role:e.role,...e.billingAccess===!0&&{canManageBilling:!0}}}function wqe(e){let t=e.user.name?`${e.user.name} <${e.user.email}>`:e.user.email;if(console.log(`- ${t} [${e.id}]`),console.log(` Kind: ${e.kind}`),console.log(` Role: ${e.role}`),console.log(` Status: ${e.status}`),console.log(` Billing access: ${e.canManageBilling?"yes":"no"}`),e.invitedAt)console.log(` Invited: ${te(e.invitedAt)}`);if(e.expiresAt)console.log(` Expires: ${te(e.expiresAt)}`);if(e.invitedBy)console.log(` Invited by: ${e.invitedBy.name??e.invitedBy.email}`)}async function eC(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/team",void 0,t.company);if(t.json){w(r);return}console.log(`Team members (${r.members.length})`);for(let i of r.members)wqe(i);return}if(e==="invite"){let r=Cqe(t),i=await E("POST","/api/v1/team/invitations",r,t.company);if(t.json){w(i);return}if(i.invitation){console.log(`Invitation sent to ${i.invitation.email}`),console.log(`ID: ${i.invitation.id}`),console.log(`Role: ${i.invitation.role}`),console.log(`Billing access: ${i.invitation.canManageBilling?"yes":"no"}`),console.log(`Status: ${i.invitation.status}`),console.log(`Expires: ${te(i.invitation.expiresAt)}`);return}console.log(`Added team member: ${i.member?.email??r.email}`),console.log(`Role: ${i.member?.role??r.role}`),console.log(`Billing access: ${i.member?.canManageBilling?"yes":"no"}`);return}if(!t.invitationId)throw new g("Invitation ID is required",400);if(!await rt(`Cancel invitation ${t.invitationId}?`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/team/invitations/${encodeURIComponent(t.invitationId)}`,void 0,t.company);if(t.json){w(n);return}console.log(`Cancelled invitation: ${t.invitationId}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}function Qm(e,t,n){return`${e} ${e===1?t:n}`}function TZ(e){let t=e.upToDate+e.edited+e.outdated,n=[e.translating>0?`${e.translating} translating`:null,e.missing>0?`${e.missing} missing`:null,(e.failed??0)>0?`${e.failed} failed`:null,e.outdated>0?`${e.outdated} outdated`:null,e.edited>0?`${e.edited} edited`:null].filter((r)=>r!==null);return`${e.locale}: ${t}/${e.total} translated${n.length>0?` (${n.join(", ")})`:""}`}function Sqe(e){let t=e.queuedPushes??0;if(e.queuedEmails===0&&t===0)return"Nothing new to translate: every email and push is translated or already translating";return`Queued ${[e.queuedEmails>0?`${Qm(e.queuedTranslations,"translation","translations")} for ${Qm(e.queuedEmails,"email","emails")}`:null,t>0?`${Qm(e.queuedPushTranslations??t,"translation","translations")} for ${Qm(t,"push","pushes")}`:null].filter(Boolean).join(" and ")}: ${e.locales.join(", ")}`}async function LR(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="coverage"){let r=await E("GET","/api/v1/templates/localizations/coverage",void 0,t.company);if(t.json){w(r);return}if(console.log(`Emails: ${r.totalEmails} (${Qm(r.sequenceEmails,"sequence email","sequence emails")}, ${Qm(r.transactionalEmails,"transactional email","transactional emails")})`),console.log(`Primary locale: ${r.primaryLocale}`),r.locales.length===0){console.log("No translated languages configured");return}for(let i of r.locales)console.log(`- ${TZ(i)}`);if(r.push&&r.push.totalPushes>0){console.log(`Sequence pushes: ${r.push.totalPushes}`);for(let i of r.push.locales)console.log(`- ${TZ(i)}`)}return}let n=await E("POST","/api/v1/templates/localizations/translate-missing",{...t.locales!==void 0&&{locales:t.locales}},t.company);if(t.json){w(n);return}console.log(Sqe(n))}catch(n){T(n),process.exit(1)}}function OZ(e){if(e.length===0)return"none";return e.map((t)=>`${t.locale}:${t.status}${t.editedAt?" (edited)":""}`).join(", ")}function tC(e){return e&&e.length>0?e.join(", "):"None"}function nC(e){return e?"yes":"no"}function Dqe(e,t){if(e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&e.label===void 0&&e.template===void 0&&t.html===void 0&&t.blocks===void 0)throw new g("Provide at least one of: --name, --subject, --preview-text, --label, --template/--no-template, --html, --html-file, --blocks-json, --blocks-file",400);return{name:e.name,subject:e.subject,previewText:e.previewText,html:t.html,blocks:t.blocks,labels:e.label,...e.template!==void 0&&{isTemplate:e.template}}}function _qe(e,t){let n=e.subject?.trim();if(!n)throw new g("Localization subject is required",400);if(t.html===void 0&&t.blocks===void 0)throw new g("Provide localized content with --html, --html-file, --blocks-json, or --blocks-file",400);return{subject:n,previewText:e.previewText,html:t.html,blocks:t.blocks,...e.keepEdits===!0&&{keepEdits:!0}}}async function Ha(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.label)for(let v of t.label)c.append("label",v);if(t.templatesOnly)c.set("isTemplate","true");let l=nt(t.limit,"--limit");if(l!==void 0)c.set("limit",String(l));let d=nt(t.offset,"--offset");if(d!==void 0){if(d<0)throw new g("--offset must be zero or greater",400);c.set("offset",String(d))}let m=await E("GET",`/api/v1/templates${c.size>0?`?${c.toString()}`:""}`,void 0,t.company),A=ut({companyId:m.companyId}),y=m.templates.map((v)=>Qs(v,{emailId:v.id},"email",m.companyId));if(t.json){w({...m,templates:y,appUrls:A.urls});return}console.log(`Templates (${m.templates.length})`);let b=m.pagination;if(b?.hasMore){let v=b.offset+b.count;console.log(`Showing ${b.count} of ${b.total}. Re-run with --offset ${v} for the next page.`)}if(m.emailLocalizationConfig)console.log(`Primary locale: ${m.emailLocalizationConfig.primaryLocale}`);for(let v of y)console.log(`- ${v.name} [${v.id}]`),console.log(` Subject: ${v.subject}`),console.log(` Format: ${Ns(v.emailPreset)}`),console.log(` Labels: ${tC(v.labels)}`),console.log(` Reusable template: ${nC(v.isTemplate)}`),De(" URL",v.url),console.log(` Localizations: ${OZ(v.localizations)}`);return}let n=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile});if(e==="create"){if(!t.name)throw new g("Template name is required",400);let c=t.prompt?.trim()||void 0;if([c,n.html,n.blocks].filter((b)=>b!==void 0).length!==1)throw new g("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!c&&(t.style!==void 0||t.tone!==void 0))throw new g("--style and --tone require --prompt",400);if(!t.subject&&!c)throw new g("Template subject is required unless --prompt is provided",400);let d=await E("POST","/api/v1/templates",{name:t.name,subject:t.subject,previewText:t.previewText,prompt:c,style:t.style,tone:t.tone,html:n.html,blocks:n.blocks,labels:t.label,...t.template!==void 0&&{isTemplate:t.template}},t.company),m=await jt(t.company),A=d.template?.id??d.templateId,y=m!==void 0&&A!==void 0?ut({companyId:m,emailId:A}):void 0;if(t.json){w({...d,...d.template!==void 0&&y?.urls.email!==void 0&&{template:{...d.template,url:y.urls.email}},...y!==void 0&&{appUrls:y.urls}});return}$n(d),console.log(`Created template: ${d.template?.name??t.name}`),console.log(`ID: ${d.template?.id??"Unknown"}`),De("URL",y?.urls.email),console.log(`Labels: ${tC(d.template?.labels)}`),console.log(`Reusable template: ${nC(d.template?.isTemplate)}`),console.log(`Subject: ${d.template?.subject??t.subject??"Unknown"}`);return}if(!t.id)throw new g("Template ID is required",400);if(e==="set-localization"){if(!t.locale)throw new g("Localization locale is required",400);let c=await E("PUT",`/api/v1/templates/${t.id}/localizations/${encodeURIComponent(t.locale)}`,_qe(t,n),t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:c.templateId}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(`Set ${c.localization.locale} localization for template ${c.templateId}`),console.log(`Status: ${c.localization.status}`),console.log(`Subject: ${c.localization.subject}`),De("URL",d?.urls.email);return}if(e==="sync-localizations"){let c=await E("POST",`/api/v1/templates/${t.id}/localizations/sync`,{...t.locales!==void 0&&{locales:t.locales},...t.skipEdited===!0&&{skipEdited:!0}},t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:c.templateId}):void 0;if(t.json){w({...c,...d!==void 0&&{appUrls:d.urls}});return}console.log(c.queuedLocales.length>0?`Queued ${c.queuedVariantCount} localization${c.queuedVariantCount===1?"":"s"}: ${c.queuedLocales.join(", ")}`:"Queued 0 localizations");let m=c.skippedLocales??[];if(m.length>0)console.log(`Kept ${m.length} edited localization${m.length===1?"":"s"}: ${m.join(", ")}`);De("URL",d?.urls.email);return}if(e==="update"){let c=await E("PUT",`/api/v1/templates/${t.id}`,Dqe(t,n),t.company),l=await jt(t.company),d=l!==void 0?ut({companyId:l,emailId:t.id}):void 0;if(t.json){w({...c,...c.template!==void 0&&d?.urls.email!==void 0&&{template:{...c.template,url:d.urls.email}},...d!==void 0&&{appUrls:d.urls}});return}$n(c),console.log(`Updated template: ${c.template?.name??t.id}`),console.log(`ID: ${c.template?.id??t.id}`),De("URL",d?.urls.email),console.log(`Labels: ${tC(c.template?.labels)}`),console.log(`Reusable template: ${nC(c.template?.isTemplate)}`),console.log(`Subject: ${c.template?.subject??"Unchanged"}`);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/templates/${t.id}`,void 0,t.company);if(t.json){w(c);return}console.log(c.message??`Deleted template: ${t.id}`);return}if(e==="share"){let c=await E("POST",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){w(c);return}console.log(c.created?"Public link created.":"Public link already active."),De("Share URL",c.shareUrl),console.log("Anyone with the link sees an anonymized copy - no subscriber data, no tracking.");return}if(e==="unshare"){let c=await E("DELETE",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){w(c);return}console.log(c.revoked?"Public link revoked. The old URL now returns 404.":"No public link to revoke.");return}let r=await E("GET",`/api/v1/templates/${t.id}`,void 0,t.company),i=ut({companyId:r.template.companyId,emailId:t.id});if(t.json){w({...r,template:{...r.template,url:i.urls.email},appUrls:i.urls});return}let o=r.template;if(console.log(o.name),console.log(`ID: ${o.id}`),console.log(`Company: ${o.companyId}`),De("URL",i.urls.email),o.shareUrl)De("Share URL",o.shareUrl);console.log(`Subject: ${o.subject}`),console.log(`Labels: ${tC(o.labels)}`),console.log(`Reusable template: ${nC(o.isTemplate)}`),console.log(`Preview: ${o.previewText??"None"}`),console.log(`Blocks: ${o.blocks.length}`),console.log(`Format: ${Ns(o.emailPreset)}`),console.log(`Font: ${o.fontFamily??"Default"}`),console.log(`Created: ${te(o.createdAt)}`),console.log(`Updated: ${te(o.updatedAt)}`),console.log(`Localizations: ${OZ(o.localizations)}`);for(let c of o.localizations){let l=c.lastError?` | error: ${c.lastError}`:"";console.log(`- ${c.locale} [${c.status}${c.editedAt?", edited":""}] blocks=${c.blocks.length}${l}`)}}catch(n){T(n instanceof g?n:n),process.exit(1)}}function xqe(e){if(!e){console.log("Tracking domain: none (links use the shared Sequenzy domain)");return}console.log(`Tracking domain: ${e.domain}`),console.log(` Status: ${e.status}`);let t=e.status==="verified",n=t?"shared Sequenzy domain":"shared Sequenzy domain until it verifies";if(console.log(` Links: ${e.active?e.domain:n}`),e.sslStatus)console.log(` SSL: ${e.sslStatus}`);if(e.error)console.log(` Error: ${e.error}`);if(!e.active&&!t)console.log(` DNS: ${e.cnameRecord.name} CNAME ${e.cnameRecord.value}`)}async function Bqe(e,t){if(!await j())T(z()),process.exit(1);try{let n;if(e==="show")n=await E("GET","/api/v1/tracking-domain",void 0,t.company);else if(e==="set"){let r=t.domain?.trim();if(!r)throw new g("Provide a tracking domain, like links.acme.com",400);n=await E("PUT","/api/v1/tracking-domain",{domain:r},t.company)}else if(e==="verify")n=await E("POST","/api/v1/tracking-domain/verify",void 0,t.company);else{if(!await rt("Remove the tracking domain? Links and images in emails already sent through it will stop working.",t)){console.log("Cancelled.");return}n=await E("DELETE","/api/v1/tracking-domain",void 0,t.company)}if(t.json){w(n);return}if(e==="remove"){console.log(n.removed?"Tracking domain removed. Links use the shared Sequenzy domain.":"No tracking domain was set.");return}if(n.message)console.log(n.message),console.log("");xqe(n.trackingDomain)}catch(n){T(n),process.exit(1)}}function NZ(e,t=Bqe){let n=(l)=>l.optsWithGlobals(),r=e.command("domain").description("Show the company tracking domain used by every sending domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").allowExcessArguments(!1).action((l,d)=>t("show",n(d)));S(r,{notes:["Every sending domain uses the company tracking domain for tracked links and opens. It never blocks sending: until it verifies, or when it breaks or is removed, links use the shared Sequenzy domain."],examples:["sequenzy tracking domain","sequenzy tracking domain set links.example.com","sequenzy tracking domain verify"]});let i=r.command("set <hostname>").description("Set or change the company tracking domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d,m)=>t("set",{...n(m),domain:l}));S(i,{notes:["Any subdomain you control works (it does not have to match a sending domain), for example links.example.com. Add the returned CNAME record.","Changing it keeps the previous hostname serving links in emails already sent, as long as its old CNAME stays in place."],examples:["sequenzy tracking domain set links.example.com"]});let o=r.command("verify").description("Check the company tracking domain's DNS and HTTPS now").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t("verify",n(d)));S(o,{examples:["sequenzy tracking domain verify"]});let c=r.command("remove").description("Remove the company tracking domain").option("-y, --yes","Skip the confirmation prompt").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t("remove",n(d)));return S(c,{notes:["Links and images in emails already sent through the tracking domain stop working. New emails use the shared Sequenzy domain."],examples:["sequenzy tracking domain remove --yes"]}),r}function UR(e,t,n){if(e!==void 0&&!n.includes(e))throw new g(`${t} must be one of: ${n.join(", ")}`,400)}function kqe(e){UR(e.status,"--status",["all","active","disabled"]),UR(e.sort,"--sort",["date","sends","opens","open-rate","clicks","ctr"]),UR(e.order,"--order",["asc","desc"]);let t=new URLSearchParams;for(let n of e.label??[])t.append("label",n);if(e.search?.trim())t.set("search",e.search.trim());if(e.status)t.set("status",e.status);if(e.sort)t.set("sort",e.sort);if(e.order)t.set("order",e.order);if(e.includeBots)t.set("includeMachineEngagement","true");return t.size>0?`?${t.toString()}`:""}function Rqe(e,t){if(e.previewText!==void 0&&e.clearPreviewText===!0)throw new g("Use either --preview-text or --clear-preview-text, not both",400);if(e.label!==void 0&&e.clearLabels)throw new g("Use either --label or --clear-labels, not both",400);let n=e.clearPreviewText===!0?null:void 0;if(e.label===void 0&&!e.clearLabels&&e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&n===void 0&&e.enabled===void 0&&t.html===void 0&&t.blocks===void 0)throw new g("Provide at least one of: --name, --subject, --preview-text, --clear-preview-text, --enabled/--no-enabled, --label, --clear-labels, --html, --html-file, --blocks-json, --blocks-file",400);return{...e.label!==void 0&&{labels:e.label},...e.clearLabels&&{labels:[]},...e.name!==void 0&&{name:e.name},...e.subject!==void 0&&{subject:e.subject},...e.previewText!==void 0&&{previewText:e.previewText},...n===null&&{previewText:null},...e.enabled!==void 0&&{enabled:e.enabled},...t.html!==void 0&&{html:t.html},...t.blocks!==void 0&&{blocks:t.blocks}}}async function qm(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="create"){if(!t.name)throw new g("Transactional name is required",400);let i=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),o=t.prompt?.trim()||void 0;if([o,i.html,i.blocks].filter((A)=>A!==void 0).length!==1)throw new g("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!o&&!t.subject)throw new g("Transactional subject is required unless --prompt is provided",400);if(!o&&(t.style!==void 0||t.tone!==void 0))throw new g("--style and --tone require --prompt",400);let l=await E("POST","/api/v1/transactional",{name:t.name,...t.label!==void 0&&{labels:t.label},...t.slug!==void 0&&{slug:t.slug},...t.subject!==void 0&&{subject:t.subject},...t.previewText!==void 0&&{previewText:t.previewText},...o!==void 0&&{prompt:o},...t.style!==void 0&&{style:t.style},...t.tone!==void 0&&{tone:t.tone},...i.html!==void 0&&{html:i.html},...i.blocks!==void 0&&{blocks:i.blocks},...t.enabled!==void 0&&{enabled:t.enabled}},t.company),d=await jt(t.company),m=d?ut({companyId:d,transactionalId:l.transactional.id}).urls.transactionalEmail:void 0;if(t.json){w({...l,transactional:{...l.transactional,url:m},...m&&{appUrls:{transactionalEmail:m}}});return}$n(l),console.log(`Created transactional template: ${l.transactional.name}`),console.log(`ID: ${l.transactional.id}`),console.log(`Slug: ${l.transactional.slug}`),console.log(`Enabled: ${l.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${l.transactional.labels?.join(", ")||"None"}`),De("URL",m);return}if(e==="list"){let i=await E("GET",`/api/v1/transactional${kqe(t)}`,void 0,t.company),o=await jt(t.company),c=i.transactional.map((d)=>Qs(d,{transactionalId:d.id},"transactionalEmail",o)),l=ut({companyId:o});if(t.json){w({...i,transactional:c,appUrls:l.urls});return}console.log(`Transactional templates (${i.transactional.length})`);for(let d of c)console.log(`- ${d.name} [${d.slug}] ${d.enabled?"enabled":"disabled"}${d.managedBy==="code"?" · managed in code":""}`),console.log(` Subject: ${d.subject??"Unknown"}`),console.log(` Labels: ${d.labels?.join(", ")||"None"}`),console.log(` Format: ${Ns(d.emailPreset)}`),console.log(` Sends: ${d.stats.sends} · Opens: ${d.stats.opens} (${d.stats.openRate.toFixed(2)}%) · Clicks: ${d.stats.clicks} (${d.stats.clickRate.toFixed(2)}%)`),De(" URL",d.url);return}if(!t.slug)throw new g("Transactional template slug is required",400);if(e==="update"){let i=$s({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),o=await E("PATCH",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,Rqe(t,i),t.company),c=await jt(t.company),l=c?ut({companyId:c,transactionalId:o.transactional.id}).urls.transactionalEmail:void 0;if(t.json){w({...o,transactional:{...o.transactional,url:l},...l&&{appUrls:{transactionalEmail:l}}});return}if($n(o),console.log(`Updated transactional template: ${o.transactional.name}`),console.log(`ID: ${o.transactional.id}`),console.log(`Slug: ${o.transactional.slug}`),console.log(`Enabled: ${o.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${o.transactional.labels?.join(", ")||"None"}`),o.transactional.subject)console.log(`Subject: ${o.transactional.subject}`);De("URL",l);return}if(e==="delete"){if(!await rt(`Delete transactional template ${t.slug}?`,t)){console.log("Aborted.");return}let i=await E("DELETE",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){w(i);return}if(console.log(`Deleted transactional template: ${i.deleted?.name??t.slug}`),console.log(`Slug: ${i.deleted?.slug??t.slug}`),i.deleted?.emailDeleted)console.log("Code-managed content snapshot deleted with it");else if(i.deleted?.emailId)console.log(`Email content kept as a template: ${i.deleted.emailId}`);return}let n=await E("GET",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){w(n);return}let r=n.transactional;if(console.log(r.name),console.log(`ID: ${r.id}`),console.log(`Slug: ${r.slug}`),console.log(`Enabled: ${r.enabled?"yes":"no"}`),r.managedBy==="code")console.log(`Managed in code: sends with --track-as ${r.slug}; content is a snapshot of a recent send`);if(r.subject)console.log(`Subject: ${r.subject}`);if(console.log(`Labels: ${r.labels?.join(", ")||"None"}`),console.log(`Format: ${Ns(r.emailPreset)}`),(r.variables?.length??0)>0)console.log(`Variables: ${r.variables?.join(", ")}`)}catch(n){T(n instanceof g?n:n),process.exit(1)}}import{readFileSync as Tqe}from"node:fs";var $Z=["snowflake","bigquery","redshift","postgres"],Oqe=["subscribers","events"],PZ=["every_15_minutes","hourly","daily","weekly","manual"],QZ=["confirmed","double_opt_in"],Vl="SEQUENZY_WAREHOUSE_PASSWORD";function Ni(e){T(new g(e,400)),process.exit(1)}function zA(e,t){if(!e||e.trim().length===0)Ni(`${t} is required.`);return e.trim()}function Fm(e,t,n){if(e===void 0)return;if(!t.includes(e))Ni(`Invalid ${n} "${e}". Use one of: ${t.join(", ")}.`);return e}function GA(e,t){try{return Tqe(e,"utf8")}catch{Ni(`Could not read ${t} file "${e}".`)}}function rC(e,t){let n;try{n=JSON.parse(e)}catch{Ni(`${t} must be valid JSON.`)}if(!n||typeof n!=="object"||Array.isArray(n))Ni(`${t} must be a JSON object.`);return n}function qZ(e){let t=e.configJson?rC(e.configJson,"--config-json"):{},n=[["account","account"],["username","username"],["warehouse","warehouse"],["database","database"],["schema","schema"],["role","role"],["projectId","projectId"],["location","location"],["host","host"],["sslMode","sslMode"]];for(let[r,i]of n){let o=e[r];if(typeof o==="string")t[i]=o}if(e.port!==void 0){let r=Number(e.port);if(!Number.isInteger(r))Ni("--port must be a number.");t.port=r}return t}function FZ(e,t="create"){let n=e.credentialsFile?rC(GA(e.credentialsFile,"--credentials-file"),"--credentials-file"):{};if(e.privateKeyFile)n.privateKey=GA(e.privateKeyFile,"--private-key-file");if(e.privateKeyPassphrase)n.privateKeyPassphrase=e.privateKeyPassphrase;if(e.serviceAccountFile)n.serviceAccountJson=GA(e.serviceAccountFile,"--service-account-file");let r=t==="create"||e.passwordFromEnv?process.env[Vl]:void 0;if(t==="update"&&e.passwordFromEnv&&!r)Ni(`--password-from-env needs ${Vl} to be set.`);let i=e.password??r;if(i)n.password=i;return Object.keys(n).length>0?n:void 0}function zR(e,t){if(e.query&&e.queryFile)Ni("Use either --query or --query-file, not both.");let n=e.queryFile?GA(e.queryFile,"--query-file"):e.query;if(t&&!n?.trim())Ni("--query or --query-file is required.");return n}function LZ(e){if(e.mappingJson&&e.mappingFile)Ni("Use either --mapping-json or --mapping-file, not both.");if(e.mappingFile)return rC(GA(e.mappingFile,"--mapping-file"),"--mapping-file");return e.mappingJson?rC(e.mappingJson,"--mapping-json"):void 0}function UZ(e){if(e===void 0)return;return e.split(",").map((t)=>t.trim()).filter(Boolean)}function MR(e){let t=e.config.host??e.config.account??e.config.projectId??"";if(console.log(`- ${e.name} (${e.provider}) ${String(t)}`),console.log(` id: ${e.id} | status: ${e.status} | syncs: ${e.syncCount??0} | tested: ${e.lastTestedAt??"never"}`),e.lastError)console.log(` last error: ${e.lastError}`)}function MZ(e){if(e.status==="running")return`running, ${e.rowsRead} rows read so far`;return`${e.status}: ${e.rowsRead} read, ${e.rowsSynced} synced, ${e.rowsUnchanged} unchanged, ${e.rowsSkipped} skipped, ${e.rowsFailed} failed`}function jR(e){let t=!e.isEnabled?"paused":e.status;if(console.log(`- ${e.name} (${e.kind})`),console.log(` id: ${e.id} | connection: ${e.connectionId} | ${e.frequency} | status: ${t}${e.cursorColumn?` | cursor: ${e.cursorColumn} >= ${e.cursorValue??"start"}`:""}`),console.log(` last success: ${e.lastSuccessAt??"never"} | next run: ${e.nextRunAt??"not scheduled"}`),e.latestRun)console.log(` latest run ${MZ(e.latestRun)}`);if(e.lastError)console.log(` last error: ${e.lastError}`)}async function jZ(){if(!await j())T(z()),process.exit(1)}function zZ(e){return(t,n)=>{if(e.json){console.log(JSON.stringify(t,null,2));return}n()}}async function Wl(e,t){await jZ();let n=zZ(t);try{if(e==="list"){let o=await E("GET","/api/v1/warehouse-connections",void 0,t.company);n(o,()=>{console.log(`Warehouse connections (${o.connections.length})`),o.connections.forEach(MR)});return}if(e==="create"){let o=Fm(t.provider,$Z,"--provider");if(!o)Ni(`--provider is required (${$Z.join(", ")}).`);let c=FZ(t);if(!c)Ni(`Provide credentials: --private-key-file (Snowflake), --service-account-file (BigQuery), ${Vl} or --password (Redshift/Postgres), or --credentials-file.`);let l=await E("POST","/api/v1/warehouse-connections",{name:zA(t.name,"--name"),provider:o,config:qZ(t),credentials:c},t.company);n(l,()=>{console.log(`Connected ${l.connection.name} (${l.connection.id}).`),console.log("The test query succeeded. Create a sync with `sequenzy warehouse syncs create`.")});return}let r=encodeURIComponent(zA(t.id,"<id>"));if(e==="get"){let o=await E("GET",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(o,()=>MR(o.connection));return}if(e==="update"){let o=qZ(t),c=FZ(t,"update"),l={...t.name!==void 0?{name:t.name}:{},...Object.keys(o).length>0?{config:o}:{},...c?{credentials:c}:{}};if(Object.keys(l).length===0)Ni("Nothing to update. Pass --name, connection settings or new credentials.");let d=await E("PATCH",`/api/v1/warehouse-connections/${r}`,l,t.company);n(d,()=>{console.log(`Updated ${d.connection.name}.`),MR(d.connection)});return}if(e==="delete"){if(!await rt(`Delete warehouse connection ${decodeURIComponent(r)}?`,t)){console.log("Cancelled.");return}let c=await E("DELETE",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(c,()=>console.log(`Deleted connection ${c.connectionId}.`));return}if(e==="test"){let o=await E("POST",`/api/v1/warehouse-connections/${r}/test`,void 0,t.company);n(o,()=>console.log(`Connection works (${o.connection.name}).`));return}let i=await E("POST",`/api/v1/warehouse-connections/${r}/preview`,{query:zR(t,!0)},t.company);n(i,()=>{console.log(`Columns: ${i.columns.map((o)=>`${o.name} (${o.type})`).join(", ")}`),console.log(`First ${i.rows.length} row(s):`);for(let o of i.rows)console.log(` ${JSON.stringify(o)}`)})}catch(r){T(r),process.exit(1)}}async function Yl(e,t){await jZ();let n=zZ(t);try{if(e==="list"){let c=t.connection?`?connectionId=${encodeURIComponent(t.connection)}`:"",l=await E("GET",`/api/v1/warehouse-syncs${c}`,void 0,t.company);n(l,()=>{console.log(`Warehouse syncs (${l.syncs.length})`),l.syncs.forEach(jR)});return}if(e==="create"){let c=LZ(t);if(!c)Ni("--mapping-json or --mapping-file is required.");let l=Fm(t.frequency,PZ,"--frequency"),d=Fm(t.optInMode,QZ,"--opt-in-mode"),m=UZ(t.lists),A=await E("POST","/api/v1/warehouse-syncs",{connectionId:zA(t.connection,"--connection"),name:zA(t.name,"--name"),kind:Fm(t.kind,Oqe,"--kind")??"subscribers",query:zR(t,!0),mapping:c,...t.cursorColumn?{cursorColumn:t.cursorColumn}:{},...l?{frequency:l}:{},...m?{listIds:m}:{},...d?{optInMode:d}:{},...t.triggerAutomations?{triggerAutomations:!0}:{}},t.company);n(A,()=>{console.log(`Created sync ${A.sync.name} (${A.sync.id}).`),console.log(`The first run is starting. Follow it with \`sequenzy warehouse syncs runs ${A.sync.id}\`.`)});return}let r=encodeURIComponent(zA(t.id,"<id>"));if(e==="get"){let c=await E("GET",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(c,()=>jR(c.sync));return}if(e==="update"){let c={};if(t.name!==void 0)c.name=t.name;let l=zR(t,!1);if(l!==void 0)c.query=l;let d=LZ(t);if(d)c.mapping=d;if(t.cursorColumn!==void 0)c.cursorColumn=t.cursorColumn===""?null:t.cursorColumn;let m=Fm(t.frequency,PZ,"--frequency");if(m)c.frequency=m;let A=UZ(t.lists);if(A)c.listIds=A;let y=Fm(t.optInMode,QZ,"--opt-in-mode");if(y)c.optInMode=y;if(t.triggerAutomations!==void 0)c.triggerAutomations=t.triggerAutomations;if(t.enabled!==void 0){if(t.enabled!=="true"&&t.enabled!=="false")Ni('--enabled must be "true" or "false".');c.isEnabled=t.enabled==="true"}if(Object.keys(c).length===0)Ni("Nothing to update.");let b=await E("PATCH",`/api/v1/warehouse-syncs/${r}`,c,t.company);n(b,()=>{console.log(`Updated ${b.sync.name}.`),jR(b.sync)});return}if(e==="delete"){if(!await rt(`Delete warehouse sync ${decodeURIComponent(r)}? Imported contacts and events stay.`,t)){console.log("Cancelled.");return}let l=await E("DELETE",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(l,()=>console.log(`Deleted sync ${l.syncId}.`));return}if(e==="run"){let c=await E("POST",`/api/v1/warehouse-syncs/${r}/run`,t.fullResync?{fullResync:!0}:{},t.company);n(c,()=>console.log(`${t.fullResync?"Full resync":"Run"} queued for ${c.sync.name}. Follow it with \`sequenzy warehouse syncs runs ${c.sync.id}\`.`));return}let i=t.limit?`?limit=${encodeURIComponent(t.limit)}`:"",o=await E("GET",`/api/v1/warehouse-syncs/${r}/runs${i}`,void 0,t.company);n(o,()=>{console.log(`Recent runs (${o.runs.length})`);for(let c of o.runs){let l=c.isFullResync?" (full resync)":c.isManual?" (manual)":"";console.log(`- ${c.startedAt}${l} ${MZ(c)}`);for(let d of c.imports)console.log(` import ${d.status}: ${d.processedCount}/${d.totalRows}`);for(let d of c.errorSamples.slice(0,5))console.log(` row ${d.row}: ${d.reason}`);if(c.error)console.log(` error: ${c.error}`)}})}catch(r){T(r),process.exit(1)}}var Nqe={requested:"Waiting to be added",collecting:"Collecting emails",available:"Watching",declined:"Not added"};function GZ(e){return e.slice(0,16).replace("T"," ")}function HZ(e){let t=e.status==="available"?`${e.emailCount} ${e.emailCount===1?"email":"emails"}${e.latestEmailAt?`, latest ${GZ(e.latestEmailAt)} UTC`:""}`:null,n=e.status==="declined"?e.declineReason:e.note;return[`${e.brand?.name??e.domain} (${e.domain}) · ${Nqe[e.status]}${t?` · ${t}`:""}`,n?` ${n}`:null,` ID: ${e.id}`].filter(Boolean).join(`
|
|
507
507
|
`)}function $qe(e){return[`${GZ(e.sentAt)} UTC · ${e.brand.name} · ${e.subject??"(no subject)"}`,` ${e.url}`].join(`
|
|
508
508
|
`)}async function iC(){if(!await j())T(z()),process.exit(1)}async function Pqe(e){await iC();try{let t=await E("GET","/api/v1/gallery/watchlist",void 0,e.company);if(e.json)return w(t);if(t.watchlist.length===0){console.log("You don't watch any brands yet. Add one with `sequenzy watchlist add competitor.com`.");return}for(let n of t.watchlist)console.log(HZ(n))}catch(t){T(t),process.exit(1)}}async function Qqe(e,t){await iC();try{let n=await E("POST","/api/v1/gallery/watchlist",{website:e,...t.note?{note:t.note}:{}},t.company);if(t.json)return w(n);console.log(n.message),console.log(HZ(n.watch))}catch(n){T(n),process.exit(1)}}async function qqe(e,t){await iC();try{let n=await E("DELETE",`/api/v1/gallery/watchlist/${encodeURIComponent(e)}`,void 0,t.company);if(t.json)return w(n);console.log(`Stopped watching ${n.id}`)}catch(n){T(n),process.exit(1)}}async function Fqe(e){await iC();try{let t=new URLSearchParams;if(e.brand)t.set("domain",e.brand);if(e.since)t.set("since",e.since);if(e.limit)t.set("limit",e.limit);if(e.cursor)t.set("cursor",e.cursor);let n=t.toString(),r=await E("GET",`/api/v1/gallery/watchlist/emails${n?`?${n}`:""}`,void 0,e.company);if(e.json)return w(r);if(r.emails.length===0){console.log(e.brand||e.since?"No emails from your watched brands match.":"No emails from your watched brands yet. They show up a few hours after they're sent.");return}for(let i of r.emails)console.log($qe(i));if(r.nextCursor)console.log(`
|
|
509
509
|
More: sequenzy watchlist emails --cursor ${r.nextCursor}`)}catch(t){T(t),process.exit(1)}}function JZ(e,t={list:Pqe,add:Qqe,remove:qqe,emails:Fqe}){let n=e.command("watchlist").description("Watch competitors' emails (the dashboard's Competitors page)"),r=n.command("list",{isDefault:!0}).description("The brands you watch and where each one stands").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l)=>t.list(l)),i=n.command("add <website>").description("Watch a brand by its website, e.g. competitor.com").option("--note <text>","What you want to see from them (up to 300 characters)").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t.add(l,d)),o=n.command("remove <id>").description("Stop watching a brand").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,d)=>t.remove(l,d)),c=n.command("emails").description("Emails from the brands you watch, newest first").option("--brand <domain>","Only this watched brand, e.g. linear.app").option("--since <date>","Only emails sent at or after this ISO date, e.g. 2026-10-01").option("--limit <n>","Emails per page (1-60, default 24)").option("--cursor <cursor>","Next page, from the previous output").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l)=>t.emails(l));S(n,{notes:["Watching a brand that is already in the email gallery shows its emails right away. Any other brand is requested (it also appears in `sequenzy brand-requests`) and its emails show up once it is added. New emails arrive a few hours after they are sent."],examples:["sequenzy watchlist add linear.app","sequenzy watchlist","sequenzy watchlist emails --since 2026-10-01","sequenzy watchlist remove req_123"]}),S(i,{examples:['sequenzy watchlist add competitor.com --note "Their onboarding emails"']}),S(r,{examples:["sequenzy watchlist list --json"]}),S(o,{examples:["sequenzy watchlist remove req_123"]}),S(c,{examples:["sequenzy watchlist emails --brand linear.app --limit 10","sequenzy watchlist emails --json"]})}async function HA(){if(await j())return!0;return T(z()),process.exitCode=1,!1}function oC(e){return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}function sC(e){let t=e.isActive?"active":"revoked";console.log(`${e.name} (${t})`),console.log(` ID: ${e.id}`),console.log(` Key: ${e.publicKey}`);let n=e.allowedAppIds??[];if(console.log(` Allowed origins: ${e.allowedOrigins.length>0?e.allowedOrigins.join(", "):e.unrestricted?"any (unrestricted)":"none (apps only)"}`),console.log(` Allowed app IDs: ${n.length>0?n.join(", "):e.unrestricted?"any (unrestricted)":"none (websites only)"}`),console.log(` Last used: ${e.lastUsedAt?te(e.lastUsedAt):"never"}`),e.warning)console.log(` Warning: ${e.warning}`)}function KZ(e){console.log(""),console.log("Add this to every page:"),console.log(` ${e.installSnippet}`),console.log(""),console.log("Then instrument the events you care about:"),console.log(' sequenzy.identify("buyer@example.com", identityToken) // token minted by your backend'),console.log(' sequenzy.viewedProduct({ providerProductId: "sku-1", title: "Item" })'),console.log(' sequenzy.addedToCart({ providerProductId: "sku-1", quantity: 1 })'),console.log(" sequenzy.page() // identified visitors, e.g. on your pricing page"),console.log(""),console.log("Events from visitors who have not identified yet are buffered in the browser and replayed once they do.")}async function VZ(e){if(!await HA())return;try{let t=await E("GET","/api/v1/web-tracking-keys",void 0,e.company);if(e.json){w(t);return}if(t.keys.length===0){console.log("No web tracking keys yet."),console.log('Create one with: sequenzy web-tracking create --name "My site" --origins https://example.com');return}console.log(`Web tracking keys (${t.keys.length})`);for(let n of t.keys)console.log(""),sC(n)}catch(t){T(t instanceof g?t:t),process.exitCode=1}}async function WZ(e,t){if(!await HA())return;try{let n=await E("GET",`/api/v1/web-tracking-keys/${encodeURIComponent(e)}`,void 0,t.company);if(t.json){w(n);return}sC(n.key),KZ(n.key)}catch(n){T(n instanceof g?n:n),process.exitCode=1}}async function YZ(e){if(!await HA())return;if(!e.name){T(Error("--name is required")),process.exitCode=1;return}try{let t=await E("POST","/api/v1/web-tracking-keys",{name:e.name,allowedOrigins:e.origins?oC(e.origins):[],allowedAppIds:e.appIds?oC(e.appIds):[]},e.company);if(e.json){w(t);return}console.log("Web tracking key created."),console.log(""),sC(t.key),KZ(t.key)}catch(t){T(t instanceof g?t:t),process.exitCode=1}}async function ZZ(e,t){if(!await HA())return;if(t.activate&&t.deactivate){T(Error("Pass only one of --activate and --deactivate")),process.exitCode=1;return}let n={};if(t.name!==void 0)n.name=t.name;if(t.origins!==void 0)n.allowedOrigins=oC(t.origins);if(t.appIds!==void 0)n.allowedAppIds=oC(t.appIds);if(t.activate)n.isActive=!0;if(t.deactivate)n.isActive=!1;if(Object.keys(n).length===0){T(Error("Nothing to update. Pass --name, --origins, --app-ids, --activate or --deactivate.")),process.exitCode=1;return}try{let r=await E("PATCH",`/api/v1/web-tracking-keys/${encodeURIComponent(e)}`,n,t.company);if(t.json){w(r);return}console.log("Web tracking key updated."),console.log(""),sC(r.key)}catch(r){T(r instanceof g?r:r),process.exitCode=1}}async function XZ(e,t){if(!await HA())return;if(!await rt(`Delete web tracking key ${e}? Cached authorization expires within one minute.`,{yes:t.yes})){console.log("Cancelled.");return}try{let r=await E("DELETE",`/api/v1/web-tracking-keys/${encodeURIComponent(e)}`,void 0,t.company);if(t.json){w(r);return}console.log(r.message)}catch(r){T(r instanceof g?r:r),process.exitCode=1}}function t5(e){if(e===void 0||e.length===0)return;let t=new Set(sx);for(let n of e)if(!t.has(n))throw new g(`Invalid --event value '${n}'. Valid events: ${sx.join(", ")}`,400);return e}function Lqe(e){if(!e.name||e.name.trim()==="")throw new g("--name is required",400);if(!e.url||e.url.trim()==="")throw new g("--url is required",400);let t=t5(e.event);return{name:e.name,url:e.url,...t!==void 0&&{events:t}}}function Uqe(e){if(e.enable===!0&&e.disable===!0)throw new g("Use either --enable or --disable, not both",400);let t=t5(e.event),n=e.enable===!0?"enabled":e.disable===!0?"disabled":void 0,r={...e.name!==void 0&&{name:e.name},...e.url!==void 0&&{url:e.url},...t!==void 0&&{events:t},...n!==void 0&&{status:n}};if(Object.keys(r).length===0)throw new g("Provide at least one of: --name, --url, --event, --enable, --disable",400);return r}function e5(e){if(console.log(`- ${e.name} [${e.id}]`),console.log(` URL: ${e.url}`),console.log(` Status: ${e.status}`),e.status==="disabled"&&e.autoDisabledAt)console.log(` Disabled automatically: ${te(e.autoDisabledAt)} (every delivery failed for 7 days; re-enable with --enable once the endpoint returns 2xx)`);else if(e.failingSince)console.log(` Failing since: ${te(e.failingSince)}`);if(console.log(` Events: ${e.events.join(", ")||"None"}`),e.consecutiveFailures>0)console.log(` Consecutive failures: ${e.consecutiveFailures}`);if(e.lastSuccessAt)console.log(` Last success: ${te(e.lastSuccessAt)}`);if(e.lastFailureAt)console.log(` Last failure: ${te(e.lastFailureAt)}`);console.log(` Created: ${te(e.createdAt)}`)}function GR(e){if(console.log(`- ${e.id} [${e.status}]`),console.log(` Event: ${e.eventType} (${e.eventId})`),console.log(` Attempts: ${e.attempts}`),e.lastStatusCode!==null)console.log(` Last status code: ${e.lastStatusCode}`);if(e.lastError)console.log(` Last error: ${e.lastError}`);if(e.lastAttemptAt)console.log(` Last attempt: ${te(e.lastAttemptAt)}`);if(e.nextAttemptAt)console.log(` Next attempt: ${te(e.nextAttemptAt)}`);console.log(` Created: ${te(e.createdAt)}`)}async function Zl(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let i=await E("GET","/api/v1/webhooks",void 0,t.company);if(t.json){w(i);return}console.log(`Webhooks (${i.webhooks.length})`);for(let o of i.webhooks)e5(o);return}if(e==="create"){let i=await E("POST","/api/v1/webhooks",Lqe(t),t.company);if(t.json){w(i);return}let o=i.webhook;console.log(`Created webhook: ${o?.name??t.name}`),console.log(`ID: ${o?.id??"Unknown"}`),console.log(`URL: ${o?.url??t.url}`),console.log(`Status: ${o?.status??"enabled"}`),console.log(`Events: ${o?.events.join(", ")??"None"}`),console.log(""),console.log("Signing secret (shown only once - store it somewhere safe now):"),console.log(` ${o?.signingSecret??"Unavailable"}`);return}if(!t.id)throw new g("Webhook ID is required",400);let n=`/api/v1/webhooks/${encodeURIComponent(t.id)}`;if(e==="update"){let i=await E("PATCH",n,Uqe(t),t.company);if(t.json){w(i);return}if(console.log(`Updated webhook: ${i.webhook?.name??t.id}`),i.webhook)e5(i.webhook);return}if(e==="delete"){if(!await rt(`Permanently delete webhook ${t.id} and its delivery history?`,t)){console.log("Aborted.");return}let i=await E("DELETE",n,void 0,t.company);if(t.json){w(i);return}console.log(`Deleted webhook: ${t.id}`);return}if(e==="test"){let i=await E("POST",`${n}/test`,void 0,t.company);if(t.json){w(i);return}if(console.log(`Queued test event for webhook: ${t.id}`),console.log(`Event ID: ${i.eventId}`),console.log(`Queued deliveries: ${i.queuedDeliveries}`),i.delivery)GR(i.delivery),console.log(`Check the result with: sequenzy webhooks deliveries ${t.id}`);return}if(e==="deliveries"){let i=nt(t.limit,"--limit");if(i!==void 0&&(i<1||i>100))throw new g("--limit must be an integer between 1 and 100",400);let o=await E("GET",`${n}/deliveries${i!==void 0?`?limit=${i}`:""}`,void 0,t.company);if(t.json){w(o);return}console.log(`Deliveries (${o.deliveries.length})`);for(let c of o.deliveries)GR(c);return}if(!t.deliveryId)throw new g("Delivery ID is required",400);let r=await E("POST",`${n}/deliveries/${encodeURIComponent(t.deliveryId)}/replay`,void 0,t.company);if(t.json){w(r);return}console.log(`Replay queued for delivery: ${t.deliveryId}`),GR(r.delivery)}catch(n){T(n instanceof g?n:n),process.exit(1)}}var Mqe={dkim:"DKIM",dkim_spare:"Spare DKIM",return_path:"Return path",ses_return_path:"Second return path"};function aC(e,t,n=""){if(!t)return;if(t.status==="available"){console.log(`${n}DNS upgrade: available. Run \`sequenzy websites upgrade-dns ${e}\` for a one-time, optional upgrade to our new DNS structure that improves deliverability and security. Sending isn't interrupted.`);return}if(t.status==="in_progress"){console.log(`${n}DNS upgrade: in progress since ${te(t.startedAt)}. Add these records next to your current ones; the domain switches by itself about an hour after the required ones are visible on public DNS:`);for(let i of t.records??[]){let o=Mqe[i.purpose]??i.purpose;console.log(`${n} ${o}: ${i.name} ${i.type} ${i.value} (${i.status??"pending"}${i.required?", required":""})`)}let r=t.trackingRecord;if(r)console.log(`${n} Link tracking: ${r.name} ${r.type} ${r.value} (${r.status}, optional)`);if(t.replacedRecords?.length){console.log(`${n}Optional: about a week after the switch, you can remove these current records:`);for(let i of t.replacedRecords)console.log(`${n} ${i.type} ${i.name}`)}return}if(t.status==="completed"){if((t.oldRecords??[]).filter((i)=>!i.removed).length===0){console.log(`${n}DNS upgrade: completed ${te(t.completedAt)}. Old records removed.`);return}console.log(`${n}DNS upgrade: completed ${te(t.completedAt)}. Optional: you can remove these old records after ${te(t.deleteOldRecordsAfter)}; until then emails sent before the switch still use them:`);for(let i of t.oldRecords??[])console.log(`${n} ${i.type} ${i.name}${i.removed?" (removed)":""}`)}}function n5(e){if(console.log(`DNS: ${e.dnsVerified===void 0?e.status:e.dnsVerified?"verified":e.status}`),e.readyToSend!==void 0){let t=e.readiness?.reason;console.log(`Sending: ${e.readyToSend?"ready":e.readiness?.status??"not ready"}${!e.readyToSend&&t?` (${t})`:""}`)}for(let t of e.dnsRecords?.platformDnsRecords??[]){let n=t.purpose==="dkim"?"DKIM":t.purpose==="dkim_spare"?"Spare DKIM":"Return path (recommended)";console.log(`${n}: ${t.name} CNAME ${t.value} (${t.status??"pending"})`)}if(e.bounceRecords){let t=e.bounceRecords;console.log(t.style==="cname"&&t.cnameRecord?`Bounce: ${t.cnameRecord.name} CNAME ${t.cnameRecord.value} (${t.status})`:`Bounce: SPF TXT + MX records (${t.status})`)}if(e.tracking?.cnameRecord){if(console.log(`Tracking (company-wide, optional): ${e.tracking.cnameRecord.name} CNAME ${e.tracking.cnameRecord.value} (${e.tracking.status??"pending"})`),e.tracking.error)console.log(e.tracking.error)}if(e.dnsRecords?.inboundRoutingStatus){if(console.log(`Reply routing: ${e.dnsRecords.inboundRoutingStatus}`),e.dnsRecords.inboundRoutingError)console.log(e.dnsRecords.inboundRoutingError)}aC(e.domain,e.dnsUpgrade)}async function Xl(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="list"){let l=await E("GET","/api/v1/websites",void 0,t.company);if(t.json){w(l);return}console.log(`Websites (${l.websites.length})`);for(let d of l.websites){if(console.log(`- ${d.domain}`),console.log(` DNS: ${d.dnsVerified===void 0?d.status:d.dnsVerified?"verified":d.status}`),d.readyToSend!==void 0)console.log(` Sending: ${d.readyToSend?"ready":d.readiness?.status??"not ready"}`);aC(d.domain,d.dnsUpgrade," "),console.log(` Created: ${te(d.createdAt)}`)}return}if(e==="guide"){let l=await E("POST","/api/v1/integration-guide",{framework:t.framework,use_case:t.useCase});if(t.json){w(l);return}if(console.log(`Integration guide: ${l.framework} / ${l.use_case}`),console.log(""),console.log(l.code),l.tip)console.log(""),console.log(`Tip: ${l.tip}`);return}if(!t.domain)throw new g("Domain is required",400);if(e==="verify"){let l=await E("POST",`/api/v1/websites/${encodeURIComponent(t.domain)}/verify`,void 0,t.company);if(t.json){w(l);return}if(console.log(l.website.domain),n5(l.website),console.log(l.message),l.website.dnsRecords!==void 0)console.log("DNS Records:"),w(l.website.dnsRecords);return}if(e==="upgrade-dns"){let l=await E("POST",`/api/v1/websites/${encodeURIComponent(t.domain)}/dns-upgrade`,t.mailFromPrefix!==void 0?{mailFromPrefix:t.mailFromPrefix}:void 0,t.company);if(t.json){w(l);return}console.log(l.website.domain),aC(l.website.domain,l.website.dnsUpgrade);return}if(e==="configure"&&!t.trackingPrefix)throw new g("--tracking-prefix is required",400);let n=e==="add"?"POST":e==="configure"?"PATCH":"GET",r=e==="add"?"/api/v1/websites":`/api/v1/websites/${encodeURIComponent(t.domain)}`,i=e==="add"?{domain:t.domain,...t.mailFromPrefix!==void 0&&{mailFromPrefix:t.mailFromPrefix},...t.trackingPrefix!==void 0&&{trackingPrefix:t.trackingPrefix}}:e==="configure"?{trackingPrefix:t.trackingPrefix}:void 0,o=await E(n,r,i,t.company);if(t.json){w(o);return}if(console.log(o.website.domain),n5(o.website),o.website.createdAt)console.log(`Created: ${te(o.website.createdAt)}`);let c=o.message??o.website.message;if(c)console.log(c);if(o.website.dnsRecords!==void 0)console.log("DNS Records:"),w(o.website.dnsRecords)}catch(n){T(n instanceof g?n:n),process.exit(1)}}async function r5(){if(!await j()){T(z()),process.exit(1);return}let e=pv();console.log(`Email: ${e.userEmail??"Unknown"}`),console.log(`User ID: ${e.userId??"Unknown"}`),console.log(""),console.log("A local API key is available."),console.log("Use `sequenzy account` to verify the active API key, permissions, and available companies.")}async function i5(e,t){if(!await j())T(z()),process.exit(1);try{if(e==="preferences-token"){if(!t.email)throw new g("Email is required",400);let n=await E("POST","/api/v1/widgets/preferences/token",{email:t.email},t.company);if(t.json){w(n);return}console.log(n.token)}}catch(n){T(n instanceof g?n:n),process.exit(1)}}var a5=Ky.version,jqe="\x1B[38;5;208m",Ja="\x1B[2m",o5="\x1B[1m",zqe="\x1B[32m",Gqe="\x1B[33m",Hqe="\x1B[36m",$i="\x1B[0m",JA='Poll/NPS blocks are supported in block JSON. Use {"type":"poll","variant":"options","question":"...","options":[{"label":"Yes","value":"yes"},{"label":"No","value":"no"}],"attributeKey":"email_feedback"}; for NPS use variant "nps", options [], and attributeKey "nps_score".';async function Jqe(){let e=await j(),t=pv(),n=`${jqe}
|