@dereekb/zoho 13.35.0 → 13.37.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 +2 -2
- 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 Gc=Object.defineProperty;var Kc=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?Kc(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&&Gc(t,o,n),n},I=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Vc,mkdirSync as Hc,writeFileSync as zc}from"node:fs";import{join as qc}from"node:path";var Or=1;var po=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],Er=6e4,Le={},Dr=[...po],uo,jc=!1,Wc=Er;function lo(e){Le=e}function kt(){return Le}function Mr(e){jc=e}function _r(e){Wc=e===void 0?Er:e}function ho(e){Dr=e}function vr(e){uo=e}function le(e){let t=e;for(let o of Dr)t=t.replace(o,"[REDACTED]");return t}function Nr(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function dt(e,t){let{dumpDir:o,commandPath:r}=Le,n;if(o){Vc(o)||Hc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Nr(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=qc(o,`${s}.${e}`)}else n=void 0;return n}function Bc(e,t){let o=dt("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};zc(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=>kr(n,o)):e!=null&&typeof e=="object"?r=kr(e,o):r=e,r}function kr(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 wr(e){return Le.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function l(e,t){Bc(e,t);let r={ok:!0,data:Le.pick?be(e,Le.pick):e,...t?{meta:t}:{}};console.log(wr(r))}function Ur(e){console.log(wr(mo(e)))}var pt=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function mo(e){let t=uo?uo(e):void 0,o;return t?o=t:e instanceof pt?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 Ge(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 lt(e){let t=!0;for(let o of e){t=!1;break}return t}function yo(e,t){for(let o of e)t(o)}function J(e,t,o=!1){e!=null&&(Ge(e,o)?yo(e,t):t(e))}function Lr(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 Jc(e){return e==null?[]:$c(e)}var T=Jc;function $c(e){return Array.isArray(e)?e:[e]}function Gr(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function go(e){return Object.keys(e).length===0}function Kr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Vr(e){return{...e}}function Hr(e){return e!=null}function Ot(e){return Ge(e,!1)?!lt(e):zr(e)}function fo(e){let t;return Ge(e,!0)?t=!lt(e):zr(e)?t=typeof e=="object"?!go(e):!0:t=!1,t}function zr(e){return e!=null&&e!==""}function Xc(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ge=Xc(Hr);function qr({base:e,build:t}){let o=e??{};return t(o),o}var Yc=(e=>e);function jr(){return Yc}function Ke(e,t){let o=Qc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Qc(e,t){return Kr(eu(e,t))}function eu(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 Wr(e,t,o){return T(t).forEach(r=>e.set(r,o)),e}function Ro(e){return Array.from(e.entries())}function Br(e){return tu(Ro(e))}function tu(e){let t=[];return e.forEach(([o,r])=>{J(r,n=>{t.push([o,n])})}),t}function Jr(){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,Lr(i));return{map:()=>e,entries:()=>Ro(e),tuples:()=>Br(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 ou(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function $r(e){let t=ou(e);return t!=null&&t!=="class"}function Xr(e){return $r(e)?e:()=>e}function Yr(e,t){return Math.log(t)/Math.log(e)}var Qr=",",ru=" ";function nu(e,t=Qr,o=!1){if(e==null)return e;let r=T(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Co(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 iu(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return nu(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function en(e){let{joiner:t}=e,o=iu(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 Co(n,t,i)}}}var To=en({joiner:Qr}),au=en({joiner:ru,trimByDefault:!0});var k=To.joinStrings,$m=To.splitStrings,Xm=To.splitStringsToSet,Ym=au.joinStrings;var tn=Gr;function rn(e,{forEach:t,filter:o}){su(e,o).forEach((n,i)=>t(n,i))}function su(e,t){return xo(t)(e)}function xo(e){let t;if(e==null)t=on;else{let o=cu(e);t=r=>on(r).filter((n,i)=>o(n,i))}return t}function on(e){return Object.entries(e)}function Zo(e){return typeof e=="object"?e:{valueFilter:e}}function cu(e){let t=Zo(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])=>Ot(a);break;case 5:i=([,a])=>fo(a);break;case 6:i=([,a])=>!!a&&Ot(a);break;case 7:i=([,a])=>!!a&&fo(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 tn(i,r)}function ht(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 nn(e){let t;return e==null||yu(e)?t=e:t=uu(e),t}function uu(e){return e==null?e:new Date(e)}var an=24,pu=60;var du=60,lu=du*pu,G=1e3,Ie=G*60,So=Ie*60,hu=So*an,ay=lu*an,mu=7,sy=hu*mu;function yu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function sn(e){return e.getTime()<Date.now()}function cn(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function gu(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:nn(n);function c(y){return y??r??new Date}function u(y,m=!1){let C=c(y),g=d(C),f;return g==null?f=m:f=g<=C,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=cn(s??(i===!1?null:y),a)),m}return{input:e,hasExpired:u,getExpirationDate:p}}function un(e,t){let o=!0;return e!=null&&(o=gu(e).hasExpired(t,!0)),o}function fu({filter:e,copy:t,dynamic:o=!1}){let r=e==null?Cu:Ve({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:ht(i);return s=>{let c=a();return t&&(s=Vr(s)),Object.assign(s,c),s}}}function pn(e,t){return Ru(t)(e)}function Ru(e){let t=fu({filter:e,copy:!1,dynamic:!0});return o=>t(ge(o))({})}var gy=Ve({copy:!0,filter:{valueFilter:1}}),fy=Ve({copy:!0,filter:{valueFilter:2}}),dn=Ve({copy:!0,filter:{valueFilter:4}}),Ry=Ve({copy:!0,filter:{valueFilter:6}}),Cy=Fo({valueFilter:1}),Ty=Fo({valueFilter:6}),xy=Fo({valueFilter:2});function Fo(e){let t=ln({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ve({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Zo(t);o.invertFilter=!o.invertFilter;let r=ln({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var Cu=Ve({copy:!1});function ln({forEach:e,filter:t}){let o=xo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function hn(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 mn(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 yn(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 Et(e,t,o){let[r,n]=Ao(e,t,!1);return r+o+n}function Ao(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var Tu=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],Py=new Set(Tu);function gn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=Dt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=Et(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],C=n.substring(u,p)+o(y);s.push(C),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function xu(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 Dt(e,t,o){return xu(e)(t,o)}function Zu(e,t){return Dt(e,t,1)[0]}function Su(e){return t=>{let r=Zu(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=Ao(t,r,!1),n}}function fn(e,t){return Su(t)(e)}var He="/",Fu=".";function Au(e){let t=e.split(Fu,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===He?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Rn(e){return Au(e)!=="invalid"}var bu=/^\/+/,Iu=/\/+$/;var Pu=/\/{2,}/g;function Cn(e){return e.startsWith(He)?e.replace(bu,He):`${He}${e}`}function Tn(e){return e.replaceAll(Pu,He)}function xn(e){return e.replace(Iu,"")}function ku(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Zn=/:(\d+)/;function Ou(e){return Zn.test(e)}function Eu(e){let t=Zn.exec(e);return t?Number(t[1]):void 0}function Du(e){let t=bn(e),o=Mu(t),{domain:r,path:n}=o,i=ku(r),a=Ou(e),s=a?Eu(e)??void 0:void 0,[c,u]=fn(o.path,"?"),p=i&&(c===""||Rn(c+"/")),d=vu(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 Sn(e){let t=Du(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Fn(e,t=!1){let o=Dt(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=Et(n,i,"&")),n}function Mu(e){let t=bn(e);return _u(t)}function _u(e){let t=Co(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Cn(r??"/")}}var An=/^https:\/\/|http:\/\//;function bn(e){return e.replace(An,"")}function vu(e){return An.test(e)}function Z(){}function In(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function bo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Nu(e){let n=So,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(A){u=A}function m(A,L=!1){let q=Math.max(0,A.startLimitAt??1),b=A.cooldownRate??1,N=A.maxWaitTime??n,H=A.exponentRate??2;i={startLimitAt:q,cooldownRate:b,maxWaitTime:N,exponentRate:H},s=Yr(H,N/G+1),L&&C()}function C(){a=0,c=new Date}function g(A){let L;if(u){let{cooldownRate:q}=i,N=(Date.now()-c.getTime())*q/G,H=Math.max(a-N,0),j=Math.max(0,H-i.startLimitAt);A&&(a=H+A,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(A){return g(A??0)}function S(){let A=g(1);return bo(A)}return{waitForRateLimit:S,getNextWaitTime:f,getConfig:p,setConfig:m,getEnabled:d,setEnabled:y,reset:C}}function Pn(e){let o=Nu({exponentRate:1.5,maxWaitTime:G*8,...e}),r=Ie,n=new Date,i=0,a=0,s=!0;S(e,!0);function c(){sn(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 C(b){n=b}function g(){return c(),a}function f(b){a=b}function S(b,N=!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,N),N&&d(),n=b.resetAt??n}function A(b){let N=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var H=j;a>0?N=j():(c(),a>0?N=j():N=m())}return N}function L(b){return A(b??0)}function q(){let b=A(1);return bo(b)}return{getRemainingLimit:g,setRemainingLimit:f,getTimeUntilNextReset:m,getResetAt:y,setNextResetAt:C,setConfig:S,reset:d,getNextWaitTime:L,waitForRateLimit:q,getEnabled:u,setEnabled:p}}var wu="__CATCH_ALL_HANDLE_RESULT_KEY__";function kn(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===wu?a(p):Wr(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return qr({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 Uu(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Lu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Gu(e,t,o){let r=Lu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function On(e,t){return o=>Gu(e,o,t)}function En(e){return t=>(o,r)=>{let n=Uu(o,t),i=e.configurerForAccessor(n);r(i)}}var Ku=-1,Dn=0;function Vu(e){return e?.page??Ku}function Mn(e){return Vu(e)+1}import{BaseError as _n}from"make-error";var $=class extends _n{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function vn(e){return(t,o)=>Hu(e(t,o))}var ze=class extends _n{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Hu(e){return e.then(t=>{if(!t.ok)throw new ze(t);return t})}import{BaseError as tg}from"make-error";function Nn(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 Un(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Ln({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>qu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var zu=(e,t)=>t(e);function qu(e){let{makeFetch:t=fetch,fetchHandler:o=zu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=Nn(a)),n&&(a=vn(a));let s=Ln(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var ju=(e,t)=>new Request(e,t??void 0);function Ln(e){let{makeRequest:t=ju,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(xn(o)):void 0,u=c?m=>{let C,g=m.toString();if(!s&&Sn(g))C=new URL(g);else{let f=c.origin+Tn("/"+c.pathname+"/"+m);C=new URL(f,c)}return C}:void 0;async function p(m){let C=In(m)?await m:m;return wn(C)?C:t(C)}let d=u?async m=>{let C,g,f;if(typeof m=="string"?C=m:wn(m)?a?(C=m.url,g=m):f=m:f=await t(m),!f){let S=u(C);f=await t(S.href,g)}return f}:p,y;if(r!=null||n!=null){let m=Xr(r);async function C(){let f=await m();return n?{...f,timeout:n}:f}async function g(f,S){let A=await C(),L=Wu(A,await S),q=L.timeout===void 0?f.timeout:L.timeout;return{...L,timeout:q}}i?y=(f,S)=>i(f,g(f,S)):y=(f,S)=>g(f,S)}else i?y=i:y=(m,C)=>C;return async(m,C)=>{try{let g=await d(m);C=await y(g,C??void 0);let f=await t(g,C);return f.timeout=n,f}catch(g){throw g instanceof $?g:new $(g)}}}function Wu(e,t){let o;if(t){let r=Bu([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Bu(e){let t=Jr();return ge(e).forEach(o=>{let r=Ju(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 Ju(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 wn(e){return!!e.url}import{safeParse as $u}from"fast-content-type-parse";function Mt(e){let t=e.headers.get("content-type"),o=$u(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Gn(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 Io=class extends ${constructor(o){super("There was no next page for this.");this.page=o}},Po=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}},Xu=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??Xu;function y(C,g=void 0){return async()=>{let f=await t(C),{cursor:S,nextPageCursor:A,hasNext:L}=await o(f),q=S??g?.cursor,b=L!==!1,N=g?g.page+1:Dn,H=N>=d,j={input:C,result:f,page:N,previous:g,hasNext:b,isAtMaxPage:H,cursor:q,nextPageCursor:A,fetchNext:ht(async()=>{if(H)throw new Po(j,d);let Pr=b?await r(j,C,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Pr)throw new Io(j);return y({...C,...Pr},j)()})};return j}}return{input:a,fetchNext:ht(()=>y(a)())}}}function R(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?pn(e):e,i=r??!0?dn(n??{}):n,a=new URLSearchParams(i);return o!=null&&J(o,s=>a.delete(s),!1),a}function ko(e){let t;if(typeof e=="string")t=e;else if(Yu(e))t=e.href;else{let o=ko(e.url);if(e.queryParams){let r=tp(e.queryParams);lt(r)?t=o:t=Fn(o+`?${r.toString()}`)}else t=o}return t}function Yu(e){return typeof e=="object"&&e instanceof URL}function Qu(e){return typeof e=="object"&&e instanceof URLSearchParams}function ep(e){let t=[];return yo(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 tp(e){let t;return Qu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Ge(e)?t=new URLSearchParams(ep(e)):t=op(e),t}function op(e){let t=[];return rn(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&J(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var Oo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function rp(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var np=e=>{throw new Oo(e)},ee=e=>null;function te(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??np};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=Kn(o);return(a,s,c)=>{let u=ko(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(m=>{let C=m.json().catch(r),g=n?C.then(f=>n(f,m)):C;return d?g.then(f=>d(f,m)):g})}}function Kn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=jr()}=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:rp(i.body)}}}var Tg=Kn();var oe=Un({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function Vn(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 _t(e,t=Or){return async o=>{try{await e(o)}catch(r){Ur(r),process.exit(t)}}}var ip=["raw","page_by_line","data_by_line"],ap=["replace","concat"],sp=["meta","pages","merged_page"];function vt(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:sp,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:ip,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:ap,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as cp}from"@nestjs/common";var Xg=cp((e,t)=>up(t));function up(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Eo,BadRequestException as pp,InternalServerErrorException as dp,Logger as lp}from"@nestjs/common";import hp from"raw-body";import{parse as mp}from"node:querystring";var Hn=new lp("RawBody"),of=Eo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Hn.error("RawBody request was not readable. This is generally due to bad configuration."),new pp("Invalid body");return hp(o)}),zn=Eo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Hn.error("RawBody expected a buffer set to req.body."),new dp("failed parsing body");return r}),rf=Eo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=yp(o.body),o.body});function yp(e){let t=gp(e);return mp(t)}function gp(e){return e.toString("utf8").trim()}import{Injectable as fp}from"@nestjs/common";import Rp from"body-parser";var je=class{use(t,o,r){Rp.json()(t,o,r)}};je=F([fp()],je);import{Injectable as Cp}from"@nestjs/common";import Tp from"body-parser";var We=class{use(t,o,r){Tp.raw({type:"*/*"})(t,o,r)}};We=F([Cp()],We);import{Logger as xp,Module as Zp,RequestMethod as Sp}from"@nestjs/common";var Fp="/webhook",Ap={path:`${Fp}/{*path}`,method:Sp.POST},Do=class{configure(t){bp(t)}},Nt=class extends Do{logger=new xp("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Nt=F([Zp({})],Nt);function bp(e){e.apply(We).forRoutes(Ap).apply(je).forRoutes("{*path}")}var qn="CLIENT_WEB_APP_URL";var Pe=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as Ip,Injectable as Pp}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=F([Pp(),I(0,Ip(Pe))],ke);import{Module as kp}from"@nestjs/common";import{ConfigModule as Op,ConfigService as Ep}from"@nestjs/config";function Dp(e){let t={client:{clientWebAppUrl:e.get(qn)}};return Pe.assertValidConfig(t),t}var wt=class{};wt=F([kp({imports:[Op],providers:[{provide:Pe,inject:[Ep],useFactory:Dp},ke],exports:[ke]})],wt);var jn="SERVER_ENV_TOKEN";import{Inject as Mp,Injectable as _p}from"@nestjs/common";function Wn(){return process.env.NODE_ENV==="test"}var Ut=class{constructor(t){this.env=t}get isTestingEnv(){return Wn()}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}};Ut=F([_p(),I(0,Mp(jn))],Ut);import{dirname as Gp}from"node:path";import{chmod as vp,mkdirSync as Np,readFile as wp,writeFile as Up}from"node:fs";import{rm as Lp}from"node:fs/promises";function fe(e){return new Promise((t,o)=>{wp(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 Lt(e){return Np(e.dirPath,{recursive:!0}),new Promise((t,o)=>{Up(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():vp(e.filePath,e.mode,n=>{n?o(n):t()})})})}function mt(e){return Lp(e,{force:!0})}var Kp=384;function Bn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??Kp;async function a(){let p=await fe(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 Lt({filePath:t,dirPath:Gp(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 mt(t)})}}var xR=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 yt(e){return fe(e.configFilePath)}function Vp(e){return Lt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function gt(e){let t=await yt({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:Mo(t.output,e.updates.output)};return await Vp({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Mo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Hp(e?.commands,t)}}function Hp(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 Jn(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 Re(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as zp}from"node:os";import{join as _o}from"node:path";function Gt(e){let t=e.configDirOverride??_o(zp(),`.${e.cliName}`);return{configDir:t,configFilePath:_o(t,"config.json"),tokenCachePath:_o(t,".tokens.json")}}function $n(e){let t=Gt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await yt({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await gt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{Mr(!!n.verbose),_r(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("."),C={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,C)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?Jn({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};lo({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function qp(e){let t=Gt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await yt({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>gt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>gt({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 Xn(e){let t=qp(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:_t(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:_t(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:_t(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new pt({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 jp,appendFileSync as Wp}from"node:fs";function Yn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=kt(),n=t==="raw"?"json":"ndjson",i=dt(n),a=r?dt(n,"pick"):void 0,s;if(i){let c=0,u=g=>{let f;if(r){let S=be(g.data,r);f={...g,data:S}}else f=g;return f},p=g=>{let f=g.append?Wp:jp;f(i,g.mainContent),a&&g.pickContent!==void 0&&f(a,g.pickContent)},d=(g,f)=>{let S=JSON.stringify(g,null,2),A=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:S,pickContent:A,append:f})},y=(g,f)=>{let S=JSON.stringify(g)+`
|
|
4
|
+
var Gc=Object.defineProperty;var Kc=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?Kc(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&&Gc(t,o,n),n},I=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Vc,mkdirSync as Hc,writeFileSync as zc}from"node:fs";import{join as qc}from"node:path";var Or=1;var po=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],Er=6e4,Le={},Dr=[...po],uo,jc=!1,Bc=Er;function lo(e){Le=e}function kt(){return Le}function Mr(e){jc=e}function _r(e){Bc=e===void 0?Er:e}function ho(e){Dr=e}function vr(e){uo=e}function le(e){let t=e;for(let o of Dr)t=t.replace(o,"[REDACTED]");return t}function Nr(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function dt(e,t){let{dumpDir:o,commandPath:r}=Le,n;if(o){Vc(o)||Hc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Nr(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=qc(o,`${s}.${e}`)}else n=void 0;return n}function Wc(e,t){let o=dt("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};zc(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=>kr(n,o)):e!=null&&typeof e=="object"?r=kr(e,o):r=e,r}function kr(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 wr(e){return Le.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function l(e,t){Wc(e,t);let r={ok:!0,data:Le.pick?be(e,Le.pick):e,...t?{meta:t}:{}};console.log(wr(r))}function Ur(e){console.log(wr(mo(e)))}var pt=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function mo(e){let t=uo?uo(e):void 0,o;return t?o=t:e instanceof pt?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 Ge(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 lt(e){let t=!0;for(let o of e){t=!1;break}return t}function yo(e,t){for(let o of e)t(o)}function J(e,t,o=!1){e!=null&&(Ge(e,o)?yo(e,t):t(e))}function Lr(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 Jc(e){return e==null?[]:$c(e)}var T=Jc;function $c(e){return Array.isArray(e)?e:[e]}function Gr(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function go(e){return Object.keys(e).length===0}function Kr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Vr(e){return{...e}}function Hr(e){return e!=null}function Ot(e){return Ge(e,!1)?!lt(e):zr(e)}function fo(e){let t;return Ge(e,!0)?t=!lt(e):zr(e)?t=typeof e=="object"?!go(e):!0:t=!1,t}function zr(e){return e!=null&&e!==""}function Xc(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ge=Xc(Hr);function qr({base:e,build:t}){let o=e??{};return t(o),o}var Yc=(e=>e);function jr(){return Yc}function Ke(e,t){let o=Qc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Qc(e,t){return Kr(eu(e,t))}function eu(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 Br(e,t,o){return T(t).forEach(r=>e.set(r,o)),e}function Ro(e){return Array.from(e.entries())}function Wr(e){return tu(Ro(e))}function tu(e){let t=[];return e.forEach(([o,r])=>{J(r,n=>{t.push([o,n])})}),t}function Jr(){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,Lr(i));return{map:()=>e,entries:()=>Ro(e),tuples:()=>Wr(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 ou(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function $r(e){let t=ou(e);return t!=null&&t!=="class"}function Xr(e){return $r(e)?e:()=>e}function Yr(e,t){return Math.log(t)/Math.log(e)}var Qr=",",ru=" ";function nu(e,t=Qr,o=!1){if(e==null)return e;let r=T(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Co(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 iu(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return nu(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function en(e){let{joiner:t}=e,o=iu(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 Co(n,t,i)}}}var To=en({joiner:Qr}),au=en({joiner:ru,trimByDefault:!0});var k=To.joinStrings,Xm=To.splitStrings,Ym=To.splitStringsToSet,Qm=au.joinStrings;var tn=Gr;function rn(e,{forEach:t,filter:o}){su(e,o).forEach((n,i)=>t(n,i))}function su(e,t){return xo(t)(e)}function xo(e){let t;if(e==null)t=on;else{let o=cu(e);t=r=>on(r).filter((n,i)=>o(n,i))}return t}function on(e){return Object.entries(e)}function Zo(e){return typeof e=="object"?e:{valueFilter:e}}function cu(e){let t=Zo(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])=>Ot(a);break;case 5:i=([,a])=>fo(a);break;case 6:i=([,a])=>!!a&&Ot(a);break;case 7:i=([,a])=>!!a&&fo(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 tn(i,r)}function ht(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 nn(e){let t;return e==null||yu(e)?t=e:t=uu(e),t}function uu(e){return e==null?e:new Date(e)}var an=24,pu=60;var du=60,lu=du*pu,G=1e3,Ie=G*60,So=Ie*60,hu=So*an,sy=lu*an,mu=7,cy=hu*mu;function yu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function sn(e){return e.getTime()<Date.now()}function cn(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function gu(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:nn(n);function c(y){return y??r??new Date}function u(y,m=!1){let C=c(y),g=d(C),f;return g==null?f=m:f=g<=C,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=cn(s??(i===!1?null:y),a)),m}return{input:e,hasExpired:u,getExpirationDate:p}}function un(e,t){let o=!0;return e!=null&&(o=gu(e).hasExpired(t,!0)),o}function fu({filter:e,copy:t,dynamic:o=!1}){let r=e==null?Cu:Ve({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:ht(i);return s=>{let c=a();return t&&(s=Vr(s)),Object.assign(s,c),s}}}function pn(e,t){return Ru(t)(e)}function Ru(e){let t=fu({filter:e,copy:!1,dynamic:!0});return o=>t(ge(o))({})}var fy=Ve({copy:!0,filter:{valueFilter:1}}),Ry=Ve({copy:!0,filter:{valueFilter:2}}),dn=Ve({copy:!0,filter:{valueFilter:4}}),Cy=Ve({copy:!0,filter:{valueFilter:6}}),Ty=Fo({valueFilter:1}),xy=Fo({valueFilter:6}),Zy=Fo({valueFilter:2});function Fo(e){let t=ln({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ve({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Zo(t);o.invertFilter=!o.invertFilter;let r=ln({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var Cu=Ve({copy:!1});function ln({forEach:e,filter:t}){let o=xo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function hn(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 mn(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 yn(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 Et(e,t,o){let[r,n]=Ao(e,t,!1);return r+o+n}function Ao(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var Tu=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],ky=new Set(Tu);function gn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=Dt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=Et(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],C=n.substring(u,p)+o(y);s.push(C),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function xu(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 Dt(e,t,o){return xu(e)(t,o)}function Zu(e,t){return Dt(e,t,1)[0]}function Su(e){return t=>{let r=Zu(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=Ao(t,r,!1),n}}function fn(e,t){return Su(t)(e)}var He="/",Fu=".";function Au(e){let t=e.split(Fu,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===He?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Rn(e){return Au(e)!=="invalid"}var bu=/^\/+/,Iu=/\/+$/;var Pu=/\/{2,}/g;function Cn(e){return e.startsWith(He)?e.replace(bu,He):`${He}${e}`}function Tn(e){return e.replaceAll(Pu,He)}function xn(e){return e.replace(Iu,"")}function ku(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Zn=/:(\d+)/;function Ou(e){return Zn.test(e)}function Eu(e){let t=Zn.exec(e);return t?Number(t[1]):void 0}function Du(e){let t=bn(e),o=Mu(t),{domain:r,path:n}=o,i=ku(r),a=Ou(e),s=a?Eu(e)??void 0:void 0,[c,u]=fn(o.path,"?"),p=i&&(c===""||Rn(c+"/")),d=vu(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 Sn(e){let t=Du(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Fn(e,t=!1){let o=Dt(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=Et(n,i,"&")),n}function Mu(e){let t=bn(e);return _u(t)}function _u(e){let t=Co(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Cn(r??"/")}}var An=/^https:\/\/|http:\/\//;function bn(e){return e.replace(An,"")}function vu(e){return An.test(e)}function Z(){}function In(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function bo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Nu(e){let n=So,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(A){u=A}function m(A,L=!1){let q=Math.max(0,A.startLimitAt??1),b=A.cooldownRate??1,N=A.maxWaitTime??n,H=A.exponentRate??2;i={startLimitAt:q,cooldownRate:b,maxWaitTime:N,exponentRate:H},s=Yr(H,N/G+1),L&&C()}function C(){a=0,c=new Date}function g(A){let L;if(u){let{cooldownRate:q}=i,N=(Date.now()-c.getTime())*q/G,H=Math.max(a-N,0),j=Math.max(0,H-i.startLimitAt);A&&(a=H+A,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(A){return g(A??0)}function S(){let A=g(1);return bo(A)}return{waitForRateLimit:S,getNextWaitTime:f,getConfig:p,setConfig:m,getEnabled:d,setEnabled:y,reset:C}}function Pn(e){let o=Nu({exponentRate:1.5,maxWaitTime:G*8,...e}),r=Ie,n=new Date,i=0,a=0,s=!0;S(e,!0);function c(){sn(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 C(b){n=b}function g(){return c(),a}function f(b){a=b}function S(b,N=!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,N),N&&d(),n=b.resetAt??n}function A(b){let N=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var H=j;a>0?N=j():(c(),a>0?N=j():N=m())}return N}function L(b){return A(b??0)}function q(){let b=A(1);return bo(b)}return{getRemainingLimit:g,setRemainingLimit:f,getTimeUntilNextReset:m,getResetAt:y,setNextResetAt:C,setConfig:S,reset:d,getNextWaitTime:L,waitForRateLimit:q,getEnabled:u,setEnabled:p}}var wu="__CATCH_ALL_HANDLE_RESULT_KEY__";function kn(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===wu?a(p):Br(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return qr({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 Uu(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Lu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Gu(e,t,o){let r=Lu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function On(e,t){return o=>Gu(e,o,t)}function En(e){return t=>(o,r)=>{let n=Uu(o,t),i=e.configurerForAccessor(n);r(i)}}var Ku=-1,Dn=0;function Vu(e){return e?.page??Ku}function Mn(e){return Vu(e)+1}import{BaseError as _n}from"make-error";var $=class extends _n{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function vn(e){return(t,o)=>Hu(e(t,o))}var ze=class extends _n{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Hu(e){return e.then(t=>{if(!t.ok)throw new ze(t);return t})}import{BaseError as og}from"make-error";function Nn(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 Un(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Ln({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>qu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var zu=(e,t)=>t(e);function qu(e){let{makeFetch:t=fetch,fetchHandler:o=zu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=Nn(a)),n&&(a=vn(a));let s=Ln(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var ju=(e,t)=>new Request(e,t??void 0);function Ln(e){let{makeRequest:t=ju,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(xn(o)):void 0,u=c?m=>{let C,g=m.toString();if(!s&&Sn(g))C=new URL(g);else{let f=c.origin+Tn("/"+c.pathname+"/"+m);C=new URL(f,c)}return C}:void 0;async function p(m){let C=In(m)?await m:m;return wn(C)?C:t(C)}let d=u?async m=>{let C,g,f;if(typeof m=="string"?C=m:wn(m)?a?(C=m.url,g=m):f=m:f=await t(m),!f){let S=u(C);f=await t(S.href,g)}return f}:p,y;if(r!=null||n!=null){let m=Xr(r);async function C(){let f=await m();return n?{...f,timeout:n}:f}async function g(f,S){let A=await C(),L=Bu(A,await S),q=L.timeout===void 0?f.timeout:L.timeout;return{...L,timeout:q}}i?y=(f,S)=>i(f,g(f,S)):y=(f,S)=>g(f,S)}else i?y=i:y=(m,C)=>C;return async(m,C)=>{try{let g=await d(m);C=await y(g,C??void 0);let f=await t(g,C);return f.timeout=n,f}catch(g){throw g instanceof $?g:new $(g)}}}function Bu(e,t){let o;if(t){let r=Wu([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Wu(e){let t=Jr();return ge(e).forEach(o=>{let r=Ju(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 Ju(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 wn(e){return!!e.url}import{safeParse as $u}from"fast-content-type-parse";function Mt(e){let t=e.headers.get("content-type"),o=$u(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Gn(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 Io=class extends ${constructor(o){super("There was no next page for this.");this.page=o}},Po=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}},Xu=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??Xu;function y(C,g=void 0){return async()=>{let f=await t(C),{cursor:S,nextPageCursor:A,hasNext:L}=await o(f),q=S??g?.cursor,b=L!==!1,N=g?g.page+1:Dn,H=N>=d,j={input:C,result:f,page:N,previous:g,hasNext:b,isAtMaxPage:H,cursor:q,nextPageCursor:A,fetchNext:ht(async()=>{if(H)throw new Po(j,d);let Pr=b?await r(j,C,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Pr)throw new Io(j);return y({...C,...Pr},j)()})};return j}}return{input:a,fetchNext:ht(()=>y(a)())}}}function Yu(e){let t=[];function o(r,n){n!=null&&(Array.isArray(n)?n.forEach((i,a)=>o(`${r}[${a}]`,i)):typeof n=="object"?Object.entries(n).forEach(([i,a])=>o(`${r}[${i}]`,a)):t.push([r,String(n)]))}return Object.entries(e??{}).forEach(([r,n])=>o(r,n)),t}function R(e,t){let{omitKeys:o,filterEmptyValues:r,useBracketNotation:n}=t??{},i=Array.isArray(e)?pn(e):e,a=r??!0?dn(i??{}):i,s=n?Yu(a):a,c=new URLSearchParams(s);return o!=null&&J(o,u=>c.delete(u),!1),c}function ko(e){let t;if(typeof e=="string")t=e;else if(Qu(e))t=e.href;else{let o=ko(e.url);if(e.queryParams){let r=op(e.queryParams);lt(r)?t=o:t=Fn(o+`?${r.toString()}`)}else t=o}return t}function Qu(e){return typeof e=="object"&&e instanceof URL}function ep(e){return typeof e=="object"&&e instanceof URLSearchParams}function tp(e){let t=[];return yo(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 op(e){let t;return ep(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Ge(e)?t=new URLSearchParams(tp(e)):t=rp(e),t}function rp(e){let t=[];return rn(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&J(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var Oo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function np(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var ip=e=>{throw new Oo(e)},ee=e=>null;function te(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??ip};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=Kn(o);return(a,s,c)=>{let u=ko(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(m=>{let C=m.json().catch(r),g=n?C.then(f=>n(f,m)):C;return d?g.then(f=>d(f,m)):g})}}function Kn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=jr()}=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:np(i.body)}}}var xg=Kn();var oe=Un({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function Vn(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 _t(e,t=Or){return async o=>{try{await e(o)}catch(r){Ur(r),process.exit(t)}}}var ap=["raw","page_by_line","data_by_line"],sp=["replace","concat"],cp=["meta","pages","merged_page"];function vt(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:cp,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:ap,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:sp,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as up}from"@nestjs/common";var Yg=up((e,t)=>pp(t));function pp(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Eo,BadRequestException as dp,InternalServerErrorException as lp,Logger as hp}from"@nestjs/common";import mp from"raw-body";import{parse as yp}from"node:querystring";var Hn=new hp("RawBody"),rf=Eo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Hn.error("RawBody request was not readable. This is generally due to bad configuration."),new dp("Invalid body");return mp(o)}),zn=Eo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Hn.error("RawBody expected a buffer set to req.body."),new lp("failed parsing body");return r}),nf=Eo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=gp(o.body),o.body});function gp(e){let t=fp(e);return yp(t)}function fp(e){return e.toString("utf8").trim()}import{Injectable as Rp}from"@nestjs/common";import Cp from"body-parser";var je=class{use(t,o,r){Cp.json()(t,o,r)}};je=F([Rp()],je);import{Injectable as Tp}from"@nestjs/common";import xp from"body-parser";var Be=class{use(t,o,r){xp.raw({type:"*/*"})(t,o,r)}};Be=F([Tp()],Be);import{Logger as Zp,Module as Sp,RequestMethod as Fp}from"@nestjs/common";var Ap="/webhook",bp={path:`${Ap}/{*path}`,method:Fp.POST},Do=class{configure(t){Ip(t)}},Nt=class extends Do{logger=new Zp("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Nt=F([Sp({})],Nt);function Ip(e){e.apply(Be).forRoutes(bp).apply(je).forRoutes("{*path}")}var qn="CLIENT_WEB_APP_URL";var Pe=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as Pp,Injectable as kp}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=F([kp(),I(0,Pp(Pe))],ke);import{Module as Op}from"@nestjs/common";import{ConfigModule as Ep,ConfigService as Dp}from"@nestjs/config";function Mp(e){let t={client:{clientWebAppUrl:e.get(qn)}};return Pe.assertValidConfig(t),t}var wt=class{};wt=F([Op({imports:[Ep],providers:[{provide:Pe,inject:[Dp],useFactory:Mp},ke],exports:[ke]})],wt);var jn="SERVER_ENV_TOKEN";import{Inject as _p,Injectable as vp}from"@nestjs/common";function Bn(){return process.env.NODE_ENV==="test"}var Ut=class{constructor(t){this.env=t}get isTestingEnv(){return Bn()}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}};Ut=F([vp(),I(0,_p(jn))],Ut);import{dirname as Kp}from"node:path";import{chmod as Np,mkdirSync as wp,readFile as Up,writeFile as Lp}from"node:fs";import{rm as Gp}from"node:fs/promises";function fe(e){return new Promise((t,o)=>{Up(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 Lt(e){return wp(e.dirPath,{recursive:!0}),new Promise((t,o)=>{Lp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():Np(e.filePath,e.mode,n=>{n?o(n):t()})})})}function mt(e){return Gp(e,{force:!0})}var Vp=384;function Wn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??Vp;async function a(){let p=await fe(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 Lt({filePath:t,dirPath:Kp(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 mt(t)})}}var ZR=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 yt(e){return fe(e.configFilePath)}function Hp(e){return Lt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function gt(e){let t=await yt({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:Mo(t.output,e.updates.output)};return await Hp({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Mo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:zp(e?.commands,t)}}function zp(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 Jn(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 Re(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as qp}from"node:os";import{join as _o}from"node:path";function Gt(e){let t=e.configDirOverride??_o(qp(),`.${e.cliName}`);return{configDir:t,configFilePath:_o(t,"config.json"),tokenCachePath:_o(t,".tokens.json")}}function $n(e){let t=Gt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await yt({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await gt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{Mr(!!n.verbose),_r(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("."),C={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,C)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?Jn({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};lo({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function jp(e){let t=Gt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await yt({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>gt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>gt({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 Xn(e){let t=jp(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:_t(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:_t(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:_t(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new pt({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 Bp,appendFileSync as Wp}from"node:fs";function Yn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=kt(),n=t==="raw"?"json":"ndjson",i=dt(n),a=r?dt(n,"pick"):void 0,s;if(i){let c=0,u=g=>{let f;if(r){let S=be(g.data,r);f={...g,data:S}}else f=g;return f},p=g=>{let f=g.append?Wp:Bp;f(i,g.mainContent),a&&g.pickContent!==void 0&&f(a,g.pickContent)},d=(g,f)=>{let S=JSON.stringify(g,null,2),A=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:S,pickContent:A,append:f})},y=(g,f)=>{let S=JSON.stringify(g)+`
|
|
5
5
|
`,A=a?JSON.stringify(u(g))+`
|
|
6
6
|
`:void 0;p({mainContent:S,pickContent:A,append:f})},m=(g,f)=>{let S=g.data??[],A=a?be(S,r):void 0;S.length===0?f||p({mainContent:"",pickContent:a?"":void 0,append:!1}):S.forEach((L,q)=>{let b=f||q>0,N=JSON.stringify(L)+`
|
|
7
7
|
`,H=a&&A?JSON.stringify(A[q])+`
|
|
8
|
-
`:void 0;p({mainContent:N,pickContent:H,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let S=o==="concat"&&!(c===0);t==="raw"?d(g,S):t==="page_by_line"?y(g,S):m(g,S),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Bp(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 Jp(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 P(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=kt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Yn({dumpOutput:i,dumpMerge:a}),d;try{d=await Bp({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),Jp({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import ym from"yargs";import{hideBin as gm}from"yargs/helpers";import{writeFile as $p,mkdirSync as Xp}from"node:fs";import{join as vo}from"node:path";import{homedir as Yp}from"node:os";var Kt=["recruit","crm","desk","sign"],Qp=new Set(["sign"]);function No(){return vo(Yp(),".zoho-cli")}function ft(){return vo(No(),"config.json")}function Rt(){return vo(No(),".tokens.json")}function Oe(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function z(){let e=ft(),t=await fe(e),o=Oe("ACCOUNTS_CLIENT_ID"),r=Oe("ACCOUNTS_CLIENT_SECRET"),n=Oe("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:Oe("ACCOUNTS_URL")??t?.shared?.region,apiMode:Oe("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Oe("API_URL",p),y=u==="desk"?Oe("DESK_ORG_ID"):void 0,m=t?.[u],C=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],f=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],S=C||g||f,A;return!m&&!S&&!y?A=void 0:A={clientId:C??m?.clientId,clientSecret:g??m?.clientSecret,refreshToken:f??m?.refreshToken,apiUrl:d??m?.apiUrl,orgId:y??m?.orgId},A};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=!Qp.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 ed(e){let t=ft();return Xp(No(),{recursive:!0}),new Promise((o,r)=>{$p(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function X(e){let t=await z(),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:Mo(t?.output,e.output)};return await ed(o),o}async function Qn(){await X({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function ei(){let e=ft(),t=Rt();await mt(e),await mt(t)}function re(e){return Kt.filter(t=>{let o=Be(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as oc,Injectable as nl}from"@nestjs/common";function Je(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function w(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:Mn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function Vt(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 $e="Candidates",ti="Job_Openings",Ht="Notes",oi="Emails",Ct="Attachments";function zt(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=qt(o);break}default:break}return t}function qt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(wo):a&&(s=qt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=ge(a.map(t)).flatMap(T);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 ri=gn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function wo(e){let t=ri(e.value);return`(${e.field}:${e.filter}:${t})`}var ni=zt;import{BaseError as hd}from"make-error";import{BaseError as od}from"make-error";var rd="__internal_data_array_blank_error";function nd(e){return Array.isArray(e?.data)}var et="success";function Y(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var Ce=class extends od{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},K=class extends Ce{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Xe=class extends K{constructor(t,o){super({code:rd,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 Xe&&!o||(r instanceof K?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof Ce?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 ze){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 ze(o),i=e(t,n);if(i)throw i}return t}}var id="INTERNAL_ERROR",ad="INVALID_TOKEN",V=class extends K{},ii="FAILURE",Uo=class extends K{},sd="4834",Ye=class extends K{},cd="INVALID_QUERY",Lo=class extends K{get details(){return this.error.details}},jt="MANDATORY_NOT_FOUND",Te="DUPLICATE_DATA",Wt="INVALID_DATA",ud="TOO_MANY_REQUESTS",ai=429,pd="X-RATELIMIT-LIMIT",dd="X-RATELIMIT-REMAINING",ld="X-RATELIMIT-RESET",si=100,ci=Ie;function Go(e){let t=e.get(pd),o=e.get(dd),r=e.get(ld),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 Qe=class extends K{get headerDetails(){return Go(this.responseError.response.headers)}};function se(e,t){let o;if(nd(e))o=new Xe(e,t);else{let r=he(e,t);if(r){let n=Y(r);switch(n.code){case id:o=new Uo(n,e,t);break;case ad:o=new V(n,e,t);break;case sd:o=new Ye(n,e,t);break;case cd:o=new Lo(n,e,t);break;case ud:o=new Qe(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 ui="ALREADY_ASSOCIATED",Ko=class extends hd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},tt=class extends Ce{},Vo=class extends tt{},Ho=class extends tt{},Bt=class extends tt{get invalidFieldDetails(){return this.error.details}},zo=class extends Bt{};function pi(e){let t;switch(e.code){case Wt:{let o=new Bt(e);o.invalidFieldDetails.id?t=new zo(e):t=o;break}case jt:t=new Vo(e);break;case Te:t=new Ho(e);break;default:t=new tt(e);break}return t}function di(e,t){return o=>{if(!o?.data?.length)throw new Ko(e,t);return o}}var md=ne("ZohoRecruit");async function yd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=li(t,e)),o}function li(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var hi=ae(li),mi=ie(yd,md);import{BaseError as gd}from"make-error";function jo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,_(o,{data:T(r)})).then(i=>{let a=Array.isArray(r),s=ce(T(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw pi(p[0].result);c=u[0].result.details}return c}))}function yi(e){return jo(e,"","POST")}function gi(e){return jo(e,"/upsert","POST")}function fi(e){return jo(e,"","PUT")}function Ri(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${R({ids:t,wf_trigger:r})}`,_("DELETE")).then(fd)}function Ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,_("GET")).then(di(t.module)).then(o=>o.data[0])}function Ti(e){return(t=>e.fetchJson(`/v2/${t.module}?${Pi(t).toString()}`,_("GET")))}function Wo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=ni(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 Pi(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,_("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function xi(e){return w(Wo(e))}function ot(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${$o(n,n.filter).toString()}`,_("GET")).then(i=>i??(r===!1?i:Je()))}}function Bo(e){return ot(e)({targetModule:oi})}function Zi(e){return w(Bo(e))}function Jo(e){return ot(e)({targetModule:Ct})}function Si(e){return w(Jo(e))}var _C=20*1024*1024;function Fi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:k(o),attachments_category:k(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}/${Ct}?${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 Ai(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ct}/${t.attachment_id}`,{method:"GET"}).then(Mt)}function bi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ct}/${t.attachment_id}`,{method:"DELETE"})}var qo=class extends gd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Ii(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?Vt(t.apiUrl):""}${a}`;return e.fetchJson(c,_("POST")).then(u=>{if(u.code!=="success")throw new qo(u);return u.details})}}function Pi(...e){return R(e,{omitKeys:"module"})}function $o(...e){return R(e,{omitKeys:["id","module"]})}function _(e,t){return{method:e,body:t??void 0}}function fd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===et?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===et?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function ki(e){return t=>e.fetchJson(`/v2/${$e}/actions/associate`,_("PUT",{data:T(t)})).then(o=>{let r=o.data.map(()=>t),n=ce(r,o.data),{included:i,excluded:a}=Ke(n.errorItems,s=>s.result.code===ii&&s.result.details.error[0].code===ui);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function Oi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${$o(t).toString()}`,_("GET")).then(o=>o??Je())}function Xo(e){let t=Oi(e);return o=>t({...o,module:$e})}function Ei(e){return w(Xo(e))}function Yo(e,t=ti){let o=Oi(e);return r=>o({...r,module:t})}function Di(e){return w(Yo(e))}function Qo(e){return t=>e.fetchJson(`/v2/${Ht}`,_("POST",{data:t.data})).then(o=>ce(T(t.data),o.data))}function Mi(e){return t=>e.fetchJson(`/v2/${Ht}?${R({ids:t.ids})}`,_("DELETE")).then(o=>ce(T(t.ids),o.data))}function er(e){return ot(e)({targetModule:Ht})}function _i(e){return w(er(e))}function vi(e){let t=Qo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:T(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Ui(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module})}`,_("POST",{tags:T(t.tags)})).then(o=>{let r=ce(T(t.tags),o.tags),{included:n,excluded:i}=Ke(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Li(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 Ni=100;function Gi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Ni)throw new Error(`Cannot add tags to more than ${Ni} records at once.`);return e.fetchJson(`/v2/${$e}/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 wi=100;function Ki(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>wi)throw new Error(`Cannot remove tags from more than ${wi} records at once.`);return e.fetchJson(`/v2/${$e}/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 Rd="invalid_code",Cd="invalid_client",tr=class extends ${constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},rt=class extends ${constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},Td=ne("ZohoAccounts");async function xd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Vi(t,e)),o}function Vi(e,t){let o,r=e.error;if(r){let n=Y(r);switch(n.code){case Rd:case Cd:o=new tr(n.code);break;default:o=se(e,t);break}}return o}var Hi=ae(Vi),zi=ie(xd,Td);function xe(e){return async()=>{let t=await e();if(!t.accessToken)throw new rt;return t.accessToken}}var Zd=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 or(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??Zd,r=e.maxRateLimit??si,n=e.resetPeriod??ci;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=Pn(a);return Gn({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:m,limit:C,resetAt:g}=p;if(C!=null&&C!==r){let f=i(C,g??void 0);s.setConfig(f,!1)}if(s.setRemainingLimit(m),g&&s.setNextResetAt(g),y=!0,c.status===ai){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function me(e){return or({...e,readRateLimitDetails:Sd})}function Sd(e){let t=Go(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function qi(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=Vt(a.apiUrl),c=i({apiUrl:s}),u=mi(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:hi,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 $t="Notes",ji="Emails",Tt="Attachments";var Wi=zt;import{BaseError as Fd}from"make-error";var rr=class extends Fd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},nt=class extends Ce{},nr=class extends nt{},ir=class extends nt{},Xt=class extends nt{get invalidFieldDetails(){return this.error.details}},ar=class extends Xt{};function Bi(e){let t;switch(e.code){case Wt:{let o=new Xt(e);o.invalidFieldDetails.api_name==="id"?t=new ar(e):t=o;break}case jt:t=new nr(e);break;case Te:t=new ir(e);break;default:t=new nt(e);break}return t}function Ji(e,t){return o=>{if(!o?.data?.length)throw new rr(e,t);return o}}var Ad=ne("ZohoCrm",{logDataArrayErrors:!1});async function bd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=$i(t,e)),o}function $i(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var Xi=ae($i),Yi=ie(bd,Ad);import{BaseError as Id}from"make-error";function cr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,U(o,{data:T(r)})).catch(ha).then(i=>{let a=Array.isArray(r),s=Ze(T(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Bi(p[0].result);c=u[0].result.details}return c}))}function Qi(e){return cr(e,"","POST")}function ea(e){return cr(e,"/upsert","POST")}function ta(e){return cr(e,"","PUT")}function oa(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${R({ids:t,wf_trigger:r})}`,U("DELETE")).catch(ha).then(kd)}function ra(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,U("GET")).then(Ji(t.module)).then(o=>o.data[0])}function na(e){return(t=>e.fetchJson(`/v8/${t.module}?${la(t).toString()}`,U("GET")))}function ur(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Wi(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 la(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,U("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function ia(e){return w(ur(e))}function it(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()}`,U("GET")).then(i=>i??(r===!1?i:Je()))}}function pr(e){let t=it(e)({targetModule:ji});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function aa(e){return w(pr(e))}function dr(e){return it(e)({targetModule:Tt})}function sa(e){return w(dr(e))}var WT=20*1024*1024;function ca(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:k(o),attachments_category:k(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}/${Tt}?${R(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function ua(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Tt}/${t.attachment_id}`,{method:"GET"}).then(Mt)}function pa(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Tt}/${t.attachment_id}`,{method:"DELETE"})}var sr=class extends Id{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function da(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 sr(u);return u.details})}}function la(...e){return R(e,{omitKeys:"module"})}function Pd(...e){return R(e,{omitKeys:["id","module"]})}function U(e,t){return{method:e,body:t??void 0}}function ha(e){let t;if(e instanceof Xe)t={data:e.errorDataArray};else throw e;return t}function kd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===et?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===et?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function lr(e){return t=>e.fetchJson(`/v2/${$t}`,U("POST",{data:t.data})).then(o=>Ze(T(t.data),o.data))}function ma(e){return t=>e.fetchJson(`/v2/${$t}?${R({ids:t.ids})}`,U("DELETE")).then(o=>Ze(T(t.ids),o.data))}function hr(e){return it(e)({targetModule:$t})}function ya(e){return w(hr(e))}function ga(e){let t=lr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:T(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Ra(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module})}`,U("POST",{tags:T(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(T(t.tags),o.tags),{included:n,excluded:i}=Ke(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ca(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,U("DELETE")).then(o=>o.tags)}function Ta(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 fa=100;function xa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,U("POST",Za(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function Za(e){if(Array.isArray(e.ids)&&e.ids.length>fa)throw new Error(`Cannot add/remove tags from more than ${fa} records at once.`);let t=[...T(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&T(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:T(e.ids)}}function Sa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,U("POST",Za(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function Fa(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=Yi(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Xi,handleFetchJsonParseErrorFunction:ee});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Aa="https://signsandbox.zoho.com/api/v1",Od="https://sign.zoho.com/api/v1";function mr(e){let t;switch(e){case"sandbox":t=Aa;break;case"production":t=Od;break;default:t=e;break}return t}function ba(e){let t=mr(e),o;try{o=new URL(t).hostname!==new URL(Aa).hostname}catch{o=!0}return o}function Ia(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 Pa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ue("GET"))}function yr(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 ka(e){let t=yr(e);return Ia(t)}function Oa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ue("GET"))}function Ea(e){return()=>e.fetchJson("/fieldtypes",ue("GET"))}function Da(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 Ma(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function _a(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 va(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 Na(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,ue("GET"))}function wa(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 Ua(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ue("PUT",{requests:o}))}function La(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ue("POST",r))}}function Ga(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ue("PUT",{expire_by:o}))}function Ka(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 Va(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ba(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 Ed=ne("ZohoSign",{logDataArrayErrors:!1});async function Dd(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 za=ae(Ha),qa=ie(Dd,Ed);function ja(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=mr(a.apiUrl),c=i({apiUrl:s}),u=qa(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:za,handleFetchJsonParseErrorFunction:ee});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Wa(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var Md=ne("ZohoDesk",{logDataArrayErrors:!1});async function _d(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ba(t,e)),o}function Ba(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var Ja=ae(Ba),$a=ie(_d,Md);var vd="X-Rate-Limit-Remaining-v3",Nd="Retry-After",wd=200;function Ud(e){let t=e.get(vd),o;if(t!=null){let r=Number(t),n,i=e.get(Nd);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 Xa(e){return or({maxRateLimit:wd,...e,readRateLimitDetails:Ud})}function Ya(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=Xa(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=Wa(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=$a(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Ja,handleFetchJsonParseErrorFunction:ee});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Qa=25;function Q(e,t){return qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Qa}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Qa,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ee(e,t){return{method:e,body:t??void 0}}function at(e,t){return R(e,{omitKeys:t})}function Yt(e){let t;return e&&(t=k(T(e))),t}function gr(e){return t=>{let{include:o,...r}=t,n=at([{...r,include:Yt(o)}]);return e.fetchJson(`/tickets?${n}`,Ee("GET")).then(i=>i??{data:[]})}}function es(e){return t=>{let{ticketId:o,include:r}=t,i=at([{include:Yt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ee("GET"))}}function fr(e){return t=>{let o=at([t]);return e.fetchJson(`/tickets/search?${o}`,Ee("GET")).then(r=>r??{data:[]})}}function ts(e){return t=>{let{contactId:o,include:r,...n}=t,i=at([{...n,include:Yt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function os(e){return t=>{let{productId:o,include:r,...n}=t,i=at([{...n,include:Yt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ee("GET"))}function ns(e){return t=>{let o=at([{agentIds:k(T(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ee("GET"))}}function is(e){return Q(gr(e))}function as(e){return Q(fr(e))}function ss(e){return{method:e}}function cs(e){return t=>{let o=R([t]);return e.fetchJson(`/departments?${o}`,ss("GET")).then(r=>r??{data:[]})}}function us(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,ss("GET"))}function Rr(e){return{method:e}}function ps(e){let t;return e&&(t=k(T(e))),t}function Cr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:ps(o)}]);return e.fetchJson(`/contacts?${n}`,Rr("GET")).then(i=>i??{data:[]})}}function ds(e){return t=>{let{contactId:o,include:r}=t,i=R([{include:ps(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,Rr("GET"))}}function ls(e){return t=>{let o=R([{contactIds:k(T(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Rr("GET")).then(r=>r??[])}}function hs(e){return Q(Cr(e))}function xt(e,t){return{method:e,body:t??void 0}}function ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,xt("GET")).then(o=>o??[])}function ys(e){return t=>{let o={tags:T(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,xt("POST",o)).then(r=>r??[])}}function gs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,xt("DELETE"))}function fs(e){return t=>{let o=R([t]);return e.fetchJson(`/tags/search?${o}`,xt("GET")).then(r=>r??{data:[]})}}function Rs(e){return t=>{let o=R([t]);return e.fetchJson(`/ticketTags?${o}`,xt("GET")).then(r=>r??{data:[]})}}function Tr(e,t){return{method:e,body:t??void 0}}function Cs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("GET")).then(o=>o??[])}function Ts(e){return t=>{let o={ids:T(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("POST",o))}}function xs(e){return t=>{let o={ids:T(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("DELETE",o))}}function Zs(e,t){return{method:e,body:t??void 0}}function Ld(e){let t;return e&&(t=k(T(e))),t}function Ss(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Ld(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,Zs("GET")).then(a=>a??{data:[]})}}function Fs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,Zs("DELETE"))}function Qt(e,t){return{method:e,body:t??void 0}}function As(e){let t;return e&&(t=k(T(e))),t}function bs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:As(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,Qt("GET")).then(a=>a??{data:[]})}}function Is(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=R([{include:As(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,Qt("GET"))}}function Ps(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,Qt("POST",r))}}function ks(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,Qt("DELETE"))}function Zt(e,t){return{method:e,body:t??void 0}}function Os(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Zt("GET"))}function Es(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Zt("POST",r))}}function Ds(e){return t=>{let{ticketId:o,...r}=t,n=R([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Zt("GET")).then(i=>i??{data:[]})}}function Ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Zt("GET"))}function _s(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Zt("GET"))}function vs(e){return{method:e}}function Ns(e){let t;return e&&(t=k(T(e))),t}function xr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Ns(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,vs("GET")).then(a=>a??{data:[]})}}function ws(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=R([{include:Ns(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,vs("GET"))}}function Us(e){return Q(xr(e))}function Gd(e){return{method:e}}function Kd(e){let t;return e&&(t=k(T(e))),t}function Zr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Kd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,Gd("GET")).then(a=>a??{data:[]})}}function Ls(e){return Q(Zr(e))}function eo(e){return{method:e}}function Gs(e){let t;return e&&(t=k(T(e))),t}function Sr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:Gs(o)}]);return e.fetchJson(`/agents?${n}`,eo("GET")).then(i=>i??{data:[]})}}function Ks(e){return t=>{let{agentId:o,include:r}=t,i=R([{include:Gs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,eo("GET"))}}function Vs(e){return t=>{let o=R([{agentIds:k(T(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,eo("GET")).then(r=>r?.data??[])}}function Hs(e){return()=>e.fetchJson("/myinfo",eo("GET"))}function zs(e){return Q(Sr(e))}var Vd="https://accounts.zoho.com",Hd="https://accounts.zoho.eu",zd="https://accounts.zoho.in",qd="https://accounts.zoho.com.au",jd="https://accounts.zoho.jp",Wd="https://accounts.zoho.uk",Bd="https://accounts.zohocloud.ca",Jd="https://accounts.zoho.sa",$d={us:Vd,eu:Hd,in:zd,au:qd,jp:jd,uk:Wd,ca:Bd,sa:Jd};function De(e){return $d[e]??e}var to="/oauth/v2/token";function oo(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(`${to}?${p}`,Fr("POST"))}}function qs(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,refreshToken:i}=t,a=n?.clientId??o,s=n?.clientSecret??r,c=R({grant_type:"refresh_token",client_id:a,client_secret:s,refresh_token:i});return e.fetchJson(`${to}?${c}`,Fr("POST"))}}function js(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,code:i,redirectUri:a}=t,s=n?.clientId??o,c=n?.clientSecret??r,u=R({grant_type:"authorization_code",client_id:s,client_secret:c,code:i,redirect_uri:a});return e.fetchJson(`${to}?${u}`,Fr("POST"))}}var Xd="/oauth/user/info";function Ws(e){return t=>e.fetchJson(Xd,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Fr(e,t){return{method:e,body:t}}function Bs(e){return t=>oe.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function Js(e,t){let o=zi(e,t),r=te(o,{interceptJsonResponse:Hi,handleFetchJsonParseErrorFunction:ee});return{fetch:o,fetchJson:r}}function $s(e){let t=me(),{logZohoServerErrorFunction:o,fetchFactory:r=Bs(t)}=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=De(n.apiUrl??"us"),a=r({apiUrl:i}),{fetch:s,fetchJson:c}=Js(a,o),u=async()=>{let m=Date.now(),{access_token:C,api_domain:g,scope:f,expires_in:S}=await oo(d)();return{accessToken:C,apiDomain:g,expiresIn:S,expiresAt:new Date(m+S*G),scope:f}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=Yd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function Xs(e){let t=e.fetchHandler??me(),{logZohoServerErrorFunction:o,fetchFactory:r=Bs(t)}=e;return n=>{if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsOAuthClientConfig missing clientSecret.")}else throw new Error("ZohoAccountsOAuthClientConfig missing clientId.");let i=De(n.apiUrl??"us"),a=r({apiUrl:i}),{fetchJson:s}=Js(a,o),c={...n,apiUrl:i};return{oauthClientContext:{fetchJson:s,config:c}}}}function Yd(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 rt("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Se(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 Qd}from"@nestjs/common";var st=class{};st=F([Qd()],st);function el(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!un(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function tl(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function ol(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Qs(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:ol;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(el),c=yn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>tl(d,u)));if(r!=null){let d=ge(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function ec(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=hn(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 rl=".tmp/zoho-access-tokens.json";function Ys(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 tc(e=rl,t=!0){let o=Bn({filePath:e,reviver:Ys}),r=t?mn(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 fe(e),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Ys(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=$s(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return oo(this.accountsContext)}};v=F([nl(),I(0,oc(Fe)),I(1,oc(st))],v);import{Inject as sl,Injectable as cl}from"@nestjs/common";var il="ZOHO_ACCOUNTS_CLIENT_ID",al="ZOHO_ACCOUNTS_CLIENT_SECRET",ct=class{zohoAccountsOAuth;factoryConfig;static assertValidConfig(t){let{zohoAccountsOAuth:o}=t;if(!o)throw new Error("ZohoAccountsOAuthServiceConfig.zohoAccountsOAuth is required");if(!o.clientId)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientId (${il}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${al}).`)}};var St=class{constructor(t){this.config=t;ct.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=De(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Xs(t.factoryConfig??{})}_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=De(t),r=this._clients.get(o);return r==null&&(r=this._clientFactory({clientId:this.clientId,clientSecret:this._clientSecret,apiUrl:o}).oauthClientContext,this._clients.set(o,r)),r}exchangeAuthorizationCode(t){let{code:o,redirectUri:r,accountsApiUrl:n}=t,i=this.oauthClientContextForApiUrl(n??this.apiUrl);return js(i)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return qs(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Ws(n)({accessToken:o})}};St=F([cl(),I(0,sl(ct))],St);import{ConfigModule as yF,ConfigService as gF}from"@nestjs/config";import{Inject as rc,Injectable as ul}from"@nestjs/common";var Ft=class{zohoCrm;factoryConfig;static assertValidConfig(t){Se(t.zohoCrm)}};var Me=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=Fa({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Qi(this.crmContext)}get upsertRecord(){return ea(this.crmContext)}get updateRecord(){return ta(this.crmContext)}get deleteRecord(){return oa(this.crmContext)}get getRecordById(){return ra(this.crmContext)}get getRecords(){return na(this.crmContext)}get searchRecords(){return ur(this.crmContext)}get searchRecordsPageFactory(){return ia(this.crmContext)}get getRelatedRecordsFunctionFactory(){return it(this.crmContext)}get getEmailsForRecord(){return pr(this.crmContext)}get getEmailsForRecordPageFactory(){return aa(this.crmContext)}get getAttachmentsForRecord(){return dr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return sa(this.crmContext)}get uploadAttachmentForRecord(){return ca(this.crmContext)}get downloadAttachmentForRecord(){return ua(this.crmContext)}get deleteAttachmentFromRecord(){return pa(this.crmContext)}get createNotes(){return lr(this.crmContext)}get deleteNotes(){return ma(this.crmContext)}get createNotesForRecord(){return ga(this.crmContext)}get getNotesForRecord(){return hr(this.crmContext)}get getNotesForRecordPageFactory(){return ya(this.crmContext)}get executeRestApiFunction(){return da(this.crmContext)}get createTagsForModule(){return Ra(this.crmContext)}get deleteTag(){return Ca(this.crmContext)}get getTagsForModule(){return Ta(this.crmContext)}get addTagsToRecords(){return xa(this.crmContext)}get removeTagsFromRecords(){return Sa(this.crmContext)}};Me=F([ul(),I(0,rc(Ft)),I(1,rc(v))],Me);import{ConfigModule as wF,ConfigService as UF}from"@nestjs/config";import{Inject as nc,Injectable as pl}from"@nestjs/common";var At=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Se(t.zohoRecruit)}};var _e=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=qi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return yi(this.recruitContext)}get upsertRecord(){return gi(this.recruitContext)}get updateRecord(){return fi(this.recruitContext)}get deleteRecord(){return Ri(this.recruitContext)}get getRecordById(){return Ci(this.recruitContext)}get getRecords(){return Ti(this.recruitContext)}get searchRecords(){return Wo(this.recruitContext)}get searchRecordsPageFactory(){return xi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ot(this.recruitContext)}get getEmailsForRecord(){return Bo(this.recruitContext)}get getEmailsForRecordPageFactory(){return Zi(this.recruitContext)}get getAttachmentsForRecord(){return Jo(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Si(this.recruitContext)}get uploadAttachmentForRecord(){return Fi(this.recruitContext)}get downloadAttachmentForRecord(){return Ai(this.recruitContext)}get deleteAttachmentFromRecord(){return bi(this.recruitContext)}get createNotes(){return Qo(this.recruitContext)}get deleteNotes(){return Mi(this.recruitContext)}get createNotesForRecord(){return vi(this.recruitContext)}get getNotesForRecord(){return er(this.recruitContext)}get getNotesForRecordPageFactory(){return _i(this.recruitContext)}get executeRestApiFunction(){return Ii(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return ki(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Xo(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return Ei(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Yo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return Di(this.recruitContext)}get createTagsForModule(){return Ui(this.recruitContext)}get getTagsForModule(){return Li(this.recruitContext)}get addTagsToRecords(){return Gi(this.recruitContext)}get removeTagsFromRecords(){return Ki(this.recruitContext)}};_e=F([pl(),I(0,nc(At)),I(1,nc(v))],_e);import{ConfigModule as aA,ConfigService as sA}from"@nestjs/config";import{Inject as ic,Injectable as dl}from"@nestjs/common";var bt=class{zohoSign;factoryConfig;static assertValidConfig(t){Se(t.zohoSign)}};var ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ja({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Pa(this.signContext)}get getDocuments(){return yr(this.signContext)}get getDocumentsPageFactory(){return ka(this.signContext)}get getDocumentFormData(){return Oa(this.signContext)}get retrieveFieldTypes(){return Ea(this.signContext)}get downloadPdf(){return Da(this.signContext)}get downloadCompletionCertificate(){return Ma(this.signContext)}get createDocument(){return _a(this.signContext)}get createDocumentFromTemplate(){return va(this.signContext)}get getTemplate(){return Na(this.signContext)}get getTemplates(){return wa(this.signContext)}get updateDocument(){return Ua(this.signContext)}get sendDocumentForSignature(){return La(this.signContext)}get extendDocument(){return Ga(this.signContext)}get deleteDocument(){return Ka(this.signContext)}get getEmbeddedSigningUrl(){return Va(this.signContext)}};ve=F([dl(),I(0,ic(bt)),I(1,ic(v))],ve);import{ConfigModule as kA,ConfigService as OA}from"@nestjs/config";function ac(e){return{...e,operationType:e.notifications.operation_type}}var sc=kn(e=>e.operationType),cc=En({configurerForAccessor:e=>{let t=On(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 uc="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Ne=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as Rl,Inject as Cl,Post as Tl,Req as xl}from"@nestjs/common";import{Inject as yl,Injectable as gl,Logger as fl}from"@nestjs/common";import{createHmac as ll,timingSafeEqual as hl}from"node:crypto";var ml="x-zs-webhook-signature";function pc(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[ml],i={valid:!1};if(n){let a=r.toString("utf-8"),s=ll("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=hl(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=ac(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var ye=class{logger=new fl("ZohoSignWebhookService");_verifier;handler=sc();configure=cc(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=pc({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)}};ye=F([gl(),I(0,yl(Ne))],ye);var we=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([Tl(),I(0,xl()),I(1,zn())],we.prototype,"handleZohoSignWebhook",1),we=F([Rl("/webhook/zoho/sign"),I(0,Cl(ye))],we);import{Module as Zl}from"@nestjs/common";import{ConfigModule as Sl,ConfigService as Fl}from"@nestjs/config";function Al(e){let t={zohoSignWebhook:{webhookSecret:e.get(uc)}};return Ne.assertValidConfig(t),t}var no=class{};no=F([Zl({imports:[Sl],controllers:[we],providers:[{provide:Ne,inject:[Fl],useFactory:Al},ye],exports:[ye]})],no);import{Inject as dc,Injectable as bl}from"@nestjs/common";var It=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Se(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var Ue=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Ya({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return gr(this.deskContext)}get getTicketById(){return es(this.deskContext)}get searchTickets(){return fr(this.deskContext)}get getTicketsForContact(){return ts(this.deskContext)}get getTicketsForProduct(){return os(this.deskContext)}get getTicketMetrics(){return rs(this.deskContext)}get getAgentsTicketsCount(){return ns(this.deskContext)}get getTicketsPageFactory(){return is(this.deskContext)}get searchTicketsPageFactory(){return as(this.deskContext)}get getDepartments(){return cs(this.deskContext)}get getDepartmentById(){return us(this.deskContext)}get getContacts(){return Cr(this.deskContext)}get getContactById(){return ds(this.deskContext)}get getContactsByIds(){return ls(this.deskContext)}get getContactsPageFactory(){return hs(this.deskContext)}get getTicketTags(){return ms(this.deskContext)}get associateTicketTags(){return ys(this.deskContext)}get dissociateTicketTag(){return gs(this.deskContext)}get searchTags(){return fs(this.deskContext)}get getAllTags(){return Rs(this.deskContext)}get getTicketFollowers(){return Cs(this.deskContext)}get addTicketFollowers(){return Ts(this.deskContext)}get removeTicketFollowers(){return xs(this.deskContext)}get getTicketAttachments(){return Ss(this.deskContext)}get deleteTicketAttachment(){return Fs(this.deskContext)}get getTicketComments(){return bs(this.deskContext)}get getTicketCommentById(){return Is(this.deskContext)}get createTicketComment(){return Ps(this.deskContext)}get deleteTicketComment(){return ks(this.deskContext)}get getTicketTimer(){return Os(this.deskContext)}get performTicketTimerAction(){return Es(this.deskContext)}get getTicketTimeEntries(){return Ds(this.deskContext)}get getTicketTimeEntryById(){return Ms(this.deskContext)}get getTicketTimeEntrySummation(){return _s(this.deskContext)}get getTicketThreads(){return xr(this.deskContext)}get getTicketThreadById(){return ws(this.deskContext)}get getTicketThreadsPageFactory(){return Us(this.deskContext)}get getTicketActivities(){return Zr(this.deskContext)}get getTicketActivitiesPageFactory(){return Ls(this.deskContext)}get getAgents(){return Sr(this.deskContext)}get getAgentById(){return Ks(this.deskContext)}get getAgentsByIds(){return Vs(this.deskContext)}get getMyInfo(){return Hs(this.deskContext)}get getAgentsPageFactory(){return zs(this.deskContext)}};Ue=F([bl(),I(0,dc(It)),I(1,dc(v))],Ue);import{ConfigModule as Ob,ConfigService as Eb}from"@nestjs/config";function Il(e){return`${e.clientId}:${e.refreshToken}`}function ut(e){let t=Qs([ec(),tc(Rt())]),o=new Map;function r(y,m){let C=Il(y),g=o.get(C),f;if(g)f=g;else{let S={zohoAccounts:{serviceAccessTokenKey:m,refreshToken:y.refreshToken,clientId:y.clientId,clientSecret:y.clientSecret,apiUrl:y.region??"us"}};f=new v(S,t),o.set(C,f)}return f}let n,i=Be(e,"recruit");if(i){let y=r(i,"recruit"),m={zohoRecruit:{apiUrl:i.apiMode}};n=new _e(m,y)}let a,s=Be(e,"crm");if(s){let y=r(s,"crm"),m={zohoCrm:{apiUrl:s.apiMode}};a=new Me(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 Ue(m,y)}let p,d=Be(e,"sign");if(d){let y=r(d,"sign"),m={zohoSign:{apiUrl:d.apiMode}};p=new ve(m,y)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:p}}ho([...po,/1000\.\w{20,}/g]);function lc(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 Ye?t={ok:!1,error:le(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Qe?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=mo(e),t}vr(e=>e instanceof V||e instanceof Ye||e instanceof Qe||e instanceof K?lc(e):void 0);function h(e){console.log(JSON.stringify(lc(e)))}var hc={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"},Ir={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 Pl(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 kl={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:[...Kt],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 z(),o=Ol(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 El(o,t):o.code?await Dl(o,t):await Ml(o,t)}catch(t){h(t),process.exit(1)}}};function Ol(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:Pl(e.code),token:e.token,accountsUrl:hc[o]??hc.us,apiMode:e.apiMode,orgId:e.orgId}}async function mc(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 El(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await mc(e,o,t?.shared);l({success:!0,...e.product?{product:e.product}:{},refreshToken:Re(e.token),configSaved:!0,configuredProducts:re(r)})}async function Dl(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 mc(e,s,t?.shared);l({step:2,success:!0,product:e.product??"shared",refreshToken:Re(a),accessToken:i.access_token?Re(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:re(c)})}async function Ml(e,t){let o=e.product?Ir[e.product]??[]:e.scopes.flatMap(i=>Ir[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Ir).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 _l={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:[...Kt],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 z())?.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)}}},vl={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?Re(r.clientId):void 0,clientSecret:r.clientSecret?Re(r.clientSecret):void 0,refreshToken:r.refreshToken?Re(r.refreshToken):void 0}:void 0};var e=o;let t=await z();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)}}},Nl={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await z();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=ut(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)}}},wl={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await ei(),l({cleared:!0})}catch(e){h(e),process.exit(1)}}},yc={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(kl).command(_l).command(vl).command(Nl).command(wl).demandCommand(1,"Please specify an auth subcommand."),handler:Z};import{access as Ul,constants as Ll}from"node:fs";import{dirname as Gl}from"node:path";var gc={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await z(),t=[];t.push(Kl(e));let o=Vl(e);if(o&&t.push(o),t.push(await Hl()),e){let n=re(e);t.push(zl(n),...await ql(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 Kl(e){return e?{name:"config",status:"pass",message:`Config loaded from ${ft()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function Vl(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=Gl(Rt());return await Jl(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 ql(e,t){let o=ut(e),r=[];for(let n of t)r.push(await jl(o,n));return r}async function jl(e,t){let o=Wl(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 Wl(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 Jl(e){return new Promise(t=>{Ul(e,Ll.W_OK,o=>{t(!o)})})}var fc=Vn({notInitializedMessage:"CLI context not initialized. This is a bug."});function Rc(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await z();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)),fc.set(ut(r))}catch(r){h(r),process.exit(4)}}}function io(e){return fc.require()}function W(e){let{recruitApi:t}=io(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}=io(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}=io(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}=io(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 vt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function O(e){return vt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function ao(e){return vt(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 Pt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function so(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 $l={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},E={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}},Xl={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 P({initialInput:o,fetchPage:r,adapter:$l,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 co(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await P({initialInput:o,fetchPage:async i=>{let a=await r(i);return{data:a.requests??[],page_context:a.page_context}},adapter:Xl,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 Yl={command:"list",describe:"List records from a module",builder:e=>so(Pt(pe(M(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 de({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Ql={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)}}},eh={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)}}},th={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)}}},oh={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)}}},rh={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)}}},nh={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)}}},ih={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)}}},ah={command:"attachments",describe:"Get attachments 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.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Cc={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(Yl).command(Ql).command(eh).command(th).command(oh).command(rh).command(nh).command(ih).command(ah).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 sh={command:"list",describe:"List records from a module",builder:e=>so(Pt(pe(M(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 de({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},ch={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)}}},uh={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)}}},ph={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)}}},dh={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)}}},lh={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)}}},hh={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)}}},mh={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)}}},yh={command:"attachments",describe:"Get attachments for a record",builder:e=>Pt(pe(Ae(M(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 de({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Tc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(sh).command(ch).command(uh).command(ph).command(dh).command(lh).command(hh).command(mh).command(yh).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 gh={command:"list",describe:"List tickets",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:E,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>",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)}}},Rh={command:"search",describe:"Search tickets",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:E,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:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:E,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)}}},Th={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)}}},xh={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)}}},xc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(gh).command(fh).command(Rh).command(Ch).command(Th).command(xh).demandCommand(1),handler:Z};var Zh={command:"list",describe:"List departments",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:E,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)}}},Sh={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)}}},Zc={command:"departments",describe:"Desk department operations",builder:e=>e.command(Zh).command(Sh).demandCommand(1),handler:Z};var Fh={command:"list",describe:"List contacts",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:E,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)}}},Ah={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)}}},Sc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Fh).command(Ah).demandCommand(1),handler:Z};var bh={command:"list",describe:"List agents",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:E,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)}}},Ph={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)}}},Fc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(bh).command(Ih).command(Ph).demandCommand(1),handler:Z};var kh={command:"list",describe:"List all tags",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:E,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)}}},Oh={command:"search",describe:"Search tags",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:E,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)}}},Dh={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)}}},Mh={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)}}},Ac={command:"tags",describe:"Desk tag operations",builder:e=>e.command(kh).command(Oh).command(Eh).command(Dh).command(Mh).demandCommand(1),handler:Z};var _h={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:E,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)}}},vh={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)}}},Nh={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)}}},wh={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)}}},bc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(_h).command(vh).command(Nh).command(wh).demandCommand(1),handler:Z};var Uh={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:E,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)}}},Lh={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)}}},Ic={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(Uh).command(Lh).demandCommand(1),handler:Z};var Gh={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)}}},Kh={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)}}},Vh={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)}}},Pc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Gh).command(Kh).command(Vh).demandCommand(1),handler:Z};var Hh={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)}}},qh={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:E,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)}}},jh={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)}}},kc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Hh).command(zh).command(qh).command(jh).demandCommand(1),handler:Z};var Wh={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:E,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)}}},Oc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Wh).command(Bh).demandCommand(1),handler:Z};var Jh={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:E,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)}}},Ec={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Jh).demandCommand(1),handler:Z};var Dc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(xc).command(Zc).command(Sc).command(Fc).command(Ac).command(bc).command(Ic).command(Pc).command(kc).command(Oc).command(Ec).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 $h,writeFile as Mc}from"node:fs/promises";import{basename as Xh}from"node:path";function Yh(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 Qh={command:"list",describe:"List sign requests (documents)",builder:e=>ao(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:Yh(e)};await co({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){h(t),process.exit(1)}}},em={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)}}},tm={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)}}},om={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 $h(e.file),n=new File([r],Xh(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});l(i)}catch(t){h(t),process.exit(1)}}},rm={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)}}},nm={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)}}},im={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)}}},am={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)}}},sm={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)}}},cm={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 Mc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},um={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 Mc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},pm={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)}}},_c={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Qh).command(em).command(tm).command(om).command(rm).command(nm).command(im).command(am).command(sm).command(cm).command(um).command(pm).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 dm(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 lm={command:"list",describe:"List templates",builder:e=>ao(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:dm(e)};await co({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){h(t),process.exit(1)}}},hm={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)}}},vc={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(lm).command(hm).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 mm={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)}}},Nc={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command(_c).command(vc).command(mm).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 wc={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=W(e).recruitContext;break;case"crm":n=B(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 fm=Xn({cliName:"zoho-cli",loadOutputConfig:async()=>(await z())?.output,mergeOutputConfig:e=>X({output:e}),clearOutputConfig:Qn}),Rm=[Cc,Tc,Dc,Nc,wc],Uc=[yc,fm,gc];function Cm(e){return e.command.split(" ")[0]}var Lc=new Set(Uc.map(Cm)),Tm=$n({cliName:"zoho-cli",skipCommands:Lc,loadOutputConfig:async()=>(await z())?.output,saveCommandOutputConfig:async(e,t)=>{await X({output:{commands:{[e]:t}}})}});async function xm(){try{await ym(gm(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([Rc(Lc),Tm],!0).command(Uc).command(Rm).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 xm();
|
|
8
|
+
`:void 0;p({mainContent:N,pickContent:H,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let S=o==="concat"&&!(c===0);t==="raw"?d(g,S):t==="page_by_line"?y(g,S):m(g,S),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Jp(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 $p(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 P(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=kt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Yn({dumpOutput:i,dumpMerge:a}),d;try{d=await Jp({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),$p({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import gm from"yargs";import{hideBin as fm}from"yargs/helpers";import{writeFile as Xp,mkdirSync as Yp}from"node:fs";import{join as vo}from"node:path";import{homedir as Qp}from"node:os";var Kt=["recruit","crm","desk","sign"],ed=new Set(["sign"]);function No(){return vo(Qp(),".zoho-cli")}function ft(){return vo(No(),"config.json")}function Rt(){return vo(No(),".tokens.json")}function Oe(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function z(){let e=ft(),t=await fe(e),o=Oe("ACCOUNTS_CLIENT_ID"),r=Oe("ACCOUNTS_CLIENT_SECRET"),n=Oe("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:Oe("ACCOUNTS_URL")??t?.shared?.region,apiMode:Oe("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Oe("API_URL",p),y=u==="desk"?Oe("DESK_ORG_ID"):void 0,m=t?.[u],C=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],f=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],S=C||g||f,A;return!m&&!S&&!y?A=void 0:A={clientId:C??m?.clientId,clientSecret:g??m?.clientSecret,refreshToken:f??m?.refreshToken,apiUrl:d??m?.apiUrl,orgId:y??m?.orgId},A};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 We(e,t){let o=e[t],r=e.shared,n=!ed.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 td(e){let t=ft();return Yp(No(),{recursive:!0}),new Promise((o,r)=>{Xp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function X(e){let t=await z(),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:Mo(t?.output,e.output)};return await td(o),o}async function Qn(){await X({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function ei(){let e=ft(),t=Rt();await mt(e),await mt(t)}function re(e){return Kt.filter(t=>{let o=We(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as oc,Injectable as il}from"@nestjs/common";function Je(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function w(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:Mn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function Vt(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 $e="Candidates",ti="Job_Openings",Ht="Notes",oi="Emails",Ct="Attachments";function zt(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=qt(o);break}default:break}return t}function qt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(wo):a&&(s=qt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=ge(a.map(t)).flatMap(T);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 ri=gn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function wo(e){let t=ri(e.value);return`(${e.field}:${e.filter}:${t})`}var ni=zt;import{BaseError as md}from"make-error";import{BaseError as rd}from"make-error";var nd="__internal_data_array_blank_error";function id(e){return Array.isArray(e?.data)}var et="success";function Y(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var Ce=class extends rd{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},K=class extends Ce{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Xe=class extends K{constructor(t,o){super({code:nd,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 Xe&&!o||(r instanceof K?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof Ce?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 ze){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 ze(o),i=e(t,n);if(i)throw i}return t}}var ad="INTERNAL_ERROR",sd="INVALID_TOKEN",V=class extends K{},ii="FAILURE",Uo=class extends K{},cd="4834",Ye=class extends K{},ud="INVALID_QUERY",Lo=class extends K{get details(){return this.error.details}},jt="MANDATORY_NOT_FOUND",Te="DUPLICATE_DATA",Bt="INVALID_DATA",pd="TOO_MANY_REQUESTS",ai=429,dd="X-RATELIMIT-LIMIT",ld="X-RATELIMIT-REMAINING",hd="X-RATELIMIT-RESET",si=100,ci=Ie;function Go(e){let t=e.get(dd),o=e.get(ld),r=e.get(hd),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 Qe=class extends K{get headerDetails(){return Go(this.responseError.response.headers)}};function se(e,t){let o;if(id(e))o=new Xe(e,t);else{let r=he(e,t);if(r){let n=Y(r);switch(n.code){case ad:o=new Uo(n,e,t);break;case sd:o=new V(n,e,t);break;case cd:o=new Ye(n,e,t);break;case ud:o=new Lo(n,e,t);break;case pd:o=new Qe(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 ui="ALREADY_ASSOCIATED",Ko=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}},tt=class extends Ce{},Vo=class extends tt{},Ho=class extends tt{},Wt=class extends tt{get invalidFieldDetails(){return this.error.details}},zo=class extends Wt{};function pi(e){let t;switch(e.code){case Bt:{let o=new Wt(e);o.invalidFieldDetails.id?t=new zo(e):t=o;break}case jt:t=new Vo(e);break;case Te:t=new Ho(e);break;default:t=new tt(e);break}return t}function di(e,t){return o=>{if(!o?.data?.length)throw new Ko(e,t);return o}}var yd=ne("ZohoRecruit");async function gd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=li(t,e)),o}function li(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var hi=ae(li),mi=ie(gd,yd);import{BaseError as fd}from"make-error";function jo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,_(o,{data:T(r)})).then(i=>{let a=Array.isArray(r),s=ce(T(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw pi(p[0].result);c=u[0].result.details}return c}))}function yi(e){return jo(e,"","POST")}function gi(e){return jo(e,"/upsert","POST")}function fi(e){return jo(e,"","PUT")}function Ri(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${R({ids:t,wf_trigger:r})}`,_("DELETE")).then(Rd)}function Ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,_("GET")).then(di(t.module)).then(o=>o.data[0])}function Ti(e){return(t=>e.fetchJson(`/v2/${t.module}?${Pi(t).toString()}`,_("GET")))}function Bo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=ni(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 Pi(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,_("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function xi(e){return w(Bo(e))}function ot(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${$o(n,n.filter).toString()}`,_("GET")).then(i=>i??(r===!1?i:Je()))}}function Wo(e){return ot(e)({targetModule:oi})}function Zi(e){return w(Wo(e))}function Jo(e){return ot(e)({targetModule:Ct})}function Si(e){return w(Jo(e))}var vC=20*1024*1024;function Fi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:k(o),attachments_category:k(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}/${Ct}?${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 Ai(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ct}/${t.attachment_id}`,{method:"GET"}).then(Mt)}function bi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ct}/${t.attachment_id}`,{method:"DELETE"})}var qo=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 Ii(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?Vt(t.apiUrl):""}${a}`;return e.fetchJson(c,_("POST")).then(u=>{if(u.code!=="success")throw new qo(u);return u.details})}}function Pi(...e){return R(e,{omitKeys:"module"})}function $o(...e){return R(e,{omitKeys:["id","module"]})}function _(e,t){return{method:e,body:t??void 0}}function Rd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===et?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===et?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function ki(e){return t=>e.fetchJson(`/v2/${$e}/actions/associate`,_("PUT",{data:T(t)})).then(o=>{let r=o.data.map(()=>t),n=ce(r,o.data),{included:i,excluded:a}=Ke(n.errorItems,s=>s.result.code===ii&&s.result.details.error[0].code===ui);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function Oi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${$o(t).toString()}`,_("GET")).then(o=>o??Je())}function Xo(e){let t=Oi(e);return o=>t({...o,module:$e})}function Ei(e){return w(Xo(e))}function Yo(e,t=ti){let o=Oi(e);return r=>o({...r,module:t})}function Di(e){return w(Yo(e))}function Qo(e){return t=>e.fetchJson(`/v2/${Ht}`,_("POST",{data:t.data})).then(o=>ce(T(t.data),o.data))}function Mi(e){return t=>e.fetchJson(`/v2/${Ht}?${R({ids:t.ids})}`,_("DELETE")).then(o=>ce(T(t.ids),o.data))}function er(e){return ot(e)({targetModule:Ht})}function _i(e){return w(er(e))}function vi(e){let t=Qo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:T(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Ui(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module})}`,_("POST",{tags:T(t.tags)})).then(o=>{let r=ce(T(t.tags),o.tags),{included:n,excluded:i}=Ke(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Li(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 Ni=100;function Gi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Ni)throw new Error(`Cannot add tags to more than ${Ni} records at once.`);return e.fetchJson(`/v2/${$e}/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 wi=100;function Ki(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>wi)throw new Error(`Cannot remove tags from more than ${wi} records at once.`);return e.fetchJson(`/v2/${$e}/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",Td="invalid_client",tr=class extends ${constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},rt=class extends ${constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},xd=ne("ZohoAccounts");async function Zd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Vi(t,e)),o}function Vi(e,t){let o,r=e.error;if(r){let n=Y(r);switch(n.code){case Cd:case Td:o=new tr(n.code);break;default:o=se(e,t);break}}return o}var Hi=ae(Vi),zi=ie(Zd,xd);function xe(e){return async()=>{let t=await e();if(!t.accessToken)throw new rt;return t.accessToken}}var Sd=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 or(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??Sd,r=e.maxRateLimit??si,n=e.resetPeriod??ci;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=Pn(a);return Gn({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:m,limit:C,resetAt:g}=p;if(C!=null&&C!==r){let f=i(C,g??void 0);s.setConfig(f,!1)}if(s.setRemainingLimit(m),g&&s.setNextResetAt(g),y=!0,c.status===ai){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function me(e){return or({...e,readRateLimitDetails:Fd})}function Fd(e){let t=Go(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function qi(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=Vt(a.apiUrl),c=i({apiUrl:s}),u=mi(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:hi,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 $t="Notes",ji="Emails",Tt="Attachments";var Bi=zt;import{BaseError as Ad}from"make-error";var rr=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}},nt=class extends Ce{},nr=class extends nt{},ir=class extends nt{},Xt=class extends nt{get invalidFieldDetails(){return this.error.details}},ar=class extends Xt{};function Wi(e){let t;switch(e.code){case Bt:{let o=new Xt(e);o.invalidFieldDetails.api_name==="id"?t=new ar(e):t=o;break}case jt:t=new nr(e);break;case Te:t=new ir(e);break;default:t=new nt(e);break}return t}function Ji(e,t){return o=>{if(!o?.data?.length)throw new rr(e,t);return o}}var bd=ne("ZohoCrm",{logDataArrayErrors:!1});async function Id(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=$i(t,e)),o}function $i(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var Xi=ae($i),Yi=ie(Id,bd);import{BaseError as Pd}from"make-error";function cr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,U(o,{data:T(r)})).catch(ha).then(i=>{let a=Array.isArray(r),s=Ze(T(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Wi(p[0].result);c=u[0].result.details}return c}))}function Qi(e){return cr(e,"","POST")}function ea(e){return cr(e,"/upsert","POST")}function ta(e){return cr(e,"","PUT")}function oa(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${R({ids:t,wf_trigger:r})}`,U("DELETE")).catch(ha).then(Od)}function ra(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,U("GET")).then(Ji(t.module)).then(o=>o.data[0])}function na(e){return(t=>e.fetchJson(`/v8/${t.module}?${la(t).toString()}`,U("GET")))}function ur(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Bi(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 la(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,U("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function ia(e){return w(ur(e))}function it(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${kd(n,n.filter).toString()}`,U("GET")).then(i=>i??(r===!1?i:Je()))}}function pr(e){let t=it(e)({targetModule:ji});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function aa(e){return w(pr(e))}function dr(e){return it(e)({targetModule:Tt})}function sa(e){return w(dr(e))}var WT=20*1024*1024;function ca(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:k(o),attachments_category:k(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}/${Tt}?${R(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function ua(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Tt}/${t.attachment_id}`,{method:"GET"}).then(Mt)}function pa(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Tt}/${t.attachment_id}`,{method:"DELETE"})}var sr=class extends Pd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function da(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 sr(u);return u.details})}}function la(...e){return R(e,{omitKeys:"module"})}function kd(...e){return R(e,{omitKeys:["id","module"]})}function U(e,t){return{method:e,body:t??void 0}}function ha(e){let t;if(e instanceof Xe)t={data:e.errorDataArray};else throw e;return t}function Od(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===et?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===et?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function lr(e){return t=>e.fetchJson(`/v2/${$t}`,U("POST",{data:t.data})).then(o=>Ze(T(t.data),o.data))}function ma(e){return t=>e.fetchJson(`/v2/${$t}?${R({ids:t.ids})}`,U("DELETE")).then(o=>Ze(T(t.ids),o.data))}function hr(e){return it(e)({targetModule:$t})}function ya(e){return w(hr(e))}function ga(e){let t=lr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:T(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Ra(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module})}`,U("POST",{tags:T(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(T(t.tags),o.tags),{included:n,excluded:i}=Ke(r.errorItems,a=>a.result.code===Te);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ca(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,U("DELETE")).then(o=>o.tags)}function Ta(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 fa=100;function xa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,U("POST",Za(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function Za(e){if(Array.isArray(e.ids)&&e.ids.length>fa)throw new Error(`Cannot add/remove tags from more than ${fa} records at once.`);let t=[...T(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&T(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:T(e.ids)}}function Sa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,U("POST",Za(t))).then(o=>{let r=o.data.map(()=>t);return Ze(r,o.data)})}function Fa(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=Yi(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Xi,handleFetchJsonParseErrorFunction:ee});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Aa="https://signsandbox.zoho.com/api/v1",Ed="https://sign.zoho.com/api/v1";function mr(e){let t;switch(e){case"sandbox":t=Aa;break;case"production":t=Ed;break;default:t=e;break}return t}function ba(e){let t=mr(e),o;try{o=new URL(t).hostname!==new URL(Aa).hostname}catch{o=!0}return o}function Ia(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 Pa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ue("GET"))}function yr(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 ka(e){let t=yr(e);return Ia(t)}function Oa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ue("GET"))}function Ea(e){return()=>e.fetchJson("/fieldtypes",ue("GET"))}function Da(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 Ma(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function _a(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 va(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 Na(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,ue("GET"))}function wa(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 Ua(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ue("PUT",{requests:o}))}function La(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ue("POST",r))}}function Ga(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ue("PUT",{expire_by:o}))}function Ka(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 Va(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ba(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 Dd=ne("ZohoSign",{logDataArrayErrors:!1});async function Md(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 za=ae(Ha),qa=ie(Md,Dd);function ja(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=me(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=mr(a.apiUrl),c=i({apiUrl:s}),u=qa(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:za,handleFetchJsonParseErrorFunction:ee});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ba(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var _d=ne("ZohoDesk",{logDataArrayErrors:!1});async function vd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Wa(t,e)),o}function Wa(e,t){let o,r=he(e,t);if(r)switch(Y(r).code){default:o=se(e,t);break}return o}var Ja=ae(Wa),$a=ie(vd,_d);var Nd="X-Rate-Limit-Remaining-v3",wd="Retry-After",Ud=200;function Ld(e){let t=e.get(Nd),o;if(t!=null){let r=Number(t),n,i=e.get(wd);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 Xa(e){return or({maxRateLimit:Ud,...e,readRateLimitDetails:Ld})}function Ya(e){let{accountsContext:t}=e,o=xe(t.loadAccessToken),r=Xa(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=Ba(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=$a(c,n,m=>{m instanceof V&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Ja,handleFetchJsonParseErrorFunction:ee});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Qa=25;function Q(e,t){return qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Qa}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Qa,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ee(e,t){return{method:e,body:t??void 0}}function at(e,t){return R(e,{omitKeys:t})}function Yt(e){let t;return e&&(t=k(T(e))),t}function gr(e){return t=>{let{include:o,...r}=t,n=at([{...r,include:Yt(o)}]);return e.fetchJson(`/tickets?${n}`,Ee("GET")).then(i=>i??{data:[]})}}function es(e){return t=>{let{ticketId:o,include:r}=t,i=at([{include:Yt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ee("GET"))}}function fr(e){return t=>{let o=at([t]);return e.fetchJson(`/tickets/search?${o}`,Ee("GET")).then(r=>r??{data:[]})}}function ts(e){return t=>{let{contactId:o,include:r,...n}=t,i=at([{...n,include:Yt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function os(e){return t=>{let{productId:o,include:r,...n}=t,i=at([{...n,include:Yt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ee("GET"))}function ns(e){return t=>{let o=at([{agentIds:k(T(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ee("GET"))}}function is(e){return Q(gr(e))}function as(e){return Q(fr(e))}function ss(e){return{method:e}}function cs(e){return t=>{let o=R([t]);return e.fetchJson(`/departments?${o}`,ss("GET")).then(r=>r??{data:[]})}}function us(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,ss("GET"))}function Rr(e){return{method:e}}function ps(e){let t;return e&&(t=k(T(e))),t}function Cr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:ps(o)}]);return e.fetchJson(`/contacts?${n}`,Rr("GET")).then(i=>i??{data:[]})}}function ds(e){return t=>{let{contactId:o,include:r}=t,i=R([{include:ps(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,Rr("GET"))}}function ls(e){return t=>{let o=R([{contactIds:k(T(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Rr("GET")).then(r=>r??[])}}function hs(e){return Q(Cr(e))}function xt(e,t){return{method:e,body:t??void 0}}function ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,xt("GET")).then(o=>o??[])}function ys(e){return t=>{let o={tags:T(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,xt("POST",o)).then(r=>r??[])}}function gs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,xt("DELETE"))}function fs(e){return t=>{let o=R([t]);return e.fetchJson(`/tags/search?${o}`,xt("GET")).then(r=>r??{data:[]})}}function Rs(e){return t=>{let o=R([t]);return e.fetchJson(`/ticketTags?${o}`,xt("GET")).then(r=>r??{data:[]})}}function Tr(e,t){return{method:e,body:t??void 0}}function Cs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("GET")).then(o=>o??[])}function Ts(e){return t=>{let o={ids:T(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("POST",o))}}function xs(e){return t=>{let o={ids:T(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Tr("DELETE",o))}}function Zs(e,t){return{method:e,body:t??void 0}}function Gd(e){let t;return e&&(t=k(T(e))),t}function Ss(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Gd(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,Zs("GET")).then(a=>a??{data:[]})}}function Fs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,Zs("DELETE"))}function Qt(e,t){return{method:e,body:t??void 0}}function As(e){let t;return e&&(t=k(T(e))),t}function bs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:As(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,Qt("GET")).then(a=>a??{data:[]})}}function Is(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=R([{include:As(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,Qt("GET"))}}function Ps(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,Qt("POST",r))}}function ks(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,Qt("DELETE"))}function Zt(e,t){return{method:e,body:t??void 0}}function Os(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Zt("GET"))}function Es(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Zt("POST",r))}}function Ds(e){return t=>{let{ticketId:o,...r}=t,n=R([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Zt("GET")).then(i=>i??{data:[]})}}function Ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Zt("GET"))}function _s(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Zt("GET"))}function vs(e){return{method:e}}function Ns(e){let t;return e&&(t=k(T(e))),t}function xr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Ns(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,vs("GET")).then(a=>a??{data:[]})}}function ws(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=R([{include:Ns(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,vs("GET"))}}function Us(e){return Q(xr(e))}function Kd(e){return{method:e}}function Vd(e){let t;return e&&(t=k(T(e))),t}function Zr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Vd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,Kd("GET")).then(a=>a??{data:[]})}}function Ls(e){return Q(Zr(e))}function eo(e){return{method:e}}function Gs(e){let t;return e&&(t=k(T(e))),t}function Sr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:Gs(o)}]);return e.fetchJson(`/agents?${n}`,eo("GET")).then(i=>i??{data:[]})}}function Ks(e){return t=>{let{agentId:o,include:r}=t,i=R([{include:Gs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,eo("GET"))}}function Vs(e){return t=>{let o=R([{agentIds:k(T(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,eo("GET")).then(r=>r?.data??[])}}function Hs(e){return()=>e.fetchJson("/myinfo",eo("GET"))}function zs(e){return Q(Sr(e))}var Hd="https://accounts.zoho.com",zd="https://accounts.zoho.eu",qd="https://accounts.zoho.in",jd="https://accounts.zoho.com.au",Bd="https://accounts.zoho.jp",Wd="https://accounts.zoho.uk",Jd="https://accounts.zohocloud.ca",$d="https://accounts.zoho.sa",Xd={us:Hd,eu:zd,in:qd,au:jd,jp:Bd,uk:Wd,ca:Jd,sa:$d};function De(e){return Xd[e]??e}var to="/oauth/v2/token";function oo(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(`${to}?${p}`,Fr("POST"))}}function qs(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,refreshToken:i}=t,a=n?.clientId??o,s=n?.clientSecret??r,c=R({grant_type:"refresh_token",client_id:a,client_secret:s,refresh_token:i});return e.fetchJson(`${to}?${c}`,Fr("POST"))}}function js(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,code:i,redirectUri:a}=t,s=n?.clientId??o,c=n?.clientSecret??r,u=R({grant_type:"authorization_code",client_id:s,client_secret:c,code:i,redirect_uri:a});return e.fetchJson(`${to}?${u}`,Fr("POST"))}}var Yd="/oauth/user/info";function Bs(e){return t=>e.fetchJson(Yd,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Fr(e,t){return{method:e,body:t}}function Ws(e){return t=>oe.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function Js(e,t){let o=zi(e,t),r=te(o,{interceptJsonResponse:Hi,handleFetchJsonParseErrorFunction:ee});return{fetch:o,fetchJson:r}}function $s(e){let t=me(),{logZohoServerErrorFunction:o,fetchFactory:r=Ws(t)}=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=De(n.apiUrl??"us"),a=r({apiUrl:i}),{fetch:s,fetchJson:c}=Js(a,o),u=async()=>{let m=Date.now(),{access_token:C,api_domain:g,scope:f,expires_in:S}=await oo(d)();return{accessToken:C,apiDomain:g,expiresIn:S,expiresAt:new Date(m+S*G),scope:f}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=Qd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function Xs(e){let t=e.fetchHandler??me(),{logZohoServerErrorFunction:o,fetchFactory:r=Ws(t)}=e;return n=>{if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsOAuthClientConfig missing clientSecret.")}else throw new Error("ZohoAccountsOAuthClientConfig missing clientId.");let i=De(n.apiUrl??"us"),a=r({apiUrl:i}),{fetchJson:s}=Js(a,o),c={...n,apiUrl:i};return{oauthClientContext:{fetchJson:s,config:c}}}}function Qd(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 rt("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Se(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 el}from"@nestjs/common";var st=class{};st=F([el()],st);function tl(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!un(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function ol(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function rl(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Qs(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:rl;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(tl),c=yn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>ol(d,u)));if(r!=null){let d=ge(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function ec(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=hn(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 nl=".tmp/zoho-access-tokens.json";function Ys(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 tc(e=nl,t=!0){let o=Wn({filePath:e,reviver:Ys}),r=t?mn(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 fe(e),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Ys(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=$s(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return oo(this.accountsContext)}};v=F([il(),I(0,oc(Fe)),I(1,oc(st))],v);import{Inject as cl,Injectable as ul}from"@nestjs/common";var al="ZOHO_ACCOUNTS_CLIENT_ID",sl="ZOHO_ACCOUNTS_CLIENT_SECRET",ct=class{zohoAccountsOAuth;factoryConfig;static assertValidConfig(t){let{zohoAccountsOAuth:o}=t;if(!o)throw new Error("ZohoAccountsOAuthServiceConfig.zohoAccountsOAuth is required");if(!o.clientId)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientId (${al}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${sl}).`)}};var St=class{constructor(t){this.config=t;ct.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=De(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Xs(t.factoryConfig??{})}_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=De(t),r=this._clients.get(o);return r==null&&(r=this._clientFactory({clientId:this.clientId,clientSecret:this._clientSecret,apiUrl:o}).oauthClientContext,this._clients.set(o,r)),r}exchangeAuthorizationCode(t){let{code:o,redirectUri:r,accountsApiUrl:n}=t,i=this.oauthClientContextForApiUrl(n??this.apiUrl);return js(i)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return qs(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Bs(n)({accessToken:o})}};St=F([ul(),I(0,cl(ct))],St);import{ConfigModule as gF,ConfigService as fF}from"@nestjs/config";import{Inject as rc,Injectable as pl}from"@nestjs/common";var Ft=class{zohoCrm;factoryConfig;static assertValidConfig(t){Se(t.zohoCrm)}};var Me=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=Fa({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Qi(this.crmContext)}get upsertRecord(){return ea(this.crmContext)}get updateRecord(){return ta(this.crmContext)}get deleteRecord(){return oa(this.crmContext)}get getRecordById(){return ra(this.crmContext)}get getRecords(){return na(this.crmContext)}get searchRecords(){return ur(this.crmContext)}get searchRecordsPageFactory(){return ia(this.crmContext)}get getRelatedRecordsFunctionFactory(){return it(this.crmContext)}get getEmailsForRecord(){return pr(this.crmContext)}get getEmailsForRecordPageFactory(){return aa(this.crmContext)}get getAttachmentsForRecord(){return dr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return sa(this.crmContext)}get uploadAttachmentForRecord(){return ca(this.crmContext)}get downloadAttachmentForRecord(){return ua(this.crmContext)}get deleteAttachmentFromRecord(){return pa(this.crmContext)}get createNotes(){return lr(this.crmContext)}get deleteNotes(){return ma(this.crmContext)}get createNotesForRecord(){return ga(this.crmContext)}get getNotesForRecord(){return hr(this.crmContext)}get getNotesForRecordPageFactory(){return ya(this.crmContext)}get executeRestApiFunction(){return da(this.crmContext)}get createTagsForModule(){return Ra(this.crmContext)}get deleteTag(){return Ca(this.crmContext)}get getTagsForModule(){return Ta(this.crmContext)}get addTagsToRecords(){return xa(this.crmContext)}get removeTagsFromRecords(){return Sa(this.crmContext)}};Me=F([pl(),I(0,rc(Ft)),I(1,rc(v))],Me);import{ConfigModule as UF,ConfigService as LF}from"@nestjs/config";import{Inject as nc,Injectable as dl}from"@nestjs/common";var At=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Se(t.zohoRecruit)}};var _e=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=qi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return yi(this.recruitContext)}get upsertRecord(){return gi(this.recruitContext)}get updateRecord(){return fi(this.recruitContext)}get deleteRecord(){return Ri(this.recruitContext)}get getRecordById(){return Ci(this.recruitContext)}get getRecords(){return Ti(this.recruitContext)}get searchRecords(){return Bo(this.recruitContext)}get searchRecordsPageFactory(){return xi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ot(this.recruitContext)}get getEmailsForRecord(){return Wo(this.recruitContext)}get getEmailsForRecordPageFactory(){return Zi(this.recruitContext)}get getAttachmentsForRecord(){return Jo(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Si(this.recruitContext)}get uploadAttachmentForRecord(){return Fi(this.recruitContext)}get downloadAttachmentForRecord(){return Ai(this.recruitContext)}get deleteAttachmentFromRecord(){return bi(this.recruitContext)}get createNotes(){return Qo(this.recruitContext)}get deleteNotes(){return Mi(this.recruitContext)}get createNotesForRecord(){return vi(this.recruitContext)}get getNotesForRecord(){return er(this.recruitContext)}get getNotesForRecordPageFactory(){return _i(this.recruitContext)}get executeRestApiFunction(){return Ii(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return ki(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Xo(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return Ei(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Yo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return Di(this.recruitContext)}get createTagsForModule(){return Ui(this.recruitContext)}get getTagsForModule(){return Li(this.recruitContext)}get addTagsToRecords(){return Gi(this.recruitContext)}get removeTagsFromRecords(){return Ki(this.recruitContext)}};_e=F([dl(),I(0,nc(At)),I(1,nc(v))],_e);import{ConfigModule as sA,ConfigService as cA}from"@nestjs/config";import{Inject as ic,Injectable as ll}from"@nestjs/common";var bt=class{zohoSign;factoryConfig;static assertValidConfig(t){Se(t.zohoSign)}};var ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ja({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Pa(this.signContext)}get getDocuments(){return yr(this.signContext)}get getDocumentsPageFactory(){return ka(this.signContext)}get getDocumentFormData(){return Oa(this.signContext)}get retrieveFieldTypes(){return Ea(this.signContext)}get downloadPdf(){return Da(this.signContext)}get downloadCompletionCertificate(){return Ma(this.signContext)}get createDocument(){return _a(this.signContext)}get createDocumentFromTemplate(){return va(this.signContext)}get getTemplate(){return Na(this.signContext)}get getTemplates(){return wa(this.signContext)}get updateDocument(){return Ua(this.signContext)}get sendDocumentForSignature(){return La(this.signContext)}get extendDocument(){return Ga(this.signContext)}get deleteDocument(){return Ka(this.signContext)}get getEmbeddedSigningUrl(){return Va(this.signContext)}};ve=F([ll(),I(0,ic(bt)),I(1,ic(v))],ve);import{ConfigModule as OA,ConfigService as EA}from"@nestjs/config";function ac(e){return{...e,operationType:e.notifications.operation_type}}var sc=kn(e=>e.operationType),cc=En({configurerForAccessor:e=>{let t=On(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 uc="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Ne=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as Cl,Inject as Tl,Post as xl,Req as Zl}from"@nestjs/common";import{Inject as gl,Injectable as fl,Logger as Rl}from"@nestjs/common";import{createHmac as hl,timingSafeEqual as ml}from"node:crypto";var yl="x-zs-webhook-signature";function pc(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[yl],i={valid:!1};if(n){let a=r.toString("utf-8"),s=hl("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=ml(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=ac(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var ye=class{logger=new Rl("ZohoSignWebhookService");_verifier;handler=sc();configure=cc(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=pc({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)}};ye=F([fl(),I(0,gl(Ne))],ye);var we=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([xl(),I(0,Zl()),I(1,zn())],we.prototype,"handleZohoSignWebhook",1),we=F([Cl("/webhook/zoho/sign"),I(0,Tl(ye))],we);import{Module as Sl}from"@nestjs/common";import{ConfigModule as Fl,ConfigService as Al}from"@nestjs/config";function bl(e){let t={zohoSignWebhook:{webhookSecret:e.get(uc)}};return Ne.assertValidConfig(t),t}var no=class{};no=F([Sl({imports:[Fl],controllers:[we],providers:[{provide:Ne,inject:[Al],useFactory:bl},ye],exports:[ye]})],no);import{Inject as dc,Injectable as Il}from"@nestjs/common";var It=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Se(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var Ue=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Ya({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return gr(this.deskContext)}get getTicketById(){return es(this.deskContext)}get searchTickets(){return fr(this.deskContext)}get getTicketsForContact(){return ts(this.deskContext)}get getTicketsForProduct(){return os(this.deskContext)}get getTicketMetrics(){return rs(this.deskContext)}get getAgentsTicketsCount(){return ns(this.deskContext)}get getTicketsPageFactory(){return is(this.deskContext)}get searchTicketsPageFactory(){return as(this.deskContext)}get getDepartments(){return cs(this.deskContext)}get getDepartmentById(){return us(this.deskContext)}get getContacts(){return Cr(this.deskContext)}get getContactById(){return ds(this.deskContext)}get getContactsByIds(){return ls(this.deskContext)}get getContactsPageFactory(){return hs(this.deskContext)}get getTicketTags(){return ms(this.deskContext)}get associateTicketTags(){return ys(this.deskContext)}get dissociateTicketTag(){return gs(this.deskContext)}get searchTags(){return fs(this.deskContext)}get getAllTags(){return Rs(this.deskContext)}get getTicketFollowers(){return Cs(this.deskContext)}get addTicketFollowers(){return Ts(this.deskContext)}get removeTicketFollowers(){return xs(this.deskContext)}get getTicketAttachments(){return Ss(this.deskContext)}get deleteTicketAttachment(){return Fs(this.deskContext)}get getTicketComments(){return bs(this.deskContext)}get getTicketCommentById(){return Is(this.deskContext)}get createTicketComment(){return Ps(this.deskContext)}get deleteTicketComment(){return ks(this.deskContext)}get getTicketTimer(){return Os(this.deskContext)}get performTicketTimerAction(){return Es(this.deskContext)}get getTicketTimeEntries(){return Ds(this.deskContext)}get getTicketTimeEntryById(){return Ms(this.deskContext)}get getTicketTimeEntrySummation(){return _s(this.deskContext)}get getTicketThreads(){return xr(this.deskContext)}get getTicketThreadById(){return ws(this.deskContext)}get getTicketThreadsPageFactory(){return Us(this.deskContext)}get getTicketActivities(){return Zr(this.deskContext)}get getTicketActivitiesPageFactory(){return Ls(this.deskContext)}get getAgents(){return Sr(this.deskContext)}get getAgentById(){return Ks(this.deskContext)}get getAgentsByIds(){return Vs(this.deskContext)}get getMyInfo(){return Hs(this.deskContext)}get getAgentsPageFactory(){return zs(this.deskContext)}};Ue=F([Il(),I(0,dc(It)),I(1,dc(v))],Ue);import{ConfigModule as Eb,ConfigService as Db}from"@nestjs/config";function Pl(e){return`${e.clientId}:${e.refreshToken}`}function ut(e){let t=Qs([ec(),tc(Rt())]),o=new Map;function r(y,m){let C=Pl(y),g=o.get(C),f;if(g)f=g;else{let S={zohoAccounts:{serviceAccessTokenKey:m,refreshToken:y.refreshToken,clientId:y.clientId,clientSecret:y.clientSecret,apiUrl:y.region??"us"}};f=new v(S,t),o.set(C,f)}return f}let n,i=We(e,"recruit");if(i){let y=r(i,"recruit"),m={zohoRecruit:{apiUrl:i.apiMode}};n=new _e(m,y)}let a,s=We(e,"crm");if(s){let y=r(s,"crm"),m={zohoCrm:{apiUrl:s.apiMode}};a=new Me(m,y)}let c,u=We(e,"desk");if(u?.orgId){let y=r(u,"desk"),m={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new Ue(m,y)}let p,d=We(e,"sign");if(d){let y=r(d,"sign"),m={zohoSign:{apiUrl:d.apiMode}};p=new ve(m,y)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:p}}ho([...po,/1000\.\w{20,}/g]);function lc(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 Ye?t={ok:!1,error:le(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Qe?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=mo(e),t}vr(e=>e instanceof V||e instanceof Ye||e instanceof Qe||e instanceof K?lc(e):void 0);function h(e){console.log(JSON.stringify(lc(e)))}var hc={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"},Ir={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 kl(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 Ol={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:[...Kt],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 z(),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 Dl(o,t):o.code?await Ml(o,t):await _l(o,t)}catch(t){h(t),process.exit(1)}}};function El(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:kl(e.code),token:e.token,accountsUrl:hc[o]??hc.us,apiMode:e.apiMode,orgId:e.orgId}}async function mc(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 Dl(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await mc(e,o,t?.shared);l({success:!0,...e.product?{product:e.product}:{},refreshToken:Re(e.token),configSaved:!0,configuredProducts:re(r)})}async function Ml(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 mc(e,s,t?.shared);l({step:2,success:!0,product:e.product??"shared",refreshToken:Re(a),accessToken:i.access_token?Re(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:re(c)})}async function _l(e,t){let o=e.product?Ir[e.product]??[]:e.scopes.flatMap(i=>Ir[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Ir).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 vl={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:[...Kt],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 z())?.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)}}},Nl={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?Re(r.clientId):void 0,clientSecret:r.clientSecret?Re(r.clientSecret):void 0,refreshToken:r.refreshToken?Re(r.refreshToken):void 0}:void 0};var e=o;let t=await z();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)}}},wl={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await z();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=ut(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)}}},Ul={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await ei(),l({cleared:!0})}catch(e){h(e),process.exit(1)}}},yc={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Ol).command(vl).command(Nl).command(wl).command(Ul).demandCommand(1,"Please specify an auth subcommand."),handler:Z};import{access as Ll,constants as Gl}from"node:fs";import{dirname as Kl}from"node:path";var gc={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await z(),t=[];t.push(Vl(e));let o=Hl(e);if(o&&t.push(o),t.push(await zl()),e){let n=re(e);t.push(ql(n),...await jl(e,n));let i=Jl(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 Vl(e){return e?{name:"config",status:"pass",message:`Config loaded from ${ft()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function Hl(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 zl(){let e=Kl(Rt());return await $l(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 ql(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 jl(e,t){let o=ut(e),r=[];for(let n of t)r.push(await Bl(o,n));return r}async function Bl(e,t){let o=Wl(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 Wl(e,t){return t==="recruit"?e.recruitApi:t==="crm"?e.crmApi:t==="sign"?e.signApi:e.deskApi}function Jl(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 $l(e){return new Promise(t=>{Ll(e,Gl.W_OK,o=>{t(!o)})})}var fc=Vn({notInitializedMessage:"CLI context not initialized. This is a bug."});function Rc(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await z();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)),fc.set(ut(r))}catch(r){h(r),process.exit(4)}}}function io(e){return fc.require()}function B(e){let{recruitApi:t}=io(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}=io(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}=io(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}=io(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 vt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function O(e){return vt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function ao(e){return vt(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 Pt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function so(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 Xl={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},E={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}},Yl={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 P({initialInput:o,fetchPage:r,adapter:Xl,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 co(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await P({initialInput:o,fetchPage:async i=>{let a=await r(i);return{data:a.requests??[],page_context:a.page_context}},adapter:Yl,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 Ql={command:"list",describe:"List records from a module",builder:e=>so(Pt(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)}}},eh={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)}}},th={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)}}},oh={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)}}},rh={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)}}},nh={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)}}},ih={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)}}},ah={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)}}},sh={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)}}},Cc={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(Ql).command(eh).command(th).command(oh).command(rh).command(nh).command(ih).command(ah).command(sh).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 ch={command:"list",describe:"List records from a module",builder:e=>so(Pt(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)}}},uh={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)}}},ph={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)}}},dh={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)}}},lh={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)}}},hh={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)}}},mh={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)}}},yh={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)}}},gh={command:"attachments",describe:"Get attachments for a record",builder:e=>Pt(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)}}},Tc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(ch).command(uh).command(ph).command(dh).command(lh).command(hh).command(mh).command(yh).command(gh).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 fh={command:"list",describe:"List tickets",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:E,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 <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)}}},Ch={command:"search",describe:"Search tickets",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:E,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)}}},Th={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:E,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)}}},xh={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)}}},Zh={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)}}},xc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(fh).command(Rh).command(Ch).command(Th).command(xh).command(Zh).demandCommand(1),handler:Z};var Sh={command:"list",describe:"List departments",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:E,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)}}},Fh={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)}}},Zc={command:"departments",describe:"Desk department operations",builder:e=>e.command(Sh).command(Fh).demandCommand(1),handler:Z};var Ah={command:"list",describe:"List contacts",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:E,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 <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)}}},Sc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Ah).command(bh).demandCommand(1),handler:Z};var Ih={command:"list",describe:"List agents",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:E,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)}}},Ph={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)}}},kh={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)}}},Fc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Ih).command(Ph).command(kh).demandCommand(1),handler:Z};var Oh={command:"list",describe:"List all tags",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:E,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:"search",describe:"Search tags",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:E,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)}}},Dh={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)}}},Mh={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)}}},_h={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)}}},Ac={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Oh).command(Eh).command(Dh).command(Mh).command(_h).demandCommand(1),handler:Z};var vh={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:E,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)}}},wh={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)}}},Uh={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)}}},bc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(vh).command(Nh).command(wh).command(Uh).demandCommand(1),handler:Z};var Lh={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:E,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)}}},Gh={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)}}},Ic={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(Lh).command(Gh).demandCommand(1),handler:Z};var Kh={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)}}},Vh={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)}}},Hh={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)}}},Pc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Kh).command(Vh).command(Hh).demandCommand(1),handler:Z};var zh={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)}}},qh={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)}}},jh={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:E,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:"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)}}},kc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(zh).command(qh).command(jh).command(Bh).demandCommand(1),handler:Z};var Wh={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:E,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)}}},Jh={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)}}},Oc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Wh).command(Jh).demandCommand(1),handler:Z};var $h={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>O(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 P({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:E,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)}}},Ec={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command($h).demandCommand(1),handler:Z};var Dc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(xc).command(Zc).command(Sc).command(Fc).command(Ac).command(bc).command(Ic).command(Pc).command(kc).command(Oc).command(Ec).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 Xh,writeFile as Mc}from"node:fs/promises";import{basename as Yh}from"node:path";function Qh(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 em={command:"list",describe:"List sign requests (documents)",builder:e=>ao(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:Qh(e)};await co({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){h(t),process.exit(1)}}},tm={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)}}},om={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)}}},rm={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 Xh(e.file),n=new File([r],Yh(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});l(i)}catch(t){h(t),process.exit(1)}}},nm={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)}}},im={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)}}},am={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)}}},sm={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)}}},cm={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)}}},um={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 Mc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},pm={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 Mc(e.output,r),l({saved:!0,path:e.output,bytes:r.length})}catch(t){h(t),process.exit(1)}}},dm={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)}}},_c={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(em).command(tm).command(om).command(rm).command(nm).command(im).command(am).command(sm).command(cm).command(um).command(pm).command(dm).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 lm(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 hm={command:"list",describe:"List templates",builder:e=>ao(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:lm(e)};await co({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){h(t),process.exit(1)}}},mm={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)}}},vc={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(hm).command(mm).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 ym={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)}}},Nc={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command(_c).command(vc).command(ym).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 wc={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 Rm=Xn({cliName:"zoho-cli",loadOutputConfig:async()=>(await z())?.output,mergeOutputConfig:e=>X({output:e}),clearOutputConfig:Qn}),Cm=[Cc,Tc,Dc,Nc,wc],Uc=[yc,Rm,gc];function Tm(e){return e.command.split(" ")[0]}var Lc=new Set(Uc.map(Tm)),xm=$n({cliName:"zoho-cli",skipCommands:Lc,loadOutputConfig:async()=>(await z())?.output,saveCommandOutputConfig:async(e,t)=>{await X({output:{commands:{[e]:t}}})}});async function Zm(){try{await gm(fm(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([Rc(Lc),xm],!0).command(Uc).command(Cm).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 Zm();
|
package/cli/package.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/cli",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.37.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.37.0",
|
|
10
|
+
"@dereekb/nestjs": "13.37.0",
|
|
11
|
+
"@dereekb/rxjs": "13.37.0",
|
|
12
|
+
"@dereekb/util": "13.37.0",
|
|
13
|
+
"@dereekb/zoho": "13.37.0",
|
|
14
|
+
"@dereekb/zoho/nestjs": "13.37.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.37.0",
|
|
4
4
|
"peerDependencies": {
|
|
5
|
-
"@dereekb/nestjs": "13.
|
|
6
|
-
"@dereekb/rxjs": "13.
|
|
7
|
-
"@dereekb/util": "13.
|
|
8
|
-
"@dereekb/zoho": "13.
|
|
5
|
+
"@dereekb/nestjs": "13.37.0",
|
|
6
|
+
"@dereekb/rxjs": "13.37.0",
|
|
7
|
+
"@dereekb/util": "13.37.0",
|
|
8
|
+
"@dereekb/zoho": "13.37.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.37.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.37.0",
|
|
27
|
+
"@dereekb/dbx-cli": "13.37.0",
|
|
28
|
+
"@dereekb/firebase": "13.37.0",
|
|
29
|
+
"@dereekb/model": "13.37.0",
|
|
30
|
+
"@dereekb/nestjs": "13.37.0",
|
|
31
|
+
"@dereekb/rxjs": "13.37.0",
|
|
32
|
+
"@dereekb/util": "13.37.0",
|
|
33
33
|
"@nestjs/common": "^11.1.19",
|
|
34
34
|
"@nestjs/config": "^4.0.4",
|
|
35
35
|
"express": "^5.2.1",
|