@dereekb/zoho 13.27.1 → 13.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/index.js +5 -5
- package/cli/package.json +7 -7
- package/nestjs/package.json +5 -5
- package/package.json +8 -8
package/cli/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from 'node:module';
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
var Fc=Object.defineProperty;var Sc=Object.getOwnPropertyDescriptor;var A=(e,t,o,r)=>{for(var n=r>1?void 0:r?Sc(t,o):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(r?a(t,o,n):a(n))||n);return r&&n&&Fc(t,o,n),n},k=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Ac,mkdirSync as bc,writeFileSync as Ic}from"node:fs";import{join as kc}from"node:path";var xr=1;var to=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],Zr=6e4,Ne={},Fr=[...to],eo,Pc=!1,Ec=Zr;function oo(e){Ne=e}function At(){return Ne}function Sr(e){Pc=e}function Ar(e){Ec=e===void 0?Zr:e}function ro(e){Fr=e}function br(e){eo=e}function de(e){let t=e;for(let o of Fr)t=t.replace(o,"[REDACTED]");return t}function Ir(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function at(e,t){let{dumpDir:o,commandPath:r}=Ne,n;if(o){Ac(o)||bc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Ir(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=kc(o,`${s}.${e}`)}else n=void 0;return n}function Oc(e,t){let o=at("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Ic(o,JSON.stringify(r,null,2))}function Ae(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>Cr(n,o)):e!=null&&typeof e=="object"?r=Cr(e,o):r=e,r}function Cr(e,t){let o;if(e==null||typeof e!="object")o=e;else{let r={};for(let n of t)n in e&&(r[n]=e[n]);o=r}return o}function kr(e){return Ne.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function l(e,t){Oc(e,t);let r={ok:!0,data:Ne.pick?Ae(e,Ne.pick):e,...t?{meta:t}:{}};console.log(kr(r))}function Pr(e){console.log(kr(no(e)))}var it=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function no(e){let t=eo?eo(e):void 0,o;return t?o=t:e instanceof it?o={ok:!1,error:de(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:de(e.message),code:"ERROR"}:o={ok:!1,error:de(String(e)),code:"UNKNOWN_ERROR"},o}function we(e,t=!1){let o;return typeof e=="string"?o=t:e!=null&&typeof e=="object"&&Symbol.iterator in e?o=!0:o=!1,o}function st(e){let t=!0;for(let o of e){t=!1;break}return t}function io(e,t){for(let o of e)t(o)}function q(e,t,o=!1){e!=null&&(we(e,o)?io(e,t):t(e))}function Er(e){if(!Array.isArray(e))throw new TypeError("Input is not an array/tuple...");let t;if(e.length>0){let o=e[0],r=!1;if(Array.isArray(o)){let n=o.length;r=e.findIndex(a=>Array.isArray(a)?a.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Dc(e){return e==null?[]:Mc(e)}var C=Dc;function Mc(e){return Array.isArray(e)?e:[e]}function Or(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function ao(e){return Object.keys(e).length===0}function Dr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Mr(e){return{...e}}function _r(e){return e!=null}function bt(e){return we(e,!1)?!st(e):vr(e)}function so(e){let t;return we(e,!0)?t=!st(e):vr(e)?t=typeof e=="object"?!ao(e):!0:t=!1,t}function vr(e){return e!=null&&e!==""}function _c(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var me=_c(_r);function Nr({base:e,build:t}){let o=e??{};return t(o),o}var vc=(e=>e);function wr(){return vc}function Ue(e,t){let o=Nc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Nc(e,t){return Dr(wc(e,t))}function wc(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),i=o.get(n);i==null?o.set(n,[r]):i.push(r)}),o}function Ur(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function co(e){return Array.from(e.entries())}function Lr(e){return Uc(co(e))}function Uc(e){let t=[];return e.forEach(([o,r])=>{q(r,n=>{t.push([o,n])})}),t}function Gr(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),q(i,s=>a.push(s))},o=(n,i)=>t(n,Er(i));return{map:()=>e,entries:()=>co(e),tuples:()=>Lr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>q(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>q(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Lc(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function Kr(e){let t=Lc(e);return t!=null&&t!=="class"}function Vr(e){return Kr(e)?e:()=>e}function Hr(e,t){return Math.log(t)/Math.log(e)}var zr=",",Gc=" ";function Kc(e,t=zr,o=!1){if(e==null)return e;let r=C(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function uo(e,t,o){let r;switch(o){case 1:r=[e];break;case 2:{let n=e.indexOf(t);r=n<0?[e]:[e.slice(0,n),e.slice(n+t.length)];break}default:{let n=e.split(t),i=[];if(n.length>1){let a=n.length>o,s=a?o-1:n.length;for(let c=0;c<s;c+=1)i.push(n[c]);a&&i.push(n.slice(s).join(t))}else i.push(n[0]);r=i;break}}return r}function Vc(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return Kc(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function jr(e){let{joiner:t}=e,o=Vc(e),r=(n,i=a=>a)=>n.split(t).map(s=>i(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,i){return uo(n,t,i)}}}var po=jr({joiner:zr}),Hc=jr({joiner:Gc,trimByDefault:!0});var P=po.joinStrings,em=po.splitStrings,tm=po.splitStringsToSet,om=Hc.joinStrings;var Wr=Or;function qr(e,{forEach:t,filter:o}){zc(e,o).forEach((n,i)=>t(n,i))}function zc(e,t){return lo(t)(e)}function lo(e){let t;if(e==null)t=Br;else{let o=jc(e);t=r=>Br(r).filter((n,i)=>o(n,i))}return t}function Br(e){return Object.entries(e)}function ho(e){return typeof e=="object"?e:{valueFilter:e}}function jc(e){let t=ho(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,i;switch(o){case 1:i=([,a])=>a!==void 0;break;case 2:i=([,a])=>a!=null;break;case 3:i=([,a])=>!!a;break;case 4:i=([,a])=>bt(a);break;case 5:i=([,a])=>so(a);break;case 6:i=([,a])=>!!a&&bt(a);break;case 7:i=([,a])=>!!a&&so(a);break;default:i=()=>!0;break}if(n){let a=i,s=new Set(n.map(c=>c.toString()));i=(c,u)=>a(c,u)&&s.has(c[0])}return Wr(i,r)}function ct(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function Jr(e){let t;return e==null||Yc(e)?t=e:t=Wc(e),t}function Wc(e){return e==null?e:new Date(e)}var $r=24,Bc=60;var qc=60,Jc=qc*Bc,L=1e3,be=L*60,mo=be*60,$c=mo*$r,pm=Jc*$r,Xc=7,dm=$c*Xc;function Yc(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Xr(e){return e.getTime()<Date.now()}function Yr(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function Qc(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:Jr(n);function c(y){return y??r??new Date}function u(y,m=!1){let T=c(y),g=d(T),R;return g==null?R=m:R=g<=T,R}function p(y){let m=c(y);return d(m)}function d(y){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:a!=null&&(m=Yr(s??(i===!1?null:y),a)),m}return{input:e,hasExpired:u,getExpirationDate:p}}function Qr(e,t){let o=!0;return e!=null&&(o=Qc(e).hasExpired(t,!0)),o}function eu({filter:e,copy:t,dynamic:o=!1}){let r=e==null?ou:Le({filter:e,copy:!1});return n=>{let i=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},a=o?i:ct(i);return s=>{let c=a();return t&&(s=Mr(s)),Object.assign(s,c),s}}}function en(e,t){return tu(t)(e)}function tu(e){let t=eu({filter:e,copy:!1,dynamic:!0});return o=>t(me(o))({})}var Cm=Le({copy:!0,filter:{valueFilter:1}}),xm=Le({copy:!0,filter:{valueFilter:2}}),tn=Le({copy:!0,filter:{valueFilter:4}}),Zm=Le({copy:!0,filter:{valueFilter:6}}),Fm=yo({valueFilter:1}),Sm=yo({valueFilter:6}),Am=yo({valueFilter:2});function yo(e){let t=on({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Le({copy:e=!1,filter:t={valueFilter:1}}={}){let o=ho(t);o.invertFilter=!o.invertFilter;let r=on({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var ou=Le({copy:!1});function on({forEach:e,filter:t}){let o=lo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function rn(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function nn(e){let t,o,r=0;function n(){let i;if(t==null){if(o==null){let a=r;o=e.load().then(s=>(r===a&&(t={entries:s},o=void 0),s),s=>{throw r===a&&(o=void 0),s})}i=o}else i=Promise.resolve(t.entries);return i}return{load:async()=>({...await n()}),get:async i=>(await n())[i],set:async(i,a)=>{let s=await n();r+=1,o=void 0,await e.set(i,a),t={entries:{...s,[i]:a}}},remove:async i=>{let a=await n();r+=1,o=void 0,await e.remove(i);let s={...a};delete s[i],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function an(e){return{load:async()=>{let t;for(let o of e){let r=await o.load();if(r!=null){t=r;break}}return t},update:async t=>{for(let o=e.length-1;o>=0;o-=1)await e[o].update(t)},clear:async()=>{for(let t=e.length-1;t>=0;t-=1)await e[t].clear()}}}function It(e,t,o){let[r,n]=go(e,t,!1);return r+o+n}function go(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var ru=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],Dm=new Set(ru);function sn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=kt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=It(n,i[0],o(s));break}default:{let s=[],c=i.length,u=0,p=0;for(let d=0;d<c;d+=1){p=i[d];let y=n[p],T=n.substring(u,p)+o(y);s.push(T),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function nu(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of[...t].entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function kt(e,t,o){return nu(e)(t,o)}function iu(e,t){return kt(e,t,1)[0]}function au(e){return t=>{let r=iu(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=go(t,r,!1),n}}function cn(e,t){return au(t)(e)}var Ge="/",su=".";function cu(e){let t=e.split(su,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ge?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function un(e){return cu(e)!=="invalid"}var uu=/^\/+/,pu=/\/+$/;var du=/\/{2,}/g;function pn(e){return e.startsWith(Ge)?e.replace(uu,Ge):`${Ge}${e}`}function dn(e){return e.replaceAll(du,Ge)}function ln(e){return e.replace(pu,"")}function lu(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var hn=/:(\d+)/;function hu(e){return hn.test(e)}function mu(e){let t=hn.exec(e);return t?Number(t[1]):void 0}function yu(e){let t=fn(e),o=gu(t),{domain:r,path:n}=o,i=lu(r),a=hu(e),s=a?mu(e)??void 0:void 0,[c,u]=cn(o.path,"?"),p=i&&(c===""||un(c+"/")),d=Ru(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:i,hasHttpPrefix:d,hasPortNumber:a,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function mn(e){let t=yu(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function yn(e,t=!1){let o=kt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(i=>n=It(n,i,"&")),n}function gu(e){let t=fn(e);return fu(t)}function fu(e){let t=uo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:pn(r??"/")}}var gn=/^https:\/\/|http:\/\//;function fn(e){return e.replace(gn,"")}function Ru(e){return gn.test(e)}function S(){}function Rn(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function fo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Tu(e){let n=mo,i={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},a=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;m(e??i);function p(){return{...i}}function d(){return u}function y(F){u=F}function m(F,U=!1){let z=Math.max(0,F.startLimitAt??1),b=F.cooldownRate??1,v=F.maxWaitTime??n,V=F.exponentRate??2;i={startLimitAt:z,cooldownRate:b,maxWaitTime:v,exponentRate:V},s=Hr(V,v/L+1),U&&T()}function T(){a=0,c=new Date}function g(F){let U;if(u){let{cooldownRate:z}=i,v=(Date.now()-c.getTime())*z/L,V=Math.max(a-v,0),j=Math.max(0,V-i.startLimitAt);F&&(a=V+F,c=new Date),U=j>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(j,0))-1)*L}else U=0;return U}function R(F){return g(F??0)}function Z(){let F=g(1);return fo(F)}return{waitForRateLimit:Z,getNextWaitTime:R,getConfig:p,setConfig:m,getEnabled:d,setEnabled:y,reset:T}}function Tn(e){let o=Tu({exponentRate:1.5,maxWaitTime:L*8,...e}),r=be,n=new Date,i=0,a=0,s=!0;Z(e,!0);function c(){Xr(n)&&d()}function u(){return s}function p(b){s=b}function d(){a=i,n=new Date(Date.now()+r)}function y(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function T(b){n=b}function g(){return c(),a}function R(b){a=b}function Z(b,v=!1){i=b.limit??i,r=b.resetPeriod??r;let V={cooldownRate:b.cooldownRate??Math.max(.1,r/L),exponentRate:b.exponentRate??1.5,maxWaitTime:b.maxWaitTime??L*8};o.setConfig(V,v),v&&d(),n=b.resetAt??n}function F(b){let v=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var V=j;a>0?v=j():(c(),a>0?v=j():v=m())}return v}function U(b){return F(b??0)}function z(){let b=F(1);return fo(b)}return{getRemainingLimit:g,setRemainingLimit:R,getTimeUntilNextReset:m,getResetAt:y,setNextResetAt:T,setConfig:Z,reset:d,getNextWaitTime:U,waitForRateLimit:z,getEnabled:u,setEnabled:p}}var Cu="__CATCH_ALL_HANDLE_RESULT_KEY__";function Cn(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,i=new Map,a=u=>{n=u},s=(u,p)=>{u===Cu?a(p):Ur(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return Nr({base:(u=>{let p=e(u),d=(p==null?void 0:i.get(p))??n,y;return d?y=Promise.resolve(d(u)).then(m=>m??o):y=Promise.resolve(r),y}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function xu(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Zu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Fu(e,t,o){let r=Zu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function xn(e,t){return o=>Fu(e,o,t)}function Zn(e){return t=>(o,r)=>{let n=xu(o,t),i=e.configurerForAccessor(n);r(i)}}var Su=-1,Fn=0;function Au(e){return e?.page??Su}function Sn(e){return Au(e)+1}import{BaseError as An}from"make-error";var J=class extends An{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function bn(e){return(t,o)=>bu(e(t,o))}var Ke=class extends An{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function bu(e){return e.then(t=>{if(!t.ok)throw new Ke(t);return t})}import{BaseError as iy}from"make-error";function In(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let a=new AbortController;r=a,o={...o,signal:a.signal}}let i=e(t,o??void 0);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function Pn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>En({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>ku({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Iu=(e,t)=>t(e);function ku(e){let{makeFetch:t=fetch,fetchHandler:o=Iu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=In(a)),n&&(a=bn(a));let s=En(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var Pu=(e,t)=>new Request(e,t??void 0);function En(e){let{makeRequest:t=Pu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(ln(o)):void 0,u=c?m=>{let T,g=m.toString();if(!s&&mn(g))T=new URL(g);else{let R=c.origin+dn("/"+c.pathname+"/"+m);T=new URL(R,c)}return T}:void 0;async function p(m){let T=Rn(m)?await m:m;return kn(T)?T:t(T)}let d=u?async m=>{let T,g,R;if(typeof m=="string"?T=m:kn(m)?a?(T=m.url,g=m):R=m:R=await t(m),!R){let Z=u(T);R=await t(Z.href,g)}return R}:p,y;if(r!=null||n!=null){let m=Vr(r);async function T(){let R=await m();return n?{...R,timeout:n}:R}async function g(R,Z){let F=await T(),U=Eu(F,await Z),z=U.timeout===void 0?R.timeout:U.timeout;return{...U,timeout:z}}i?y=(R,Z)=>i(R,g(R,Z)):y=(R,Z)=>g(R,Z)}else i?y=i:y=(m,T)=>T;return async(m,T)=>{try{let g=await d(m);T=await y(g,T??void 0);let R=await t(g,T);return R.timeout=n,R}catch(g){throw g instanceof J?g:new J(g)}}}function Eu(e,t){let o;if(t){let r=Ou([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Ou(e){let t=Gr();return me(e).forEach(o=>{let r=Du(o),n=new Set;r.forEach(([i,a])=>{n.has(i)||(t.delete(i),n.add(i)),a&&t.add(i,a)})}),t.tuples()}function Du(e){let t=[];return Array.isArray(e)?t=e:typeof e.forEach=="function"?e.forEach((o,r)=>{t.push([r,o])}):typeof e=="object"&&(t=Object.entries(e)),t}function kn(e){return!!e.url}import{safeParse as Mu}from"fast-content-type-parse";function Pt(e){let t=e.headers.get("content-type"),o=Mu(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function On(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,i=async(a,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(a.clone())}catch(m){d=m,p=d.response}if(await t(p,d)&&u<r)p=await c(u+1);else if(d!=null)throw d;return p}return c(0)};return i._rateLimiter=n,i}var Ro=class extends J{constructor(o){super("There was no next page for this.");this.page=o}},To=class extends J{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},_u=100;function Ve(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:i}=e;return(a,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??i,d=c===null?Number.MAX_SAFE_INTEGER:c??_u;function y(T,g=void 0){return async()=>{let R=await t(T),{cursor:Z,nextPageCursor:F,hasNext:U}=await o(R),z=Z??g?.cursor,b=U!==!1,v=g?g.page+1:Fn,V=v>=d,j={input:T,result:R,page:v,previous:g,hasNext:b,isAtMaxPage:V,cursor:z,nextPageCursor:F,fetchNext:ct(async()=>{if(V)throw new To(j,d);let Tr=b?await r(j,T,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Tr)throw new Ro(j);return y({...T,...Tr},j)()})};return j}}return{input:a,fetchNext:ct(()=>y(a)())}}}function f(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?en(e):e,i=r??!0?tn(n??{}):n,a=new URLSearchParams(i);return o!=null&&q(o,s=>a.delete(s),!1),a}function Co(e){let t;if(typeof e=="string")t=e;else if(vu(e))t=e.href;else{let o=Co(e.url);if(e.queryParams){let r=Uu(e.queryParams);st(r)?t=o:t=yn(o+`?${r.toString()}`)}else t=o}return t}function vu(e){return typeof e=="object"&&e instanceof URL}function Nu(e){return typeof e=="object"&&e instanceof URLSearchParams}function wu(e){let t=[];return io(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);q(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Uu(e){let t;return Nu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):we(e)?t=new URLSearchParams(wu(e)):t=Lu(e),t}function Lu(e){let t=[];return qr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&q(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var xo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Gu(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Ku=e=>{throw new xo(e)},Y=e=>null;function Q(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Ku};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=Dn(o);return(a,s,c)=>{let u=Co(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(m=>{let T=m.json().catch(r),g=n?T.then(R=>n(R,m)):T;return d?g.then(R=>d(R,m)):g})}}function Dn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=wr()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r??{method:t,body:n},i=o(i),{...i,method:i.method,body:Gu(i.body)}}}var Sy=Dn();var ee=Pn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function Mn(e){let t,o=e?.notInitializedMessage??"Context slot has not been initialized.";return{set:r=>{t=r},get:()=>t,require:()=>{if(t==null)throw new Error(o);return t}}}function Et(e,t=xr){return async o=>{try{await e(o)}catch(r){Pr(r),process.exit(t)}}}var Vu=["raw","page_by_line","data_by_line"],Hu=["replace","concat"],zu=["meta","pages","merged_page"];function Zo(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from the per-API page/offset flag."}).option("multiple-pages-output",{type:"string",choices:zu,default:"meta",describe:"Stdout shape when multiple-pages > 1: meta (summary, low memory), pages (array of page responses, WARNING: holds all pages in memory), merged_page (concat all records into one array, WARNING: holds all records in memory)."}).option("dump-output",{type:"string",choices:Vu,default:"raw",describe:"Dump file format when --dump-dir is set. raw: one full JSON page response (concatenated JSON when --dump-merge=concat, not standard JSON). page_by_line: NDJSON of page responses. data_by_line: NDJSON of records."}).option("dump-merge",{type:"string",choices:Hu,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as ju}from"@nestjs/common";var tg=ju((e,t)=>Wu(t));function Wu(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Fo,BadRequestException as Bu,InternalServerErrorException as qu,Logger as Ju}from"@nestjs/common";import $u from"raw-body";import{parse as Xu}from"node:querystring";var _n=new Ju("RawBody"),ag=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw _n.error("RawBody request was not readable. This is generally due to bad configuration."),new Bu("Invalid body");return $u(o)}),vn=Fo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw _n.error("RawBody expected a buffer set to req.body."),new qu("failed parsing body");return r}),sg=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Yu(o.body),o.body});function Yu(e){let t=Qu(e);return Xu(t)}function Qu(e){return e.toString("utf8").trim()}import{Injectable as ep}from"@nestjs/common";import tp from"body-parser";var He=class{use(t,o,r){tp.json()(t,o,r)}};He=A([ep()],He);import{Injectable as op}from"@nestjs/common";import rp from"body-parser";var ze=class{use(t,o,r){rp.raw({type:"*/*"})(t,o,r)}};ze=A([op()],ze);import{Logger as np,Module as ip,RequestMethod as ap}from"@nestjs/common";var sp="/webhook",cp={path:`${sp}/{*path}`,method:ap.POST},So=class{configure(t){up(t)}},Ot=class extends So{logger=new np("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Ot=A([ip({})],Ot);function up(e){e.apply(ze).forRoutes(cp).apply(He).forRoutes("{*path}")}var Nn="CLIENT_WEB_APP_URL";var Ie=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as pp,Injectable as dp}from"@nestjs/common";var ke=class{_config;constructor(t){this._config=t}get config(){return this._config}get webAppUrl(){return this.config.client.clientWebAppUrl}get webAppHost(){return this.webAppUrl.split("://",2)[1]}};ke=A([dp(),k(0,pp(Ie))],ke);import{Module as lp}from"@nestjs/common";import{ConfigModule as hp,ConfigService as mp}from"@nestjs/config";function yp(e){let t={client:{clientWebAppUrl:e.get(Nn)}};return Ie.assertValidConfig(t),t}var Dt=class{};Dt=A([lp({imports:[hp],providers:[{provide:Ie,inject:[mp],useFactory:yp},ke],exports:[ke]})],Dt);var wn="SERVER_ENV_TOKEN";import{Inject as gp,Injectable as fp}from"@nestjs/common";function Un(){return process.env.NODE_ENV==="test"}var Mt=class{constructor(t){this.env=t}get isTestingEnv(){return Un()}get isProduction(){return this.env.production}get isStaging(){return!!this.env.staging}get developerToolsEnabled(){return!!(!this.isProduction&&this.env.developerToolsEnabled)}get appUrl(){return this.env.appUrl}get appApiUrl(){return this.env.appApiUrl}};Mt=A([fp(),k(0,gp(wn))],Mt);import{dirname as Fp}from"node:path";import{chmod as Rp,mkdirSync as Tp,readFile as Cp,writeFile as xp}from"node:fs";import{rm as Zp}from"node:fs/promises";function ye(e){return new Promise((t,o)=>{Cp(e,{encoding:"utf-8"},(r,n)=>{if(r){r.code==="ENOENT"?t(void 0):o(r);return}try{t(JSON.parse(n))}catch{t(void 0)}})})}function _t(e){return Tp(e.dirPath,{recursive:!0}),new Promise((t,o)=>{xp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():Rp(e.filePath,e.mode,n=>{n?o(n):t()})})})}function ut(e){return Zp(e,{force:!0})}var Sp=384;function Ln(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??Sp;async function a(){let p=await ye(t),d;if(p==null)d={};else if(r==null)d=p;else{d={};for(let y of Object.keys(p)){let m=r(p[y]);m!=null&&(d[y]=m)}}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([y,m])=>[y,n(m)]));await _t({filePath:t,dirPath:Fp(t),data:d,mode:i})}let c=Promise.resolve();function u(p){let d=c.then(p,p);return c=d.catch(()=>{}),d}return{load:a,get:async p=>(await a())[p],set:(p,d)=>u(async()=>{let y=await a();await s({...y,[p]:d})}),remove:p=>u(async()=>{let y={...await a()};delete y[p],await s(y)}),clear:()=>u(async()=>{await ut(t)})}}var Af=Buffer.from([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function pt(e){return ye(e.configFilePath)}function Ap(e){return _t({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function dt(e){let t=await pt({configFilePath:e.configFilePath})??{},o={activeEnv:e.updates.activeEnv??t.activeEnv,envs:e.updates.envs?{...t.envs,...e.updates.envs}:t.envs,output:e.updates.output===void 0?t.output:Ao(t.output,e.updates.output)};return await Ap({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Ao(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:bp(e?.commands,t)}}function bp(e,t){let o;if("commands"in t)if(t.commands){let r={...e};for(let n of Object.keys(t.commands))r[n]={...e?.[n],...t.commands[n]};o=r}else o=void 0;else o=e;return o}function Gn(e){let t=e.commandPath.join("."),o=t?e.outputConfig?.commands?.[t]:void 0;return{dumpDir:e.cliFlags.dumpDir??o?.dumpDir??e.outputConfig?.dumpDir,pick:e.cliFlags.pick??o?.pick??e.outputConfig?.pick}}function ge(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Ip}from"node:os";import{join as bo}from"node:path";function vt(e){let t=e.configDirOverride??bo(Ip(),`.${e.cliName}`);return{configDir:t,configFilePath:bo(t,"config.json"),tokenCachePath:bo(t,".tokens.json")}}function Kn(e){let t=vt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{Sr(!!n.verbose),Ar(typeof n.timeout=="number"?n.timeout*1e3:void 0);let i=n._?n._.map(String):[],a=i[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&a&&!e.skipCommands.has(a)){let m=i.join("."),T={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,T)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?Gn({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};oo({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function kp(e){let t=vt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{dumpDir:void 0,pick:void 0,commands:void 0}}}));return{loadOutputConfig:o,mergeOutputConfig:r,clearOutputConfig:n}}function Vn(e){let t=kp(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(a=>{if(a.setDumpDir==null&&a.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:Et(async i=>{let a=i.command,s=i.setDumpDir,c=i.setPick,u;if(a){let d={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[a]:d}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let p=await t.loadOutputConfig();l({saved:!0,output:p??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:Et(async()=>{let i=await t.loadOutputConfig();l({output:i??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:Et(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new it({message:`No per-command output config for "${a}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[a],await t.mergeOutputConfig({...s,commands:c}),l({cleared:!0,command:a})}else await t.clearOutputConfig(),l({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:i=>i.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:S}}import{writeFileSync as Pp,appendFileSync as Ep}from"node:fs";function Hn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=At(),n=t==="raw"?"json":"ndjson",i=at(n),a=r?at(n,"pick"):void 0,s;if(i){let c=0,u=g=>{let R;if(r){let Z=Ae(g.data,r);R={...g,data:Z}}else R=g;return R},p=g=>{let R=g.append?Ep:Pp;R(i,g.mainContent),a&&g.pickContent!==void 0&&R(a,g.pickContent)},d=(g,R)=>{let Z=JSON.stringify(g,null,2),F=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:Z,pickContent:F,append:R})},y=(g,R)=>{let Z=JSON.stringify(g)+`
|
|
5
|
-
`,
|
|
6
|
-
`:void 0;p({mainContent:
|
|
7
|
-
`,
|
|
8
|
-
`:void 0;p({mainContent:v,pickContent:V,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let Z=o==="concat"&&!(c===0);t==="raw"?d(g,Z):t==="page_by_line"?y(g,Z):m(g,Z),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Op(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:i,shouldCollectPages:a,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let p=0;p<o;p++){let d=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(d),c.lastResult=d,c.lastInput=u,i.writePage(d),a)c.collectedPages.push(d);else if(s)for(let m of d.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,d);let y=n.nextInput(u,d);if(!y)break;u=y}return c}function Dp(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:i}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let a=i?r.collectedPages.map(s=>({...s,data:Ae(s.data,i)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:a,meta:o}))}else{let a=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=i?Ae(r.collectedRecords,i):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...a,...o}}))}}async function I(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:i,dumpMerge:a}=e,s=Math.max(1,Math.floor(e.multiplePages||1)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=At();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Hn({dumpOutput:i,dumpMerge:a}),d;try{d=await Op({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:p,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{p.close()}let y={pagesFetched:d.pagesFetched,totalRecords:d.totalRecords,hasMorePagesAvailable:d.hasMorePagesAvailable,dumpFile:p.mainPath??null};p.pickPath&&(y.dumpFilePick=p.pickPath),Dp({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import Th from"yargs";import{hideBin as Ch}from"yargs/helpers";import{writeFile as Mp,mkdirSync as _p}from"node:fs";import{join as Io}from"node:path";import{homedir as vp}from"node:os";var Nt=["recruit","crm","desk"];function ko(){return Io(vp(),".zoho-cli")}function lt(){return Io(ko(),"config.json")}function ht(){return Io(ko(),".tokens.json")}function Pe(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function H(){let e=lt(),t=await ye(e),o=Pe("ACCOUNTS_CLIENT_ID"),r=Pe("ACCOUNTS_CLIENT_SECRET"),n=Pe("ACCOUNTS_REFRESH_TOKEN"),i=o&&r&&n,a;if(!t&&!i)a=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:Pe("ACCOUNTS_URL")??t?.shared?.region,apiMode:Pe("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Pe("API_URL",p),y=u==="desk"?Pe("DESK_ORG_ID"):void 0,m=t?.[u],T=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],Z=T||g||R,F;return!m&&!Z&&!y?F=void 0:F={clientId:T??m?.clientId,clientSecret:g??m?.clientSecret,refreshToken:R??m?.refreshToken,apiUrl:d??m?.apiUrl,orgId:y??m?.orgId},F};a={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,output:t?.output}}return a}function mt(e,t){let o=e[t],r=e.shared,n=o?.clientId??r.clientId,i=o?.clientSecret??r.clientSecret,a=o?.refreshToken??r.refreshToken,s;return!n||!i||!a?s=void 0:s={clientId:n,clientSecret:i,refreshToken:a,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},s}async function Np(e){let t=lt();return _p(ko(),{recursive:!0}),new Promise((o,r)=>{Mp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function te(e){let t=await H(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit===void 0?t?.recruit:{...t?.recruit,...e.recruit},crm:e.crm===void 0?t?.crm:{...t?.crm,...e.crm},desk:e.desk===void 0?t?.desk:{...t?.desk,...e.desk},output:e.output===void 0?t?.output:Ao(t?.output,e.output)};return await Np(o),o}async function zn(){await te({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function jn(){let e=lt(),t=ht();await ut(e),await ut(t)}function oe(e){return Nt.filter(t=>{let o=mt(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as Vs,Injectable as Dd}from"@nestjs/common";function je(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function N(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:Sn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function wt(e){let t;switch(e){case"sandbox":t="https://recruitsandbox.zoho.com/recruit";break;case"production":t="https://recruit.zoho.com/recruit";break;default:t=e;break}return t}var We="Candidates",Wn="Job_Openings",Ut="Notes",Bn="Emails",yt="Attachments";function Lt(e){let t;if(e!=null)switch(typeof e){case"string":t=e;break;case"object":{let o;Array.isArray(e)?o={and:[e]}:o=e,t=Gt(o);break}default:break}return t}function Gt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(Po):a&&(s=Gt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=me(a.map(t)).flatMap(C);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,i=n;return e.and&&(i=r([r(e.and,"and"),n],"and")),i}var qn=sn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Po(e){let t=qn(e.value);return`(${e.field}:${e.filter}:${t})`}var Jn=Lt;import{BaseError as Jp}from"make-error";import{BaseError as Up}from"make-error";var Lp="__internal_data_array_blank_error";function Gp(e){return Array.isArray(e?.data)}var $e="success";function $(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var fe=class extends Up{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},G=class extends fe{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Be=class extends G{constructor(t,o){super({code:Lp,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function re(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof Be&&!o||(r instanceof G?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof fe?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ne(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Ke){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ie(e){return(t,o)=>{if(t?.error!=null){let n=new Ke(o),i=e(t,n);if(i)throw i}return t}}var Kp="INTERNAL_ERROR",Vp="INVALID_TOKEN",K=class extends G{},$n="FAILURE",Eo=class extends G{},Hp="4834",qe=class extends G{},zp="INVALID_QUERY",Oo=class extends G{get details(){return this.error.details}},Kt="MANDATORY_NOT_FOUND",Re="DUPLICATE_DATA",Vt="INVALID_DATA",jp="TOO_MANY_REQUESTS",Xn=429,Wp="X-RATELIMIT-LIMIT",Bp="X-RATELIMIT-REMAINING",qp="X-RATELIMIT-RESET",Yn=100,Qn=be;function Do(e){let t=e.get(Wp),o=e.get(Bp),r=e.get(qp),n=null;if(t!=null&&o!=null&&r!=null){let i=Number(t),a=Number(o),s=Number(r),c=new Date(s);n={limit:i,remaining:a,reset:s,resetAt:c}}return n}var Je=class extends G{get headerDetails(){return Do(this.responseError.response.headers)}};function ae(e,t){let o;if(Gp(e))o=new Be(e,t);else{let r=le(e,t);if(r){let n=$(r);switch(n.code){case Kp:o=new Eo(n,e,t);break;case Vp:o=new K(n,e,t);break;case Hp:o=new qe(n,e,t);break;case zp:o=new Oo(n,e,t);break;case jp:o=new Je(n,e,t);break;default:o=new G(n,e,t);break}}}return o}function le(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var ei="ALREADY_ASSOCIATED",Mo=class extends Jp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Xe=class extends fe{},_o=class extends Xe{},vo=class extends Xe{},Ht=class extends Xe{get invalidFieldDetails(){return this.error.details}},No=class extends Ht{};function ti(e){let t;switch(e.code){case Vt:{let o=new Ht(e);o.invalidFieldDetails.id?t=new No(e):t=o;break}case Kt:t=new _o(e);break;case Re:t=new vo(e);break;default:t=new Xe(e);break}return t}function oi(e,t){return o=>{if(!o?.data?.length)throw new Mo(e,t);return o}}var $p=re("ZohoRecruit");async function Xp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ri(t,e)),o}function ri(e,t){let o,r=le(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var ni=ie(ri),ii=ne(Xp,$p);import{BaseError as Yp}from"make-error";function Uo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,M(o,{data:C(r)})).then(i=>{let a=Array.isArray(r),s=se(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw ti(p[0].result);c=u[0].result.details}return c}))}function ai(e){return Uo(e,"","POST")}function si(e){return Uo(e,"/upsert","POST")}function ci(e){return Uo(e,"","PUT")}function ui(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${f({ids:t,wf_trigger:r})}`,M("DELETE")).then(Qp)}function pi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,M("GET")).then(oi(t.module)).then(o=>o.data[0])}function di(e){return(t=>e.fetchJson(`/v2/${t.module}?${Ti(t).toString()}`,M("GET")))}function Lo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Jn(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return Ti(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,M("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function li(e){return N(Lo(e))}function Ye(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${Vo(n,n.filter).toString()}`,M("GET")).then(i=>i??(r===!1?i:je()))}}function Go(e){return Ye(e)({targetModule:Bn})}function hi(e){return N(Go(e))}function Ko(e){return Ye(e)({targetModule:yt})}function mi(e){return N(Ko(e))}var UR=20*1024*1024;function yi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${yt}?${f(a).toString()}`,c;if(n!=null){let u=new FormData;u.append("file",n),c=e.fetch(s,{method:"POST",headers:{"Content-Type":""},body:u})}else if(i){let u=`${s}&${f({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function gi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function fi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"DELETE"})}var wo=class extends Yp{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Ri(e){return t=>{let r=f(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v2/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?wt(t.apiUrl):""}${a}`;return e.fetchJson(c,M("POST")).then(u=>{if(u.code!=="success")throw new wo(u);return u.details})}}function Ti(...e){return f(e,{omitKeys:"module"})}function Vo(...e){return f(e,{omitKeys:["id","module"]})}function M(e,t){return{method:e,body:t??void 0}}function Qp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function se(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Ci(e){return t=>e.fetchJson(`/v2/${We}/actions/associate`,M("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=se(r,o.data),{included:i,excluded:a}=Ue(n.errorItems,s=>s.result.code===$n&&s.result.details.error[0].code===ei);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function xi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Vo(t).toString()}`,M("GET")).then(o=>o??je())}function Ho(e){let t=xi(e);return o=>t({...o,module:We})}function Zi(e){return N(Ho(e))}function zo(e,t=Wn){let o=xi(e);return r=>o({...r,module:t})}function Fi(e){return N(zo(e))}function jo(e){return t=>e.fetchJson(`/v2/${Ut}`,M("POST",{data:t.data})).then(o=>se(C(t.data),o.data))}function Si(e){return t=>e.fetchJson(`/v2/${Ut}?${f({ids:t.ids})}`,M("DELETE")).then(o=>se(C(t.ids),o.data))}function Wo(e){return Ye(e)({targetModule:Ut})}function Ai(e){return N(Wo(e))}function bi(e){let t=jo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Pi(e){return t=>e.fetchJson(`/v2/settings/tags?${f({module:t.module})}`,M("POST",{tags:C(t.tags)})).then(o=>{let r=se(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===Re);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ei(e){return t=>e.fetchJson(`/v2/settings/tags?${f({module:t.module,my_tags:t.my_tags})}`,M("GET")).then(o=>({...o,data:o.tags}))}var Ii=100;function Oi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Ii)throw new Error(`Cannot add tags to more than ${Ii} records at once.`);return e.fetchJson(`/v2/${We}/actions/add_tags?${f({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var ki=100;function Di(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ki)throw new Error(`Cannot remove tags from more than ${ki} records at once.`);return e.fetchJson(`/v2/${We}/actions/remove_tags?${f({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var ed="invalid_code",td="invalid_client",Bo=class extends J{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},Qe=class extends J{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},od=re("ZohoAccounts");async function rd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Mi(t,e)),o}function Mi(e,t){let o,r=e.error;if(r){let n=$(r);switch(n.code){case ed:case td:o=new Bo(n.code);break;default:o=ae(e,t);break}}return o}var _i=ie(Mi),vi=ne(rd,od);function Te(e){return async()=>{let t=await e();if(!t.accessToken)throw new Qe;return t.accessToken}}var nd=e=>{let t="limit"in e?e.limit:void 0,o="resetAt"in e?e.resetAt:void 0,r=t==null?"":" The limit is "+String(t)+" requests per reset period.",n=o==null?"":" Will be reset at "+String(o)+".";console.warn("zohoRateLimitedFetchHandler(): Too many requests made."+r+n)};function qo(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??nd,r=e.maxRateLimit??Yn,n=e.resetPeriod??Qn;function i(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/L)),exponentRate:1.08,maxWaitTime:L*10,resetPeriod:n,resetAt:u}}let a=i(r),s=Tn(a);return On({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:m,limit:T,resetAt:g}=p;if(T!=null&&T!==r){let R=i(T,g??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(m),g&&s.setNextResetAt(g),y=!0,c.status===Xn){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function Ce(e){return qo({...e,readRateLimitDetails:id})}function id(e){let t=Do(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Ni(e){let{accountsContext:t}=e,o=Te(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=wt(a.apiUrl),c=i({apiUrl:s}),u=ii(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:ni,handleFetchJsonParseErrorFunction:Y});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function zt(e){let t;switch(e){case"sandbox":t="https://crmsandbox.zoho.com/crm";break;case"production":t="https://www.zohoapis.com/crm";break;default:t=e;break}return t}var jt="Notes",wi="Emails",gt="Attachments";var Ui=Lt;import{BaseError as ad}from"make-error";var Jo=class extends ad{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},et=class extends fe{},$o=class extends et{},Xo=class extends et{},Wt=class extends et{get invalidFieldDetails(){return this.error.details}},Yo=class extends Wt{};function Li(e){let t;switch(e.code){case Vt:{let o=new Wt(e);o.invalidFieldDetails.api_name==="id"?t=new Yo(e):t=o;break}case Kt:t=new $o(e);break;case Re:t=new Xo(e);break;default:t=new et(e);break}return t}function Gi(e,t){return o=>{if(!o?.data?.length)throw new Jo(e,t);return o}}var sd=re("ZohoCrm",{logDataArrayErrors:!1});async function cd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ki(t,e)),o}function Ki(e,t){let o,r=le(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var Vi=ie(Ki),Hi=ne(cd,sd);import{BaseError as ud}from"make-error";function er(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,w(o,{data:C(r)})).catch(na).then(i=>{let a=Array.isArray(r),s=xe(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Li(p[0].result);c=u[0].result.details}return c}))}function zi(e){return er(e,"","POST")}function ji(e){return er(e,"/upsert","POST")}function Wi(e){return er(e,"","PUT")}function Bi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${f({ids:t,wf_trigger:r})}`,w("DELETE")).catch(na).then(dd)}function qi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,w("GET")).then(Gi(t.module)).then(o=>o.data[0])}function Ji(e){return(t=>e.fetchJson(`/v8/${t.module}?${ra(t).toString()}`,w("GET")))}function tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ui(o.criteria);r.criteria=n}if(!r.word&&!o.cvid&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, cvid, criteria, email, or phone must be provided");return ra(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,w("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function $i(e){return N(tr(e))}function tt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${pd(n,n.filter).toString()}`,w("GET")).then(i=>i??(r===!1?i:je()))}}function or(e){let t=tt(e)({targetModule:wi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Xi(e){return N(or(e))}function rr(e){return tt(e)({targetModule:gt})}function Yi(e){return N(rr(e))}var XT=20*1024*1024;function Qi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let a=`/v8/${t.module}/${t.id}/${gt}?${f(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function ea(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function ta(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"DELETE"})}var Qo=class extends ud{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function oa(e){return t=>{let r=f(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v8/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?zt(t.apiUrl):""}${a}`;return e.fetchJson(c,w("POST")).then(u=>{if(u.code!=="success")throw new Qo(u);return u.details})}}function ra(...e){return f(e,{omitKeys:"module"})}function pd(...e){return f(e,{omitKeys:["id","module"]})}function w(e,t){return{method:e,body:t??void 0}}function na(e){let t;if(e instanceof Be)t={data:e.errorDataArray};else throw e;return t}function dd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function xe(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function nr(e){return t=>e.fetchJson(`/v2/${jt}`,w("POST",{data:t.data})).then(o=>xe(C(t.data),o.data))}function ia(e){return t=>e.fetchJson(`/v2/${jt}?${f({ids:t.ids})}`,w("DELETE")).then(o=>xe(C(t.ids),o.data))}function ir(e){return tt(e)({targetModule:jt})}function aa(e){return N(ir(e))}function sa(e){let t=nr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function ua(e){return t=>e.fetchJson(`/v8/settings/tags?${f({module:t.module})}`,w("POST",{tags:C(t.tags)})).catch(o=>{let r;if(o instanceof G){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=xe(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===Re);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function pa(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,w("DELETE")).then(o=>o.tags)}function da(e){return t=>e.fetchJson(`/v8/settings/tags?${f({module:t.module,my_tags:t.my_tags})}`,w("GET")).then(o=>({...o,data:o.tags}))}var ca=100;function la(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,w("POST",ha(t))).then(o=>{let r=o.data.map(()=>t);return xe(r,o.data)})}function ha(e){if(Array.isArray(e.ids)&&e.ids.length>ca)throw new Error(`Cannot add/remove tags from more than ${ca} records at once.`);let t=[...C(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&C(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:C(e.ids)}}function ma(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,w("POST",ha(t))).then(o=>{let r=o.data.map(()=>t);return xe(r,o.data)})}function ya(e){let{accountsContext:t}=e,o=Te(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=zt(a.apiUrl),c=i({apiUrl:s}),u=Hi(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:Vi,handleFetchJsonParseErrorFunction:Y});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var ga="https://signsandbox.zoho.com/api/v1",ld="https://sign.zoho.com/api/v1";function ar(e){let t;switch(e){case"sandbox":t=ga;break;case"production":t=ld;break;default:t=e;break}return t}function fa(e){let t=ar(e),o;try{o=new URL(t).hostname!==new URL(ga).hostname}catch{o=!0}return o}function Ra(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let a=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??a?.row_count??20,c=(a?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function ce(e,t){return{method:e,body:t??void 0}}function Ta(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ce("GET"))}function sr(e){return t=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/requests",queryParams:{data:JSON.stringify(n)}},ce("GET"))}}function Ca(e){let t=sr(e);return Ra(t)}function xa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ce("GET"))}function Za(e){return()=>e.fetchJson("/fieldtypes",ce("GET"))}function Fa(e){return({requestId:t,...o})=>{let n=f(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function Sa(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function Aa(e){return({requestData:t,file:o})=>{let r=new FormData;return r.append("data",JSON.stringify({requests:t})),r.append("file",o),e.fetch("/requests",{method:"POST",headers:{"Content-Type":""},body:r}).then(n=>n.json())}}function ba(e){return({templateId:t,data:o,isQuickSend:r=!0})=>{let n=f({data:JSON.stringify({templates:o})});return e.fetchJson({url:`/templates/${t}/createdocument`,queryParams:{is_quicksend:String(r)}},{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()})}}function Ia(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,ce("GET"))}function ka(e){return(t={})=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/templates",queryParams:{data:JSON.stringify(n)}},ce("GET"))}}function Pa(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ce("PUT",{requests:o}))}function Ea(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ce("POST",r))}}function Oa(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ce("PUT",{expire_by:o}))}function Da(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let i=f(n),a=i.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...a?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()}:{}})}}function Ma(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&fa(n)&&!/^https:\/\//i.test(r))throw new Error(`Zoho Sign requires an https embedded-signing host for this environment, but received "${r}".`);return e.fetchJson({url:`/requests/${t}/actions/${o}/embedtoken`,queryParams:{host:r}},ce("POST"))}}var hd=re("ZohoSign",{logDataArrayErrors:!1});async function md(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=_a(t,e)),o}function _a(e,t){let o,r=le(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var va=ie(_a),Na=ne(md,hd);function wa(e){let{accountsContext:t}=e,o=Te(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=ar(a.apiUrl),c=i({apiUrl:s}),u=Na(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:va,handleFetchJsonParseErrorFunction:Y});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ua(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var yd=re("ZohoDesk",{logDataArrayErrors:!1});async function gd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=La(t,e)),o}function La(e,t){let o,r=le(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var Ga=ie(La),Ka=ne(gd,yd);var fd="X-Rate-Limit-Remaining-v3",Rd="Retry-After",Td=200;function Cd(e){let t=e.get(fd),o;if(t!=null){let r=Number(t),n,i=e.get(Rd);if(i!=null){let a=Number(i);Number.isNaN(a)||(n=new Date(Date.now()+a*L))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Va(e){return qo({maxRateLimit:Td,...e,readRateLimitDetails:Cd})}function Ha(e){let{accountsContext:t}=e,o=Te(t.loadAccessToken),r=Va(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:a.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!a.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=Ua(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Ka(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:Ga,handleFetchJsonParseErrorFunction:Y});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var za=25;function X(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=za}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??za,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ee(e,t){return{method:e,body:t??void 0}}function ot(e,t){return f(e,{omitKeys:t})}function Bt(e){let t;return e&&(t=P(C(e))),t}function cr(e){return t=>{let{include:o,...r}=t,n=ot([{...r,include:Bt(o)}]);return e.fetchJson(`/tickets?${n}`,Ee("GET")).then(i=>i??{data:[]})}}function ja(e){return t=>{let{ticketId:o,include:r}=t,i=ot([{include:Bt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ee("GET"))}}function ur(e){return t=>{let o=ot([t]);return e.fetchJson(`/tickets/search?${o}`,Ee("GET")).then(r=>r??{data:[]})}}function Wa(e){return t=>{let{contactId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function Ba(e){return t=>{let{productId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function qa(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ee("GET"))}function Ja(e){return t=>{let o=ot([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ee("GET"))}}function $a(e){return X(cr(e))}function Xa(e){return X(ur(e))}function Ya(e){return{method:e}}function Qa(e){return t=>{let o=f([t]);return e.fetchJson(`/departments?${o}`,Ya("GET")).then(r=>r??{data:[]})}}function es(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ya("GET"))}function pr(e){return{method:e}}function ts(e){let t;return e&&(t=P(C(e))),t}function dr(e){return t=>{let{include:o,...r}=t,n=f([{...r,include:ts(o)}]);return e.fetchJson(`/contacts?${n}`,pr("GET")).then(i=>i??{data:[]})}}function os(e){return t=>{let{contactId:o,include:r}=t,i=f([{include:ts(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,pr("GET"))}}function rs(e){return t=>{let o=f([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,pr("GET")).then(r=>r??[])}}function ns(e){return X(dr(e))}function ft(e,t){return{method:e,body:t??void 0}}function is(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("GET")).then(o=>o??[])}function as(e){return t=>{let o={tags:C(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("POST",o)).then(r=>r??[])}}function ss(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,ft("DELETE"))}function cs(e){return t=>{let o=f([t]);return e.fetchJson(`/tags/search?${o}`,ft("GET")).then(r=>r??{data:[]})}}function us(e){return t=>{let o=f([t]);return e.fetchJson(`/ticketTags?${o}`,ft("GET")).then(r=>r??{data:[]})}}function lr(e,t){return{method:e,body:t??void 0}}function ps(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,lr("GET")).then(o=>o??[])}function ds(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,lr("POST",o))}}function ls(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,lr("DELETE",o))}}function hs(e,t){return{method:e,body:t??void 0}}function xd(e){let t;return e&&(t=P(C(e))),t}function ms(e){return t=>{let{ticketId:o,include:r,...n}=t,i=f([{...n,include:xd(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,hs("GET")).then(a=>a??{data:[]})}}function ys(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,hs("DELETE"))}function qt(e,t){return{method:e,body:t??void 0}}function gs(e){let t;return e&&(t=P(C(e))),t}function fs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=f([{...n,include:gs(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,qt("GET")).then(a=>a??{data:[]})}}function Rs(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=f([{include:gs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,qt("GET"))}}function Ts(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,qt("POST",r))}}function Cs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,qt("DELETE"))}function Rt(e,t){return{method:e,body:t??void 0}}function xs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Rt("GET"))}function Zs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Rt("POST",r))}}function Fs(e){return t=>{let{ticketId:o,...r}=t,n=f([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Rt("GET")).then(i=>i??{data:[]})}}function Ss(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Rt("GET"))}function As(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Rt("GET"))}function bs(e){return{method:e}}function Is(e){let t;return e&&(t=P(C(e))),t}function hr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=f([{...n,include:Is(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,bs("GET")).then(a=>a??{data:[]})}}function ks(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=f([{include:Is(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,bs("GET"))}}function Ps(e){return X(hr(e))}function Zd(e){return{method:e}}function Fd(e){let t;return e&&(t=P(C(e))),t}function mr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=f([{...n,include:Fd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,Zd("GET")).then(a=>a??{data:[]})}}function Es(e){return X(mr(e))}function Jt(e){return{method:e}}function Os(e){let t;return e&&(t=P(C(e))),t}function yr(e){return t=>{let{include:o,...r}=t,n=f([{...r,include:Os(o)}]);return e.fetchJson(`/agents?${n}`,Jt("GET")).then(i=>i??{data:[]})}}function Ds(e){return t=>{let{agentId:o,include:r}=t,i=f([{include:Os(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Jt("GET"))}}function Ms(e){return t=>{let o=f([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Jt("GET")).then(r=>r?.data??[])}}function _s(e){return()=>e.fetchJson("/myinfo",Jt("GET"))}function vs(e){return X(yr(e))}function $t(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:i,refreshToken:a}=t??{},s=i?.clientId??o,c=i?.clientSecret??r,p=f({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`/oauth/v2/token?${p}`,Sd("POST"))}}function Sd(e,t){return{method:e,body:t}}var Ad="https://accounts.zoho.com";function Ns(e){let t;return e==="us"?t=Ad:t=e,t}function ws(e){let t=Ce(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>ee.makeFetch({baseUrl:n.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:t,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return n=>{if(n.refreshToken)if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsConfig missing clientSecret.")}else throw new Error("ZohoAccountsConfig missing clientId.");else throw new Error("ZohoAccountsConfig missing refreshToken.");let i=Ns(n.apiUrl??"us"),a=r({apiUrl:i}),s=vi(a,o),c=Q(s,{interceptJsonResponse:_i,handleFetchJsonParseErrorFunction:Y}),u=async()=>{let m=Date.now(),{access_token:T,api_domain:g,scope:R,expires_in:Z}=await $t(d)();return{accessToken:T,apiDomain:g,expiresIn:Z,expiresAt:new Date(m+Z*L),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=bd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function bd(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??be,i=null,a=async()=>{i=null},s=async()=>{if(!i){let c=await o?.loadCachedToken();c&&(i=c)}if(i!=null&&Date.now()+n>=i.expiresAt.getTime()&&(i=null),!i){try{i=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new Qe("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Ze(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Fe=class{zohoAccounts;factoryConfig;static assertValidConfig(t){let{zohoAccounts:o}=t;if(o)if(o.serviceAccessTokenKey)if(o.refreshToken)if(o.apiUrl){if(!o.clientId)throw new Error("ZohoAccountsServiceConfig.zohoAccounts.clientId is required")}else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.apiUrl is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.refreshToken is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.serviceAccessTokenKey is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts is required")}};import{Injectable as Id}from"@nestjs/common";var rt=class{};rt=A([Id()],rt);function kd(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Qr(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function Pd(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Ed(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Ls(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Ed;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(i){let a=o.map(u=>u.loadZohoAccessTokenCache(i)),s=a.map(kd),c=an(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>Pd(d,u)));if(r!=null){let d=me(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function Gs(e,t){let o={};if(e!=null)for(let i of Object.keys(e)){let a=e[i];a!=null&&(o[i]=a)}let r=rn(o);function n(i){return{loadCachedToken:async()=>{let a=await r.get(i);return t&&console.log("retrieving access token from memory: ",{service:i,hit:a!=null,expiresAt:a?.expiresAt}),a},updateCachedToken:async a=>{await r.set(i,a),t&&console.log("updating access token in memory: ",{service:i,expiresAt:a?.expiresAt})},clearCachedToken:async()=>{await r.remove(i),t&&console.log("clearing access token in memory: ",{service:i})}}}return{loadZohoAccessTokenCache:n}}var Od=".tmp/zoho-access-tokens.json";function Us(e){let t;if(e==null||typeof e!="object")t=void 0;else{let o=e,r=o.expiresAt,n=r!=null&&!(r instanceof Date)?new Date(r):r;t={...o,expiresAt:n}}return t}function Ks(e=Od,t=!0){let o=Ln({filePath:e,reviver:Us}),r=t?nn(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(p){console.error("Failed updating access token in file: ",p)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function i(){let c=await ye(e),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Us(c[d]);u=p}return u}async function a(c){await r.clear();for(let[u,p]of Object.entries(c))p!=null&&await r.set(u,p)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:i,writeTokenFile:a,deleteTokenFile:s}}var _=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=ws(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return $t(this.accountsContext)}};_=A([Dd(),k(0,Vs(Fe)),k(1,Vs(rt))],_);import{Inject as Hs,Injectable as Md}from"@nestjs/common";var Tt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Ze(t.zohoCrm)}};var Oe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=ya({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return zi(this.crmContext)}get upsertRecord(){return ji(this.crmContext)}get updateRecord(){return Wi(this.crmContext)}get deleteRecord(){return Bi(this.crmContext)}get getRecordById(){return qi(this.crmContext)}get getRecords(){return Ji(this.crmContext)}get searchRecords(){return tr(this.crmContext)}get searchRecordsPageFactory(){return $i(this.crmContext)}get getRelatedRecordsFunctionFactory(){return tt(this.crmContext)}get getEmailsForRecord(){return or(this.crmContext)}get getEmailsForRecordPageFactory(){return Xi(this.crmContext)}get getAttachmentsForRecord(){return rr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Yi(this.crmContext)}get uploadAttachmentForRecord(){return Qi(this.crmContext)}get downloadAttachmentForRecord(){return ea(this.crmContext)}get deleteAttachmentFromRecord(){return ta(this.crmContext)}get createNotes(){return nr(this.crmContext)}get deleteNotes(){return ia(this.crmContext)}get createNotesForRecord(){return sa(this.crmContext)}get getNotesForRecord(){return ir(this.crmContext)}get getNotesForRecordPageFactory(){return aa(this.crmContext)}get executeRestApiFunction(){return oa(this.crmContext)}get createTagsForModule(){return ua(this.crmContext)}get deleteTag(){return pa(this.crmContext)}get getTagsForModule(){return da(this.crmContext)}get addTagsToRecords(){return la(this.crmContext)}get removeTagsFromRecords(){return ma(this.crmContext)}};Oe=A([Md(),k(0,Hs(Tt)),k(1,Hs(_))],Oe);import{ConfigModule as xF,ConfigService as ZF}from"@nestjs/config";import{Inject as zs,Injectable as _d}from"@nestjs/common";var Ct=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Ze(t.zohoRecruit)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Ni({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return ai(this.recruitContext)}get upsertRecord(){return si(this.recruitContext)}get updateRecord(){return ci(this.recruitContext)}get deleteRecord(){return ui(this.recruitContext)}get getRecordById(){return pi(this.recruitContext)}get getRecords(){return di(this.recruitContext)}get searchRecords(){return Lo(this.recruitContext)}get searchRecordsPageFactory(){return li(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return Ye(this.recruitContext)}get getEmailsForRecord(){return Go(this.recruitContext)}get getEmailsForRecordPageFactory(){return hi(this.recruitContext)}get getAttachmentsForRecord(){return Ko(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return mi(this.recruitContext)}get uploadAttachmentForRecord(){return yi(this.recruitContext)}get downloadAttachmentForRecord(){return gi(this.recruitContext)}get deleteAttachmentFromRecord(){return fi(this.recruitContext)}get createNotes(){return jo(this.recruitContext)}get deleteNotes(){return Si(this.recruitContext)}get createNotesForRecord(){return bi(this.recruitContext)}get getNotesForRecord(){return Wo(this.recruitContext)}get getNotesForRecordPageFactory(){return Ai(this.recruitContext)}get executeRestApiFunction(){return Ri(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return Ci(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Ho(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return Zi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return zo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return Fi(this.recruitContext)}get createTagsForModule(){return Pi(this.recruitContext)}get getTagsForModule(){return Ei(this.recruitContext)}get addTagsToRecords(){return Oi(this.recruitContext)}get removeTagsFromRecords(){return Di(this.recruitContext)}};De=A([_d(),k(0,zs(Ct)),k(1,zs(_))],De);import{ConfigModule as zF,ConfigService as jF}from"@nestjs/config";import{Inject as js,Injectable as vd}from"@nestjs/common";var xt=class{zohoSign;factoryConfig;static assertValidConfig(t){Ze(t.zohoSign)}};var Zt=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=wa({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Ta(this.signContext)}get getDocuments(){return sr(this.signContext)}get getDocumentsPageFactory(){return Ca(this.signContext)}get getDocumentFormData(){return xa(this.signContext)}get retrieveFieldTypes(){return Za(this.signContext)}get downloadPdf(){return Fa(this.signContext)}get downloadCompletionCertificate(){return Sa(this.signContext)}get createDocument(){return Aa(this.signContext)}get createDocumentFromTemplate(){return ba(this.signContext)}get getTemplate(){return Ia(this.signContext)}get getTemplates(){return ka(this.signContext)}get updateDocument(){return Pa(this.signContext)}get sendDocumentForSignature(){return Ea(this.signContext)}get extendDocument(){return Oa(this.signContext)}get deleteDocument(){return Da(this.signContext)}get getEmbeddedSigningUrl(){return Ma(this.signContext)}};Zt=A([vd(),k(0,js(xt)),k(1,js(_))],Zt);import{ConfigModule as hS,ConfigService as mS}from"@nestjs/config";function Ws(e){return{...e,operationType:e.notifications.operation_type}}var Bs=Cn(e=>e.operationType),qs=Zn({configurerForAccessor:e=>{let t=xn(e,r=>r);return{...e,handleRequestSubmitted:t("RequestSubmitted"),handleRequestViewed:t("RequestViewed"),handleRequestSigningSuccess:t("RequestSigningSuccess"),handleRequestCompleted:t("RequestCompleted"),handleRequestRejected:t("RequestRejected"),handleRequestRecalled:t("RequestRecalled"),handleRequestForwarded:t("RequestForwarded"),handleRequestExpired:t("RequestExpired")}}});var Js="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Me=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as Vd,Inject as Hd,Post as zd,Req as jd}from"@nestjs/common";import{Inject as Ld,Injectable as Gd,Logger as Kd}from"@nestjs/common";import{createHmac as Nd,timingSafeEqual as wd}from"node:crypto";var Ud="x-zs-webhook-signature";function $s(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Ud],i={valid:!1};if(n){let a=r.toString("utf-8"),s=Nd("sha256",t).update(a,"utf-8").digest("base64"),c=!1;try{let p=Buffer.from(n,"base64"),d=Buffer.from(s,"base64");p.length===d.length&&(c=wd(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=Ws(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var he=class{logger=new Kd("ZohoSignWebhookService");_verifier;handler=Bs();configure=qs(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=$s({secret:o})}async updateForWebhook(t,o){let r=await this._verifier(t,o);r.valid?await this.updateForZohoSignEvent(r.event):this.logger.warn("Received invalid Zoho Sign webhook event.",t)}async updateForZohoSignEvent(t){await this.handler(t)||this.logger.warn("Received unexpected/unhandled Zoho Sign webhook event.",t)}};he=A([Gd(),k(0,Ld(Me))],he);var _e=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};A([zd(),k(0,jd()),k(1,vn())],_e.prototype,"handleZohoSignWebhook",1),_e=A([Vd("/webhook/zoho/sign"),k(0,Hd(he))],_e);import{Module as Wd}from"@nestjs/common";import{ConfigModule as Bd,ConfigService as qd}from"@nestjs/config";function Jd(e){let t={zohoSignWebhook:{webhookSecret:e.get(Js)}};return Me.assertValidConfig(t),t}var Yt=class{};Yt=A([Wd({imports:[Bd],controllers:[_e],providers:[{provide:Me,inject:[qd],useFactory:Jd},he],exports:[he]})],Yt);import{Inject as Xs,Injectable as $d}from"@nestjs/common";var Ft=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Ze(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Ha({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return cr(this.deskContext)}get getTicketById(){return ja(this.deskContext)}get searchTickets(){return ur(this.deskContext)}get getTicketsForContact(){return Wa(this.deskContext)}get getTicketsForProduct(){return Ba(this.deskContext)}get getTicketMetrics(){return qa(this.deskContext)}get getAgentsTicketsCount(){return Ja(this.deskContext)}get getTicketsPageFactory(){return $a(this.deskContext)}get searchTicketsPageFactory(){return Xa(this.deskContext)}get getDepartments(){return Qa(this.deskContext)}get getDepartmentById(){return es(this.deskContext)}get getContacts(){return dr(this.deskContext)}get getContactById(){return os(this.deskContext)}get getContactsByIds(){return rs(this.deskContext)}get getContactsPageFactory(){return ns(this.deskContext)}get getTicketTags(){return is(this.deskContext)}get associateTicketTags(){return as(this.deskContext)}get dissociateTicketTag(){return ss(this.deskContext)}get searchTags(){return cs(this.deskContext)}get getAllTags(){return us(this.deskContext)}get getTicketFollowers(){return ps(this.deskContext)}get addTicketFollowers(){return ds(this.deskContext)}get removeTicketFollowers(){return ls(this.deskContext)}get getTicketAttachments(){return ms(this.deskContext)}get deleteTicketAttachment(){return ys(this.deskContext)}get getTicketComments(){return fs(this.deskContext)}get getTicketCommentById(){return Rs(this.deskContext)}get createTicketComment(){return Ts(this.deskContext)}get deleteTicketComment(){return Cs(this.deskContext)}get getTicketTimer(){return xs(this.deskContext)}get performTicketTimerAction(){return Zs(this.deskContext)}get getTicketTimeEntries(){return Fs(this.deskContext)}get getTicketTimeEntryById(){return Ss(this.deskContext)}get getTicketTimeEntrySummation(){return As(this.deskContext)}get getTicketThreads(){return hr(this.deskContext)}get getTicketThreadById(){return ks(this.deskContext)}get getTicketThreadsPageFactory(){return Ps(this.deskContext)}get getTicketActivities(){return mr(this.deskContext)}get getTicketActivitiesPageFactory(){return Es(this.deskContext)}get getAgents(){return yr(this.deskContext)}get getAgentById(){return Ds(this.deskContext)}get getAgentsByIds(){return Ms(this.deskContext)}get getMyInfo(){return _s(this.deskContext)}get getAgentsPageFactory(){return vs(this.deskContext)}};ve=A([$d(),k(0,Xs(Ft)),k(1,Xs(_))],ve);import{ConfigModule as mA,ConfigService as yA}from"@nestjs/config";function Xd(e){return`${e.clientId}:${e.refreshToken}`}function nt(e){let t=Ls([Gs(),Ks(ht())]),o=new Map;function r(p,d){let y=Xd(p),m=o.get(y),T;if(m)T=m;else{let g={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}};T=new _(g,t),o.set(y,T)}return T}let n,i=mt(e,"recruit");if(i){let p=r(i,"recruit"),d={zohoRecruit:{apiUrl:i.apiMode}};n=new De(d,p)}let a,s=mt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};a=new Oe(d,p)}let c,u=mt(e,"desk");if(u?.orgId){let p=r(u,"desk"),d={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new ve(d,p)}return{recruitApi:n,crmApi:a,deskApi:c}}ro([...to,/1000\.\w{20,}/g]);function Ys(e){let t;return e instanceof K?t={ok:!1,error:de(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof qe?t={ok:!1,error:de(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Je?t={ok:!1,error:de(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof G?t={ok:!1,error:de(e.message),code:"API_ERROR"}:t=no(e),t}br(e=>e instanceof K||e instanceof qe||e instanceof Je||e instanceof G?Ys(e):void 0);function h(e){console.log(JSON.stringify(Ys(e)))}var Qs={us:"https://accounts.zoho.com",eu:"https://accounts.zoho.eu",in:"https://accounts.zoho.in",au:"https://accounts.zoho.com.au",jp:"https://accounts.zoho.jp"},ec={recruit:["ZohoRecruit.modules.ALL","ZohoRecruit.settings.all","ZohoRecruit.functions.execute.READ","ZohoRecruit.functions.execute.CREATE"],crm:["ZohoCRM.modules.ALL","ZohoCRM.settings.ALL","ZohoCRM.functions.execute.READ","ZohoCRM.functions.execute.CREATE"],desk:["Desk.tickets.ALL","Desk.tasks.ALL","Desk.contacts.ALL","Desk.settings.ALL","Desk.events.ALL","Desk.search.READ","Desk.articles.READ","Desk.basic.READ"],sign:["ZohoSign.documents.ALL","ZohoSign.templates.ALL"]};function Yd(e){let t;if(!e)t=void 0;else if(e.startsWith("http://")||e.startsWith("https://"))try{let r=new URL(e).searchParams.get("code");if(!r)throw new Error('No "code" parameter found in the provided URL.');t=r}catch(o){throw o instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`,{cause:o}):o}else t=e;return t}var Qd={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:"http://localhost/oauth",describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",default:"recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign)"}).option("code",{type:"string",describe:"Authorization code or the full redirect URL (code is extracted automatically)"}).option("token",{type:"string",describe:"Set a refresh token directly (skips OAuth code exchange)"}).option("product",{type:"string",choices:[...Nt],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth setup --client-id 1000.ABC --client-secret xyz","Step 1: Get OAuth URL (saves shared credentials)"],["$0 auth setup --code 1000.AUTH.CODE","Step 2: Exchange code for refresh token"],['$0 auth setup --code "http://localhost/oauth?code=1000.AUTH.CODE&location=us"',"Step 2: Paste the full redirect URL"],["$0 auth setup --client-id 1000.ABC --client-secret xyz --token 1000.REFRESH.TOKEN","Set shared refresh token directly"],["$0 auth setup --product crm --client-id 1000.CRM --client-secret xyz --token 1000.CRM.TOKEN","Set CRM-specific credentials"]]),handler:async e=>{try{let t=await H(),o=el(e,t);if(!o.clientId||!o.clientSecret)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");o.token?await tl(o,t):o.code?await ol(o,t):await rl(o,t)}catch(t){h(t),process.exit(1)}}};function el(e,t){let o=e.region??t?.shared?.region??"us";return{product:e.product,clientId:e.clientId??t?.shared?.clientId,clientSecret:e.clientSecret??t?.shared?.clientSecret,redirectUri:e.redirectUri,region:o,scopes:e.scopes.split(",").map(r=>r.trim()),code:Yd(e.code),token:e.token,accountsUrl:Qs[o]??Qs.us,apiMode:e.apiMode,orgId:e.orgId}}async function tc(e,t,o){return e.product?te({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:{...t,apiUrl:e.apiMode,orgId:e.product==="desk"?e.orgId:void 0}}):te({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function tl(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await tc(e,o,t?.shared);l({success:!0,...e.product?{product:e.product}:{},refreshToken:ge(e.token),configSaved:!0,configuredProducts:oe(r)})}async function ol(e,t){let o=`${e.accountsUrl}/oauth/v2/token`,r=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUri,code:e.code}),i=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()})).json();if(i.error)throw new Error(`Token exchange failed: ${i.error}`);let a=i.refresh_token;if(!a)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let s={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:a},c=await tc(e,s,t?.shared);l({step:2,success:!0,product:e.product??"shared",refreshToken:ge(a),accessToken:i.access_token?ge(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:oe(c)})}async function rl(e,t){let o=e.scopes.flatMap(n=>ec[n]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(ec).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;await te({shared:{clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({step:1,instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:r,redirectUri:e.redirectUri,scopes:o,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}var nl={command:"set",describe:"Save Zoho API credentials directly",builder:e=>e.option("client-id",{type:"string",demandOption:!0,describe:"OAuth client ID"}).option("client-secret",{type:"string",demandOption:!0,describe:"OAuth client secret"}).option("refresh-token",{type:"string",demandOption:!0,describe:"OAuth refresh token"}).option("product",{type:"string",choices:[...Nt],describe:"Store for a specific product instead of shared"}).option("region",{type:"string",default:"us",describe:"Zoho region (us, eu, in, au, jp)"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth set --client-id abc --client-secret xyz --refresh-token 1000.abc.xyz","Set shared credentials"],["$0 auth set --product crm --client-id abc --client-secret xyz --refresh-token 1000.crm.xyz","Set CRM-specific credentials"]]),handler:async e=>{try{let t=e.product,o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken},r;t?r=await te({shared:(await H())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await te({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({saved:!0,product:t??"shared",configuredProducts:oe(r)})}catch(t){h(t),process.exit(1)}}},il={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?ge(r.clientId):void 0,clientSecret:r.clientSecret?ge(r.clientSecret):void 0,refreshToken:r.refreshToken?ge(r.refreshToken):void 0}:void 0};var e=o;let t=await H();if(!t){l({configured:!1});return}l({configured:!0,shared:{...o(t.shared),region:t.shared?.region??"us",apiMode:t.shared?.apiMode??"production"},recruit:t.recruit?{...o(t.recruit),apiUrl:t.recruit.apiUrl}:null,crm:t.crm?{...o(t.crm),apiUrl:t.crm.apiUrl}:null,desk:t.desk?{...o(t.desk),apiUrl:t.desk.apiUrl,orgId:t.desk.orgId}:null,configuredProducts:oe(t)})}catch(t){h(t),process.exit(1)}}},al={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await H();if(e){let t=oe(e);if(t.length===0)l({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=nt(e),r={};for(let n of t)try{let i;if(n==="recruit"?i=o.recruitApi:n==="crm"?i=o.crmApi:i=o.deskApi,!i){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let a=i instanceof Error?i.message:String(i);r[n]={authenticated:!1,error:a}}l({products:r})}}else l({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){h(e),process.exit(1)}}},sl={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await jn(),l({cleared:!0})}catch(e){h(e),process.exit(1)}}},oc={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Qd).command(nl).command(il).command(al).command(sl).demandCommand(1,"Please specify an auth subcommand."),handler:S};import{access as cl,constants as ul}from"node:fs";import{dirname as pl}from"node:path";var rc={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await H(),t=[];t.push(dl(e));let o=ll(e);if(o&&t.push(o),t.push(await hl()),e){let n=oe(e);t.push(ml(n),...await yl(e,n));let i=Rl(e,n);i&&t.push(i)}let r=t.every(n=>n.status==="pass");l({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function dl(e){return e?{name:"config",status:"pass",message:`Config loaded from ${lt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function ll(e){if(e?.shared?.clientId&&e?.shared?.clientSecret&&e?.shared?.refreshToken)return{name:"shared-credentials",status:"pass",message:"Shared credentials present"};if(e)return{name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."}}async function hl(){let e=pl(ht());return await Tl(e)?{name:"token-cache",status:"pass",message:`Token cache directory writable: ${e}`}:{name:"token-cache",status:"warn",message:`Token cache directory not writable: ${e}`}}function ml(e){return e.length>0?{name:"products",status:"pass",message:`Configured products: ${e.join(", ")}`}:{name:"products",status:"fail",message:"No products have complete credentials"}}async function yl(e,t){let o=nt(e),r=[];for(let n of t)r.push(await gl(o,n));return r}async function gl(e,t){let o=fl(e,t);if(!o)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let r;try{let i=await o.zohoAccountsApi.accessToken();r={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${i.scope}`}}catch(n){let i=n instanceof Error?n.message:String(n);r={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${i}`}}return r}function fl(e,t){return t==="recruit"?e.recruitApi:t==="crm"?e.crmApi:e.deskApi}function Rl(e,t){if(e.desk?.orgId)return{name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${e.desk.orgId}`};if(!t.includes("desk"))return{name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."}}function Tl(e){return new Promise(t=>{cl(e,ul.W_OK,o=>{t(!o)})})}var nc=Mn({notInitializedMessage:"CLI context not initialized. This is a bug."});function ic(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await H();r||(h(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),oe(r).length===0&&(h(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),nc.set(nt(r))}catch(r){h(r),process.exit(4)}}}function Rr(e){return nc.require()}function W(e){let{recruitApi:t}=Rr(e);if(!t)throw new Error("Recruit not configured. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z");return t}function B(e){let{crmApi:t}=Rr(e);if(!t)throw new Error("CRM not configured. Run: zoho-cli auth setup --product crm --client-id X --client-secret Y --token Z");return t}function x(e){let{deskApi:t}=Rr(e);if(!t)throw new Error("Desk not configured. Run: zoho-cli auth setup --product desk --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function ue(e){return Zo(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function E(e){return Zo(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function D(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Se(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function St(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Qt(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}var Cl={nextInput:(e,t)=>{let o;if(t.info?.more_records){let r=e.page??1;o={...e,page:r+1}}else o=void 0;return o},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},O={nextInput:(e,t)=>{let o=e.limit??25,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let i=e.from??1;n={...e,from:i+o}}return n},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25,r=t.data?.length??0;return o>0&&r>=o}};async function pe(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await I({initialInput:o,fetchPage:r,adapter:Cl,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;l(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}var xl={command:"list",describe:"List records from a module",builder:e=>Qt(St(ue(D(e)))),handler:async e=>{try{let t=W(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await pe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Zl={command:"get",describe:"Get a record by ID",builder:e=>Se(D(e)),handler:async e=>{try{let o=await W(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){h(t),process.exit(1)}}},Fl={command:"search",describe:"Search records in a module",builder:e=>ue(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=W(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(t),process.exit(1)}}},Sl={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Al={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},bl={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Il={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=W(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){h(t),process.exit(1)}}},kl={command:"emails",describe:"Get emails for a record",builder:e=>ue(Se(D(e))),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Pl={command:"attachments",describe:"Get attachments for a record",builder:e=>ue(Se(D(e))),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},ac={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(xl).command(Zl).command(Fl).command(Sl).command(Al).command(bl).command(Il).command(kl).command(Pl).demandCommand(1,"Please specify a recruit subcommand.").example([["$0 recruit list -m Candidates --per-page 10","List first 10 candidates"],["$0 recruit get -m Candidates --id 12345","Get a candidate by ID"],['$0 recruit search -m Candidates --word "John"',"Search candidates by keyword"],[`$0 recruit insert -m Candidates --data '{"First_Name":"John","Last_Name":"Doe"}'`,"Insert a candidate"]]),handler:S};var El={command:"list",describe:"List records from a module",builder:e=>Qt(St(ue(D(e)),!0)),handler:async e=>{try{let t=B(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await pe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Ol={command:"get",describe:"Get a record by ID",builder:e=>Se(D(e)),handler:async e=>{try{let o=await B(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){h(t),process.exit(1)}}},Dl={command:"search",describe:"Search records in a module",builder:e=>ue(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=B(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(t),process.exit(1)}}},Ml={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},_l={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},vl={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Nl={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=B(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){h(t),process.exit(1)}}},wl={command:"emails",describe:"Get emails for a record",builder:e=>ue(Se(D(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Ul={command:"attachments",describe:"Get attachments for a record",builder:e=>St(ue(Se(D(e))),!0),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await pe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},sc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(El).command(Ol).command(Dl).command(Ml).command(_l).command(vl).command(Nl).command(wl).command(Ul).demandCommand(1,"Please specify a CRM subcommand.").example([['$0 crm list -m Contacts --fields "First_Name,Last_Name,Email" --per-page 10',"List contacts"],["$0 crm get -m Contacts --id 12345","Get a contact by ID"],['$0 crm search -m Leads --word "Acme"',"Search leads by keyword"],[`$0 crm insert -m Contacts --data '{"First_Name":"Jane","Last_Name":"Doe"}'`,"Insert a contact"]]),handler:S};var Ll={command:"list",describe:"List tickets",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status"}).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Gl={command:"get <ticketId>",describe:"Get a ticket by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let o=await x(e).getTicketById({ticketId:e.ticketId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},Kl={command:"search",describe:"Search tickets",builder:e=>E(e).option("subject",{type:"string",describe:"Search by subject"}).option("status",{type:"string",describe:"Filter by status"}).option("email",{type:"string",describe:"Filter by email"}).option("department-id",{type:"string",describe:"Filter by department ID"}).option("channel",{type:"string",describe:"Filter by channel"}).option("priority",{type:"string",describe:"Filter by priority"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,subject:e.subject,status:e.status,email:e.email,departmentId:e.departmentId,channel:e.channel,priority:e.priority},r=await I({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Vl={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>E(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=x(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Hl={command:"metrics <ticketId>",describe:"Get ticket metrics",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketMetrics({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},zl={command:"agent-counts",describe:"Get ticket counts per agent",builder:e=>e.option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}).option("department-id",{type:"string",describe:"Filter by department ID"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});l(r)}catch(t){h(t),process.exit(1)}}},cc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Ll).command(Gl).command(Kl).command(Vl).command(Hl).command(zl).demandCommand(1),handler:S};var jl={command:"list",describe:"List departments",builder:e=>E(e).option("search",{type:"string",describe:"Search by name"}).option("is-enabled",{type:"boolean",describe:"Filter by enabled status"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await I({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Wl={command:"get <departmentId>",describe:"Get a department by ID",builder:e=>e.positional("departmentId",{type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let o=await x(e).getDepartmentById({departmentId:e.departmentId});l(o)}catch(t){h(t),process.exit(1)}}},uc={command:"departments",describe:"Desk department operations",builder:e=>e.command(jl).command(Wl).demandCommand(1),handler:S};var Bl={command:"list",describe:"List contacts",builder:e=>E(e).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},ql={command:"get <contactId>",describe:"Get a contact by ID",builder:e=>e.positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getContactById({contactId:e.contactId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},pc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Bl).command(ql).demandCommand(1),handler:S};var Jl={command:"list",describe:"List agents",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status (active, disabled)"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. role,profile,departments)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},$l={command:"get <agentId>",describe:"Get an agent by ID",builder:e=>e.positional("agentId",{type:"string",demandOption:!0,describe:"Agent ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getAgentById({agentId:e.agentId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},Xl={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await x(e).getMyInfo();l(o)}catch(t){h(t),process.exit(1)}}},dc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Jl).command($l).command(Xl).demandCommand(1),handler:S};var Yl={command:"list",describe:"List all tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await I({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Ql={command:"search",describe:"Search tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",describe:"Department ID"}).option("query",{alias:"q",type:"string",demandOption:!0,describe:"Search string"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await I({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},eh={command:"for-ticket <ticketId>",describe:"Get tags on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTags({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},th={command:"associate <ticketId>",describe:"Add tags to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tags",{type:"string",demandOption:!0,describe:"Comma-separated tag names"}),handler:async e=>{try{let t=x(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});l(r)}catch(t){h(t),process.exit(1)}}},oh={command:"dissociate <ticketId>",describe:"Remove a tag from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tag-id",{type:"string",demandOption:!0,describe:"Tag ID to remove"}),handler:async e=>{try{await x(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},lc={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Yl).command(Ql).command(eh).command(th).command(oh).demandCommand(1),handler:S};var rh={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await I({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},nh={command:"get <ticketId> <commentId>",describe:"Get a comment by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{let o=await x(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});l(o)}catch(t){h(t),process.exit(1)}}},ih={command:"create <ticketId>",describe:"Create a comment on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("content",{type:"string",demandOption:!0,describe:"Comment content"}).option("public",{type:"boolean",default:!1,describe:"Make comment public"}).option("content-type",{type:"string",default:"plainText",choices:["plainText","html"],describe:"Content type"}),handler:async e=>{try{let o=await x(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});l(o)}catch(t){h(t),process.exit(1)}}},ah={command:"delete <ticketId> <commentId>",describe:"Delete a comment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{await x(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},hc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(rh).command(nh).command(ih).command(ah).demandCommand(1),handler:S};var sh={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},ch={command:"delete <ticketId> <attachmentId>",describe:"Delete an attachment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("attachmentId",{type:"string",demandOption:!0,describe:"Attachment ID"}),handler:async e=>{try{await x(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},mc={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(sh).command(ch).demandCommand(1),handler:S};var uh={command:"list <ticketId>",describe:"List followers of a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketFollowers({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},ph={command:"add <ticketId>",describe:"Add followers to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({added:!0})}catch(t){h(t),process.exit(1)}}},dh={command:"remove <ticketId>",describe:"Remove followers from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},yc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(uh).command(ph).command(dh).demandCommand(1),handler:S};var lh={command:"timer <ticketId>",describe:"Get current timer state for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimer({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},hh={command:"timer-action <ticketId>",describe:"Start, pause, resume, or stop a timer",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("action",{type:"string",demandOption:!0,choices:["start","pause","resume","stop"],describe:"Timer action"}),handler:async e=>{try{let o=await x(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});l(o)}catch(t){h(t),process.exit(1)}}},mh={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},yh={command:"summation <ticketId>",describe:"Get time entry summation for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimeEntrySummation({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},gc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(lh).command(hh).command(mh).command(yh).demandCommand(1),handler:S};var gh={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},fh={command:"get <ticketId> <threadId>",describe:"Get a thread by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("threadId",{type:"string",demandOption:!0,describe:"Thread ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},fc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(gh).command(fh).demandCommand(1),handler:S};var Rh={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Rc={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Rh).demandCommand(1),handler:S};var Tc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(cc).command(uc).command(pc).command(dc).command(lc).command(hc).command(mc).command(yc).command(gc).command(fc).command(Rc).demandCommand(1,"Please specify a desk subcommand.").example([["$0 desk tickets list --limit 10","List first 10 tickets"],["$0 desk tickets get 12345","Get a ticket by ID"],["$0 desk agents my-info","Get current agent info"],['$0 desk comments create 12345 --content "Looking into this"',"Add a comment"]]),handler:S};var Cc={command:"request <product> <method> <path>",describe:"Make a raw API request through the authenticated context",builder:e=>e.positional("product",{type:"string",demandOption:!0,choices:["recruit","crm","desk"],describe:"Zoho product"}).positional("method",{type:"string",demandOption:!0,choices:["GET","POST","PUT","PATCH","DELETE"],describe:"HTTP method"}).positional("path",{type:"string",demandOption:!0,describe:"API path (relative to product base URL)"}).option("body",{type:"string",describe:"JSON request body"}).option("query",{type:"string",describe:"JSON query parameters"}).example([["$0 request recruit GET /v2/Candidates","List candidates via raw API"],[`$0 request desk GET /tickets --query '{"limit":5}'`,"List 5 desk tickets via raw API"],[`$0 request crm POST /v8/Contacts --body '{"data":[{"Last_Name":"Test"}]}'`,"Create a CRM contact via raw API"]]),handler:async e=>{try{let t=e.product,o=e.method,r=e.path,n;switch(t){case"recruit":n=W(e).recruitContext;break;case"crm":n=B(e).crmContext;break;case"desk":n=x(e).deskContext;break;default:throw new Error(`Unknown product: ${t}`)}let i=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=i.includes("?")?"&":"?";i=`${i}${p}${u.toString()}`}let a={method:o};e.body&&(a.body=e.body,a.headers={"Content-Type":"application/json"});let s=await n.fetchJson(i,a);l(s)}catch(t){h(t),process.exit(1)}}};var xh=Vn({cliName:"zoho-cli",loadOutputConfig:async()=>(await H())?.output,mergeOutputConfig:e=>te({output:e}),clearOutputConfig:zn}),Zh=[ac,sc,Tc,Cc],xc=[oc,xh,rc];function Fh(e){return e.command.split(" ")[0]}var Zc=new Set(xc.map(Fh)),Sh=Kn({cliName:"zoho-cli",skipCommands:Zc,loadOutputConfig:async()=>(await H())?.output,saveCommandOutputConfig:async(e,t)=>{await te({output:{commands:{[e]:t}}})}});async function Ah(){try{await Th(Ch(process.argv)).scriptName("zoho-cli").usage("$0 <command> [options]").option("verbose",{alias:"v",type:"boolean",default:!1,global:!0,describe:"Verbose output"}).option("dump-dir",{type:"string",global:!0,describe:"Directory to save full API responses as JSON files (overrides config)"}).option("pick",{type:"string",global:!0,describe:"Comma-separated top-level fields to include in output (overrides config)"}).option("set-dump-dir",{type:"string",global:!0,describe:"Save dump directory to config for this command and apply now"}).option("set-pick",{type:"string",global:!0,describe:"Save pick fields to config for this command and apply now"}).option("pick-all",{type:"boolean",global:!0,describe:"Ignore any configured pick filters and return full response data"}).middleware([ic(Zc),Sh],!0).command(xc).command(Zh).demandCommand(1,"Please specify a command. Use --help for available commands.").strict().fail(!1).help().alias("help","h").version(!1).wrap(Math.min(120,process.stdout.columns||80)).parse()}catch(e){h(e),process.exit(1)}}await Ah();
|
|
4
|
+
var Ec=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var A=(e,t,o,r)=>{for(var n=r>1?void 0:r?Oc(t,o):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(r?a(t,o,n):a(n))||n);return r&&n&&Ec(t,o,n),n},k=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Dc,mkdirSync as Mc,writeFileSync as _c}from"node:fs";import{join as vc}from"node:path";var Ar=1;var ao=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],br=6e4,Ue={},Ir=[...ao],io,wc=!1,Nc=br;function so(e){Ue=e}function bt(){return Ue}function kr(e){wc=e}function Pr(e){Nc=e===void 0?br:e}function co(e){Ir=e}function Er(e){io=e}function le(e){let t=e;for(let o of Ir)t=t.replace(o,"[REDACTED]");return t}function Or(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function ut(e,t){let{dumpDir:o,commandPath:r}=Ue,n;if(o){Dc(o)||Mc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Or(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=vc(o,`${s}.${e}`)}else n=void 0;return n}function Uc(e,t){let o=ut("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};_c(o,JSON.stringify(r,null,2))}function be(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>Sr(n,o)):e!=null&&typeof e=="object"?r=Sr(e,o):r=e,r}function Sr(e,t){let o;if(e==null||typeof e!="object")o=e;else{let r={};for(let n of t)n in e&&(r[n]=e[n]);o=r}return o}function Dr(e){return Ue.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function l(e,t){Uc(e,t);let r={ok:!0,data:Ue.pick?be(e,Ue.pick):e,...t?{meta:t}:{}};console.log(Dr(r))}function Mr(e){console.log(Dr(uo(e)))}var ct=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function uo(e){let t=io?io(e):void 0,o;return t?o=t:e instanceof ct?o={ok:!1,error:le(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:le(e.message),code:"ERROR"}:o={ok:!1,error:le(String(e)),code:"UNKNOWN_ERROR"},o}function Le(e,t=!1){let o;return typeof e=="string"?o=t:e!=null&&typeof e=="object"&&Symbol.iterator in e?o=!0:o=!1,o}function pt(e){let t=!0;for(let o of e){t=!1;break}return t}function po(e,t){for(let o of e)t(o)}function J(e,t,o=!1){e!=null&&(Le(e,o)?po(e,t):t(e))}function _r(e){if(!Array.isArray(e))throw new TypeError("Input is not an array/tuple...");let t;if(e.length>0){let o=e[0],r=!1;if(Array.isArray(o)){let n=o.length;r=e.findIndex(a=>Array.isArray(a)?a.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Lc(e){return e==null?[]:Gc(e)}var C=Lc;function Gc(e){return Array.isArray(e)?e:[e]}function vr(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function lo(e){return Object.keys(e).length===0}function wr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Nr(e){return{...e}}function Ur(e){return e!=null}function It(e){return Le(e,!1)?!pt(e):Lr(e)}function ho(e){let t;return Le(e,!0)?t=!pt(e):Lr(e)?t=typeof e=="object"?!lo(e):!0:t=!1,t}function Lr(e){return e!=null&&e!==""}function Kc(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ye=Kc(Ur);function Gr({base:e,build:t}){let o=e??{};return t(o),o}var Vc=(e=>e);function Kr(){return Vc}function Ge(e,t){let o=Hc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Hc(e,t){return wr(qc(e,t))}function qc(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),i=o.get(n);i==null?o.set(n,[r]):i.push(r)}),o}function Vr(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function mo(e){return Array.from(e.entries())}function Hr(e){return zc(mo(e))}function zc(e){let t=[];return e.forEach(([o,r])=>{J(r,n=>{t.push([o,n])})}),t}function qr(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),J(i,s=>a.push(s))},o=(n,i)=>t(n,_r(i));return{map:()=>e,entries:()=>mo(e),tuples:()=>Hr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>J(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>J(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function jc(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function zr(e){let t=jc(e);return t!=null&&t!=="class"}function jr(e){return zr(e)?e:()=>e}function Br(e,t){return Math.log(t)/Math.log(e)}var Wr=",",Bc=" ";function Wc(e,t=Wr,o=!1){if(e==null)return e;let r=C(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function yo(e,t,o){let r;switch(o){case 1:r=[e];break;case 2:{let n=e.indexOf(t);r=n<0?[e]:[e.slice(0,n),e.slice(n+t.length)];break}default:{let n=e.split(t),i=[];if(n.length>1){let a=n.length>o,s=a?o-1:n.length;for(let c=0;c<s;c+=1)i.push(n[c]);a&&i.push(n.slice(s).join(t))}else i.push(n[0]);r=i;break}}return r}function Jc(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return Wc(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Jr(e){let{joiner:t}=e,o=Jc(e),r=(n,i=a=>a)=>n.split(t).map(s=>i(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,i){return yo(n,t,i)}}}var go=Jr({joiner:Wr}),$c=Jr({joiner:Bc,trimByDefault:!0});var P=go.joinStrings,km=go.splitStrings,Pm=go.splitStringsToSet,Em=$c.joinStrings;var $r=vr;function Yr(e,{forEach:t,filter:o}){Xc(e,o).forEach((n,i)=>t(n,i))}function Xc(e,t){return fo(t)(e)}function fo(e){let t;if(e==null)t=Xr;else{let o=Yc(e);t=r=>Xr(r).filter((n,i)=>o(n,i))}return t}function Xr(e){return Object.entries(e)}function Ro(e){return typeof e=="object"?e:{valueFilter:e}}function Yc(e){let t=Ro(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,i;switch(o){case 1:i=([,a])=>a!==void 0;break;case 2:i=([,a])=>a!=null;break;case 3:i=([,a])=>!!a;break;case 4:i=([,a])=>It(a);break;case 5:i=([,a])=>ho(a);break;case 6:i=([,a])=>!!a&&It(a);break;case 7:i=([,a])=>!!a&&ho(a);break;default:i=()=>!0;break}if(n){let a=i,s=new Set(n.map(c=>c.toString()));i=(c,u)=>a(c,u)&&s.has(c[0])}return $r(i,r)}function dt(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function Qr(e){let t;return e==null||iu(e)?t=e:t=Qc(e),t}function Qc(e){return e==null?e:new Date(e)}var en=24,eu=60;var tu=60,ou=tu*eu,G=1e3,Ie=G*60,To=Ie*60,ru=To*en,Um=ou*en,nu=7,Lm=ru*nu;function iu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function tn(e){return e.getTime()<Date.now()}function on(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function au(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:Qr(n);function c(y){return y??r??new Date}function u(y,m=!1){let T=c(y),g=d(T),f;return g==null?f=m:f=g<=T,f}function p(y){let m=c(y);return d(m)}function d(y){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:a!=null&&(m=on(s??(i===!1?null:y),a)),m}return{input:e,hasExpired:u,getExpirationDate:p}}function rn(e,t){let o=!0;return e!=null&&(o=au(e).hasExpired(t,!0)),o}function su({filter:e,copy:t,dynamic:o=!1}){let r=e==null?uu:Ke({filter:e,copy:!1});return n=>{let i=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},a=o?i:dt(i);return s=>{let c=a();return t&&(s=Nr(s)),Object.assign(s,c),s}}}function nn(e,t){return cu(t)(e)}function cu(e){let t=su({filter:e,copy:!1,dynamic:!0});return o=>t(ye(o))({})}var Wm=Ke({copy:!0,filter:{valueFilter:1}}),Jm=Ke({copy:!0,filter:{valueFilter:2}}),an=Ke({copy:!0,filter:{valueFilter:4}}),$m=Ke({copy:!0,filter:{valueFilter:6}}),Xm=Co({valueFilter:1}),Ym=Co({valueFilter:6}),Qm=Co({valueFilter:2});function Co(e){let t=sn({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ke({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Ro(t);o.invertFilter=!o.invertFilter;let r=sn({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var uu=Ke({copy:!1});function sn({forEach:e,filter:t}){let o=fo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function cn(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function un(e){let t,o,r=0;function n(){let i;if(t==null){if(o==null){let a=r;o=e.load().then(s=>(r===a&&(t={entries:s},o=void 0),s),s=>{throw r===a&&(o=void 0),s})}i=o}else i=Promise.resolve(t.entries);return i}return{load:async()=>({...await n()}),get:async i=>(await n())[i],set:async(i,a)=>{let s=await n();r+=1,o=void 0,await e.set(i,a),t={entries:{...s,[i]:a}}},remove:async i=>{let a=await n();r+=1,o=void 0,await e.remove(i);let s={...a};delete s[i],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function pn(e){return{load:async()=>{let t;for(let o of e){let r=await o.load();if(r!=null){t=r;break}}return t},update:async t=>{for(let o=e.length-1;o>=0;o-=1)await e[o].update(t)},clear:async()=>{for(let t=e.length-1;t>=0;t-=1)await e[t].clear()}}}function kt(e,t,o){let[r,n]=xo(e,t,!1);return r+o+n}function xo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var pu=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],ay=new Set(pu);function dn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=Pt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=kt(n,i[0],o(s));break}default:{let s=[],c=i.length,u=0,p=0;for(let d=0;d<c;d+=1){p=i[d];let y=n[p],T=n.substring(u,p)+o(y);s.push(T),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function du(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of[...t].entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function Pt(e,t,o){return du(e)(t,o)}function lu(e,t){return Pt(e,t,1)[0]}function hu(e){return t=>{let r=lu(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=xo(t,r,!1),n}}function ln(e,t){return hu(t)(e)}var Ve="/",mu=".";function yu(e){let t=e.split(mu,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ve?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function hn(e){return yu(e)!=="invalid"}var gu=/^\/+/,fu=/\/+$/;var Ru=/\/{2,}/g;function mn(e){return e.startsWith(Ve)?e.replace(gu,Ve):`${Ve}${e}`}function yn(e){return e.replaceAll(Ru,Ve)}function gn(e){return e.replace(fu,"")}function Tu(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var fn=/:(\d+)/;function Cu(e){return fn.test(e)}function xu(e){let t=fn.exec(e);return t?Number(t[1]):void 0}function Zu(e){let t=xn(e),o=Fu(t),{domain:r,path:n}=o,i=Tu(r),a=Cu(e),s=a?xu(e)??void 0:void 0,[c,u]=ln(o.path,"?"),p=i&&(c===""||hn(c+"/")),d=Au(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:i,hasHttpPrefix:d,hasPortNumber:a,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function Rn(e){let t=Zu(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Tn(e,t=!1){let o=Pt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(i=>n=kt(n,i,"&")),n}function Fu(e){let t=xn(e);return Su(t)}function Su(e){let t=yo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:mn(r??"/")}}var Cn=/^https:\/\/|http:\/\//;function xn(e){return e.replace(Cn,"")}function Au(e){return Cn.test(e)}function Z(){}function Zn(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function Zo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function bu(e){let n=To,i={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},a=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;m(e??i);function p(){return{...i}}function d(){return u}function y(S){u=S}function m(S,L=!1){let z=Math.max(0,S.startLimitAt??1),b=S.cooldownRate??1,w=S.maxWaitTime??n,H=S.exponentRate??2;i={startLimitAt:z,cooldownRate:b,maxWaitTime:w,exponentRate:H},s=Br(H,w/G+1),L&&T()}function T(){a=0,c=new Date}function g(S){let L;if(u){let{cooldownRate:z}=i,w=(Date.now()-c.getTime())*z/G,H=Math.max(a-w,0),j=Math.max(0,H-i.startLimitAt);S&&(a=H+S,c=new Date),L=j>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(j,0))-1)*G}else L=0;return L}function f(S){return g(S??0)}function F(){let S=g(1);return Zo(S)}return{waitForRateLimit:F,getNextWaitTime:f,getConfig:p,setConfig:m,getEnabled:d,setEnabled:y,reset:T}}function Fn(e){let o=bu({exponentRate:1.5,maxWaitTime:G*8,...e}),r=Ie,n=new Date,i=0,a=0,s=!0;F(e,!0);function c(){tn(n)&&d()}function u(){return s}function p(b){s=b}function d(){a=i,n=new Date(Date.now()+r)}function y(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function T(b){n=b}function g(){return c(),a}function f(b){a=b}function F(b,w=!1){i=b.limit??i,r=b.resetPeriod??r;let H={cooldownRate:b.cooldownRate??Math.max(.1,r/G),exponentRate:b.exponentRate??1.5,maxWaitTime:b.maxWaitTime??G*8};o.setConfig(H,w),w&&d(),n=b.resetAt??n}function S(b){let w=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var H=j;a>0?w=j():(c(),a>0?w=j():w=m())}return w}function L(b){return S(b??0)}function z(){let b=S(1);return Zo(b)}return{getRemainingLimit:g,setRemainingLimit:f,getTimeUntilNextReset:m,getResetAt:y,setNextResetAt:T,setConfig:F,reset:d,getNextWaitTime:L,waitForRateLimit:z,getEnabled:u,setEnabled:p}}var Iu="__CATCH_ALL_HANDLE_RESULT_KEY__";function Sn(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,i=new Map,a=u=>{n=u},s=(u,p)=>{u===Iu?a(p):Vr(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return Gr({base:(u=>{let p=e(u),d=(p==null?void 0:i.get(p))??n,y;return d?y=Promise.resolve(d(u)).then(m=>m??o):y=Promise.resolve(r),y}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function ku(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Pu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Eu(e,t,o){let r=Pu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function An(e,t){return o=>Eu(e,o,t)}function bn(e){return t=>(o,r)=>{let n=ku(o,t),i=e.configurerForAccessor(n);r(i)}}var Ou=-1,In=0;function Du(e){return e?.page??Ou}function kn(e){return Du(e)+1}import{BaseError as Pn}from"make-error";var $=class extends Pn{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function En(e){return(t,o)=>Mu(e(t,o))}var He=class extends Pn{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Mu(e){return e.then(t=>{if(!t.ok)throw new He(t);return t})}import{BaseError as My}from"make-error";function On(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let a=new AbortController;r=a,o={...o,signal:a.signal}}let i=e(t,o??void 0);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function Mn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>_n({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>vu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var _u=(e,t)=>t(e);function vu(e){let{makeFetch:t=fetch,fetchHandler:o=_u,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=On(a)),n&&(a=En(a));let s=_n(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var wu=(e,t)=>new Request(e,t??void 0);function _n(e){let{makeRequest:t=wu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(gn(o)):void 0,u=c?m=>{let T,g=m.toString();if(!s&&Rn(g))T=new URL(g);else{let f=c.origin+yn("/"+c.pathname+"/"+m);T=new URL(f,c)}return T}:void 0;async function p(m){let T=Zn(m)?await m:m;return Dn(T)?T:t(T)}let d=u?async m=>{let T,g,f;if(typeof m=="string"?T=m:Dn(m)?a?(T=m.url,g=m):f=m:f=await t(m),!f){let F=u(T);f=await t(F.href,g)}return f}:p,y;if(r!=null||n!=null){let m=jr(r);async function T(){let f=await m();return n?{...f,timeout:n}:f}async function g(f,F){let S=await T(),L=Nu(S,await F),z=L.timeout===void 0?f.timeout:L.timeout;return{...L,timeout:z}}i?y=(f,F)=>i(f,g(f,F)):y=(f,F)=>g(f,F)}else i?y=i:y=(m,T)=>T;return async(m,T)=>{try{let g=await d(m);T=await y(g,T??void 0);let f=await t(g,T);return f.timeout=n,f}catch(g){throw g instanceof $?g:new $(g)}}}function Nu(e,t){let o;if(t){let r=Uu([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Uu(e){let t=qr();return ye(e).forEach(o=>{let r=Lu(o),n=new Set;r.forEach(([i,a])=>{n.has(i)||(t.delete(i),n.add(i)),a&&t.add(i,a)})}),t.tuples()}function Lu(e){let t=[];return Array.isArray(e)?t=e:typeof e.forEach=="function"?e.forEach((o,r)=>{t.push([r,o])}):typeof e=="object"&&(t=Object.entries(e)),t}function Dn(e){return!!e.url}import{safeParse as Gu}from"fast-content-type-parse";function Et(e){let t=e.headers.get("content-type"),o=Gu(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function vn(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,i=async(a,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(a.clone())}catch(m){d=m,p=d.response}if(await t(p,d)&&u<r)p=await c(u+1);else if(d!=null)throw d;return p}return c(0)};return i._rateLimiter=n,i}var Fo=class extends ${constructor(o){super("There was no next page for this.");this.page=o}},So=class extends ${constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},Ku=100;function qe(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:i}=e;return(a,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??i,d=c===null?Number.MAX_SAFE_INTEGER:c??Ku;function y(T,g=void 0){return async()=>{let f=await t(T),{cursor:F,nextPageCursor:S,hasNext:L}=await o(f),z=F??g?.cursor,b=L!==!1,w=g?g.page+1:In,H=w>=d,j={input:T,result:f,page:w,previous:g,hasNext:b,isAtMaxPage:H,cursor:z,nextPageCursor:S,fetchNext:dt(async()=>{if(H)throw new So(j,d);let Fr=b?await r(j,T,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Fr)throw new Fo(j);return y({...T,...Fr},j)()})};return j}}return{input:a,fetchNext:dt(()=>y(a)())}}}function R(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?nn(e):e,i=r??!0?an(n??{}):n,a=new URLSearchParams(i);return o!=null&&J(o,s=>a.delete(s),!1),a}function Ao(e){let t;if(typeof e=="string")t=e;else if(Vu(e))t=e.href;else{let o=Ao(e.url);if(e.queryParams){let r=zu(e.queryParams);pt(r)?t=o:t=Tn(o+`?${r.toString()}`)}else t=o}return t}function Vu(e){return typeof e=="object"&&e instanceof URL}function Hu(e){return typeof e=="object"&&e instanceof URLSearchParams}function qu(e){let t=[];return po(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);J(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function zu(e){let t;return Hu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Le(e)?t=new URLSearchParams(qu(e)):t=ju(e),t}function ju(e){let t=[];return Yr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&J(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var bo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Bu(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Wu=e=>{throw new bo(e)},ee=e=>null;function te(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Wu};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=wn(o);return(a,s,c)=>{let u=Ao(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(m=>{let T=m.json().catch(r),g=n?T.then(f=>n(f,m)):T;return d?g.then(f=>d(f,m)):g})}}function wn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Kr()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r??{method:t,body:n},i=o(i),{...i,method:i.method,body:Bu(i.body)}}}var Yy=wn();var oe=Mn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function Nn(e){let t,o=e?.notInitializedMessage??"Context slot has not been initialized.";return{set:r=>{t=r},get:()=>t,require:()=>{if(t==null)throw new Error(o);return t}}}function Ot(e,t=Ar){return async o=>{try{await e(o)}catch(r){Mr(r),process.exit(t)}}}var Ju=["raw","page_by_line","data_by_line"],$u=["replace","concat"],Xu=["meta","pages","merged_page"];function Dt(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from the per-API page/offset flag."}).option("multiple-pages-output",{type:"string",choices:Xu,default:"meta",describe:"Stdout shape when multiple-pages > 1: meta (summary, low memory), pages (array of page responses, WARNING: holds all pages in memory), merged_page (concat all records into one array, WARNING: holds all records in memory)."}).option("dump-output",{type:"string",choices:Ju,default:"raw",describe:"Dump file format when --dump-dir is set. raw: one full JSON page response (concatenated JSON when --dump-merge=concat, not standard JSON). page_by_line: NDJSON of page responses. data_by_line: NDJSON of records."}).option("dump-merge",{type:"string",choices:$u,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as Yu}from"@nestjs/common";var Pg=Yu((e,t)=>Qu(t));function Qu(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Io,BadRequestException as ep,InternalServerErrorException as tp,Logger as op}from"@nestjs/common";import rp from"raw-body";import{parse as np}from"node:querystring";var Un=new op("RawBody"),_g=Io(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Un.error("RawBody request was not readable. This is generally due to bad configuration."),new ep("Invalid body");return rp(o)}),Ln=Io(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Un.error("RawBody expected a buffer set to req.body."),new tp("failed parsing body");return r}),vg=Io(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=ip(o.body),o.body});function ip(e){let t=ap(e);return np(t)}function ap(e){return e.toString("utf8").trim()}import{Injectable as sp}from"@nestjs/common";import cp from"body-parser";var ze=class{use(t,o,r){cp.json()(t,o,r)}};ze=A([sp()],ze);import{Injectable as up}from"@nestjs/common";import pp from"body-parser";var je=class{use(t,o,r){pp.raw({type:"*/*"})(t,o,r)}};je=A([up()],je);import{Logger as dp,Module as lp,RequestMethod as hp}from"@nestjs/common";var mp="/webhook",yp={path:`${mp}/{*path}`,method:hp.POST},ko=class{configure(t){gp(t)}},Mt=class extends ko{logger=new dp("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Mt=A([lp({})],Mt);function gp(e){e.apply(je).forRoutes(yp).apply(ze).forRoutes("{*path}")}var Gn="CLIENT_WEB_APP_URL";var ke=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as fp,Injectable as Rp}from"@nestjs/common";var Pe=class{_config;constructor(t){this._config=t}get config(){return this._config}get webAppUrl(){return this.config.client.clientWebAppUrl}get webAppHost(){return this.webAppUrl.split("://",2)[1]}};Pe=A([Rp(),k(0,fp(ke))],Pe);import{Module as Tp}from"@nestjs/common";import{ConfigModule as Cp,ConfigService as xp}from"@nestjs/config";function Zp(e){let t={client:{clientWebAppUrl:e.get(Gn)}};return ke.assertValidConfig(t),t}var _t=class{};_t=A([Tp({imports:[Cp],providers:[{provide:ke,inject:[xp],useFactory:Zp},Pe],exports:[Pe]})],_t);var Kn="SERVER_ENV_TOKEN";import{Inject as Fp,Injectable as Sp}from"@nestjs/common";function Vn(){return process.env.NODE_ENV==="test"}var vt=class{constructor(t){this.env=t}get isTestingEnv(){return Vn()}get isProduction(){return this.env.production}get isStaging(){return!!this.env.staging}get developerToolsEnabled(){return!!(!this.isProduction&&this.env.developerToolsEnabled)}get appUrl(){return this.env.appUrl}get appApiUrl(){return this.env.appApiUrl}};vt=A([Sp(),k(0,Fp(Kn))],vt);import{dirname as Ep}from"node:path";import{chmod as Ap,mkdirSync as bp,readFile as Ip,writeFile as kp}from"node:fs";import{rm as Pp}from"node:fs/promises";function ge(e){return new Promise((t,o)=>{Ip(e,{encoding:"utf-8"},(r,n)=>{if(r){r.code==="ENOENT"?t(void 0):o(r);return}try{t(JSON.parse(n))}catch{t(void 0)}})})}function wt(e){return bp(e.dirPath,{recursive:!0}),new Promise((t,o)=>{kp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():Ap(e.filePath,e.mode,n=>{n?o(n):t()})})})}function lt(e){return Pp(e,{force:!0})}var Op=384;function Hn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??Op;async function a(){let p=await ge(t),d;if(p==null)d={};else if(r==null)d=p;else{d={};for(let y of Object.keys(p)){let m=r(p[y]);m!=null&&(d[y]=m)}}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([y,m])=>[y,n(m)]));await wt({filePath:t,dirPath:Ep(t),data:d,mode:i})}let c=Promise.resolve();function u(p){let d=c.then(p,p);return c=d.catch(()=>{}),d}return{load:a,get:async p=>(await a())[p],set:(p,d)=>u(async()=>{let y=await a();await s({...y,[p]:d})}),remove:p=>u(async()=>{let y={...await a()};delete y[p],await s(y)}),clear:()=>u(async()=>{await lt(t)})}}var Qf=Buffer.from([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function ht(e){return ge(e.configFilePath)}function Dp(e){return wt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function mt(e){let t=await ht({configFilePath:e.configFilePath})??{},o={activeEnv:e.updates.activeEnv??t.activeEnv,envs:e.updates.envs?{...t.envs,...e.updates.envs}:t.envs,output:e.updates.output===void 0?t.output:Po(t.output,e.updates.output)};return await Dp({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Po(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Mp(e?.commands,t)}}function Mp(e,t){let o;if("commands"in t)if(t.commands){let r={...e};for(let n of Object.keys(t.commands))r[n]={...e?.[n],...t.commands[n]};o=r}else o=void 0;else o=e;return o}function qn(e){let t=e.commandPath.join("."),o=t?e.outputConfig?.commands?.[t]:void 0;return{dumpDir:e.cliFlags.dumpDir??o?.dumpDir??e.outputConfig?.dumpDir,pick:e.cliFlags.pick??o?.pick??e.outputConfig?.pick}}function fe(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as _p}from"node:os";import{join as Eo}from"node:path";function Nt(e){let t=e.configDirOverride??Eo(_p(),`.${e.cliName}`);return{configDir:t,configFilePath:Eo(t,"config.json"),tokenCachePath:Eo(t,".tokens.json")}}function zn(e){let t=Nt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await ht({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await mt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{kr(!!n.verbose),Pr(typeof n.timeout=="number"?n.timeout*1e3:void 0);let i=n._?n._.map(String):[],a=i[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&a&&!e.skipCommands.has(a)){let m=i.join("."),T={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,T)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?qn({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};so({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function vp(e){let t=Nt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await ht({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>mt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>mt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{dumpDir:void 0,pick:void 0,commands:void 0}}}));return{loadOutputConfig:o,mergeOutputConfig:r,clearOutputConfig:n}}function jn(e){let t=vp(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(a=>{if(a.setDumpDir==null&&a.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:Ot(async i=>{let a=i.command,s=i.setDumpDir,c=i.setPick,u;if(a){let d={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[a]:d}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let p=await t.loadOutputConfig();l({saved:!0,output:p??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:Ot(async()=>{let i=await t.loadOutputConfig();l({output:i??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:Ot(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new ct({message:`No per-command output config for "${a}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[a],await t.mergeOutputConfig({...s,commands:c}),l({cleared:!0,command:a})}else await t.clearOutputConfig(),l({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:i=>i.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:Z}}import{writeFileSync as wp,appendFileSync as Np}from"node:fs";function Bn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=bt(),n=t==="raw"?"json":"ndjson",i=ut(n),a=r?ut(n,"pick"):void 0,s;if(i){let c=0,u=g=>{let f;if(r){let F=be(g.data,r);f={...g,data:F}}else f=g;return f},p=g=>{let f=g.append?Np:wp;f(i,g.mainContent),a&&g.pickContent!==void 0&&f(a,g.pickContent)},d=(g,f)=>{let F=JSON.stringify(g,null,2),S=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:F,pickContent:S,append:f})},y=(g,f)=>{let F=JSON.stringify(g)+`
|
|
5
|
+
`,S=a?JSON.stringify(u(g))+`
|
|
6
|
+
`:void 0;p({mainContent:F,pickContent:S,append:f})},m=(g,f)=>{let F=g.data??[],S=a?be(F,r):void 0;F.length===0?f||p({mainContent:"",pickContent:a?"":void 0,append:!1}):F.forEach((L,z)=>{let b=f||z>0,w=JSON.stringify(L)+`
|
|
7
|
+
`,H=a&&S?JSON.stringify(S[z])+`
|
|
8
|
+
`:void 0;p({mainContent:w,pickContent:H,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let F=o==="concat"&&!(c===0);t==="raw"?d(g,F):t==="page_by_line"?y(g,F):m(g,F),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Up(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:i,shouldCollectPages:a,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let p=0;p<o;p++){let d=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(d),c.lastResult=d,c.lastInput=u,i.writePage(d),a)c.collectedPages.push(d);else if(s)for(let m of d.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,d);let y=n.nextInput(u,d);if(!y)break;u=y}return c}function Lp(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:i}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let a=i?r.collectedPages.map(s=>({...s,data:be(s.data,i)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:a,meta:o}))}else{let a=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=i?be(r.collectedRecords,i):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...a,...o}}))}}async function I(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:i,dumpMerge:a}=e,s=Math.max(1,Math.floor(e.multiplePages||1)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=bt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Bn({dumpOutput:i,dumpMerge:a}),d;try{d=await Up({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:p,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{p.close()}let y={pagesFetched:d.pagesFetched,totalRecords:d.totalRecords,hasMorePagesAvailable:d.hasMorePagesAvailable,dumpFile:p.mainPath??null};p.pickPath&&(y.dumpFilePick=p.pickPath),Lp({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import Bh from"yargs";import{hideBin as Wh}from"yargs/helpers";import{writeFile as Gp,mkdirSync as Kp}from"node:fs";import{join as Oo}from"node:path";import{homedir as Vp}from"node:os";var Ut=["recruit","crm","desk","sign"],Hp=new Set(["sign"]);function Do(){return Oo(Vp(),".zoho-cli")}function yt(){return Oo(Do(),"config.json")}function gt(){return Oo(Do(),".tokens.json")}function Ee(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function q(){let e=yt(),t=await ge(e),o=Ee("ACCOUNTS_CLIENT_ID"),r=Ee("ACCOUNTS_CLIENT_SECRET"),n=Ee("ACCOUNTS_REFRESH_TOKEN"),i=o&&r&&n,a;if(!t&&!i)a=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:Ee("ACCOUNTS_URL")??t?.shared?.region,apiMode:Ee("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Ee("API_URL",p),y=u==="desk"?Ee("DESK_ORG_ID"):void 0,m=t?.[u],T=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],f=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],F=T||g||f,S;return!m&&!F&&!y?S=void 0:S={clientId:T??m?.clientId,clientSecret:g??m?.clientSecret,refreshToken:f??m?.refreshToken,apiUrl:d??m?.apiUrl,orgId:y??m?.orgId},S};a={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,sign:c("sign")??t?.sign,output:t?.output}}return a}function Be(e,t){let o=e[t],r=e.shared,n=!Hp.has(t),i=o?.clientId??(n?r.clientId:void 0),a=o?.clientSecret??(n?r.clientSecret:void 0),s=o?.refreshToken??(n?r.refreshToken:void 0),c;return!i||!a||!s?c=void 0:c={clientId:i,clientSecret:a,refreshToken:s,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},c}async function qp(e){let t=yt();return Kp(Do(),{recursive:!0}),new Promise((o,r)=>{Gp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function X(e){let t=await q(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit===void 0?t?.recruit:{...t?.recruit,...e.recruit},crm:e.crm===void 0?t?.crm:{...t?.crm,...e.crm},desk:e.desk===void 0?t?.desk:{...t?.desk,...e.desk},sign:e.sign===void 0?t?.sign:{...t?.sign,...e.sign},output:e.output===void 0?t?.output:Po(t?.output,e.output)};return await qp(o),o}async function Wn(){await X({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Jn(){let e=yt(),t=gt();await lt(e),await lt(t)}function re(e){return Ut.filter(t=>{let o=Be(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as js,Injectable as Gd}from"@nestjs/common";function We(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function N(e,t){return qe({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:kn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function Lt(e){let t;switch(e){case"sandbox":t="https://recruitsandbox.zoho.com/recruit";break;case"production":t="https://recruit.zoho.com/recruit";break;default:t=e;break}return t}var Je="Candidates",$n="Job_Openings",Gt="Notes",Xn="Emails",ft="Attachments";function Kt(e){let t;if(e!=null)switch(typeof e){case"string":t=e;break;case"object":{let o;Array.isArray(e)?o={and:[e]}:o=e,t=Vt(o);break}default:break}return t}function Vt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(Mo):a&&(s=Vt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=ye(a.map(t)).flatMap(C);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,i=n;return e.and&&(i=r([r(e.and,"and"),n],"and")),i}var Yn=dn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Mo(e){let t=Yn(e.value);return`(${e.field}:${e.filter}:${t})`}var Qn=Kt;import{BaseError as rd}from"make-error";import{BaseError as jp}from"make-error";var Bp="__internal_data_array_blank_error";function Wp(e){return Array.isArray(e?.data)}var Qe="success";function Y(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var Re=class extends jp{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},K=class extends Re{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},$e=class extends K{constructor(t,o){super({code:Bp,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function ne(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof $e&&!o||(r instanceof K?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof Re?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ie(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof He){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ae(e){return(t,o)=>{if(t?.error!=null){let n=new He(o),i=e(t,n);if(i)throw i}return t}}var Jp="INTERNAL_ERROR",$p="INVALID_TOKEN",V=class extends K{},ei="FAILURE",_o=class extends K{},Xp="4834",Xe=class extends K{},Yp="INVALID_QUERY",vo=class extends K{get details(){return this.error.details}},Ht="MANDATORY_NOT_FOUND",Te="DUPLICATE_DATA",qt="INVALID_DATA",Qp="TOO_MANY_REQUESTS",ti=429,ed="X-RATELIMIT-LIMIT",td="X-RATELIMIT-REMAINING",od="X-RATELIMIT-RESET",oi=100,ri=Ie;function wo(e){let t=e.get(ed),o=e.get(td),r=e.get(od),n=null;if(t!=null&&o!=null&&r!=null){let i=Number(t),a=Number(o),s=Number(r),c=new Date(s);n={limit:i,remaining:a,reset:s,resetAt:c}}return n}var Ye=class extends K{get headerDetails(){return wo(this.responseError.response.headers)}};function se(e,t){let o;if(Wp(e))o=new $e(e,t);else{let r=he(e,t);if(r){let n=Y(r);switch(n.code){case Jp:o=new _o(n,e,t);break;case $p:o=new V(n,e,t);break;case Xp:o=new Xe(n,e,t);break;case Yp:o=new vo(n,e,t);break;case Qp:o=new Ye(n,e,t);break;default:o=new K(n,e,t);break}}}return o}function he(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var ni="ALREADY_ASSOCIATED",No=class extends rd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},et=class extends Re{},Uo=class extends et{},Lo=class extends et{},zt=class extends et{get invalidFieldDetails(){return this.error.details}},Go=class extends zt{};function ii(e){let t;switch(e.code){case qt:{let o=new zt(e);o.invalidFieldDetails.id?t=new Go(e):t=o;break}case Ht:t=new Uo(e);break;case Te:t=new Lo(e);break;default:t=new et(e);break}return t}function ai(e,t){return o=>{if(!o?.data?.length)throw new No(e,t);return o}}var nd=ne("ZohoRecruit");async function id(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=si(t,e)),o}function si(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var ci=ae(si),ui=ie(id,nd);import{BaseError as ad}from"make-error";function Vo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,_(o,{data:C(r)})).then(i=>{let a=Array.isArray(r),s=ce(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw ii(p[0].result);c=u[0].result.details}return c}))}function pi(e){return Vo(e,"","POST")}function di(e){return Vo(e,"/upsert","POST")}function li(e){return Vo(e,"","PUT")}function hi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${R({ids:t,wf_trigger:r})}`,_("DELETE")).then(sd)}function mi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,_("GET")).then(ai(t.module)).then(o=>o.data[0])}function yi(e){return(t=>e.fetchJson(`/v2/${t.module}?${Fi(t).toString()}`,_("GET")))}function Ho(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Qn(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return Fi(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,_("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function gi(e){return N(Ho(e))}function tt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${jo(n,n.filter).toString()}`,_("GET")).then(i=>i??(r===!1?i:We()))}}function qo(e){return tt(e)({targetModule:Xn})}function fi(e){return N(qo(e))}function zo(e){return tt(e)({targetModule:ft})}function Ri(e){return N(zo(e))}var lT=20*1024*1024;function Ti(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${ft}?${R(a).toString()}`,c;if(n!=null){let u=new FormData;u.append("file",n),c=e.fetch(s,{method:"POST",headers:{"Content-Type":""},body:u})}else if(i){let u=`${s}&${R({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function Ci(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${ft}/${t.attachment_id}`,{method:"GET"}).then(Et)}function xi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${ft}/${t.attachment_id}`,{method:"DELETE"})}var Ko=class extends ad{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Zi(e){return t=>{let r=R(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v2/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?Lt(t.apiUrl):""}${a}`;return e.fetchJson(c,_("POST")).then(u=>{if(u.code!=="success")throw new Ko(u);return u.details})}}function Fi(...e){return R(e,{omitKeys:"module"})}function jo(...e){return R(e,{omitKeys:["id","module"]})}function _(e,t){return{method:e,body:t??void 0}}function sd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===Qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function ce(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===Qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Si(e){return t=>e.fetchJson(`/v2/${Je}/actions/associate`,_("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=ce(r,o.data),{included:i,excluded:a}=Ge(n.errorItems,s=>s.result.code===ei&&s.result.details.error[0].code===ni);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function Ai(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${jo(t).toString()}`,_("GET")).then(o=>o??We())}function Bo(e){let t=Ai(e);return o=>t({...o,module:Je})}function bi(e){return N(Bo(e))}function Wo(e,t=$n){let o=Ai(e);return r=>o({...r,module:t})}function Ii(e){return N(Wo(e))}function Jo(e){return t=>e.fetchJson(`/v2/${Gt}`,_("POST",{data:t.data})).then(o=>ce(C(t.data),o.data))}function ki(e){return t=>e.fetchJson(`/v2/${Gt}?${R({ids:t.ids})}`,_("DELETE")).then(o=>ce(C(t.ids),o.data))}function $o(e){return tt(e)({targetModule:Gt})}function Pi(e){return N($o(e))}function Ei(e){let t=Jo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Mi(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module})}`,_("POST",{tags:C(t.tags)})).then(o=>{let r=ce(C(t.tags),o.tags),{included:n,excluded:i}=Ge(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function _i(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module,my_tags:t.my_tags})}`,_("GET")).then(o=>({...o,data:o.tags}))}var Oi=100;function vi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Oi)throw new Error(`Cannot add tags to more than ${Oi} records at once.`);return e.fetchJson(`/v2/${Je}/actions/add_tags?${R({tag_names:t.tag_names,ids:t.ids})}`,_("POST")).then(o=>{let r=o.data.map(()=>t);return ce(r,o.data)})}}var Di=100;function wi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Di)throw new Error(`Cannot remove tags from more than ${Di} records at once.`);return e.fetchJson(`/v2/${Je}/actions/remove_tags?${R({tag_names:t.tag_names,ids:t.ids})}`,_("POST")).then(o=>{let r=o.data.map(()=>t);return ce(r,o.data)})}}var cd="invalid_code",ud="invalid_client",Xo=class extends ${constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},ot=class extends ${constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},pd=ne("ZohoAccounts");async function dd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ni(t,e)),o}function Ni(e,t){let o,r=e.error;if(r){let n=Y(r);switch(n.code){case cd:case ud:o=new Xo(n.code);break;default:o=se(e,t);break}}return o}var Ui=ae(Ni),Li=ie(dd,pd);function Ce(e){return async()=>{let t=await e();if(!t.accessToken)throw new ot;return t.accessToken}}var ld=e=>{let t="limit"in e?e.limit:void 0,o="resetAt"in e?e.resetAt:void 0,r=t==null?"":" The limit is "+String(t)+" requests per reset period.",n=o==null?"":" Will be reset at "+String(o)+".";console.warn("zohoRateLimitedFetchHandler(): Too many requests made."+r+n)};function Yo(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??ld,r=e.maxRateLimit??oi,n=e.resetPeriod??ri;function i(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/G)),exponentRate:1.08,maxWaitTime:G*10,resetPeriod:n,resetAt:u}}let a=i(r),s=Fn(a);return vn({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:m,limit:T,resetAt:g}=p;if(T!=null&&T!==r){let f=i(T,g??void 0);s.setConfig(f,!1)}if(s.setRemainingLimit(m),g&&s.setNextResetAt(g),y=!0,c.status===ti){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function xe(e){return Yo({...e,readRateLimitDetails:hd})}function hd(e){let t=wo(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Gi(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Lt(a.apiUrl),c=i({apiUrl:s}),u=ui(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:ci,handleFetchJsonParseErrorFunction:ee});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function jt(e){let t;switch(e){case"sandbox":t="https://crmsandbox.zoho.com/crm";break;case"production":t="https://www.zohoapis.com/crm";break;default:t=e;break}return t}var Bt="Notes",Ki="Emails",Rt="Attachments";var Vi=Kt;import{BaseError as md}from"make-error";var Qo=class extends md{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},rt=class extends Re{},er=class extends rt{},tr=class extends rt{},Wt=class extends rt{get invalidFieldDetails(){return this.error.details}},or=class extends Wt{};function Hi(e){let t;switch(e.code){case qt:{let o=new Wt(e);o.invalidFieldDetails.api_name==="id"?t=new or(e):t=o;break}case Ht:t=new er(e);break;case Te:t=new tr(e);break;default:t=new rt(e);break}return t}function qi(e,t){return o=>{if(!o?.data?.length)throw new Qo(e,t);return o}}var yd=ne("ZohoCrm",{logDataArrayErrors:!1});async function gd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=zi(t,e)),o}function zi(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var ji=ae(zi),Bi=ie(gd,yd);import{BaseError as fd}from"make-error";function nr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,U(o,{data:C(r)})).catch(ca).then(i=>{let a=Array.isArray(r),s=Ze(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Hi(p[0].result);c=u[0].result.details}return c}))}function Wi(e){return nr(e,"","POST")}function Ji(e){return nr(e,"/upsert","POST")}function $i(e){return nr(e,"","PUT")}function Xi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${R({ids:t,wf_trigger:r})}`,U("DELETE")).catch(ca).then(Td)}function Yi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,U("GET")).then(qi(t.module)).then(o=>o.data[0])}function Qi(e){return(t=>e.fetchJson(`/v8/${t.module}?${sa(t).toString()}`,U("GET")))}function ir(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Vi(o.criteria);r.criteria=n}if(!r.word&&!o.cvid&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, cvid, criteria, email, or phone must be provided");return sa(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,U("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function ea(e){return N(ir(e))}function nt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${Rd(n,n.filter).toString()}`,U("GET")).then(i=>i??(r===!1?i:We()))}}function ar(e){let t=nt(e)({targetModule:Ki});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function ta(e){return N(ar(e))}function sr(e){return nt(e)({targetModule:Rt})}function oa(e){return N(sr(e))}var AC=20*1024*1024;function ra(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let a=`/v8/${t.module}/${t.id}/${Rt}?${R(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function na(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Rt}/${t.attachment_id}`,{method:"GET"}).then(Et)}function ia(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Rt}/${t.attachment_id}`,{method:"DELETE"})}var rr=class extends fd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function aa(e){return t=>{let r=R(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v8/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?jt(t.apiUrl):""}${a}`;return e.fetchJson(c,U("POST")).then(u=>{if(u.code!=="success")throw new rr(u);return u.details})}}function sa(...e){return R(e,{omitKeys:"module"})}function Rd(...e){return R(e,{omitKeys:["id","module"]})}function U(e,t){return{method:e,body:t??void 0}}function ca(e){let t;if(e instanceof $e)t={data:e.errorDataArray};else throw e;return t}function Td(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===Qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Ze(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===Qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function cr(e){return t=>e.fetchJson(`/v2/${Bt}`,U("POST",{data:t.data})).then(o=>Ze(C(t.data),o.data))}function ua(e){return t=>e.fetchJson(`/v2/${Bt}?${R({ids:t.ids})}`,U("DELETE")).then(o=>Ze(C(t.ids),o.data))}function ur(e){return nt(e)({targetModule:Bt})}function pa(e){return N(ur(e))}function da(e){let t=cr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function ha(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module})}`,U("POST",{tags:C(t.tags)})).catch(o=>{let r;if(o instanceof K){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Ze(C(t.tags),o.tags),{included:n,excluded:i}=Ge(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ma(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,U("DELETE")).then(o=>o.tags)}function ya(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module,my_tags:t.my_tags})}`,U("GET")).then(o=>({...o,data:o.tags}))}var la=100;function ga(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,U("POST",fa(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function fa(e){if(Array.isArray(e.ids)&&e.ids.length>la)throw new Error(`Cannot add/remove tags from more than ${la} records at once.`);let t=[...C(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&C(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:C(e.ids)}}function Ra(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,U("POST",fa(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function Ta(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=jt(a.apiUrl),c=i({apiUrl:s}),u=Bi(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:ji,handleFetchJsonParseErrorFunction:ee});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ca="https://signsandbox.zoho.com/api/v1",Cd="https://sign.zoho.com/api/v1";function pr(e){let t;switch(e){case"sandbox":t=Ca;break;case"production":t=Cd;break;default:t=e;break}return t}function xa(e){let t=pr(e),o;try{o=new URL(t).hostname!==new URL(Ca).hostname}catch{o=!0}return o}function Za(e,t){return qe({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let a=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??a?.row_count??20,c=(a?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function ue(e,t){return{method:e,body:t??void 0}}function Fa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ue("GET"))}function dr(e){return t=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/requests",queryParams:{data:JSON.stringify(n)}},ue("GET"))}}function Sa(e){let t=dr(e);return Za(t)}function Aa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ue("GET"))}function ba(e){return()=>e.fetchJson("/fieldtypes",ue("GET"))}function Ia(e){return({requestId:t,...o})=>{let n=R(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function ka(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function Pa(e){return({requestData:t,file:o})=>{let r=new FormData;return r.append("data",JSON.stringify({requests:t})),r.append("file",o),e.fetch("/requests",{method:"POST",headers:{"Content-Type":""},body:r}).then(n=>n.json())}}function Ea(e){return({templateId:t,data:o,isQuickSend:r=!0})=>{let n=R({data:JSON.stringify({templates:o})});return e.fetchJson({url:`/templates/${t}/createdocument`,queryParams:{is_quicksend:String(r)}},{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()})}}function Oa(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,ue("GET"))}function Da(e){return(t={})=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/templates",queryParams:{data:JSON.stringify(n)}},ue("GET"))}}function Ma(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ue("PUT",{requests:o}))}function _a(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ue("POST",r))}}function va(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ue("PUT",{expire_by:o}))}function wa(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let i=R(n),a=i.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...a?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()}:{}})}}function Na(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&xa(n)&&!/^https:\/\//i.test(r))throw new Error(`Zoho Sign requires an https embedded-signing host for this environment, but received "${r}".`);return e.fetchJson({url:`/requests/${t}/actions/${o}/embedtoken`,queryParams:{host:r}},ue("POST"))}}var xd=ne("ZohoSign",{logDataArrayErrors:!1});async function Zd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ua(t,e)),o}function Ua(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var La=ae(Ua),Ga=ie(Zd,xd);function Ka(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=pr(a.apiUrl),c=i({apiUrl:s}),u=Ga(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:La,handleFetchJsonParseErrorFunction:ee});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Va(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var Fd=ne("ZohoDesk",{logDataArrayErrors:!1});async function Sd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ha(t,e)),o}function Ha(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var qa=ae(Ha),za=ie(Sd,Fd);var Ad="X-Rate-Limit-Remaining-v3",bd="Retry-After",Id=200;function kd(e){let t=e.get(Ad),o;if(t!=null){let r=Number(t),n,i=e.get(bd);if(i!=null){let a=Number(i);Number.isNaN(a)||(n=new Date(Date.now()+a*G))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function ja(e){return Yo({maxRateLimit:Id,...e,readRateLimitDetails:kd})}function Ba(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=ja(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:a.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!a.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=Va(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=za(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:qa,handleFetchJsonParseErrorFunction:ee});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Wa=25;function Q(e,t){return qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Wa}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Wa,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Oe(e,t){return{method:e,body:t??void 0}}function it(e,t){return R(e,{omitKeys:t})}function Jt(e){let t;return e&&(t=P(C(e))),t}function lr(e){return t=>{let{include:o,...r}=t,n=it([{...r,include:Jt(o)}]);return e.fetchJson(`/tickets?${n}`,Oe("GET")).then(i=>i??{data:[]})}}function Ja(e){return t=>{let{ticketId:o,include:r}=t,i=it([{include:Jt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Oe("GET"))}}function hr(e){return t=>{let o=it([t]);return e.fetchJson(`/tickets/search?${o}`,Oe("GET")).then(r=>r??{data:[]})}}function $a(e){return t=>{let{contactId:o,include:r,...n}=t,i=it([{...n,include:Jt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Oe("GET")).then(a=>a??{data:[]})}}function Xa(e){return t=>{let{productId:o,include:r,...n}=t,i=it([{...n,include:Jt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Oe("GET")).then(a=>a??{data:[]})}}function Ya(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Oe("GET"))}function Qa(e){return t=>{let o=it([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Oe("GET"))}}function es(e){return Q(lr(e))}function ts(e){return Q(hr(e))}function os(e){return{method:e}}function rs(e){return t=>{let o=R([t]);return e.fetchJson(`/departments?${o}`,os("GET")).then(r=>r??{data:[]})}}function ns(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,os("GET"))}function mr(e){return{method:e}}function is(e){let t;return e&&(t=P(C(e))),t}function yr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:is(o)}]);return e.fetchJson(`/contacts?${n}`,mr("GET")).then(i=>i??{data:[]})}}function as(e){return t=>{let{contactId:o,include:r}=t,i=R([{include:is(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,mr("GET"))}}function ss(e){return t=>{let o=R([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,mr("GET")).then(r=>r??[])}}function cs(e){return Q(yr(e))}function Tt(e,t){return{method:e,body:t??void 0}}function us(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Tt("GET")).then(o=>o??[])}function ps(e){return t=>{let o={tags:C(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Tt("POST",o)).then(r=>r??[])}}function ds(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Tt("DELETE"))}function ls(e){return t=>{let o=R([t]);return e.fetchJson(`/tags/search?${o}`,Tt("GET")).then(r=>r??{data:[]})}}function hs(e){return t=>{let o=R([t]);return e.fetchJson(`/ticketTags?${o}`,Tt("GET")).then(r=>r??{data:[]})}}function gr(e,t){return{method:e,body:t??void 0}}function ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,gr("GET")).then(o=>o??[])}function ys(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,gr("POST",o))}}function gs(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,gr("DELETE",o))}}function fs(e,t){return{method:e,body:t??void 0}}function Pd(e){let t;return e&&(t=P(C(e))),t}function Rs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Pd(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,fs("GET")).then(a=>a??{data:[]})}}function Ts(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,fs("DELETE"))}function $t(e,t){return{method:e,body:t??void 0}}function Cs(e){let t;return e&&(t=P(C(e))),t}function xs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Cs(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,$t("GET")).then(a=>a??{data:[]})}}function Zs(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=R([{include:Cs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,$t("GET"))}}function Fs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,$t("POST",r))}}function Ss(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,$t("DELETE"))}function Ct(e,t){return{method:e,body:t??void 0}}function As(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Ct("GET"))}function bs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Ct("POST",r))}}function Is(e){return t=>{let{ticketId:o,...r}=t,n=R([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Ct("GET")).then(i=>i??{data:[]})}}function ks(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Ct("GET"))}function Ps(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Ct("GET"))}function Es(e){return{method:e}}function Os(e){let t;return e&&(t=P(C(e))),t}function fr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Os(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,Es("GET")).then(a=>a??{data:[]})}}function Ds(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=R([{include:Os(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,Es("GET"))}}function Ms(e){return Q(fr(e))}function Ed(e){return{method:e}}function Od(e){let t;return e&&(t=P(C(e))),t}function Rr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Od(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,Ed("GET")).then(a=>a??{data:[]})}}function _s(e){return Q(Rr(e))}function Xt(e){return{method:e}}function vs(e){let t;return e&&(t=P(C(e))),t}function Tr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:vs(o)}]);return e.fetchJson(`/agents?${n}`,Xt("GET")).then(i=>i??{data:[]})}}function ws(e){return t=>{let{agentId:o,include:r}=t,i=R([{include:vs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Xt("GET"))}}function Ns(e){return t=>{let o=R([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Xt("GET")).then(r=>r?.data??[])}}function Us(e){return()=>e.fetchJson("/myinfo",Xt("GET"))}function Ls(e){return Q(Tr(e))}function Yt(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:i,refreshToken:a}=t??{},s=i?.clientId??o,c=i?.clientSecret??r,p=R({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`/oauth/v2/token?${p}`,Dd("POST"))}}function Dd(e,t){return{method:e,body:t}}var Md="https://accounts.zoho.com";function Gs(e){let t;return e==="us"?t=Md:t=e,t}function Ks(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>oe.makeFetch({baseUrl:n.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:t,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return n=>{if(n.refreshToken)if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsConfig missing clientSecret.")}else throw new Error("ZohoAccountsConfig missing clientId.");else throw new Error("ZohoAccountsConfig missing refreshToken.");let i=Gs(n.apiUrl??"us"),a=r({apiUrl:i}),s=Li(a,o),c=te(s,{interceptJsonResponse:Ui,handleFetchJsonParseErrorFunction:ee}),u=async()=>{let m=Date.now(),{access_token:T,api_domain:g,scope:f,expires_in:F}=await Yt(d)();return{accessToken:T,apiDomain:g,expiresIn:F,expiresAt:new Date(m+F*G),scope:f}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=_d({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function _d(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Ie,i=null,a=async()=>{i=null},s=async()=>{if(!i){let c=await o?.loadCachedToken();c&&(i=c)}if(i!=null&&Date.now()+n>=i.expiresAt.getTime()&&(i=null),!i){try{i=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new ot("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Fe(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Se=class{zohoAccounts;factoryConfig;static assertValidConfig(t){let{zohoAccounts:o}=t;if(o)if(o.serviceAccessTokenKey)if(o.refreshToken)if(o.apiUrl){if(!o.clientId)throw new Error("ZohoAccountsServiceConfig.zohoAccounts.clientId is required")}else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.apiUrl is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.refreshToken is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.serviceAccessTokenKey is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts is required")}};import{Injectable as vd}from"@nestjs/common";var at=class{};at=A([vd()],at);function wd(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!rn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function Nd(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Ud(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Hs(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Ud;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(i){let a=o.map(u=>u.loadZohoAccessTokenCache(i)),s=a.map(wd),c=pn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>Nd(d,u)));if(r!=null){let d=ye(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function qs(e,t){let o={};if(e!=null)for(let i of Object.keys(e)){let a=e[i];a!=null&&(o[i]=a)}let r=cn(o);function n(i){return{loadCachedToken:async()=>{let a=await r.get(i);return t&&console.log("retrieving access token from memory: ",{service:i,hit:a!=null,expiresAt:a?.expiresAt}),a},updateCachedToken:async a=>{await r.set(i,a),t&&console.log("updating access token in memory: ",{service:i,expiresAt:a?.expiresAt})},clearCachedToken:async()=>{await r.remove(i),t&&console.log("clearing access token in memory: ",{service:i})}}}return{loadZohoAccessTokenCache:n}}var Ld=".tmp/zoho-access-tokens.json";function Vs(e){let t;if(e==null||typeof e!="object")t=void 0;else{let o=e,r=o.expiresAt,n=r!=null&&!(r instanceof Date)?new Date(r):r;t={...o,expiresAt:n}}return t}function zs(e=Ld,t=!0){let o=Hn({filePath:e,reviver:Vs}),r=t?un(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(p){console.error("Failed updating access token in file: ",p)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function i(){let c=await ge(e),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Vs(c[d]);u=p}return u}async function a(c){await r.clear();for(let[u,p]of Object.entries(c))p!=null&&await r.set(u,p)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:i,writeTokenFile:a,deleteTokenFile:s}}var v=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=Ks(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return Yt(this.accountsContext)}};v=A([Gd(),k(0,js(Se)),k(1,js(at))],v);import{Inject as Bs,Injectable as Kd}from"@nestjs/common";var xt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Fe(t.zohoCrm)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=Ta({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Wi(this.crmContext)}get upsertRecord(){return Ji(this.crmContext)}get updateRecord(){return $i(this.crmContext)}get deleteRecord(){return Xi(this.crmContext)}get getRecordById(){return Yi(this.crmContext)}get getRecords(){return Qi(this.crmContext)}get searchRecords(){return ir(this.crmContext)}get searchRecordsPageFactory(){return ea(this.crmContext)}get getRelatedRecordsFunctionFactory(){return nt(this.crmContext)}get getEmailsForRecord(){return ar(this.crmContext)}get getEmailsForRecordPageFactory(){return ta(this.crmContext)}get getAttachmentsForRecord(){return sr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return oa(this.crmContext)}get uploadAttachmentForRecord(){return ra(this.crmContext)}get downloadAttachmentForRecord(){return na(this.crmContext)}get deleteAttachmentFromRecord(){return ia(this.crmContext)}get createNotes(){return cr(this.crmContext)}get deleteNotes(){return ua(this.crmContext)}get createNotesForRecord(){return da(this.crmContext)}get getNotesForRecord(){return ur(this.crmContext)}get getNotesForRecordPageFactory(){return pa(this.crmContext)}get executeRestApiFunction(){return aa(this.crmContext)}get createTagsForModule(){return ha(this.crmContext)}get deleteTag(){return ma(this.crmContext)}get getTagsForModule(){return ya(this.crmContext)}get addTagsToRecords(){return ga(this.crmContext)}get removeTagsFromRecords(){return Ra(this.crmContext)}};De=A([Kd(),k(0,Bs(xt)),k(1,Bs(v))],De);import{ConfigModule as JF,ConfigService as $F}from"@nestjs/config";import{Inject as Ws,Injectable as Vd}from"@nestjs/common";var Zt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Fe(t.zohoRecruit)}};var Me=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Gi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return pi(this.recruitContext)}get upsertRecord(){return di(this.recruitContext)}get updateRecord(){return li(this.recruitContext)}get deleteRecord(){return hi(this.recruitContext)}get getRecordById(){return mi(this.recruitContext)}get getRecords(){return yi(this.recruitContext)}get searchRecords(){return Ho(this.recruitContext)}get searchRecordsPageFactory(){return gi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return tt(this.recruitContext)}get getEmailsForRecord(){return qo(this.recruitContext)}get getEmailsForRecordPageFactory(){return fi(this.recruitContext)}get getAttachmentsForRecord(){return zo(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Ri(this.recruitContext)}get uploadAttachmentForRecord(){return Ti(this.recruitContext)}get downloadAttachmentForRecord(){return Ci(this.recruitContext)}get deleteAttachmentFromRecord(){return xi(this.recruitContext)}get createNotes(){return Jo(this.recruitContext)}get deleteNotes(){return ki(this.recruitContext)}get createNotesForRecord(){return Ei(this.recruitContext)}get getNotesForRecord(){return $o(this.recruitContext)}get getNotesForRecordPageFactory(){return Pi(this.recruitContext)}get executeRestApiFunction(){return Zi(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return Si(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Bo(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return bi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Wo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return Ii(this.recruitContext)}get createTagsForModule(){return Mi(this.recruitContext)}get getTagsForModule(){return _i(this.recruitContext)}get addTagsToRecords(){return vi(this.recruitContext)}get removeTagsFromRecords(){return wi(this.recruitContext)}};Me=A([Vd(),k(0,Ws(Zt)),k(1,Ws(v))],Me);import{ConfigModule as RS,ConfigService as TS}from"@nestjs/config";import{Inject as Js,Injectable as Hd}from"@nestjs/common";var Ft=class{zohoSign;factoryConfig;static assertValidConfig(t){Fe(t.zohoSign)}};var _e=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ka({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Fa(this.signContext)}get getDocuments(){return dr(this.signContext)}get getDocumentsPageFactory(){return Sa(this.signContext)}get getDocumentFormData(){return Aa(this.signContext)}get retrieveFieldTypes(){return ba(this.signContext)}get downloadPdf(){return Ia(this.signContext)}get downloadCompletionCertificate(){return ka(this.signContext)}get createDocument(){return Pa(this.signContext)}get createDocumentFromTemplate(){return Ea(this.signContext)}get getTemplate(){return Oa(this.signContext)}get getTemplates(){return Da(this.signContext)}get updateDocument(){return Ma(this.signContext)}get sendDocumentForSignature(){return _a(this.signContext)}get extendDocument(){return va(this.signContext)}get deleteDocument(){return wa(this.signContext)}get getEmbeddedSigningUrl(){return Na(this.signContext)}};_e=A([Hd(),k(0,Js(Ft)),k(1,Js(v))],_e);import{ConfigModule as KS,ConfigService as VS}from"@nestjs/config";function $s(e){return{...e,operationType:e.notifications.operation_type}}var Xs=Sn(e=>e.operationType),Ys=bn({configurerForAccessor:e=>{let t=An(e,r=>r);return{...e,handleRequestSubmitted:t("RequestSubmitted"),handleRequestViewed:t("RequestViewed"),handleRequestSigningSuccess:t("RequestSigningSuccess"),handleRequestCompleted:t("RequestCompleted"),handleRequestRejected:t("RequestRejected"),handleRequestRecalled:t("RequestRecalled"),handleRequestForwarded:t("RequestForwarded"),handleRequestExpired:t("RequestExpired")}}});var Qs="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",ve=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as $d,Inject as Xd,Post as Yd,Req as Qd}from"@nestjs/common";import{Inject as Bd,Injectable as Wd,Logger as Jd}from"@nestjs/common";import{createHmac as qd,timingSafeEqual as zd}from"node:crypto";var jd="x-zs-webhook-signature";function ec(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[jd],i={valid:!1};if(n){let a=r.toString("utf-8"),s=qd("sha256",t).update(a,"utf-8").digest("base64"),c=!1;try{let p=Buffer.from(n,"base64"),d=Buffer.from(s,"base64");p.length===d.length&&(c=zd(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=$s(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var me=class{logger=new Jd("ZohoSignWebhookService");_verifier;handler=Xs();configure=Ys(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=ec({secret:o})}async updateForWebhook(t,o){let r=await this._verifier(t,o);r.valid?await this.updateForZohoSignEvent(r.event):this.logger.warn("Received invalid Zoho Sign webhook event.",t)}async updateForZohoSignEvent(t){await this.handler(t)||this.logger.warn("Received unexpected/unhandled Zoho Sign webhook event.",t)}};me=A([Wd(),k(0,Bd(ve))],me);var we=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};A([Yd(),k(0,Qd()),k(1,Ln())],we.prototype,"handleZohoSignWebhook",1),we=A([$d("/webhook/zoho/sign"),k(0,Xd(me))],we);import{Module as el}from"@nestjs/common";import{ConfigModule as tl,ConfigService as ol}from"@nestjs/config";function rl(e){let t={zohoSignWebhook:{webhookSecret:e.get(Qs)}};return ve.assertValidConfig(t),t}var eo=class{};eo=A([el({imports:[tl],controllers:[we],providers:[{provide:ve,inject:[ol],useFactory:rl},me],exports:[me]})],eo);import{Inject as tc,Injectable as nl}from"@nestjs/common";var St=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Fe(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var Ne=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Ba({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return lr(this.deskContext)}get getTicketById(){return Ja(this.deskContext)}get searchTickets(){return hr(this.deskContext)}get getTicketsForContact(){return $a(this.deskContext)}get getTicketsForProduct(){return Xa(this.deskContext)}get getTicketMetrics(){return Ya(this.deskContext)}get getAgentsTicketsCount(){return Qa(this.deskContext)}get getTicketsPageFactory(){return es(this.deskContext)}get searchTicketsPageFactory(){return ts(this.deskContext)}get getDepartments(){return rs(this.deskContext)}get getDepartmentById(){return ns(this.deskContext)}get getContacts(){return yr(this.deskContext)}get getContactById(){return as(this.deskContext)}get getContactsByIds(){return ss(this.deskContext)}get getContactsPageFactory(){return cs(this.deskContext)}get getTicketTags(){return us(this.deskContext)}get associateTicketTags(){return ps(this.deskContext)}get dissociateTicketTag(){return ds(this.deskContext)}get searchTags(){return ls(this.deskContext)}get getAllTags(){return hs(this.deskContext)}get getTicketFollowers(){return ms(this.deskContext)}get addTicketFollowers(){return ys(this.deskContext)}get removeTicketFollowers(){return gs(this.deskContext)}get getTicketAttachments(){return Rs(this.deskContext)}get deleteTicketAttachment(){return Ts(this.deskContext)}get getTicketComments(){return xs(this.deskContext)}get getTicketCommentById(){return Zs(this.deskContext)}get createTicketComment(){return Fs(this.deskContext)}get deleteTicketComment(){return Ss(this.deskContext)}get getTicketTimer(){return As(this.deskContext)}get performTicketTimerAction(){return bs(this.deskContext)}get getTicketTimeEntries(){return Is(this.deskContext)}get getTicketTimeEntryById(){return ks(this.deskContext)}get getTicketTimeEntrySummation(){return Ps(this.deskContext)}get getTicketThreads(){return fr(this.deskContext)}get getTicketThreadById(){return Ds(this.deskContext)}get getTicketThreadsPageFactory(){return Ms(this.deskContext)}get getTicketActivities(){return Rr(this.deskContext)}get getTicketActivitiesPageFactory(){return _s(this.deskContext)}get getAgents(){return Tr(this.deskContext)}get getAgentById(){return ws(this.deskContext)}get getAgentsByIds(){return Ns(this.deskContext)}get getMyInfo(){return Us(this.deskContext)}get getAgentsPageFactory(){return Ls(this.deskContext)}};Ne=A([nl(),k(0,tc(St)),k(1,tc(v))],Ne);import{ConfigModule as VA,ConfigService as HA}from"@nestjs/config";function il(e){return`${e.clientId}:${e.refreshToken}`}function st(e){let t=Hs([qs(),zs(gt())]),o=new Map;function r(y,m){let T=il(y),g=o.get(T),f;if(g)f=g;else{let F={zohoAccounts:{serviceAccessTokenKey:m,refreshToken:y.refreshToken,clientId:y.clientId,clientSecret:y.clientSecret,apiUrl:y.region??"us"}};f=new v(F,t),o.set(T,f)}return f}let n,i=Be(e,"recruit");if(i){let y=r(i,"recruit"),m={zohoRecruit:{apiUrl:i.apiMode}};n=new Me(m,y)}let a,s=Be(e,"crm");if(s){let y=r(s,"crm"),m={zohoCrm:{apiUrl:s.apiMode}};a=new De(m,y)}let c,u=Be(e,"desk");if(u?.orgId){let y=r(u,"desk"),m={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new Ne(m,y)}let p,d=Be(e,"sign");if(d){let y=r(d,"sign"),m={zohoSign:{apiUrl:d.apiMode}};p=new _e(m,y)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:p}}co([...ao,/1000\.\w{20,}/g]);function oc(e){let t;return e instanceof V?t={ok:!1,error:le(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof Xe?t={ok:!1,error:le(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Ye?t={ok:!1,error:le(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof K?t={ok:!1,error:le(e.message),code:"API_ERROR"}:t=uo(e),t}Er(e=>e instanceof V||e instanceof Xe||e instanceof Ye||e instanceof K?oc(e):void 0);function h(e){console.log(JSON.stringify(oc(e)))}var rc={us:"https://accounts.zoho.com",eu:"https://accounts.zoho.eu",in:"https://accounts.zoho.in",au:"https://accounts.zoho.com.au",jp:"https://accounts.zoho.jp"},Zr={recruit:["ZohoRecruit.modules.ALL","ZohoRecruit.settings.all","ZohoRecruit.functions.execute.READ","ZohoRecruit.functions.execute.CREATE"],crm:["ZohoCRM.modules.ALL","ZohoCRM.settings.ALL","ZohoCRM.functions.execute.READ","ZohoCRM.functions.execute.CREATE"],desk:["Desk.tickets.ALL","Desk.tasks.ALL","Desk.contacts.ALL","Desk.settings.ALL","Desk.events.ALL","Desk.search.READ","Desk.articles.READ","Desk.basic.READ"],sign:["ZohoSign.documents.ALL","ZohoSign.templates.ALL"]};function al(e){let t;if(!e)t=void 0;else if(e.startsWith("http://")||e.startsWith("https://"))try{let r=new URL(e).searchParams.get("code");if(!r)throw new Error('No "code" parameter found in the provided URL.');t=r}catch(o){throw o instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`,{cause:o}):o}else t=e;return t}var sl={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:"http://localhost/oauth",describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",default:"recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign)"}).option("code",{type:"string",describe:"Authorization code or the full redirect URL (code is extracted automatically)"}).option("token",{type:"string",describe:"Set a refresh token directly (skips OAuth code exchange)"}).option("product",{type:"string",choices:[...Ut],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth setup --client-id 1000.ABC --client-secret xyz","Step 1: Get OAuth URL (saves shared credentials)"],["$0 auth setup --code 1000.AUTH.CODE","Step 2: Exchange code for refresh token"],['$0 auth setup --code "http://localhost/oauth?code=1000.AUTH.CODE&location=us"',"Step 2: Paste the full redirect URL"],["$0 auth setup --client-id 1000.ABC --client-secret xyz --token 1000.REFRESH.TOKEN","Set shared refresh token directly"],["$0 auth setup --product crm --client-id 1000.CRM --client-secret xyz --token 1000.CRM.TOKEN","Set CRM-specific credentials"],["$0 auth setup --product sign --client-id 1000.SIGN --client-secret xyz","Sign uses a separate OAuth client (sign-only scopes)"]]),handler:async e=>{try{let t=await q(),o=cl(e,t);if(!o.clientId||!o.clientSecret)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");o.token?await ul(o,t):o.code?await pl(o,t):await dl(o,t)}catch(t){h(t),process.exit(1)}}};function cl(e,t){let o=e.region??t?.shared?.region??"us",r=e.product,n=r?t?.[r]:void 0;return{product:r,clientId:e.clientId??n?.clientId??t?.shared?.clientId,clientSecret:e.clientSecret??n?.clientSecret??t?.shared?.clientSecret,redirectUri:e.redirectUri,region:o,scopes:e.scopes.split(",").map(i=>i.trim()),code:al(e.code),token:e.token,accountsUrl:rc[o]??rc.us,apiMode:e.apiMode,orgId:e.orgId}}async function nc(e,t,o){return e.product?X({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:{...t,apiUrl:e.apiMode,orgId:e.product==="desk"?e.orgId:void 0}}):X({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function ul(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await nc(e,o,t?.shared);l({success:!0,...e.product?{product:e.product}:{},refreshToken:fe(e.token),configSaved:!0,configuredProducts:re(r)})}async function pl(e,t){let o=`${e.accountsUrl}/oauth/v2/token`,r=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUri,code:e.code}),i=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()})).json();if(i.error)throw new Error(`Token exchange failed: ${i.error}`);let a=i.refresh_token;if(!a)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let s={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:a},c=await nc(e,s,t?.shared);l({step:2,success:!0,product:e.product??"shared",refreshToken:fe(a),accessToken:i.access_token?fe(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:re(c)})}async function dl(e,t){let o=e.product?Zr[e.product]??[]:e.scopes.flatMap(i=>Zr[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Zr).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;e.product?await X({shared:{clientId:t?.shared?.clientId??"",clientSecret:t?.shared?.clientSecret??"",refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},[e.product]:{clientId:e.clientId,clientSecret:e.clientSecret,apiUrl:e.apiMode,orgId:e.product==="desk"?e.orgId:void 0}}):await X({shared:{clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});let n=e.product?`--product ${e.product} `:"";l({step:1,product:e.product??"shared",instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:r,redirectUri:e.redirectUri,scopes:o,credentialsSaved:!0,nextStep:`zoho-cli auth setup ${n}--code "PASTE_REDIRECT_URL_OR_AUTH_CODE"`})}var ll={command:"set",describe:"Save Zoho API credentials directly",builder:e=>e.option("client-id",{type:"string",demandOption:!0,describe:"OAuth client ID"}).option("client-secret",{type:"string",demandOption:!0,describe:"OAuth client secret"}).option("refresh-token",{type:"string",demandOption:!0,describe:"OAuth refresh token"}).option("product",{type:"string",choices:[...Ut],describe:"Store for a specific product instead of shared"}).option("region",{type:"string",default:"us",describe:"Zoho region (us, eu, in, au, jp)"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth set --client-id abc --client-secret xyz --refresh-token 1000.abc.xyz","Set shared credentials"],["$0 auth set --product crm --client-id abc --client-secret xyz --refresh-token 1000.crm.xyz","Set CRM-specific credentials"]]),handler:async e=>{try{let t=e.product,o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken},r;t?r=await X({shared:(await q())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await X({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({saved:!0,product:t??"shared",configuredProducts:re(r)})}catch(t){h(t),process.exit(1)}}},hl={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?fe(r.clientId):void 0,clientSecret:r.clientSecret?fe(r.clientSecret):void 0,refreshToken:r.refreshToken?fe(r.refreshToken):void 0}:void 0};var e=o;let t=await q();if(!t){l({configured:!1});return}l({configured:!0,shared:{...o(t.shared),region:t.shared?.region??"us",apiMode:t.shared?.apiMode??"production"},recruit:t.recruit?{...o(t.recruit),apiUrl:t.recruit.apiUrl}:null,crm:t.crm?{...o(t.crm),apiUrl:t.crm.apiUrl}:null,desk:t.desk?{...o(t.desk),apiUrl:t.desk.apiUrl,orgId:t.desk.orgId}:null,sign:t.sign?{...o(t.sign),apiUrl:t.sign.apiUrl}:null,configuredProducts:re(t)})}catch(t){h(t),process.exit(1)}}},ml={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await q();if(e){let t=re(e);if(t.length===0)l({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=st(e),r={};for(let n of t)try{let i;if(n==="recruit"?i=o.recruitApi:n==="crm"?i=o.crmApi:n==="sign"?i=o.signApi:i=o.deskApi,!i){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let a=i instanceof Error?i.message:String(i);r[n]={authenticated:!1,error:a}}l({products:r})}}else l({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){h(e),process.exit(1)}}},yl={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Jn(),l({cleared:!0})}catch(e){h(e),process.exit(1)}}},ic={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(sl).command(ll).command(hl).command(ml).command(yl).demandCommand(1,"Please specify an auth subcommand."),handler:Z};import{access as gl,constants as fl}from"node:fs";import{dirname as Rl}from"node:path";var ac={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await q(),t=[];t.push(Tl(e));let o=Cl(e);if(o&&t.push(o),t.push(await xl()),e){let n=re(e);t.push(Zl(n),...await Fl(e,n));let i=bl(e,n);i&&t.push(i)}let r=t.every(n=>n.status==="pass");l({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function Tl(e){return e?{name:"config",status:"pass",message:`Config loaded from ${yt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function Cl(e){if(e?.shared?.clientId&&e?.shared?.clientSecret&&e?.shared?.refreshToken)return{name:"shared-credentials",status:"pass",message:"Shared credentials present"};if(e)return{name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."}}async function xl(){let e=Rl(gt());return await Il(e)?{name:"token-cache",status:"pass",message:`Token cache directory writable: ${e}`}:{name:"token-cache",status:"warn",message:`Token cache directory not writable: ${e}`}}function Zl(e){return e.length>0?{name:"products",status:"pass",message:`Configured products: ${e.join(", ")}`}:{name:"products",status:"fail",message:"No products have complete credentials"}}async function Fl(e,t){let o=st(e),r=[];for(let n of t)r.push(await Sl(o,n));return r}async function Sl(e,t){let o=Al(e,t);if(!o)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let r;try{let i=await o.zohoAccountsApi.accessToken();r={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${i.scope}`}}catch(n){let i=n instanceof Error?n.message:String(n);r={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${i}`}}return r}function Al(e,t){return t==="recruit"?e.recruitApi:t==="crm"?e.crmApi:t==="sign"?e.signApi:e.deskApi}function bl(e,t){if(e.desk?.orgId)return{name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${e.desk.orgId}`};if(!t.includes("desk"))return{name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."}}function Il(e){return new Promise(t=>{gl(e,fl.W_OK,o=>{t(!o)})})}var sc=Nn({notInitializedMessage:"CLI context not initialized. This is a bug."});function cc(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await q();r||(h(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),re(r).length===0&&(h(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),sc.set(st(r))}catch(r){h(r),process.exit(4)}}}function to(e){return sc.require()}function B(e){let{recruitApi:t}=to(e);if(!t)throw new Error("Recruit not configured. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z");return t}function W(e){let{crmApi:t}=to(e);if(!t)throw new Error("CRM not configured. Run: zoho-cli auth setup --product crm --client-id X --client-secret Y --token Z");return t}function x(e){let{deskApi:t}=to(e);if(!t)throw new Error("Desk not configured. Run: zoho-cli auth setup --product desk --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function D(e){let{signApi:t}=to(e);if(!t)throw new Error("Sign not configured. Zoho Sign requires its own OAuth client. Run: zoho-cli auth setup --product sign --client-id X --client-secret Y --token Z");return t}function pe(e){return Dt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function E(e){return Dt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function oo(e){return Dt(e.option("start-index",{type:"number",default:1,describe:"Start index (1-based)"}).option("row-count",{type:"number",default:20,describe:"Records per page"}))}function M(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Ae(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function At(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function ro(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}var kl={nextInput:(e,t)=>{let o;if(t.info?.more_records){let r=e.page??1;o={...e,page:r+1}}else o=void 0;return o},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},O={nextInput:(e,t)=>{let o=e.limit??25,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let i=e.from??1;n={...e,from:i+o}}return n},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25,r=t.data?.length??0;return o>0&&r>=o}},Pl={nextInput:(e,t)=>{let o;if(t.page_context?.has_more_rows){let r=e.row_count??t.page_context?.row_count??20,n=e.start_index??t.page_context?.start_index??1;o={...e,start_index:n+r}}else o=void 0;return o},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({start_index:t.page_context?.start_index??e.start_index,row_count:t.page_context?.row_count??e.row_count,total_count:t.page_context?.total_count,has_more_rows:t.page_context?.has_more_rows??!1}),hasMorePagesAvailable:(e,t)=>t.page_context?.has_more_rows??!1};async function de(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await I({initialInput:o,fetchPage:r,adapter:kl,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;l(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}async function no(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await I({initialInput:o,fetchPage:async i=>{let a=await r(i);return{data:a.requests??[],page_context:a.page_context}},adapter:Pl,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;l(i.data,{start_index:i.page_context?.start_index,row_count:i.page_context?.row_count,total_count:i.page_context?.total_count,has_more_rows:i.page_context?.has_more_rows??!1})}}var El={command:"list",describe:"List records from a module",builder:e=>ro(At(pe(M(e)))),handler:async e=>{try{let t=B(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await de({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Ol={command:"get",describe:"Get a record by ID",builder:e=>Ae(M(e)),handler:async e=>{try{let o=await B(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){h(t),process.exit(1)}}},Dl={command:"search",describe:"Search records in a module",builder:e=>pe(M(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=B(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(t),process.exit(1)}}},Ml={command:"insert",describe:"Insert a record into a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},_l={command:"upsert",describe:"Upsert a record in a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},vl={command:"update",describe:"Update a record in a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=B(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},wl={command:"delete",describe:"Delete records from a module",builder:e=>M(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=B(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){h(t),process.exit(1)}}},Nl={command:"emails",describe:"Get emails for a record",builder:e=>pe(Ae(M(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Ul={command:"attachments",describe:"Get attachments for a record",builder:e=>pe(Ae(M(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},uc={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(El).command(Ol).command(Dl).command(Ml).command(_l).command(vl).command(wl).command(Nl).command(Ul).demandCommand(1,"Please specify a recruit subcommand.").example([["$0 recruit list -m Candidates --per-page 10","List first 10 candidates"],["$0 recruit get -m Candidates --id 12345","Get a candidate by ID"],['$0 recruit search -m Candidates --word "John"',"Search candidates by keyword"],[`$0 recruit insert -m Candidates --data '{"First_Name":"John","Last_Name":"Doe"}'`,"Insert a candidate"]]),handler:Z};var Ll={command:"list",describe:"List records from a module",builder:e=>ro(At(pe(M(e)),!0)),handler:async e=>{try{let t=W(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await de({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Gl={command:"get",describe:"Get a record by ID",builder:e=>Ae(M(e)),handler:async e=>{try{let o=await W(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){h(t),process.exit(1)}}},Kl={command:"search",describe:"Search records in a module",builder:e=>pe(M(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=W(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(t),process.exit(1)}}},Vl={command:"insert",describe:"Insert a record into a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Hl={command:"upsert",describe:"Upsert a record in a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},ql={command:"update",describe:"Update a record in a module",builder:e=>M(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},zl={command:"delete",describe:"Delete records from a module",builder:e=>M(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=W(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){h(t),process.exit(1)}}},jl={command:"emails",describe:"Get emails for a record",builder:e=>pe(Ae(M(e))),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Bl={command:"attachments",describe:"Get attachments for a record",builder:e=>At(pe(Ae(M(e))),!0),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await de({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},pc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Ll).command(Gl).command(Kl).command(Vl).command(Hl).command(ql).command(zl).command(jl).command(Bl).demandCommand(1,"Please specify a CRM subcommand.").example([['$0 crm list -m Contacts --fields "First_Name,Last_Name,Email" --per-page 10',"List contacts"],["$0 crm get -m Contacts --id 12345","Get a contact by ID"],['$0 crm search -m Leads --word "Acme"',"Search leads by keyword"],[`$0 crm insert -m Contacts --data '{"First_Name":"Jane","Last_Name":"Doe"}'`,"Insert a contact"]]),handler:Z};var Wl={command:"list",describe:"List tickets",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status"}).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Jl={command:"get <ticketId>",describe:"Get a ticket by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let o=await x(e).getTicketById({ticketId:e.ticketId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},$l={command:"search",describe:"Search tickets",builder:e=>E(e).option("subject",{type:"string",describe:"Search by subject"}).option("status",{type:"string",describe:"Filter by status"}).option("email",{type:"string",describe:"Filter by email"}).option("department-id",{type:"string",describe:"Filter by department ID"}).option("channel",{type:"string",describe:"Filter by channel"}).option("priority",{type:"string",describe:"Filter by priority"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,subject:e.subject,status:e.status,email:e.email,departmentId:e.departmentId,channel:e.channel,priority:e.priority},r=await I({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Xl={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>E(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=x(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Yl={command:"metrics <ticketId>",describe:"Get ticket metrics",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketMetrics({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},Ql={command:"agent-counts",describe:"Get ticket counts per agent",builder:e=>e.option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}).option("department-id",{type:"string",describe:"Filter by department ID"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});l(r)}catch(t){h(t),process.exit(1)}}},dc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Wl).command(Jl).command($l).command(Xl).command(Yl).command(Ql).demandCommand(1),handler:Z};var eh={command:"list",describe:"List departments",builder:e=>E(e).option("search",{type:"string",describe:"Search by name"}).option("is-enabled",{type:"boolean",describe:"Filter by enabled status"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await I({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},th={command:"get <departmentId>",describe:"Get a department by ID",builder:e=>e.positional("departmentId",{type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let o=await x(e).getDepartmentById({departmentId:e.departmentId});l(o)}catch(t){h(t),process.exit(1)}}},lc={command:"departments",describe:"Desk department operations",builder:e=>e.command(eh).command(th).demandCommand(1),handler:Z};var oh={command:"list",describe:"List contacts",builder:e=>E(e).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},rh={command:"get <contactId>",describe:"Get a contact by ID",builder:e=>e.positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getContactById({contactId:e.contactId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},hc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(oh).command(rh).demandCommand(1),handler:Z};var nh={command:"list",describe:"List agents",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status (active, disabled)"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. role,profile,departments)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},ih={command:"get <agentId>",describe:"Get an agent by ID",builder:e=>e.positional("agentId",{type:"string",demandOption:!0,describe:"Agent ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getAgentById({agentId:e.agentId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},ah={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await x(e).getMyInfo();l(o)}catch(t){h(t),process.exit(1)}}},mc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(nh).command(ih).command(ah).demandCommand(1),handler:Z};var sh={command:"list",describe:"List all tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await I({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},ch={command:"search",describe:"Search tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",describe:"Department ID"}).option("query",{alias:"q",type:"string",demandOption:!0,describe:"Search string"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await I({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},uh={command:"for-ticket <ticketId>",describe:"Get tags on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTags({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},ph={command:"associate <ticketId>",describe:"Add tags to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tags",{type:"string",demandOption:!0,describe:"Comma-separated tag names"}),handler:async e=>{try{let t=x(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});l(r)}catch(t){h(t),process.exit(1)}}},dh={command:"dissociate <ticketId>",describe:"Remove a tag from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tag-id",{type:"string",demandOption:!0,describe:"Tag ID to remove"}),handler:async e=>{try{await x(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},yc={command:"tags",describe:"Desk tag operations",builder:e=>e.command(sh).command(ch).command(uh).command(ph).command(dh).demandCommand(1),handler:Z};var lh={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await I({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},hh={command:"get <ticketId> <commentId>",describe:"Get a comment by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{let o=await x(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});l(o)}catch(t){h(t),process.exit(1)}}},mh={command:"create <ticketId>",describe:"Create a comment on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("content",{type:"string",demandOption:!0,describe:"Comment content"}).option("public",{type:"boolean",default:!1,describe:"Make comment public"}).option("content-type",{type:"string",default:"plainText",choices:["plainText","html"],describe:"Content type"}),handler:async e=>{try{let o=await x(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});l(o)}catch(t){h(t),process.exit(1)}}},yh={command:"delete <ticketId> <commentId>",describe:"Delete a comment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{await x(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},gc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(lh).command(hh).command(mh).command(yh).demandCommand(1),handler:Z};var gh={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},fh={command:"delete <ticketId> <attachmentId>",describe:"Delete an attachment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("attachmentId",{type:"string",demandOption:!0,describe:"Attachment ID"}),handler:async e=>{try{await x(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},fc={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(gh).command(fh).demandCommand(1),handler:Z};var Rh={command:"list <ticketId>",describe:"List followers of a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketFollowers({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},Th={command:"add <ticketId>",describe:"Add followers to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({added:!0})}catch(t){h(t),process.exit(1)}}},Ch={command:"remove <ticketId>",describe:"Remove followers from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},Rc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Rh).command(Th).command(Ch).demandCommand(1),handler:Z};var xh={command:"timer <ticketId>",describe:"Get current timer state for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimer({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},Zh={command:"timer-action <ticketId>",describe:"Start, pause, resume, or stop a timer",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("action",{type:"string",demandOption:!0,choices:["start","pause","resume","stop"],describe:"Timer action"}),handler:async e=>{try{let o=await x(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});l(o)}catch(t){h(t),process.exit(1)}}},Fh={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Sh={command:"summation <ticketId>",describe:"Get time entry summation for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimeEntrySummation({ticketId:e.ticketId});l(o)}catch(t){h(t),process.exit(1)}}},Tc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(xh).command(Zh).command(Fh).command(Sh).demandCommand(1),handler:Z};var Ah={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await I({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},bh={command:"get <ticketId> <threadId>",describe:"Get a thread by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("threadId",{type:"string",demandOption:!0,describe:"Thread ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});l(o)}catch(t){h(t),process.exit(1)}}},Cc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Ah).command(bh).demandCommand(1),handler:Z};var Ih={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await I({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},xc={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Ih).demandCommand(1),handler:Z};var Zc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(dc).command(lc).command(hc).command(mc).command(yc).command(gc).command(fc).command(Rc).command(Tc).command(Cc).command(xc).demandCommand(1,"Please specify a desk subcommand.").example([["$0 desk tickets list --limit 10","List first 10 tickets"],["$0 desk tickets get 12345","Get a ticket by ID"],["$0 desk agents my-info","Get current agent info"],['$0 desk comments create 12345 --content "Looking into this"',"Add a comment"]]),handler:Z};import{readFile as kh,writeFile as Fc}from"node:fs/promises";import{basename as Ph}from"node:path";function Eh(e){let t={};return e.requestName&&(t.request_name=e.requestName),e.folderName&&(t.folder_name=e.folderName),e.ownerFullName&&(t.owner_full_name=e.ownerFullName),e.recipientEmail&&(t.recipient_email=e.recipientEmail),e.recipientName&&(t.recipient_name=e.recipientName),e.formName&&(t.form_name=e.formName),Object.keys(t).length>0?t:void 0}var Oh={command:"list",describe:"List sign requests (documents)",builder:e=>oo(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. request_name, created_time, recipient_email)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("request-name",{type:"string",describe:"Filter by request name"}).option("folder-name",{type:"string",describe:"Filter by folder name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}).option("recipient-email",{type:"string",describe:"Filter by recipient email"}).option("recipient-name",{type:"string",describe:"Filter by recipient name"}).option("form-name",{type:"string",describe:"Filter by form name"}),handler:async e=>{try{let t=D(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:Eh(e)};await no({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){h(t),process.exit(1)}}},Dh={command:"get <requestId>",describe:"Get a sign request by ID",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}),handler:async e=>{try{let o=await D(e).getDocument({requestId:e.requestId});l(o)}catch(t){h(t),process.exit(1)}}},Mh={command:"form-data <requestId>",describe:"Get filled form-field values for a completed request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}),handler:async e=>{try{let o=await D(e).getDocumentFormData({requestId:e.requestId});l(o)}catch(t){h(t),process.exit(1)}}},_h={command:"create",describe:"Create a draft sign request from a local file",builder:e=>e.option("file",{type:"string",demandOption:!0,describe:"Path to the local document to upload"}).option("data",{type:"string",demandOption:!0,describe:"JSON request data (ZohoSignRequestData: request_name, is_sequential, actions, ...)"}).option("content-type",{type:"string",default:"application/pdf",describe:"MIME type of the uploaded file"}),handler:async e=>{try{let t=D(e),o=JSON.parse(e.data),r=await kh(e.file),n=new File([r],Ph(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});l(i)}catch(t){h(t),process.exit(1)}}},vh={command:"create-from-template",describe:"Create a sign request from a template",builder:e=>e.option("template-id",{type:"string",demandOption:!0,describe:"Template ID"}).option("data",{type:"string",demandOption:!0,describe:"JSON template data (ZohoSignCreateDocumentFromTemplateData: request_name, actions, field_data, ...)"}).option("quick-send",{type:"boolean",default:!0,describe:"Send immediately (true) or leave as a draft (false)"}),handler:async e=>{try{let t=D(e),o=JSON.parse(e.data),r=await t.createDocumentFromTemplate({templateId:e.templateId,data:o,isQuickSend:e.quickSend});l(r)}catch(t){h(t),process.exit(1)}}},wh={command:"update <requestId>",describe:"Update a draft sign request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("data",{type:"string",demandOption:!0,describe:"JSON partial request data to apply"}),handler:async e=>{try{let t=D(e),o=JSON.parse(e.data),r=await t.updateDocument({requestId:e.requestId,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Nh={command:"send <requestId>",describe:"Submit a draft request to its recipients for signing",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("data",{type:"string",describe:"Optional JSON partial request data to apply before sending"}),handler:async e=>{try{let t=D(e),o=e.data?JSON.parse(e.data):void 0,r=await t.sendDocumentForSignature({requestId:e.requestId,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Uh={command:"extend <requestId>",describe:"Extend the expiration date of an in-progress request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("expire-by",{type:"string",demandOption:!0,describe:'New expiration date string (e.g. "30 November 2024")'}),handler:async e=>{try{let o=await D(e).extendDocument({requestId:e.requestId,expire_by:e.expireBy});l(o)}catch(t){h(t),process.exit(1)}}},Lh={command:"delete <requestId>",describe:"Delete a request (optionally recalling an in-progress one)",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("recall-inprogress",{type:"boolean",describe:"Recall an in-progress request before deleting"}).option("reason",{type:"string",describe:"Reason for recalling/deleting"}),handler:async e=>{try{let o=await D(e).deleteDocument({requestId:e.requestId,recall_inprogress:e.recallInprogress,reason:e.reason});l(o)}catch(t){h(t),process.exit(1)}}},Gh={command:"download <requestId>",describe:"Download the signed PDF (or ZIP) for a request to a local file",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("output",{type:"string",demandOption:!0,describe:"Path to write the downloaded file to"}).option("with-coc",{type:"boolean",describe:"Include the completion certificate"}).option("merge",{type:"boolean",describe:"Merge all signed documents into one file"}).option("password",{type:"string",describe:"Password for protected documents"}),handler:async e=>{try{let o=await D(e).downloadPdf({requestId:e.requestId,with_coc:e.withCoc,merge:e.merge,password:e.password});if(!o.ok)throw new Error(`Download failed with status ${o.status}`);let r=Buffer.from(await o.arrayBuffer());await Fc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},Kh={command:"certificate <requestId>",describe:"Download the completion certificate PDF for a request to a local file",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("output",{type:"string",demandOption:!0,describe:"Path to write the certificate to"}),handler:async e=>{try{let o=await D(e).downloadCompletionCertificate({requestId:e.requestId});if(!o.ok)throw new Error(`Certificate download failed with status ${o.status}`);let r=Buffer.from(await o.arrayBuffer());await Fc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},Vh={command:"embed-url <requestId> <actionId>",describe:"Generate an embedded signing URL for a recipient action",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).positional("actionId",{type:"string",demandOption:!0,describe:"Recipient action ID"}).option("host",{type:"string",demandOption:!0,describe:"Hosting origin embedded in the token (https required in production)"}),handler:async e=>{try{let o=await D(e).getEmbeddedSigningUrl({requestId:e.requestId,actionId:e.actionId,host:e.host});l(o)}catch(t){h(t),process.exit(1)}}},Sc={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Oh).command(Dh).command(Mh).command(_h).command(vh).command(wh).command(Nh).command(Uh).command(Lh).command(Gh).command(Kh).command(Vh).demandCommand(1,"Please specify a documents subcommand.").example([["$0 sign documents list --row-count 10","List first 10 sign requests"],["$0 sign documents get 12345","Get a request by ID"],[`$0 sign documents create --file ./nda.pdf --data '{"request_name":"NDA","is_sequential":true,"actions":[{"action_type":"SIGN","recipient_name":"Jane","recipient_email":"jane@example.com"}]}'`,"Create a draft from a file"],["$0 sign documents download 12345 --output ./signed.pdf --with-coc --merge","Download the signed PDF"]]),handler:Z};function Hh(e){let t={};return e.templateName&&(t.template_name=e.templateName),e.ownerFullName&&(t.owner_full_name=e.ownerFullName),Object.keys(t).length>0?t:void 0}var qh={command:"list",describe:"List templates",builder:e=>oo(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. template_name, created_time)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("template-name",{type:"string",describe:"Filter by template name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}),handler:async e=>{try{let t=D(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:Hh(e)};await no({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){h(t),process.exit(1)}}},zh={command:"get <templateId>",describe:"Get a template by ID",builder:e=>e.positional("templateId",{type:"string",demandOption:!0,describe:"Template ID"}),handler:async e=>{try{let o=await D(e).getTemplate({templateId:e.templateId});l(o)}catch(t){h(t),process.exit(1)}}},Ac={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(qh).command(zh).demandCommand(1,"Please specify a templates subcommand.").example([["$0 sign templates list --row-count 10","List first 10 templates"],["$0 sign templates get 286906000001616000","Get a template by ID"]]),handler:Z};var jh={command:"field-types",describe:"List available document field types",builder:e=>e,handler:async e=>{try{let o=await D(e).retrieveFieldTypes();l(o)}catch(t){h(t),process.exit(1)}}},bc={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command(Sc).command(Ac).command(jh).demandCommand(1,"Please specify a sign subcommand.").example([["$0 sign documents list --row-count 10","List first 10 sign requests"],["$0 sign templates list","List templates"],["$0 sign documents get 12345","Get a request by ID"],["$0 sign field-types","List available field types"]]),handler:Z};var Ic={command:"request <product> <method> <path>",describe:"Make a raw API request through the authenticated context",builder:e=>e.positional("product",{type:"string",demandOption:!0,choices:["recruit","crm","desk","sign"],describe:"Zoho product"}).positional("method",{type:"string",demandOption:!0,choices:["GET","POST","PUT","PATCH","DELETE"],describe:"HTTP method"}).positional("path",{type:"string",demandOption:!0,describe:"API path (relative to product base URL)"}).option("body",{type:"string",describe:"JSON request body"}).option("query",{type:"string",describe:"JSON query parameters"}).example([["$0 request recruit GET /v2/Candidates","List candidates via raw API"],[`$0 request desk GET /tickets --query '{"limit":5}'`,"List 5 desk tickets via raw API"],[`$0 request crm POST /v8/Contacts --body '{"data":[{"Last_Name":"Test"}]}'`,"Create a CRM contact via raw API"],["$0 request sign GET /templates","List sign templates via raw API"]]),handler:async e=>{try{let t=e.product,o=e.method,r=e.path,n;switch(t){case"recruit":n=B(e).recruitContext;break;case"crm":n=W(e).crmContext;break;case"desk":n=x(e).deskContext;break;case"sign":n=D(e).signContext;break;default:throw new Error(`Unknown product: ${t}`)}let i=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=i.includes("?")?"&":"?";i=`${i}${p}${u.toString()}`}let a={method:o};e.body&&(a.body=e.body,a.headers={"Content-Type":"application/json"});let s=await n.fetchJson(i,a);l(s)}catch(t){h(t),process.exit(1)}}};var Jh=jn({cliName:"zoho-cli",loadOutputConfig:async()=>(await q())?.output,mergeOutputConfig:e=>X({output:e}),clearOutputConfig:Wn}),$h=[uc,pc,Zc,bc,Ic],kc=[ic,Jh,ac];function Xh(e){return e.command.split(" ")[0]}var Pc=new Set(kc.map(Xh)),Yh=zn({cliName:"zoho-cli",skipCommands:Pc,loadOutputConfig:async()=>(await q())?.output,saveCommandOutputConfig:async(e,t)=>{await X({output:{commands:{[e]:t}}})}});async function Qh(){try{await Bh(Wh(process.argv)).scriptName("zoho-cli").usage("$0 <command> [options]").option("verbose",{alias:"v",type:"boolean",default:!1,global:!0,describe:"Verbose output"}).option("dump-dir",{type:"string",global:!0,describe:"Directory to save full API responses as JSON files (overrides config)"}).option("pick",{type:"string",global:!0,describe:"Comma-separated top-level fields to include in output (overrides config)"}).option("set-dump-dir",{type:"string",global:!0,describe:"Save dump directory to config for this command and apply now"}).option("set-pick",{type:"string",global:!0,describe:"Save pick fields to config for this command and apply now"}).option("pick-all",{type:"boolean",global:!0,describe:"Ignore any configured pick filters and return full response data"}).middleware([cc(Pc),Yh],!0).command(kc).command($h).demandCommand(1,"Please specify a command. Use --help for available commands.").strict().fail(!1).help().alias("help","h").version(!1).wrap(Math.min(120,process.stdout.columns||80)).parse()}catch(e){h(e),process.exit(1)}}await Qh();
|
package/cli/package.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/cli",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.29.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"zoho-cli": "index.js"
|
|
7
7
|
},
|
|
8
8
|
"peerDependencies": {
|
|
9
|
-
"@dereekb/dbx-cli": "13.
|
|
10
|
-
"@dereekb/nestjs": "13.
|
|
11
|
-
"@dereekb/rxjs": "13.
|
|
12
|
-
"@dereekb/util": "13.
|
|
13
|
-
"@dereekb/zoho": "13.
|
|
14
|
-
"@dereekb/zoho/nestjs": "13.
|
|
9
|
+
"@dereekb/dbx-cli": "13.29.0",
|
|
10
|
+
"@dereekb/nestjs": "13.29.0",
|
|
11
|
+
"@dereekb/rxjs": "13.29.0",
|
|
12
|
+
"@dereekb/util": "13.29.0",
|
|
13
|
+
"@dereekb/zoho": "13.29.0",
|
|
14
|
+
"@dereekb/zoho/nestjs": "13.29.0",
|
|
15
15
|
"yargs": "^18.0.0"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
package/nestjs/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/nestjs",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.29.0",
|
|
4
4
|
"peerDependencies": {
|
|
5
|
-
"@dereekb/nestjs": "13.
|
|
6
|
-
"@dereekb/rxjs": "13.
|
|
7
|
-
"@dereekb/util": "13.
|
|
8
|
-
"@dereekb/zoho": "13.
|
|
5
|
+
"@dereekb/nestjs": "13.29.0",
|
|
6
|
+
"@dereekb/rxjs": "13.29.0",
|
|
7
|
+
"@dereekb/util": "13.29.0",
|
|
8
|
+
"@dereekb/zoho": "13.29.0",
|
|
9
9
|
"@nestjs/common": "^11.1.19",
|
|
10
10
|
"@nestjs/config": "^4.0.4",
|
|
11
11
|
"express": "^5.2.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.29.0",
|
|
4
4
|
"bin": {
|
|
5
5
|
"zoho-cli": "cli/index.js"
|
|
6
6
|
},
|
|
@@ -23,13 +23,13 @@
|
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"@dereekb/date": "13.
|
|
27
|
-
"@dereekb/dbx-cli": "13.
|
|
28
|
-
"@dereekb/firebase": "13.
|
|
29
|
-
"@dereekb/model": "13.
|
|
30
|
-
"@dereekb/nestjs": "13.
|
|
31
|
-
"@dereekb/rxjs": "13.
|
|
32
|
-
"@dereekb/util": "13.
|
|
26
|
+
"@dereekb/date": "13.29.0",
|
|
27
|
+
"@dereekb/dbx-cli": "13.29.0",
|
|
28
|
+
"@dereekb/firebase": "13.29.0",
|
|
29
|
+
"@dereekb/model": "13.29.0",
|
|
30
|
+
"@dereekb/nestjs": "13.29.0",
|
|
31
|
+
"@dereekb/rxjs": "13.29.0",
|
|
32
|
+
"@dereekb/util": "13.29.0",
|
|
33
33
|
"@nestjs/common": "^11.1.19",
|
|
34
34
|
"@nestjs/config": "^4.0.4",
|
|
35
35
|
"express": "^5.2.1",
|