@dereekb/zoho 13.43.0 → 14.0.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 +7 -7
- package/cli/package.json +7 -7
- package/index.esm.js +245 -559
- package/nestjs/index.esm.js +102 -185
- package/nestjs/package.json +8 -8
- package/nestjs/src/lib/zoho.config.d.ts +0 -9
- package/package.json +11 -11
- package/src/lib/accounts/accounts.config.d.ts +0 -4
- package/src/lib/crm/crm.api.d.ts +1 -13
- package/src/lib/crm/crm.config.d.ts +0 -4
- package/src/lib/crm/crm.d.ts +0 -6
- package/src/lib/crm/crm.notes.d.ts +0 -4
- package/src/lib/recruit/recruit.api.d.ts +1 -93
- package/src/lib/recruit/recruit.api.notes.d.ts +0 -24
- package/src/lib/recruit/recruit.api.tags.d.ts +0 -24
- package/src/lib/recruit/recruit.config.d.ts +0 -4
- package/src/lib/recruit/recruit.d.ts +0 -10
- package/src/lib/recruit/recruit.error.api.d.ts +0 -4
- package/src/lib/recruit/recruit.notes.d.ts +0 -4
- package/src/lib/sign/sign.config.d.ts +0 -4
- package/src/lib/zoho.limit.d.ts +0 -4
package/cli/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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 yp=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?fp(t,o):t,a=e.length-1,i;a>=0;a--)(i=e[a])&&(n=(r?i(t,o,n):i(n))||n);return r&&n&&yp(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as gp,mkdirSync as Rp,writeFileSync as Cp}from"node:fs";import{join as Tp}from"node:path";var nn=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],an=6e4,je={},sn=[...Po],Eo,xp=!1,Ap=an;function Do(e){je=e}function zt(){return je}function cn(e){xp=e}function un(e){Ap=e===void 0?an:e}function Mo(e){sn=e}function pn(e){Eo=e}function ge(e){let t=e;for(let o of sn)t=t.replace(o,"[REDACTED]");return t}function ln(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function Ct(e,t){let{dumpDir:o,commandPath:r}=je,n;if(o){gp(o)||Rp(o,{recursive:!0});let a=r?.length?r.join("_"):"response",i=ln(),s=t?`${a}_${i}_${t}`:`${a}_${i}`;n=Tp(o,`${s}.${e}`)}else n=void 0;return n}function Zp(e,t){let o=Ct("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Cp(o,JSON.stringify(r,null,2))}function Me(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>rn(n,o)):e!=null&&typeof e=="object"?r=rn(e,o):r=e,r}function rn(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 dn(e){return je.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function p(e,t){Zp(e,t);let r={ok:!0,data:je.pick?Me(e,je.pick):e,...t?{meta:t}:{}};console.log(dn(r))}function hn(e){console.log(dn(wo(e)))}var Rt=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function wo(e){let t=Eo?Eo(e):void 0,o;return t?o=t:e instanceof Rt?o={ok:!1,error:ge(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:ge(e.message),code:"ERROR"}:o={ok:!1,error:ge(String(e)),code:"UNKNOWN_ERROR"},o}function Be(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 Tt(e){let t=!0;for(let o of e){t=!1;break}return t}function _o(e,t){for(let o of e)t(o)}function j(e,t,o=!1){e!=null&&(Be(e,o)?_o(e,t):t(e))}function mn(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(i=>Array.isArray(i)?i.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Sp(e){return e==null?[]:Fp(e)}var x=Sp;function Fp(e){return Array.isArray(e)?e:[e]}import{symmetricDifference as Eg}from"extra-set";function yn(e,t){j(t,o=>e.add(o))}function fn(e,t){j(t,o=>e.delete(o))}function gn(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function vo(e){return Object.keys(e).length===0}function Rn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Cn(e){return{...e}}function Tn(e){return e!=null}function Jt(e){return Be(e,!1)?!Tt(e):xn(e)}function No(e){let t;return Be(e,!0)?t=!Tt(e):xn(e)?t=typeof e=="object"?!vo(e):!0:t=!1,t}function xn(e){return e!=null&&e!==""}function Ip(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,a)=>e(r,n,a)),o}}var ce=Ip(Tn);function An({base:e,build:t}){let o=e??{};return t(o),o}var bp=(e=>e);function Zn(){return bp}function Uo(e,t){let o=new Set(e),r=kp(t,n=>n);return r.length&&fn(o,r),Array.from(o)}function kp(e,t){return ce(e==null?[]:Array.isArray(e)?e:Op(e,t))}function Op(e,t){let o=new Set(e.keys);return e.values&&yn(o,e.values.map(t)),Array.from(o)}function $e(e,t){let o=Ep(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Ep(e,t){return Rn(Pp(e,t))}function Pp(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),a=o.get(n);a==null?o.set(n,[r]):a.push(r)}),o}function Sn(e,t,o){return x(t).forEach(r=>e.set(r,o)),e}function Lo(e){return Array.from(e.entries())}function Fn(e){return Dp(Lo(e))}function Dp(e){let t=[];return e.forEach(([o,r])=>{j(r,n=>{t.push([o,n])})}),t}function In(){let e=new Map,t=(n,a)=>{let i=e.get(n);i==null&&(i=[],e.set(n,i)),j(a,s=>i.push(s))},o=(n,a)=>t(n,mn(a));return{map:()=>e,entries:()=>Lo(e),tuples:()=>Fn(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,a)=>j(n,i=>t(i,a)),addTuplesToKeys:(n,a)=>j(n,i=>o(i,a)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Mp(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function bn(e){let t=Mp(e);return t!=null&&t!=="class"}function kn(e){return bn(e)?e:()=>e}function On(e,t){return Math.log(t)/Math.log(e)}var En=",",wp=" ";function _p(e,t=En,o=!1){if(e==null)return e;let r=x(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Go(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),a=[];if(n.length>1){let i=n.length>o,s=i?o-1:n.length;for(let c=0;c<s;c+=1)a.push(n[c]);i&&a.push(n.slice(s).join(t))}else a.push(n[0]);r=a;break}}return r}function vp(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,a=o){return _p(n,t,a)};return r.joiner=t,r.trimByDefault=o,r}function Pn(e){let{joiner:t}=e,o=vp(e),r=(n,a=i=>i)=>n.split(t).map(s=>a(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,a){return Go(n,t,a)}}}var Ko=Pn({joiner:En}),Np=Pn({joiner:wp,trimByDefault:!0});var P=Ko.joinStrings,rR=Ko.splitStrings,nR=Ko.splitStringsToSet,aR=Np.joinStrings;var Dn=gn;function wn(e,{forEach:t,filter:o}){Up(e,o).forEach((n,a)=>t(n,a))}function Up(e,t){return Vo(t)(e)}function Vo(e){let t;if(e==null)t=Mn;else{let o=Lp(e);t=r=>Mn(r).filter((n,a)=>o(n,a))}return t}function Mn(e){return Object.entries(e)}function zo(e){return typeof e=="object"?e:{valueFilter:e}}function Lp(e){let t=zo(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,a;switch(o){case 1:a=([,i])=>i!==void 0;break;case 2:a=([,i])=>i!=null;break;case 3:a=([,i])=>!!i;break;case 4:a=([,i])=>Jt(i);break;case 5:a=([,i])=>No(i);break;case 6:a=([,i])=>!!i&&Jt(i);break;case 7:a=([,i])=>!!i&&No(i);break;default:a=()=>!0;break}if(n){let i=a,s=new Set(n.map(c=>c.toString()));a=(c,u)=>i(c,u)&&s.has(c[0])}return Dn(a,r)}function xt(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 _n(e){let t;return e==null||jp(e)?t=e:t=Gp(e),t}function Gp(e){return e==null?e:new Date(e)}var Kp=365,vn=24,Vp=60,zp=1440,Jp=60,hR=Kp*zp,Hp=Jp*Vp,z=1e3,Re=z*60,Jo=Re*60,qp=Jo*vn,mR=Hp*vn,Wp=7,yR=qp*Wp;function jp(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Nn(e){return e.getTime()<Date.now()}function Un(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function Bp(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:a,expiresIn:i}=e,s=n==null?null:_n(n);function c(f){return f??r??new Date}function u(f,m=!1){let R=c(f),y=h(R),C;return y==null?C=m:C=y<=R,C}function l(f){let m=c(f);return h(m)}function h(f){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:i!=null&&(m=Un(s??(a===!1?null:f),i)),m}return{input:e,hasExpired:u,getExpirationDate:l}}function Ln(e,t){let o=!0;return e!=null&&(o=Bp(e).hasExpired(t,!0)),o}function $p({filter:e,copy:t,dynamic:o=!1}){let r=e==null?el:Ye({filter:e,copy:!1});return n=>{let a=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},i=o?a:xt(a);return s=>{let c=i();return t&&(s=Cn(s)),Object.assign(s,c),s}}}function Gn(e,t){return Yp(t)(e)}function Yp(e){let t=$p({filter:e,copy:!1,dynamic:!0});return o=>t(ce(o))({})}function Kn(e,t=!1){return(t?Qp:Xp)(e)}var Xp=Ye({copy:!0,filter:{valueFilter:1}}),Qp=Ye({copy:!0,filter:{valueFilter:2}}),Vn=Ye({copy:!0,filter:{valueFilter:4}}),SR=Ye({copy:!0,filter:{valueFilter:6}}),FR=Ho({valueFilter:1}),IR=Ho({valueFilter:6}),bR=Ho({valueFilter:2});function Ho(e){let t=zn({filter:e,forEach:([o],r,n,a)=>{a.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ye({copy:e=!1,filter:t={valueFilter:1}}={}){let o=zo(t);o.invertFilter=!o.invertFilter;let r=zn({filter:o,forEach:([n],a,i)=>{delete i[n]}});return(n,a)=>((typeof a=="boolean"?a:e)&&(n={...n}),r(n),n)}var el=Ye({copy:!1});function zn({forEach:e,filter:t}){let o=Vo(t);return((r,n)=>{o(r).forEach((i,s)=>e(i,s,r,n))})}function Jn(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 Hn(e){let t,o,r=0;function n(){let a;if(t==null){if(o==null){let i=r;o=e.load().then(s=>(r===i&&(t={entries:s},o=void 0),s),s=>{throw r===i&&(o=void 0),s})}a=o}else a=Promise.resolve(t.entries);return a}return{load:async()=>({...await n()}),get:async a=>(await n())[a],set:async(a,i)=>{let s=await n();r+=1,o=void 0,await e.set(a,i),t={entries:{...s,[a]:i}}},remove:async a=>{let i=await n();r+=1,o=void 0,await e.remove(a);let s={...i};delete s[a],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function qn(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 Ht(e,t,o){let[r,n]=qo(e,t,!1);return r+o+n}function qo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var tl=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],wR=new Set(tl);function Wn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let a=qt(r,n),i;switch(a.length){case 0:i=n;break;case 1:{let s=n[a[0]];i=Ht(n,a[0],o(s));break}default:{let s=[],c=a.length,u=0,l=0;for(let h=0;h<c;h+=1){l=a[h];let f=n[l],R=n.substring(u,l)+o(f);s.push(R),u=l+1}s.push(n.substring(u)),i=s.join("");break}}return i}}function ol(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[a,i]of Array.from(t).entries())if(e.has(i)&&(n.push(a),n.length>=r))break;return n}}function qt(e,t,o){return ol(e)(t,o)}function rl(e,t){return qt(e,t,1)[0]}function nl(e){return t=>{let r=rl(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=qo(t,r,!1),n}}function jn(e,t){return nl(t)(e)}var Xe="/",al=".";function il(e){let t=e.split(al,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Xe?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Bn(e){return il(e)!=="invalid"}var sl=/^\/+/,cl=/\/+$/;var ul=/\/{2,}/g;function $n(e){return e.startsWith(Xe)?e.replace(sl,Xe):`${Xe}${e}`}function Yn(e){return e.replaceAll(ul,Xe)}function Xn(e){return e.replace(cl,"")}function pl(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Qn=/:(\d+)/;function ll(e){return Qn.test(e)}function dl(e){let t=Qn.exec(e);return t?Number(t[1]):void 0}function hl(e){let t=ra(e),o=ml(t),{domain:r,path:n}=o,a=pl(r),i=ll(e),s=i?dl(e)??void 0:void 0,[c,u]=jn(o.path,"?"),l=a&&(c===""||Bn(c+"/")),h=fl(e);return{input:e,isWebsiteUrl:l,hasWebsiteDomain:a,hasHttpPrefix:h,hasPortNumber:i,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function ea(e){let t=hl(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function ta(e,t=!1){let o=qt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(a=>n=Ht(n,a,"&")),n}function ml(e){let t=ra(e);return yl(t)}function yl(e){let t=Go(e,"/",2),o=t[0],r=t[1];return{domain:o,path:$n(r??"/")}}var oa=/^https:\/\/|http:\/\//;function ra(e){return e.replace(oa,"")}function fl(e){return oa.test(e)}function A(){}async function na(e){let t,o=e.initValue;if(o==null||await e.checkContinue(o,-1)){let n=0,a=o,i;do a=await e.next(n,a),n+=1,i=await e.checkContinue(a,n);while(i);t=a}else t=o;return t}function aa(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function At(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function gl(e){let n=Jo,a={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},i=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;m(e??a);function l(){return{...a}}function h(){return u}function f(S){u=S}function m(S,O=!1){let q=Math.max(0,S.startLimitAt??1),I=S.cooldownRate??1,_=S.maxWaitTime??n,v=S.exponentRate??2;a={startLimitAt:q,cooldownRate:I,maxWaitTime:_,exponentRate:v},s=On(v,_/z+1),O&&R()}function R(){i=0,c=new Date}function y(S){let O;if(u){let{cooldownRate:q}=a,_=(Date.now()-c.getTime())*q/z,v=Math.max(i-_,0),W=Math.max(0,v-a.startLimitAt);S&&(i=v+S,c=new Date),O=W>=s?a.maxWaitTime:(Math.pow(a.exponentRate,Math.max(W,0))-1)*z}else O=0;return O}function C(S){return y(S??0)}function g(){let S=y(1);return At(S)}return{waitForRateLimit:g,getNextWaitTime:C,getConfig:l,setConfig:m,getEnabled:h,setEnabled:f,reset:R}}function ia(e){let o=gl({exponentRate:1.5,maxWaitTime:z*8,...e}),r=Re,n=new Date,a=0,i=0,s=!0;g(e,!0);function c(){Nn(n)&&h()}function u(){return s}function l(I){s=I}function h(){i=a,n=new Date(Date.now()+r)}function f(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function R(I){n=I}function y(){return c(),i}function C(I){i=I}function g(I,_=!1){a=I.limit??a,r=I.resetPeriod??r;let v={cooldownRate:I.cooldownRate??Math.max(.1,r/z),exponentRate:I.exponentRate??1.5,maxWaitTime:I.maxWaitTime??z*8};o.setConfig(v,_),_&&h(),n=I.resetAt??n}function S(I){let _=0;if(s){let W=function(){return i-=I,o.getNextWaitTime(I)};var v=W;i>0?_=W():(c(),i>0?_=W():_=m())}return _}function O(I){return S(I??0)}function q(){let I=S(1);return At(I)}return{getRemainingLimit:y,setRemainingLimit:C,getTimeUntilNextReset:m,getResetAt:f,setNextResetAt:R,setConfig:g,reset:h,getNextWaitTime:O,waitForRateLimit:q,getEnabled:u,setEnabled:l}}var Rl="__CATCH_ALL_HANDLE_RESULT_KEY__";function sa(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,a=new Map,i=u=>{n=u},s=(u,l)=>{u===Rl?i(l):Sn(a,u,l)},c=(u,l,h)=>{let f=h.bind(u);s(l,f)};return An({base:(u=>{let l=e(u),h=(l==null?void 0:a.get(l))??n,f;return h?f=Promise.resolve(h(u)).then(m=>m??o):f=Promise.resolve(r),f}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=i}})}}function Cl(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Tl(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function xl(e,t,o){let r=Tl(e,t);return n=>{r(function(a){let i=o(a);return n.call(this,i)})}}function ca(e,t){return o=>xl(e,o,t)}function ua(e){return t=>(o,r)=>{let n=Cl(o,t),a=e.configurerForAccessor(n);r(a)}}var Al=-1,pa=0;function Zl(e){return e?.page??Al}function la(e){return Zl(e)+1}import{BaseError as da}from"make-error";var ne=class extends da{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function ha(e){return(t,o)=>Sl(e(t,o))}var Se=class extends da{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Sl(e){return e.then(t=>{if(!t.ok)throw new Se(t);return t})}import{BaseError as cC}from"make-error";function ma(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let i=new AbortController;r=i,o={...o,signal:i.signal}}let a=e(t,o??void 0);if(n){let i=setTimeout(()=>{r?.abort()},n);a=a.finally(()=>{clearTimeout(i)})}return a}}function fa(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>ga({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>Il({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Fl=(e,t)=>t(e);function Il(e){let{makeFetch:t=fetch,fetchHandler:o=Fl,useTimeout:r,requireOkResponse:n,mapResponse:a}=e,i=t;r&&(i=ma(i)),n&&(i=ha(i));let s=ga(e);return async(c,u)=>{let l=await s(c,u),h=o(l,i);return a&&(h=a(h)),h}}var bl=(e,t)=>new Request(e,t??void 0);function ga(e){let{makeRequest:t=bl,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:a,useBaseUrlForConfiguredFetchRequests:i=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=i}=e,c=o?new URL(Xn(o)):void 0,u=c?m=>{let R,y=m.toString();if(!s&&ea(y))R=new URL(y);else{let C=c.origin+Yn("/"+c.pathname+"/"+m);R=new URL(C,c)}return R}:void 0;async function l(m){let R=aa(m)?await m:m;return ya(R)?R:t(R)}let h=u?async m=>{let R,y,C;if(typeof m=="string"?R=m:ya(m)?i?(R=m.url,y=m):C=m:C=await t(m),!C){let g=u(R);C=await t(g.href,y)}return C}:l,f;if(r!=null||n!=null){let m=kn(r);async function R(){let C=await m();return n?{...C,timeout:n}:C}async function y(C,g){let S=await R(),O=kl(S,await g),q=O.timeout===void 0?C.timeout:O.timeout;return{...O,timeout:q}}a?f=(C,g)=>a(C,y(C,g)):f=(C,g)=>y(C,g)}else a?f=a:f=(m,R)=>R;return async(m,R)=>{try{let y=await h(m);R=await f(y,R??void 0);let C=await t(y,R);return C.timeout=n,C}catch(y){throw y instanceof ne?y:new ne(y)}}}function kl(e,t){let o;if(t){let r=Ol([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Ol(e){let t=In();return ce(e).forEach(o=>{let r=El(o),n=new Set;r.forEach(([a,i])=>{n.has(a)||(t.delete(a),n.add(a)),i&&t.add(a,i)})}),t.tuples()}function El(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 ya(e){return!!e.url}import{safeParse as Pl}from"fast-content-type-parse";function Ra(e){let t={};return e.mimeType&&(t.type=e.mimeType),e.lastModified!=null&&(t.lastModified=e.lastModified),new File(x(e.content),e.fileName,t)}function Wt(e){let t=e.headers.get("content-type"),o=Pl(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ca(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,a=async(i,s)=>{async function c(u){await n.waitForRateLimit();let l,h;try{l=await s(i.clone())}catch(m){h=m,l=h.response}if(await t(l,h)&&u<r)l=await c(u+1);else if(h!=null)throw h;return l}return c(0)};return a._rateLimiter=n,a}var Wo=class extends ne{constructor(o){super("There was no next page for this.");this.page=o}},jo=class extends ne{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},Dl=100;function Qe(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:a}=e;return(i,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},l=u??a,h=c===null?Number.MAX_SAFE_INTEGER:c??Dl;function f(R,y=void 0){return async()=>{let C=await t(R),{cursor:g,nextPageCursor:S,hasNext:O}=await o(C),q=g??y?.cursor,I=O!==!1,_=y?y.page+1:pa,v=_>=h,W={input:R,result:C,page:_,previous:y,hasNext:I,isAtMaxPage:v,cursor:q,nextPageCursor:S,fetchNext:xt(async()=>{if(v)throw new jo(W,h);let on=I?await r(W,R,{maxPage:h,maxItemsPerPage:l}):void 0;if(!on)throw new Wo(W);return f({...R,...on},W)()})};return W}}return{input:i,fetchNext:xt(()=>f(i)())}}}function Ml(e){let t=[];function o(r,n){n!=null&&(Array.isArray(n)?n.forEach((a,i)=>o(`${r}[${i}]`,a)):typeof n=="object"?Object.entries(n).forEach(([a,i])=>o(`${r}[${a}]`,i)):t.push([r,String(n)]))}return Object.entries(e??{}).forEach(([r,n])=>o(r,n)),t}function T(e,t){let{omitKeys:o,filterEmptyValues:r,useBracketNotation:n}=t??{},a=Array.isArray(e)?Gn(e):e,i=r??!0?Vn(a??{}):a,s=n?Ml(i):i,c=new URLSearchParams(s);return o!=null&&j(o,u=>c.delete(u),!1),c}function Bo(e){let t;if(typeof e=="string")t=e;else if(wl(e))t=e.href;else{let o=Bo(e.url);if(e.queryParams){let r=Nl(e.queryParams);Tt(r)?t=o:t=ta(o+`?${r.toString()}`)}else t=o}return t}function wl(e){return typeof e=="object"&&e instanceof URL}function _l(e){return typeof e=="object"&&e instanceof URLSearchParams}function vl(e){let t=[];return _o(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let a=String(r);j(n,i=>{i!=null&&t.push([a,String(i)])})}}),t}function Nl(e){let t;return _l(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Be(e)?t=new URLSearchParams(vl(e)):t=Ul(e),t}function Ul(e){let t=[];return wn(e,{forEach:o=>{let[r,n]=o,a=String(r);n!=null&&j(n,i=>{t.push([a,String(i)])})}}),new URLSearchParams(t)}var $o=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Ll(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Gl=e=>{throw new $o(e)},$=e=>null;function Y(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Gl};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,a=Ta(o);return(i,s,c)=>{let u=Bo(i),l=a(s,c),h=typeof s=="object"?s.interceptResponse:void 0;return e(u,l).then(m=>{let R=m.json().catch(r),y=n?R.then(C=>n(C,m)):R;return h?y.then(C=>h(C,m)):y})}}function Ta(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Zn()}=e;return(r=t,n)=>{let a;return typeof r=="string"?a={method:r,body:n}:a=r??{method:t,body:n},a=o(a),{...a,method:a.method,body:Ll(a.body)}}}var OC=Ta();var X=fa({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});import{createParamDecorator as Kl}from"@nestjs/common";var oT=Kl((e,t)=>Vl(t));function Vl(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Yo,BadRequestException as zl,InternalServerErrorException as Jl,Logger as Hl}from"@nestjs/common";import ql from"raw-body";import{parse as Wl}from"node:querystring";var xa=new Hl("RawBody"),sT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw xa.error("RawBody request was not readable. This is generally due to bad configuration."),new zl("Invalid body");return ql(o)}),Aa=Yo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw xa.error("RawBody expected a buffer set to req.body."),new Jl("failed parsing body");return r}),cT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=jl(o.body),o.body});function jl(e){let t=Bl(e);return Wl(t)}function Bl(e){return e.toString("utf8").trim()}import{Injectable as $l}from"@nestjs/common";import Yl from"body-parser";var et=class{use(t,o,r){Yl.json()(t,o,r)}};et=F([$l()],et);import{Injectable as Xl}from"@nestjs/common";import Ql from"body-parser";var tt=class{use(t,o,r){Ql.raw({type:"*/*"})(t,o,r)}};tt=F([Xl()],tt);import{Logger as ed,Module as td,RequestMethod as od}from"@nestjs/common";var rd="/webhook",nd={path:`${rd}/{*path}`,method:od.POST},Xo=class{configure(t){ad(t)}},jt=class extends Xo{logger=new ed("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};jt=F([td({})],jt);function ad(e){e.apply(tt).forRoutes(nd).apply(et).forRoutes("{*path}")}var Za="CLIENT_WEB_APP_URL";var we=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as id,Injectable as sd}from"@nestjs/common";var _e=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]}};_e=F([sd(),b(0,id(we))],_e);import{Module as cd}from"@nestjs/common";import{ConfigModule as ud,ConfigService as pd}from"@nestjs/config";function ld(e){let t={client:{clientWebAppUrl:e.get(Za)}};return we.assertValidConfig(t),t}var Bt=class{};Bt=F([cd({imports:[ud],providers:[{provide:we,inject:[pd],useFactory:ld},_e],exports:[_e]})],Bt);var Sa="SERVER_ENV_TOKEN";import{Inject as dd,Injectable as hd}from"@nestjs/common";function Fa(){return process.env.NODE_ENV==="test"}var $t=class{constructor(t){this.env=t}get isTestingEnv(){return Fa()}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}};$t=F([hd(),b(0,dd(Sa))],$t);import{dirname as Cd}from"node:path";import{chmod as md,mkdirSync as yd,readFile as fd,writeFile as gd}from"node:fs";import{rm as Rd}from"node:fs/promises";function Fe(e){return new Promise((t,o)=>{fd(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 Yt(e){return yd(e.dirPath,{recursive:!0}),new Promise((t,o)=>{gd(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():md(e.filePath,e.mode,n=>{n?o(n):t()})})})}function Zt(e){return Rd(e,{force:!0})}var Td=384;function Ia(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,a=o??Td;async function i(){let l=await Fe(t),h;if(l==null)h={};else if(r==null)h=l;else{h={};for(let f of Object.keys(l)){let m=r(l[f]);m!=null&&(h[f]=m)}}return h}async function s(l){let h=n==null?l:Object.fromEntries(Object.entries(l).map(([f,m])=>[f,n(m)]));await Yt({filePath:t,dirPath:Cd(t),data:h,mode:a})}let c=Promise.resolve();function u(l){let h=c.then(l,l);return c=h.catch(()=>{}),h}return{load:i,get:async l=>(await i())[l],set:(l,h)=>u(async()=>{let f=await i();await s({...f,[l]:h})}),remove:l=>u(async()=>{let f={...await i()};delete f[l],await s(f)}),clear:()=>u(async()=>{await Zt(t)})}}var Fx=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 ba(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 Xt(e,t=nn){return async o=>{try{await e(o)}catch(r){hn(r),process.exit(t)}}}var xd=["raw","page_by_line","data_by_line"],Ad=["replace","concat"],Zd=["meta","pages","merged_page"];function Qt(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:Zd,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:xd,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:Ad,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function St(e){return Fe(e.configFilePath)}function Sd(e){return Yt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function Ft(e){let t=await St({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:Qo(t.output,e.updates.output)};return await Sd({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Qo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Fd(e?.commands,t)}}function Fd(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 ka(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 Ie(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Id}from"node:os";import{join as eo}from"node:path";function to(e){let t=e.configDirOverride??eo(Id(),`.${e.cliName}`);return{configDir:t,configFilePath:eo(t,"config.json"),tokenCachePath:eo(t,".tokens.json"),firestoreSessionCachePath:eo(t,".firestore-sessions.json")}}function Oa(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,a)=>{await Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:a}}}})});return async n=>{cn(!!n.verbose),un(typeof n.timeout=="number"?n.timeout*1e3:void 0);let a=n._?n._.map(String):[],i=a[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&i&&!e.skipCommands.has(i)){let m=a.join("."),R={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,R)}let l=i&&!e.skipCommands.has(i),h=l?await o():void 0,f=l?ka({outputConfig:h,commandPath:a,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};Do({dumpDir:f.dumpDir,pick:n.pickAll?void 0:f.pick,commandPath:a,pretty:!!n.pretty})}}function bd(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(a=>Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:a}})),n=e.clearOutputConfig??(()=>Ft({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 Ea(e){let t=bd(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:a=>a.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(i=>{if(i.setDumpDir==null&&i.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:Xt(async a=>{let i=a.command,s=a.setDumpDir,c=a.setPick,u;if(i){let h={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[i]:h}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let l=await t.loadOutputConfig();p({saved:!0,output:l??{}})})},r={command:"show",describe:"Show current output configuration",builder:a=>a,handler:Xt(async()=>{let a=await t.loadOutputConfig();p({output:a??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:a=>a.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:Xt(async a=>{let i=a.command;if(i){let s=await t.loadOutputConfig();if(!s?.commands?.[i])throw new Rt({message:`No per-command output config for "${i}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[i],await t.mergeOutputConfig({...s,commands:c}),p({cleared:!0,command:i})}else await t.clearOutputConfig(),p({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:a=>a.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:A}}import{writeFileSync as kd,appendFileSync as Od}from"node:fs";function Pa(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=zt(),n=t==="raw"?"json":"ndjson",a=Ct(n),i=r?Ct(n,"pick"):void 0,s;if(a){let c=0,u=y=>{let C;if(r){let g=Me(y.data,r);C={...y,data:g}}else C=y;return C},l=y=>{let C=y.append?Od:kd;C(a,y.mainContent),i&&y.pickContent!==void 0&&C(i,y.pickContent)},h=(y,C)=>{let g=JSON.stringify(y,null,2),S=i?JSON.stringify(u(y),null,2):void 0;l({mainContent:g,pickContent:S,append:C})},f=(y,C)=>{let g=JSON.stringify(y)+`
|
|
5
|
-
`,S=
|
|
6
|
-
`:void 0;l({mainContent:g,pickContent:S,append:C})},m=(y,C)=>{let g=y.data??[],S=
|
|
7
|
-
`,v=
|
|
8
|
-
`:void 0;l({mainContent:_,pickContent:v,append:I})})};s={mainPath:a,pickPath:i,writePage:y=>{let g=o==="concat"&&!(c===0);t==="raw"?h(y,g):t==="page_by_line"?f(y,g):m(y,g),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Ed(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:a,shouldCollectPages:i,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let l=0;l<o;l++){let h=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(h),c.lastResult=h,c.lastInput=u,a.writePage(h),i)c.collectedPages.push(h);else if(s)for(let m of h.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,h);let f=n.nextInput(u,h);if(!f)break;u=f}return c}function Pd(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:a}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let i=a?r.collectedPages.map(s=>({...s,data:Me(s.data,a)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:i,meta:o}))}else{let i=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=a?Me(r.collectedRecords,a):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...i,...o}}))}}async function k(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:a,dumpMerge:i}=e,s=Math.max(1,Math.floor(e.multiplePages||1)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=zt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let l=Pa({dumpOutput:a,dumpMerge:i}),h;try{h=await Ed({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:l,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{l.close()}let f={pagesFetched:h.pagesFetched,totalRecords:h.totalRecords,hasMorePagesAvailable:h.hasMorePagesAvailable,dumpFile:l.mainPath??null};l.pickPath&&(f.dumpFilePick=l.pickPath),Pd({multiplePagesOutput:n,summaryMeta:f,state:h,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import hg from"yargs";import{hideBin as mg}from"yargs/helpers";import{writeFile as Dd,mkdirSync as Md}from"node:fs";import{join as er}from"node:path";import{homedir as wd}from"node:os";var It=["recruit","crm","desk","sign","analytics"],_d=new Set(["sign","analytics"]),Ne=new Set(["desk","analytics"]);function tr(){return er(wd(),".zoho-cli")}function bt(){return er(tr(),"config.json")}function kt(){return er(tr(),".tokens.json")}function ve(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function B(){let e=bt(),t=await Fe(e),o=ve("ACCOUNTS_CLIENT_ID"),r=ve("ACCOUNTS_CLIENT_SECRET"),n=ve("ACCOUNTS_REFRESH_TOKEN"),a=o&&r&&n,i;if(!t&&!a)i=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:ve("ACCOUNTS_URL")??t?.shared?.region,apiMode:ve("API_URL")??t?.shared?.apiMode},c=u=>{let l=u.toUpperCase(),h=ve("API_URL",l),f=Ne.has(u)?ve("ORG_ID",l):void 0,m=t?.[u],R=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_ID`],y=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_SECRET`],C=process.env[`ZOHO_${l}_ACCOUNTS_REFRESH_TOKEN`],g=R||y||C,S;return!m&&!g&&!f?S=void 0:S={clientId:R??m?.clientId,clientSecret:y??m?.clientSecret,refreshToken:C??m?.refreshToken,apiUrl:h??m?.apiUrl,orgId:f??m?.orgId},S};i={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,sign:c("sign")??t?.sign,analytics:c("analytics")??t?.analytics,output:t?.output}}return i}function Ue(e,t){let o=e[t],r=e.shared,n=!_d.has(t),a=o?.clientId??(n?r.clientId:void 0),i=o?.clientSecret??(n?r.clientSecret:void 0),s=o?.refreshToken??(n?r.refreshToken:void 0),c;return!a||!i||!s?c=void 0:c={clientId:a,clientSecret:i,refreshToken:s,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},c}async function vd(e){let t=bt();return Md(tr(),{recursive:!0}),new Promise((o,r)=>{Dd(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}function ot(e,t){return t==null?e??void 0:{...e,...Kn(t)}}async function ae(e){let t=await B(),o={shared:ot(t?.shared,e.shared),recruit:ot(t?.recruit,e.recruit),crm:ot(t?.crm,e.crm),desk:ot(t?.desk,e.desk),sign:ot(t?.sign,e.sign),analytics:ot(t?.analytics,e.analytics),output:e.output===void 0?t?.output:Qo(t?.output,e.output)};return await vd(o),o}async function Da(){await ae({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Ma(){let e=bt(),t=kt();await Zt(e),await Zt(t)}function ue(e){return It.filter(t=>{let o=Ue(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as mu,Injectable as Tm}from"@nestjs/common";function rt(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function J(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:la(o),per_page:n.maxItemsPerPage??r.per_page}}})}function oo(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 nt="Candidates",wa="Job_Openings",ro="Notes",_a="Emails",Ot="Attachments";function no(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=ao(o);break}default:break}return t}function ao(e){function t(i){let s;return typeof i=="object"?Array.isArray(i)?s=i.map(or):i&&(s=ao(i)):s=i,s}function o(i,s){return i.length>1?`(${i.join(s)})`:i[0]}function r(i,s){let c=ce(i.map(t)).flatMap(x);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,a=n;return e.and&&(a=r([r(e.and,"and"),n],"and")),a}var va=Wn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function or(e){let t=va(e.value);return`(${e.field}:${e.filter}:${t})`}var Na=no;import{BaseError as Bd}from"make-error";import{BaseError as Ud}from"make-error";var Ld="__internal_data_array_blank_error";function Gd(e){return Array.isArray(e?.data)}var st="success";function ie(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var be=class extends Ud{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},L=class extends be{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},at=class extends L{constructor(t,o){super({code:Ld,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function Q(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof at&&!o||(r instanceof L?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof be?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ee(e,t){return(o,r=t,n)=>async(a,i)=>{try{return await o(a,i)}catch(s){if(s instanceof Se){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function pe(e){return(t,o)=>{if(t?.error!=null){let n=new Se(o),a=e(t,n);if(a)throw a}return t}}var Kd="INTERNAL_ERROR",Vd="INVALID_TOKEN",G=class extends L{},Ua="FAILURE",rr=class extends L{},zd="4834",it=class extends L{},Jd="INVALID_QUERY",nr=class extends L{get details(){return this.error.details}},io="MANDATORY_NOT_FOUND",ke="DUPLICATE_DATA",so="INVALID_DATA",Hd="TOO_MANY_REQUESTS",ar=429,qd="X-RATELIMIT-LIMIT",Wd="X-RATELIMIT-REMAINING",jd="X-RATELIMIT-RESET",La=100,Ga=Re;function ir(e){let t=e.get(qd),o=e.get(Wd),r=e.get(jd),n=null;if(t!=null&&o!=null&&r!=null){let a=Number(t),i=Number(o),s=Number(r),c=new Date(s);n={limit:a,remaining:i,reset:s,resetAt:c}}return n}var Ce=class extends L{get headerDetails(){return ir(this.responseError.response.headers)}};function te(e,t){let o;if(Gd(e))o=new at(e,t);else{let r=Te(e,t);if(r){let n=ie(r);switch(n.code){case Kd:o=new rr(n,e,t);break;case Vd:o=new G(n,e,t);break;case zd:o=new it(n,e,t);break;case Jd:o=new nr(n,e,t);break;case Hd:o=new Ce(n,e,t);break;default:o=new L(n,e,t);break}}}return o}function Te(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var Ka="ALREADY_ASSOCIATED",sr=class extends Bd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},ct=class extends be{},cr=class extends ct{},ur=class extends ct{},co=class extends ct{get invalidFieldDetails(){return this.error.details}},pr=class extends co{};function Va(e){let t;switch(e.code){case so:{let o=new co(e);o.invalidFieldDetails.id?t=new pr(e):t=o;break}case io:t=new cr(e);break;case ke:t=new ur(e);break;default:t=new ct(e);break}return t}function za(e,t){return o=>{if(!o?.data?.length)throw new sr(e,t);return o}}var $d=Q("ZohoRecruit");async function Yd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ja(t,e)),o}function Ja(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var Ha=pe(Ja),qa=ee(Yd,$d);import{BaseError as Xd}from"make-error";function dr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,K(o,{data:x(r)})).then(a=>{let i=Array.isArray(r),s=le(x(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Va(l[0].result);c=u[0].result.details}return c}))}function Wa(e){return dr(e,"","POST")}function ja(e){return dr(e,"/upsert","POST")}function Ba(e){return dr(e,"","PUT")}function $a(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,K("DELETE")).then(Qd)}function Ya(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,K("GET")).then(za(t.module)).then(o=>o.data[0])}function Xa(e){return(t=>e.fetchJson(`/v2/${t.module}?${ii(t).toString()}`,K("GET")))}function hr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Na(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 ii(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,K("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Qa(e){return J(hr(e))}function ut(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${fr(n,n.filter).toString()}`,K("GET")).then(a=>a??(r===!1?a:rt()))}}function mr(e){return ut(e)({targetModule:_a})}function ei(e){return J(mr(e))}function yr(e){return ut(e)({targetModule:Ot})}function ti(e){return J(yr(e))}var zA=20*1024*1024;function oi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:a}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${Ot}?${T(i).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(a){let u=`${s}&${T({attachment_url:a}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function ri(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function ni(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"DELETE"})}var lr=class extends Xd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function ai(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v2/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?oo(t.apiUrl):""}${i}`;return e.fetchJson(c,K("POST")).then(u=>{if(u.code!=="success")throw new lr(u);return u.details})}}function ii(...e){return T(e,{omitKeys:"module"})}function fr(...e){return T(e,{omitKeys:["id","module"]})}function K(e,t){return{method:e,body:t??void 0}}function Qd(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===st?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function le(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===st?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function si(e){return t=>e.fetchJson(`/v2/${nt}/actions/associate`,K("PUT",{data:x(t)})).then(o=>{let r=o.data.map(()=>t),n=le(r,o.data),{included:a,excluded:i}=$e(n.errorItems,s=>s.result.code===Ua&&s.result.details.error[0].code===Ka);return{...n,errorItems:i,alreadyAssociatedErrorItems:a,allErrorItems:n.errorItems}})}function ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${fr(t).toString()}`,K("GET")).then(o=>o??rt())}function gr(e){let t=ci(e);return o=>t({...o,module:nt})}function ui(e){return J(gr(e))}function Rr(e,t=wa){let o=ci(e);return r=>o({...r,module:t})}function pi(e){return J(Rr(e))}function Cr(e){return t=>e.fetchJson(`/v2/${ro}`,K("POST",{data:t.data})).then(o=>le(x(t.data),o.data))}function li(e){return t=>e.fetchJson(`/v2/${ro}?${T({ids:t.ids})}`,K("DELETE")).then(o=>le(x(t.ids),o.data))}function Tr(e){return ut(e)({targetModule:ro})}function di(e){return J(Tr(e))}function hi(e){let t=Cr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:x(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function fi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,K("POST",{tags:x(t.tags)})).then(o=>{let r=le(x(t.tags),o.tags),{included:n,excluded:a}=$e(r.errorItems,i=>i.result.code===ke);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function gi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,K("GET")).then(o=>({...o,data:o.tags}))}var mi=100;function Ri(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>mi)throw new Error(`Cannot add tags to more than ${mi} records at once.`);return e.fetchJson(`/v2/${nt}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var yi=100;function Ci(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>yi)throw new Error(`Cannot remove tags from more than ${yi} records at once.`);return e.fetchJson(`/v2/${nt}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var eh="invalid_code",th="invalid_client",xr=class extends ne{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},pt=class extends ne{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},oh=Q("ZohoAccounts");async function rh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ti(t,e)),o}function Ti(e,t){let o,r=e.error;if(r){let n=ie(r);switch(n.code){case eh:case th:o=new xr(n.code);break;default:o=te(e,t);break}}return o}var xi=pe(Ti),Ai=ee(rh,oh);function de(e){return async()=>{let t=await e();if(!t.accessToken)throw new pt;return t.accessToken}}var nh=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 Et(e){let{readRateLimitDetails:t,enabledWithoutRateLimitDetails:o=!1}=e,r=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??nh,n=e.maxRateLimit??La,a=e.resetPeriod??Ga;function i(u,l){return{limit:u,startLimitAt:Math.ceil(u/10),cooldownRate:1.2*(u/(a/z)),exponentRate:1.08,maxWaitTime:z*10,resetPeriod:a,resetAt:l}}let s=i(n),c=ia(s);return Ca({rateLimiter:c,maxRetries:e.maxRetries,updateWithResponse:function(u,l){let h=t(u.headers),f=!1,m=o;if(h){let{remaining:R,limit:y,resetAt:C}=h;if(y!=null&&y!==n){let g=i(y,C??void 0);c.setConfig(g,!1)}if(c.setRemainingLimit(R),C&&c.setNextResetAt(C),m=!0,u.status===ar){f=!0;try{r?.(h,u,l)}catch{}}}else if(o&&u.status===ar){f=!0;try{r?.({remaining:0},u,l)}catch{}}return c.setEnabled(m),f}})}function xe(e){return Et({...e,readRateLimitDetails:Ar})}function Ar(e){let t=ir(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Zi(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=oo(i.apiUrl),c=a({apiUrl:s}),u=qa(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Ha,handleFetchJsonParseErrorFunction:$});return{recruitContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function uo(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 po="Notes",Si="Emails",Pt="Attachments";var Fi=no;import{BaseError as ah}from"make-error";var Zr=class extends ah{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},lt=class extends be{},Sr=class extends lt{},Fr=class extends lt{},lo=class extends lt{get invalidFieldDetails(){return this.error.details}},Ir=class extends lo{};function Ii(e){let t;switch(e.code){case so:{let o=new lo(e);o.invalidFieldDetails.api_name==="id"?t=new Ir(e):t=o;break}case io:t=new Sr(e);break;case ke:t=new Fr(e);break;default:t=new lt(e);break}return t}function bi(e,t){return o=>{if(!o?.data?.length)throw new Zr(e,t);return o}}var ih=Q("ZohoCrm",{logDataArrayErrors:!1});async function sh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ki(t,e)),o}function ki(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var Oi=pe(ki),Ei=ee(sh,ih);import{BaseError as ch}from"make-error";function kr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,H(o,{data:x(r)})).catch(Hi).then(a=>{let i=Array.isArray(r),s=Oe(x(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Ii(l[0].result);c=u[0].result.details}return c}))}function Pi(e){return kr(e,"","POST")}function Di(e){return kr(e,"/upsert","POST")}function Mi(e){return kr(e,"","PUT")}function wi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,H("DELETE")).catch(Hi).then(ph)}function _i(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,H("GET")).then(bi(t.module)).then(o=>o.data[0])}function vi(e){return(t=>e.fetchJson(`/v8/${t.module}?${Ji(t).toString()}`,H("GET")))}function Or(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Fi(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 Ji(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,H("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Ni(e){return J(Or(e))}function dt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${uh(n,n.filter).toString()}`,H("GET")).then(a=>a??(r===!1?a:rt()))}}function Er(e){let t=dt(e)({targetModule:Si});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Ui(e){return J(Er(e))}function Pr(e){return dt(e)({targetModule:Pt})}function Li(e){return J(Pr(e))}var oS=20*1024*1024;function Gi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let i=`/v8/${t.module}/${t.id}/${Pt}?${T(a).toString()}`,s=new FormData;return s.append("file",n),e.fetch(i,{method:"POST",headers:{"Content-Type":""},body:s})}}function Ki(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function Vi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"DELETE"})}var br=class extends ch{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function zi(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v8/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?uo(t.apiUrl):""}${i}`;return e.fetchJson(c,H("POST")).then(u=>{if(u.code!=="success")throw new br(u);return u.details})}}function Ji(...e){return T(e,{omitKeys:"module"})}function uh(...e){return T(e,{omitKeys:["id","module"]})}function H(e,t){return{method:e,body:t??void 0}}function Hi(e){let t;if(e instanceof at)t={data:e.errorDataArray};else throw e;return t}function ph(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===st?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function Oe(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===st?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function Dr(e){return t=>e.fetchJson(`/v2/${po}`,H("POST",{data:t.data})).then(o=>Oe(x(t.data),o.data))}function qi(e){return t=>e.fetchJson(`/v2/${po}?${T({ids:t.ids})}`,H("DELETE")).then(o=>Oe(x(t.ids),o.data))}function Mr(e){return dt(e)({targetModule:po})}function Wi(e){return J(Mr(e))}function ji(e){let t=Dr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:x(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function $i(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,H("POST",{tags:x(t.tags)})).catch(o=>{let r;if(o instanceof L){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Oe(x(t.tags),o.tags),{included:n,excluded:a}=$e(r.errorItems,i=>i.result.code===ke);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Yi(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,H("DELETE")).then(o=>o.tags)}function Xi(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,H("GET")).then(o=>({...o,data:o.tags}))}var Bi=100;function Qi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function es(e){if(Array.isArray(e.ids)&&e.ids.length>Bi)throw new Error(`Cannot add/remove tags from more than ${Bi} records at once.`);let t=[...x(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&x(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:x(e.ids)}}function ts(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function os(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=uo(i.apiUrl),c=a({apiUrl:s}),u=Ei(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Oi,handleFetchJsonParseErrorFunction:$});return{crmContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var rs="https://signsandbox.zoho.com/api/v1",lh="https://sign.zoho.com/api/v1";function wr(e){let t;switch(e){case"sandbox":t=rs;break;case"production":t=lh;break;default:t=e;break}return t}function ns(e){let t=wr(e),o;try{o=new URL(t).hostname!==new URL(rs).hostname}catch{o=!0}return o}function as(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 i=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??i?.row_count??20,c=(i?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function he(e,t){return{method:e,body:t??void 0}}function is(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,he("GET"))}function _r(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)}},he("GET"))}}function ss(e){let t=_r(e);return as(t)}function cs(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,he("GET"))}function us(e){return()=>e.fetchJson("/fieldtypes",he("GET"))}function ps(e){return({requestId:t,...o})=>{let n=T(o).toString(),a=n?`?${n}`:"",i=`/requests/${t}/pdf${a}`;return e.fetch(i,{method:"GET"})}}function ls(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function ds(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 hs(e){return({templateId:t,data:o,isQuickSend:r=!0})=>{let n=T({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 ms(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,he("GET"))}function ys(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)}},he("GET"))}}function fs(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,he("PUT",{requests:o}))}function gs(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,he("POST",r))}}function Rs(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,he("PUT",{expire_by:o}))}function Cs(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let a=T(n),i=a.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...i?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()}:{}})}}function Ts(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ns(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}},he("POST"))}}var dh=Q("ZohoSign",{logDataArrayErrors:!1});async function hh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=xs(t,e)),o}function xs(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var As=pe(xs),Zs=ee(hh,dh);function Ss(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=wr(i.apiUrl),c=a({apiUrl:s}),u=Zs(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:As,handleFetchJsonParseErrorFunction:$});return{signContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Fs(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var mh=Q("ZohoDesk",{logDataArrayErrors:!1});async function yh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Is(t,e)),o}function Is(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var bs=pe(Is),ks=ee(yh,mh);var fh="X-Rate-Limit-Remaining-v3",gh="Retry-After",Rh=200;function Ch(e){let t=e.get(fh),o;if(t!=null){let r=Number(t),n,a=e.get(gh);if(a!=null){let i=Number(a);Number.isNaN(i)||(n=new Date(Date.now()+i*z))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Os(e){return Et({maxRateLimit:Rh,...e,readRateLimitDetails:Ch})}function Es(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Os(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:i.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!i.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=Fs(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=ks(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:bs,handleFetchJsonParseErrorFunction:$});return{deskContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ps=25;function se(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ps}},buildInputForNextPage:function(o,r,n){let a=n.maxItemsPerPage??r.limit??Ps,s=(r.from??1)+a;return{...r,from:s,limit:a}}})}function Le(e,t){return{method:e,body:t??void 0}}function ht(e,t){return T(e,{omitKeys:t})}function ho(e){let t;return e&&(t=P(x(e))),t}function vr(e){return t=>{let{include:o,...r}=t,n=ht([{...r,include:ho(o)}]);return e.fetchJson(`/tickets?${n}`,Le("GET")).then(a=>a??{data:[]})}}function Ds(e){return t=>{let{ticketId:o,include:r}=t,a=ht([{include:ho(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/tickets/${o}${i}`,Le("GET"))}}function Nr(e){return t=>{let o=ht([t]);return e.fetchJson(`/tickets/search?${o}`,Le("GET")).then(r=>r??{data:[]})}}function Ms(e){return t=>{let{contactId:o,include:r,...n}=t,a=ht([{...n,include:ho(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${a}`,Le("GET")).then(i=>i??{data:[]})}}function ws(e){return t=>{let{productId:o,include:r,...n}=t,a=ht([{...n,include:ho(r)}]);return e.fetchJson(`/products/${o}/tickets?${a}`,Le("GET")).then(i=>i??{data:[]})}}function _s(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Le("GET"))}function vs(e){return t=>{let o=ht([{agentIds:P(x(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Le("GET"))}}function Ns(e){return se(vr(e))}function Us(e){return se(Nr(e))}function Ls(e){return{method:e}}function Gs(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Ls("GET")).then(r=>r??{data:[]})}}function Ks(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ls("GET"))}function Ur(e){return{method:e}}function Vs(e){let t;return e&&(t=P(x(e))),t}function Lr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Vs(o)}]);return e.fetchJson(`/contacts?${n}`,Ur("GET")).then(a=>a??{data:[]})}}function zs(e){return t=>{let{contactId:o,include:r}=t,a=T([{include:Vs(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/contacts/${o}${i}`,Ur("GET"))}}function Js(e){return t=>{let o=T([{contactIds:P(x(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Ur("GET")).then(r=>r??[])}}function Hs(e){return se(Lr(e))}function Dt(e,t){return{method:e,body:t??void 0}}function qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("GET")).then(o=>o??[])}function Ws(e){return t=>{let o={tags:x(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("POST",o)).then(r=>r??[])}}function js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Dt("DELETE"))}function Bs(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function $s(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function Gr(e,t){return{method:e,body:t??void 0}}function Ys(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("GET")).then(o=>o??[])}function Xs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("POST",o))}}function Qs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("DELETE",o))}}function ec(e,t){return{method:e,body:t??void 0}}function Th(e){let t;return e&&(t=P(x(e))),t}function tc(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:Th(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${a}`,ec("GET")).then(i=>i??{data:[]})}}function oc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,ec("DELETE"))}function mo(e,t){return{method:e,body:t??void 0}}function rc(e){let t;return e&&(t=P(x(e))),t}function nc(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:rc(r)}]);return e.fetchJson(`/tickets/${o}/comments?${a}`,mo("GET")).then(i=>i??{data:[]})}}function ac(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,i=T([{include:rc(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,mo("GET"))}}function ic(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,mo("POST",r))}}function sc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,mo("DELETE"))}function Mt(e,t){return{method:e,body:t??void 0}}function cc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Mt("GET"))}function uc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Mt("POST",r))}}function pc(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Mt("GET")).then(a=>a??{data:[]})}}function lc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Mt("GET"))}function dc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Mt("GET"))}function hc(e){return{method:e}}function mc(e){let t;return e&&(t=P(x(e))),t}function Kr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:mc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${a}`,hc("GET")).then(i=>i??{data:[]})}}function yc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,i=T([{include:mc(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,hc("GET"))}}function fc(e){return se(Kr(e))}function xh(e){return{method:e}}function Ah(e){let t;return e&&(t=P(x(e))),t}function Vr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:Ah(r)}]);return e.fetchJson(`/tickets/${o}/activities?${a}`,xh("GET")).then(i=>i??{data:[]})}}function gc(e){return se(Vr(e))}function yo(e){return{method:e}}function Rc(e){let t;return e&&(t=P(x(e))),t}function zr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Rc(o)}]);return e.fetchJson(`/agents?${n}`,yo("GET")).then(a=>a??{data:[]})}}function Cc(e){return t=>{let{agentId:o,include:r}=t,a=T([{include:Rc(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/agents/${o}${i}`,yo("GET"))}}function Tc(e){return t=>{let o=T([{agentIds:P(x(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,yo("GET")).then(r=>r?.data??[])}}function xc(e){return()=>e.fetchJson("/myinfo",yo("GET"))}function Ac(e){return se(zr(e))}var Zh="https://accounts.zoho.com",Sh="https://accounts.zoho.eu",Fh="https://accounts.zoho.in",Ih="https://accounts.zoho.com.au",bh="https://accounts.zoho.jp",kh="https://accounts.zoho.uk",Oh="https://accounts.zohocloud.ca",Eh="https://accounts.zoho.sa",Ph={us:Zh,eu:Sh,in:Fh,au:Ih,jp:bh,uk:kh,ca:Oh,sa:Eh};function Ge(e){return Ph[e]??e}var fo="/oauth/v2/token";function go(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:a,refreshToken:i}=t??{},s=a?.clientId??o,c=a?.clientSecret??r,l=T({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:i??n});return e.fetchJson(`${fo}?${l}`,Jr("POST"))}}function Zc(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,refreshToken:a}=t,i=n?.clientId??o,s=n?.clientSecret??r,c=T({grant_type:"refresh_token",client_id:i,client_secret:s,refresh_token:a});return e.fetchJson(`${fo}?${c}`,Jr("POST"))}}function Sc(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,code:a,redirectUri:i}=t,s=n?.clientId??o,c=n?.clientSecret??r,u=T({grant_type:"authorization_code",client_id:s,client_secret:c,code:a,redirect_uri:i});return e.fetchJson(`${fo}?${u}`,Jr("POST"))}}var Dh="/oauth/user/info";function Fc(e){return t=>e.fetchJson(Dh,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Jr(e,t){return{method:e,body:t}}function Ic(e){return t=>X.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function bc(e,t){let o=Ai(e,t),r=Y(o,{interceptJsonResponse:xi,handleFetchJsonParseErrorFunction:$});return{fetch:o,fetchJson:r}}function kc(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(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 a=Ge(n.apiUrl??"us"),i=r({apiUrl:a}),{fetch:s,fetchJson:c}=bc(i,o),u=async()=>{let m=Date.now(),{access_token:R,api_domain:y,scope:C,expires_in:g}=await go(h)();return{accessToken:R,apiDomain:y,expiresIn:g,expiresAt:new Date(m+g*z),scope:C}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let l=Mh({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),h={fetch:s,fetchJson:c,loadAccessToken:l,config:{...n,apiUrl:a}};return{accountsContext:h}}}function Oc(e){let t=e.fetchHandler??xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(t)}=e;return n=>{if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsOAuthClientConfig missing clientSecret.")}else throw new Error("ZohoAccountsOAuthClientConfig missing clientId.");let a=Ge(n.apiUrl??"us"),i=r({apiUrl:a}),{fetchJson:s}=bc(i,o),c={...n,apiUrl:a};return{oauthClientContext:{fetchJson:s,config:c}}}}function Mh(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Re,a=null,i=async()=>{a=null},s=async()=>{if(!a){let c=await o?.loadCachedToken();c&&(a=c)}if(a!=null&&Date.now()+n>=a.expiresAt.getTime()&&(a=null),!a){try{a=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new pt("Token Refresh Failed")}try{await o?.updateCachedToken(a)}catch{}}return a};return s.resetAccessToken=i,s}var Ec="ZANALYTICS-ORGID";function Pc(e){let t;switch(e){case"sandbox":case"production":t="https://analyticsapi.zoho.com/restapi/v2";break;default:t=e;break}return t}var wh="CONFIG",_h="application/x-www-form-urlencoded";function Dc(e){return e==null?"":T({[wh]:JSON.stringify(e)}).toString()}function Ee(e){let t=Dc(e);return t?`?${t}`:""}function V(e,t){return{method:e,body:t??void 0}}function Ro(e,t){return{method:e,headers:{"Content-Type":_h},body:Dc(t)}}var vh="failure",Nh="8535",Uh="8083",Lh="6045",Gh=["6043","6044"],Hr=class extends L{};function Mc(e){return e?.status===vh}function Kh(e){let{summary:t,data:o}=e,r=o?.errorCode;return{code:r==null?t??"":String(r),message:o?.errorMessage??t??"",details:{summary:t}}}function wc(e,t){let o;if(Mc(e)){let r=Kh(e),n={error:r};switch(r.code){case Nh:o=new G(r,n,t);break;case Uh:o=new Hr(r,n,t);break;case Lh:o=new Ce(r,n,t);break;default:o=Gh.includes(r.code)?new Ce(r,n,t):new L(r,n,t);break}}else o=te(e,t);return o}var Vh=Q("ZohoAnalytics",{logDataArrayErrors:!1});async function zh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=wc(t,e)),o}var _c=(e,t)=>{if(Mc(e)){let o=wc(e,new Se(t));if(o)throw o}return e},vc=ee(zh,Vh);var Jh=100;var Hh=Re;function Nc(e){return Et({maxRateLimit:Jh,resetPeriod:Hh,...e,readRateLimitDetails:Ar,enabledWithoutRateLimitDetails:!0})}var qh="1001",Wh="1002";var jh="1004";var Bh=z*2,$h=150;function Yh(e){return e===qh||e===Wh}function Pe(e){return e===jh}function Co(e){let{loadJob:t,readJobCode:o,pollWait:r=Bh,maxPolls:n=$h}=e;return na({next:async a=>(a>0&&await At(r),t()),checkContinue:(a,i)=>a!=null&&Yh(o(a))&&i<n})}var Xh=65279;function Qh(e,t){let o=e.codePointAt(0)===Xh?e.slice(1):e,r=[],n=[],a="",i=!1,s=!1,c=0;for(;c<o.length;){let u=o[c];i?u==='"'?o[c+1]==='"'?(a+='"',c+=2):(i=!1,c+=1):(a+=u,c+=1):u==='"'&&a===""?(i=!0,s=!0,c+=1):u===t?(n.push(a),a="",s=!0,c+=1):u===`
|
|
9
|
-
`||u==="\r"?(n.push(
|
|
10
|
-
`?2:1):(a+=u,s=!0,c+=1)}return(s||a!==""||n.length>0)&&(n.push(a),r.push(n)),r}function em(e,t){let o=Qh(e,t??","),[r,...n]=o,a;if(r==null)a={columnNames:[],rows:[]};else{let i=r.map(c=>c.trim()),s=n.map(c=>{let u={};return i.forEach((l,h)=>{l!==""&&(u[l]=c[h]??"")}),u});a={columnNames:Uo(i.filter(c=>c!=="")),rows:s}}return a}function tm(e){let t;try{t=JSON.parse(e)}catch(a){throw new Error(`zohoAnalyticsRowDataFromJson(): the content is not valid JSON. ${a.message}`,{cause:a})}let o=a=>a!=null&&typeof a=="object"&&!Array.isArray(a),r=Array.isArray(t)?t:[t];if(!r.every(o))throw new Error("zohoAnalyticsRowDataFromJson(): the content must be an array of row objects, as a Zoho Analytics JSON import is.");let n=r;return{columnNames:Uo(n.flatMap(a=>Object.keys(a))),rows:n}}function Uc(e){let{content:t,fileType:o,delimiter:r}=e;return o==="json"?tm(t):em(t,r)}var om=3,rm=/[\s,%$£€¥]/g,nm=new Set(["true","false","yes","no","y","n","t","f","1","0"]),am=/^[\d\s/.:+-]+$/,im=new Set(["PLAIN","MULTI_LINE","EMAIL","URL"]);function qr(e){return e==null?"":String(e).trim()}var sm=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,cm=/^www\./i;function mt(e){let{text:t,allowNegative:o,allowFraction:r}=e,n=Number(t.replaceAll(rm,"")),a;return Number.isFinite(n)?!o&&n<0?a="negative":!r&&!Number.isInteger(n)&&(a="notAnInteger"):a="notANumber",a}var um={NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),AUTO_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),POSITIVE_NUMBER:e=>mt({text:e,allowNegative:!1,allowFraction:!1}),DECIMAL_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),CURRENCY:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),PERCENT:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),DATE:e=>Number.isNaN(Date.parse(e))&&!am.test(e)?"notADate":void 0,BOOLEAN:e=>nm.has(e.toLowerCase())?void 0:"notABoolean",EMAIL:e=>sm.test(e)?void 0:"notAnEmail",URL:e=>URL.canParse(e)||cm.test(e)?void 0:"notAUrl"};function pm(e,t,o){let r=o==null||im.has(o);return t.columnMaxSize!=null&&e.length>t.columnMaxSize&&r}function lm(e,t){let o=qr(e),r=t.dataType?.toUpperCase(),n;return o===""?n=t.isNullable===!1&&t.defaultValue==null?"emptyInNonNullable":void 0:pm(o,t,r)?n="tooLong":n=r==null?void 0:um[r]?.(o),n}function dm(e,t){return`${e}\0${t}`}function Lc(e){let{columns:t,columnNames:o,rows:r,maxSamples:n}=e,a=n??om,i=new Map(t.map(g=>[g.columnName,g])),s=new Map(t.map(g=>[g.columnName.trim().toLowerCase(),g.columnName])),c=new Set(o),u=[],l=[],h=[],f=new Set;o.forEach(g=>{let S=s.get(g.trim().toLowerCase());i.has(g)?u.push(g):S==null?l.push(g):(h.push({dataColumnName:g,tableColumnName:S}),f.add(S))});let m=l.map(g=>({columnName:g,valueCount:r.reduce((S,O)=>qr(O[g])===""?S:S+1,0)})),R=t.filter(g=>!c.has(g.columnName)&&!f.has(g.columnName)).map(g=>({columnName:g.columnName,dataType:g.dataType,isNullable:g.isNullable,required:g.isNullable===!1&&g.defaultValue==null})),y=new Map;r.forEach((g,S)=>{u.forEach(O=>{let q=i.get(O),I=lm(g[O],q);if(I!=null){let _=dm(O,I),v=y.get(_);if(v==null){let W=[];v={conflict:{columnName:O,dataType:q.dataType,reason:I,conflictCount:0,samples:W},count:0,samples:W},y.set(_,v)}v.count+=1,v.samples.length<a&&v.samples.push({row:S+1,value:qr(g[O])})}})});let C=Array.from(y.values()).map(g=>({...g.conflict,conflictCount:g.count}));return{matchedColumns:u,droppedColumns:m,emptyColumns:R,caseMismatchedColumns:h,conflicts:C,rowCount:r.length}}function Gc(e,t){let o=t?.strict?e.emptyColumns.length:e.emptyColumns.filter(r=>r.required).length;return e.droppedColumns.length===0&&e.caseMismatchedColumns.length===0&&e.conflicts.length===0&&o===0}function Kc(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Nc(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Zoho-oauthtoken ${await o()}`,...i.orgId?{[Ec]:i.orgId}:void 0}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoAnalyticsConfig missing api url.");let s=Pc(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=vc(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:_c,handleFetchJsonParseErrorFunction:$});return{analyticsContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Vc(e){return()=>e.fetchJson("/orgs",V("GET"))}function zc(e){return()=>e.fetchJson("/workspaces",V("GET"))}function Jc(e){return()=>e.fetchJson("/workspaces/owned",V("GET"))}function Hc(e){return()=>e.fetchJson("/workspaces/shared",V("GET"))}function qc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("GET"))}function Wc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views`,V("GET"))}function jc(e){return t=>e.fetchJson(`/views/${t.viewId}`,V("GET"))}function Bc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/metadata`,V("GET"))}var hm="import";function mm(e,t){let{file:o,data:r,rows:n}=e,a=new FormData;if(o!=null)a.append("FILE",o);else{if(r==null&&n==null)throw new Error("zohoAnalyticsImportFormData(): one of file, data, or rows must be provided.");{let i=r??JSON.stringify(n);if(t?.asFile){let s=t.fileType??(n==null?"csv":"json");a.append("FILE",new File([i],`${hm}.${s}`,{type:s==="json"?"application/json":"text/csv"}))}else a.append("DATA",i)}}return a}function Wr(e,t){let{file:o,rows:r}=e,n=t;if(n==null){if(r!=null)n="json";else if(o!=null){let a=o.name.split(".").pop()?.toLowerCase();n=a==="json"||a==="csv"?a:void 0}}return n}function To(e){return e??!0}function $c(e,t){let o=Wr(e,t);if(o==null)throw new Error("zohoAnalyticsCreateImportJob(): config.fileType is required for an async import job when the data is not rows or a file with a .csv/.json name.");return o}async function xo(e){let{context:t,url:o,config:r,dataInput:n,formDataOptions:a}=e,i=mm(n,a);return(await t.fetch(`${o}${Ee(r)}`,{method:"POST",headers:{"Content-Type":""},body:i})).json()}function Yc(e){return t=>{let{workspaceId:o,viewId:r,config:n,...a}=t,i={...n,autoIdentify:To(n.autoIdentify),fileType:Wr(a,n.fileType)};return xo({context:e,url:`/workspaces/${o}/views/${r}/data`,config:i,dataInput:a})}}function Xc(e){return t=>{let{workspaceId:o,config:r,...n}=t,a={...r,autoIdentify:To(r.autoIdentify),fileType:Wr(n,r.fileType)};return xo({context:e,url:`/workspaces/${o}/data`,config:a,dataInput:n})}}function jr(e){return t=>{let{workspaceId:o,viewId:r,config:n,...a}=t,i=$c(a,n.fileType),s={...n,autoIdentify:To(n.autoIdentify),fileType:i};return xo({context:e,url:`/bulk/workspaces/${o}/views/${r}/data`,config:s,dataInput:a,formDataOptions:{asFile:!0,fileType:i}})}}function Qc(e){return t=>{let{workspaceId:o,config:r,...n}=t,a=$c(n,r.fileType),i={...r,autoIdentify:To(r.autoIdentify),fileType:a};return xo({context:e,url:`/bulk/workspaces/${o}/data`,config:i,dataInput:n,formDataOptions:{asFile:!0,fileType:a}})}}function Br(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/importjobs/${t.jobId}`,{method:"GET"})}function eu(e){let t=jr(e),o=Br(e);return async r=>{let{poll:n,...a}=r,{data:i}=await t(a);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:i.jobId}),readJobCode:s=>s.data.jobCode})}}function tu(e){return t=>e.fetch(`/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,{method:"GET"})}function $r(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,V("GET"))}function ou(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/data${Ee(t.config)}`,V("GET"))}function Yr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}`,V("GET"))}function ru(e){return t=>e.fetch(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}/data`,{method:"GET"})}function nu(e){let t=$r(e),o=Yr(e);return async r=>{let{poll:n,...a}=r,{data:i}=await t(a);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:i.jobId}),readJobCode:s=>s.data.jobCode})}}function au(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("POST",t.config))}function iu(e){return t=>{let{criteria:o,updateAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsUpdateRows(): either criteria or updateAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("PUT",t.config))}}function su(e){return t=>{let{criteria:o,deleteAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsDeleteRows(): either criteria or deleteAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("DELETE",t.config))}}function cu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}${Ee(t.config)}`,V("DELETE"))}function uu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("DELETE"))}function me(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Ae=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 ym}from"@nestjs/common";var yt=class{};yt=F([ym()],yt);function fm(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Ln(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function gm(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Rm(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function lu(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Rm;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(a){let i=o.map(u=>u.loadZohoAccessTokenCache(a)),s=i.map(fm),c=qn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let l=await Promise.allSettled(i.map(h=>gm(h,u)));if(r!=null){let h=ce(l.map(f=>f.value));h.length&&r(h)}},clearCachedToken:async()=>{await Promise.allSettled(i.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function du(e,t){let o={};if(e!=null)for(let a of Object.keys(e)){let i=e[a];i!=null&&(o[a]=i)}let r=Jn(o);function n(a){return{loadCachedToken:async()=>{let i=await r.get(a);return t&&console.log("retrieving access token from memory: ",{service:a,hit:i!=null,expiresAt:i?.expiresAt}),i},updateCachedToken:async i=>{await r.set(a,i),t&&console.log("updating access token in memory: ",{service:a,expiresAt:i?.expiresAt})},clearCachedToken:async()=>{await r.remove(a),t&&console.log("clearing access token in memory: ",{service:a})}}}return{loadZohoAccessTokenCache:n}}var Cm=".tmp/zoho-access-tokens.json";function pu(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 hu(e=Cm,t=!0){let o=Ia({filePath:e,reviver:pu}),r=t?Hn(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(l){console.error("Failed updating access token in file: ",l)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function a(){let c=await Fe(e),u;if(c==null)u=void 0;else{let l={};for(let h of Object.keys(c))l[h]=pu(c[h]);u=l}return u}async function i(c){await r.clear();for(let[u,l]of Object.entries(c))l!=null&&await r.set(u,l)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:a,writeTokenFile:i,deleteTokenFile:s}}var w=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=kc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return go(this.accountsContext)}};w=F([Tm(),b(0,mu(Ae)),b(1,mu(yt))],w);import{Inject as Zm,Injectable as Sm}from"@nestjs/common";var xm="ZOHO_ACCOUNTS_CLIENT_ID",Am="ZOHO_ACCOUNTS_CLIENT_SECRET",ft=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 (${xm}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${Am}).`)}};var _t=class{constructor(t){this.config=t;ft.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=Ge(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Oc(t.factoryConfig??{})}_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=Ge(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,a=this.oauthClientContextForApiUrl(n??this.apiUrl);return Sc(a)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Zc(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Fc(n)({accessToken:o})}};_t=F([Sm(),b(0,Zm(ft))],_t);import{ConfigModule as Ek,ConfigService as Pk}from"@nestjs/config";import{Inject as yu,Injectable as Fm}from"@nestjs/common";var vt=class{zohoCrm;factoryConfig;static assertValidConfig(t){me(t.zohoCrm)}};var Ke=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=os({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Pi(this.crmContext)}get upsertRecord(){return Di(this.crmContext)}get updateRecord(){return Mi(this.crmContext)}get deleteRecord(){return wi(this.crmContext)}get getRecordById(){return _i(this.crmContext)}get getRecords(){return vi(this.crmContext)}get searchRecords(){return Or(this.crmContext)}get searchRecordsPageFactory(){return Ni(this.crmContext)}get getRelatedRecordsFunctionFactory(){return dt(this.crmContext)}get getEmailsForRecord(){return Er(this.crmContext)}get getEmailsForRecordPageFactory(){return Ui(this.crmContext)}get getAttachmentsForRecord(){return Pr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Li(this.crmContext)}get uploadAttachmentForRecord(){return Gi(this.crmContext)}get downloadAttachmentForRecord(){return Ki(this.crmContext)}get deleteAttachmentFromRecord(){return Vi(this.crmContext)}get createNotes(){return Dr(this.crmContext)}get deleteNotes(){return qi(this.crmContext)}get createNotesForRecord(){return ji(this.crmContext)}get getNotesForRecord(){return Mr(this.crmContext)}get getNotesForRecordPageFactory(){return Wi(this.crmContext)}get executeRestApiFunction(){return zi(this.crmContext)}get createTagsForModule(){return $i(this.crmContext)}get deleteTag(){return Yi(this.crmContext)}get getTagsForModule(){return Xi(this.crmContext)}get addTagsToRecords(){return Qi(this.crmContext)}get removeTagsFromRecords(){return ts(this.crmContext)}};Ke=F([Fm(),b(0,yu(vt)),b(1,yu(w))],Ke);import{ConfigModule as Xk,ConfigService as Qk}from"@nestjs/config";import{Inject as fu,Injectable as Im}from"@nestjs/common";var Nt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){me(t.zohoRecruit)}};var Ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Zi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Wa(this.recruitContext)}get upsertRecord(){return ja(this.recruitContext)}get updateRecord(){return Ba(this.recruitContext)}get deleteRecord(){return $a(this.recruitContext)}get getRecordById(){return Ya(this.recruitContext)}get getRecords(){return Xa(this.recruitContext)}get searchRecords(){return hr(this.recruitContext)}get searchRecordsPageFactory(){return Qa(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ut(this.recruitContext)}get getEmailsForRecord(){return mr(this.recruitContext)}get getEmailsForRecordPageFactory(){return ei(this.recruitContext)}get getAttachmentsForRecord(){return yr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return ti(this.recruitContext)}get uploadAttachmentForRecord(){return oi(this.recruitContext)}get downloadAttachmentForRecord(){return ri(this.recruitContext)}get deleteAttachmentFromRecord(){return ni(this.recruitContext)}get createNotes(){return Cr(this.recruitContext)}get deleteNotes(){return li(this.recruitContext)}get createNotesForRecord(){return hi(this.recruitContext)}get getNotesForRecord(){return Tr(this.recruitContext)}get getNotesForRecordPageFactory(){return di(this.recruitContext)}get executeRestApiFunction(){return ai(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return si(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return gr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return ui(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Rr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return pi(this.recruitContext)}get createTagsForModule(){return fi(this.recruitContext)}get getTagsForModule(){return gi(this.recruitContext)}get addTagsToRecords(){return Ri(this.recruitContext)}get removeTagsFromRecords(){return Ci(this.recruitContext)}};Ve=F([Im(),b(0,fu(Nt)),b(1,fu(w))],Ve);import{ConfigModule as xO,ConfigService as AO}from"@nestjs/config";import{Inject as gu,Injectable as bm}from"@nestjs/common";var Ut=class{zohoSign;factoryConfig;static assertValidConfig(t){me(t.zohoSign)}};var ze=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ss({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return is(this.signContext)}get getDocuments(){return _r(this.signContext)}get getDocumentsPageFactory(){return ss(this.signContext)}get getDocumentFormData(){return cs(this.signContext)}get retrieveFieldTypes(){return us(this.signContext)}get downloadPdf(){return ps(this.signContext)}get downloadCompletionCertificate(){return ls(this.signContext)}get createDocument(){return ds(this.signContext)}get createDocumentFromTemplate(){return hs(this.signContext)}get getTemplate(){return ms(this.signContext)}get getTemplates(){return ys(this.signContext)}get updateDocument(){return fs(this.signContext)}get sendDocumentForSignature(){return gs(this.signContext)}get extendDocument(){return Rs(this.signContext)}get deleteDocument(){return Cs(this.signContext)}get getEmbeddedSigningUrl(){return Ts(this.signContext)}};ze=F([bm(),b(0,gu(Ut)),b(1,gu(w))],ze);import{ConfigModule as JO,ConfigService as HO}from"@nestjs/config";function Ru(e){return{...e,operationType:e.notifications.operation_type}}var Cu=sa(e=>e.operationType),Tu=ua({configurerForAccessor:e=>{let t=ca(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 xu="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Je=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as wm,Inject as _m,Post as vm,Req as Nm}from"@nestjs/common";import{Inject as Pm,Injectable as Dm,Logger as Mm}from"@nestjs/common";import{createHmac as km,timingSafeEqual as Om}from"node:crypto";var Em="x-zs-webhook-signature";function Au(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Em],a={valid:!1};if(n){let i=r.toString("utf-8"),s=km("sha256",t).update(i,"utf-8").digest("base64"),c=!1;try{let l=Buffer.from(n,"base64"),h=Buffer.from(s,"base64");l.length===h.length&&(c=Om(l,h))}catch{c=!1}let u;if(c)try{let l=JSON.parse(i);u=Ru(l)}catch{c=!1}c&&u&&(a={valid:!0,event:u})}return a}}var Ze=class{logger=new Mm("ZohoSignWebhookService");_verifier;handler=Cu();configure=Tu(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Au({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)}};Ze=F([Dm(),b(0,Pm(Je))],Ze);var He=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([vm(),b(0,Nm()),b(1,Aa())],He.prototype,"handleZohoSignWebhook",1),He=F([wm("/webhook/zoho/sign"),b(0,_m(Ze))],He);import{Module as Um}from"@nestjs/common";import{ConfigModule as Lm,ConfigService as Gm}from"@nestjs/config";function Km(e){let t={zohoSignWebhook:{webhookSecret:e.get(xu)}};return Je.assertValidConfig(t),t}var So=class{};So=F([Um({imports:[Lm],controllers:[He],providers:[{provide:Je,inject:[Gm],useFactory:Km},Ze],exports:[Ze]})],So);import{Inject as Zu,Injectable as Vm}from"@nestjs/common";var Lt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(me(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var qe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Es({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return vr(this.deskContext)}get getTicketById(){return Ds(this.deskContext)}get searchTickets(){return Nr(this.deskContext)}get getTicketsForContact(){return Ms(this.deskContext)}get getTicketsForProduct(){return ws(this.deskContext)}get getTicketMetrics(){return _s(this.deskContext)}get getAgentsTicketsCount(){return vs(this.deskContext)}get getTicketsPageFactory(){return Ns(this.deskContext)}get searchTicketsPageFactory(){return Us(this.deskContext)}get getDepartments(){return Gs(this.deskContext)}get getDepartmentById(){return Ks(this.deskContext)}get getContacts(){return Lr(this.deskContext)}get getContactById(){return zs(this.deskContext)}get getContactsByIds(){return Js(this.deskContext)}get getContactsPageFactory(){return Hs(this.deskContext)}get getTicketTags(){return qs(this.deskContext)}get associateTicketTags(){return Ws(this.deskContext)}get dissociateTicketTag(){return js(this.deskContext)}get searchTags(){return Bs(this.deskContext)}get getAllTags(){return $s(this.deskContext)}get getTicketFollowers(){return Ys(this.deskContext)}get addTicketFollowers(){return Xs(this.deskContext)}get removeTicketFollowers(){return Qs(this.deskContext)}get getTicketAttachments(){return tc(this.deskContext)}get deleteTicketAttachment(){return oc(this.deskContext)}get getTicketComments(){return nc(this.deskContext)}get getTicketCommentById(){return ac(this.deskContext)}get createTicketComment(){return ic(this.deskContext)}get deleteTicketComment(){return sc(this.deskContext)}get getTicketTimer(){return cc(this.deskContext)}get performTicketTimerAction(){return uc(this.deskContext)}get getTicketTimeEntries(){return pc(this.deskContext)}get getTicketTimeEntryById(){return lc(this.deskContext)}get getTicketTimeEntrySummation(){return dc(this.deskContext)}get getTicketThreads(){return Kr(this.deskContext)}get getTicketThreadById(){return yc(this.deskContext)}get getTicketThreadsPageFactory(){return fc(this.deskContext)}get getTicketActivities(){return Vr(this.deskContext)}get getTicketActivitiesPageFactory(){return gc(this.deskContext)}get getAgents(){return zr(this.deskContext)}get getAgentById(){return Cc(this.deskContext)}get getAgentsByIds(){return Tc(this.deskContext)}get getMyInfo(){return xc(this.deskContext)}get getAgentsPageFactory(){return Ac(this.deskContext)}};qe=F([Vm(),b(0,Zu(Lt)),b(1,Zu(w))],qe);import{ConfigModule as HE,ConfigService as qE}from"@nestjs/config";import{Inject as Su,Injectable as zm}from"@nestjs/common";var Gt=class{zohoAnalytics;factoryConfig;static assertValidConfig(t){me(t.zohoAnalytics)}};var We=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoAnalytics=Kc({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoAnalytics)}zohoAnalytics;get analyticsContext(){return this.zohoAnalytics.analyticsContext}get zohoRateLimiter(){return this.zohoAnalytics.analyticsContext.zohoRateLimiter}get getOrgs(){return Vc(this.analyticsContext)}get getAllWorkspaces(){return zc(this.analyticsContext)}get getOwnedWorkspaces(){return Jc(this.analyticsContext)}get getSharedWorkspaces(){return Hc(this.analyticsContext)}get getWorkspaceDetails(){return qc(this.analyticsContext)}get getViews(){return Wc(this.analyticsContext)}get getViewDetails(){return jc(this.analyticsContext)}get getTableMetadata(){return Bc(this.analyticsContext)}get importDataInTable(){return Yc(this.analyticsContext)}get importDataInNewTable(){return Xc(this.analyticsContext)}get createImportJobInTable(){return jr(this.analyticsContext)}get createImportJobInNewTable(){return Qc(this.analyticsContext)}get getImportJob(){return Br(this.analyticsContext)}get importDataInTableAndAwaitJob(){return eu(this.analyticsContext)}get exportData(){return tu(this.analyticsContext)}get createExportJob(){return $r(this.analyticsContext)}get createExportJobForSqlQuery(){return ou(this.analyticsContext)}get getExportJob(){return Yr(this.analyticsContext)}get downloadExport(){return ru(this.analyticsContext)}get exportDataAndAwaitJob(){return nu(this.analyticsContext)}get addRow(){return au(this.analyticsContext)}get updateRows(){return iu(this.analyticsContext)}get deleteRows(){return su(this.analyticsContext)}get deleteView(){return cu(this.analyticsContext)}get deleteWorkspace(){return uu(this.analyticsContext)}};We=F([zm(),b(0,Su(Gt)),b(1,Su(w))],We);import{ConfigModule as mP,ConfigService as yP}from"@nestjs/config";function Fo(e){return{recruit:e.recruitApi,crm:e.crmApi,desk:e.deskApi,sign:e.signApi,analytics:e.analyticsApi}}function Jm(e){return`${e.clientId}:${e.refreshToken}`}function gt(e){let t=lu([du(),hu(kt())]),o=new Map;function r(R,y){let C=Jm(R),g=o.get(C),S;if(g)S=g;else{let O={zohoAccounts:{serviceAccessTokenKey:y,refreshToken:R.refreshToken,clientId:R.clientId,clientSecret:R.clientSecret,apiUrl:R.region??"us"}};S=new w(O,t),o.set(C,S)}return S}let n,a=Ue(e,"recruit");if(a){let R=r(a,"recruit"),y={zohoRecruit:{apiUrl:a.apiMode}};n=new Ve(y,R)}let i,s=Ue(e,"crm");if(s){let R=r(s,"crm"),y={zohoCrm:{apiUrl:s.apiMode}};i=new Ke(y,R)}let c,u=Ue(e,"desk");if(u?.orgId){let R=r(u,"desk"),y={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new qe(y,R)}let l,h=Ue(e,"sign");if(h){let R=r(h,"sign"),y={zohoSign:{apiUrl:h.apiMode}};l=new ze(y,R)}let f,m=Ue(e,"analytics");if(m){let R=r(m,"analytics"),y={zohoAnalytics:{apiUrl:m.apiMode,orgId:m.orgId}};f=new We(y,R)}return{recruitApi:n,crmApi:i,deskApi:c,signApi:l,analyticsApi:f}}Mo([...Po,/1000\.\w{20,}/g]);function Fu(e){let t;return e instanceof G?t={ok:!1,error:ge(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof it?t={ok:!1,error:ge(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Ce?t={ok:!1,error:ge(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof L?t={ok:!1,error:ge(e.message),code:"API_ERROR"}:t=wo(e),t}pn(e=>e instanceof G||e instanceof it||e instanceof Ce||e instanceof L?Fu(e):void 0);function d(e){console.log(JSON.stringify(Fu(e)))}var Iu={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"},Xr={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"],analytics:["ZohoAnalytics.data.all","ZohoAnalytics.metadata.all","ZohoAnalytics.modeling.all"]},bu="http://localhost/oauth",ku=`Organization ID, for the products scoped by one (${Array.from(Ne).join(", ")})`;function Hm(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 qm={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:bu,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",defaultDescription:"--product when given, otherwise recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign,analytics)"}).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:[...It],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:ku}).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)"],["$0 auth setup --product analytics --client-id 1000.ANALYTICS --client-secret xyz --org-id 1234567","Analytics uses a separate OAuth client; --scopes defaults to analytics"]]),handler:async e=>{try{let t=await B(),o=Bm(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 $m(o,t):o.code?await Ym(o,t):await Qm(o,t)}catch(t){d(t),process.exit(1)}}},Wm="recruit,crm,desk";function jm(e,t){return(e??t??Wm).split(",").map(o=>o.trim())}function Bm(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??bu,region:o,scopes:jm(e.scopes,r),code:Hm(e.code),token:e.token,accountsUrl:Iu[o]??Iu.us,apiMode:e.apiMode,orgId:e.orgId}}function Qr({product:e,credentials:t,apiMode:o,orgId:r}){return{...t,apiUrl:o??void 0,orgId:Ne.has(e)?r??void 0:void 0}}async function Ou(e,t,o){return e.product?ae({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:Qr({product:e.product,credentials:t,apiMode:e.apiMode,orgId:e.orgId})}):ae({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function $m(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await Ou(e,o,t?.shared);p({success:!0,...e.product?{product:e.product}:{},refreshToken:Ie(e.token),configSaved:!0,configuredProducts:ue(r)})}async function Ym(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}),a=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()})).json();if(a.error)throw new Error(`Token exchange failed: ${a.error}`);let i=a.refresh_token;if(!i)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:i},c=await Ou(e,s,t?.shared);p({step:2,success:!0,product:e.product??"shared",refreshToken:Ie(i),accessToken:a.access_token?Ie(a.access_token):null,scope:a.scope,configSaved:!0,configuredProducts:ue(c)})}async function Xm(e,t){let o;return e.product?o=await ae({shared:{clientId:t?.shared?.clientId??"",clientSecret:t?.shared?.clientSecret??"",refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},[e.product]:Qr({product:e.product,credentials:{clientId:e.clientId,clientSecret:e.clientSecret},apiMode:e.apiMode,orgId:e.orgId})}):o=await ae({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}),o}async function Qm(e,t){let o=e.product?Xr[e.product]??[]:e.scopes.flatMap(a=>Xr[a]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Xr).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;await Xm(e,t);let n=e.product?`--product ${e.product} `:"";p({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 ey={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:[...It],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:ku}).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 ae({shared:(await B())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:Qr({product:t,credentials:o,apiMode:e.apiMode,orgId:e.orgId})}):r=await ae({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),p({saved:!0,product:t??"shared",configuredProducts:ue(r)})}catch(t){d(t),process.exit(1)}}};function Eu(e){return e?{clientId:e.clientId?Ie(e.clientId):void 0,clientSecret:e.clientSecret?Ie(e.clientSecret):void 0,refreshToken:e.refreshToken?Ie(e.refreshToken):void 0}:void 0}function ty(e,t){return t?{...Eu(t),apiUrl:t.apiUrl,...Ne.has(e)?{orgId:t.orgId}:{}}:null}function oy(e){let t=Object.fromEntries(It.map(o=>[o,ty(o,e[o])]));return{configured:!0,shared:{...Eu(e.shared),region:e.shared?.region??"us",apiMode:e.shared?.apiMode??"production"},...t,configuredProducts:ue(e)}}var ry={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let e=await B();p(e?oy(e):{configured:!1})}catch(e){d(e),process.exit(1)}}},ny={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await B();if(e){let t=ue(e);if(t.length===0)p({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=gt(e),r=Fo(o),n={};for(let a of t)try{let i=r[a];if(!i){n[a]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();n[a]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let s=i instanceof Error?i.message:String(i);n[a]={authenticated:!1,error:s}}p({products:n})}}else p({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){d(e),process.exit(1)}}},ay={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Ma(),p({cleared:!0})}catch(e){d(e),process.exit(1)}}},Pu={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(qm).command(ey).command(ry).command(ny).command(ay).demandCommand(1,"Please specify an auth subcommand."),handler:A};import{access as iy,constants as sy}from"node:fs";import{dirname as cy}from"node:path";function uy(e){return e.every(t=>t.status==="pass")}var Du={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await B(),t=[];t.push(py(e));let o=ly(e);if(o&&t.push(o),t.push(await dy()),e){let n=ue(e);t.push(hy(n),...await my(e,n),...fy(e,n))}let r=uy(t);p({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function py(e){return e?{name:"config",status:"pass",message:`Config loaded from ${bt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function ly(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 dy(){let e=cy(kt());return await gy(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 hy(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 my(e,t){let o=Fo(gt(e)),r=[];for(let n of t)r.push(await yy(o[n],n));return r}async function yy(e,t){if(!e)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let o;try{let r=await e.zohoAccountsApi.accessToken();o={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${r.scope}`}}catch(r){let n=r instanceof Error?r.message:String(r);o={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${n}`}}return o}function fy(e,t){return Array.from(Ne).map(o=>{let r=e[o]?.orgId,n=`${o}-org-id`,a;return r?a={name:n,status:"pass",message:`${o}: Org ID configured: ${r}`}:t.includes(o)?a={name:n,status:"fail",message:`${o}: No org ID configured, but ${o} is reported as configured \u2014 every org-scoped ${o} command will fail. Run: zoho-cli auth set --product ${o} --org-id <ORG_ID>`}:a={name:n,status:"warn",message:`${o}: No org ID. ${o} commands unavailable.`},a})}function gy(e){return new Promise(t=>{iy(e,sy.W_OK,o=>{t(!o)})})}var Mu=ba({notInitializedMessage:"CLI context not initialized. This is a bug."});function wu(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await B();r||(d(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),ue(r).length===0&&(d(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Mu.set(gt(r))}catch(r){d(r),process.exit(4)}}}function Kt(e){return Mu.require()}function oe(e){let{recruitApi:t}=Kt(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 re(e){let{crmApi:t}=Kt(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 Z(e){let{deskApi:t}=Kt(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 N(e){let{signApi:t}=Kt(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 E(e){let{analyticsApi:t}=Kt(e);if(!t)throw new Error("Analytics not configured. Zoho Analytics requires its own OAuth client. Run: zoho-cli auth setup --product analytics --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function ye(e){return Qt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function D(e){return Qt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function Io(e){return Qt(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 U(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function De(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function Vt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function bo(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 Ry={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},M={nextInput:(e,t)=>{let o=e.limit??25,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let a=e.from??1;n={...e,from:a+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}},Cy={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 fe(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Ry,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let a=n.result;p(a.data,{page:a.info?.page,per_page:a.info?.per_page,more_records:a.info?.more_records})}}async function ko(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:async a=>{let i=await r(a);return{data:i.requests??[],page_context:i.page_context}},adapter:Cy,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let a=n.result;p(a.data,{start_index:a.page_context?.start_index,row_count:a.page_context?.row_count,total_count:a.page_context?.total_count,has_more_rows:a.page_context?.has_more_rows??!1})}}var Ty={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)))),handler:async e=>{try{let t=oe(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},xy={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await oe(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Ay={command:"search",describe:"Search records in a module",builder:e=>ye(U(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=oe(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 fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Zy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Sy={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Fy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Iy={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=oe(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},by={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},ky={command:"attachments",describe:"Get attachments for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},_u={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(Ty).command(xy).command(Ay).command(Zy).command(Sy).command(Fy).command(Iy).command(by).command(ky).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:A};var Oy={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)),!0)),handler:async e=>{try{let t=re(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},Ey={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await re(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Py={command:"search",describe:"Search records in a module",builder:e=>ye(U(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=re(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 fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Dy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},My={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},wy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},_y={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=re(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},vy={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},Ny={command:"attachments",describe:"Get attachments for a record",builder:e=>Vt(ye(De(U(e))),!0),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},vu={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Oy).command(Ey).command(Py).command(Dy).command(My).command(wy).command(_y).command(vy).command(Ny).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:A};var Uy={command:"list",describe:"List tickets",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ly={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 Z(e).getTicketById({ticketId:e.ticketId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Gy={command:"search",describe:"Search tickets",builder:e=>D(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=Z(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 k({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ky={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>D(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=Z(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Vy={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 Z(e).getTicketMetrics({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},zy={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=Z(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});p(r)}catch(t){d(t),process.exit(1)}}},Nu={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Uy).command(Ly).command(Gy).command(Ky).command(Vy).command(zy).demandCommand(1),handler:A};var Jy={command:"list",describe:"List departments",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await k({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Hy={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 Z(e).getDepartmentById({departmentId:e.departmentId});p(o)}catch(t){d(t),process.exit(1)}}},Uu={command:"departments",describe:"Desk department operations",builder:e=>e.command(Jy).command(Hy).demandCommand(1),handler:A};var qy={command:"list",describe:"List contacts",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wy={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 Z(e).getContactById({contactId:e.contactId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Lu={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(qy).command(Wy).demandCommand(1),handler:A};var jy={command:"list",describe:"List agents",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},By={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 Z(e).getAgentById({agentId:e.agentId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},$y={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await Z(e).getMyInfo();p(o)}catch(t){d(t),process.exit(1)}}},Gu={command:"agents",describe:"Desk agent operations",builder:e=>e.command(jy).command(By).command($y).demandCommand(1),handler:A};var Yy={command:"list",describe:"List all tags",builder:e=>D(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await k({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Xy={command:"search",describe:"Search tags",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await k({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Qy={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 Z(e).getTicketTags({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},ef={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=Z(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});p(r)}catch(t){d(t),process.exit(1)}}},tf={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 Z(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ku={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Yy).command(Xy).command(Qy).command(ef).command(tf).demandCommand(1),handler:A};var of={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await k({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},rf={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 Z(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});p(o)}catch(t){d(t),process.exit(1)}}},nf={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 Z(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});p(o)}catch(t){d(t),process.exit(1)}}},af={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 Z(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},Vu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(of).command(rf).command(nf).command(af).demandCommand(1),handler:A};var sf={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},cf={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 Z(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},zu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(sf).command(cf).demandCommand(1),handler:A};var uf={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 Z(e).getTicketFollowers({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},pf={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=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({added:!0})}catch(t){d(t),process.exit(1)}}},lf={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=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ju={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(uf).command(pf).command(lf).demandCommand(1),handler:A};var df={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 Z(e).getTicketTimer({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},hf={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 Z(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});p(o)}catch(t){d(t),process.exit(1)}}},mf={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},yf={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 Z(e).getTicketTimeEntrySummation({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},Hu={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(df).command(hf).command(mf).command(yf).demandCommand(1),handler:A};var ff={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},gf={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 Z(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},qu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(ff).command(gf).demandCommand(1),handler:A};var Rf={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wu={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Rf).demandCommand(1),handler:A};var ju={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(Nu).command(Uu).command(Lu).command(Gu).command(Ku).command(Vu).command(zu).command(Ju).command(Hu).command(qu).command(Wu).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:A};import{readFile as Cf,writeFile as Bu}from"node:fs/promises";import{basename as Tf}from"node:path";function xf(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 Af={command:"list",describe:"List sign requests (documents)",builder:e=>Io(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=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:xf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){d(t),process.exit(1)}}},Zf={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 N(e).getDocument({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Sf={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 N(e).getDocumentFormData({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Ff={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=N(e),o=JSON.parse(e.data),r=await Cf(e.file),n=new File([r],Tf(e.file),{type:e.contentType}),a=await t.createDocument({requestData:o,file:n});p(a)}catch(t){d(t),process.exit(1)}}},If={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=N(e),o=JSON.parse(e.data),r=await t.createDocumentFromTemplate({templateId:e.templateId,data:o,isQuickSend:e.quickSend});p(r)}catch(t){d(t),process.exit(1)}}},bf={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=N(e),o=JSON.parse(e.data),r=await t.updateDocument({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},kf={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=N(e),o=e.data?JSON.parse(e.data):void 0,r=await t.sendDocumentForSignature({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Of={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 N(e).extendDocument({requestId:e.requestId,expire_by:e.expireBy});p(o)}catch(t){d(t),process.exit(1)}}},Ef={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 N(e).deleteDocument({requestId:e.requestId,recall_inprogress:e.recallInprogress,reason:e.reason});p(o)}catch(t){d(t),process.exit(1)}}},Pf={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 N(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 Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Df={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 N(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 Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Mf={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 N(e).getEmbeddedSigningUrl({requestId:e.requestId,actionId:e.actionId,host:e.host});p(o)}catch(t){d(t),process.exit(1)}}},$u={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Af).command(Zf).command(Sf).command(Ff).command(If).command(bf).command(kf).command(Of).command(Ef).command(Pf).command(Df).command(Mf).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:A};function wf(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 _f={command:"list",describe:"List templates",builder:e=>Io(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=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:wf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){d(t),process.exit(1)}}},vf={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 N(e).getTemplate({templateId:e.templateId});p(o)}catch(t){d(t),process.exit(1)}}},Yu={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(_f).command(vf).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:A};var Nf={command:"field-types",describe:"List available document field types",builder:e=>e,handler:async e=>{try{let o=await N(e).retrieveFieldTypes();p(o)}catch(t){d(t),process.exit(1)}}},Xu={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command($u).command(Yu).command(Nf).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:A};var Uf={command:"list",describe:"List the organizations available to the authenticated user",handler:async e=>{try{let o=await E(e).getOrgs();p(o.data.orgs,{count:o.data.orgs?.length})}catch(t){d(t),process.exit(1)}}},Qu={command:"orgs",describe:"Analytics organization operations",builder:e=>e.command(Uf).demandCommand(1).example([["$0 analytics orgs list","Find the org id needed by every other Analytics command"]]),handler:A};var Lf={command:"list",describe:"List all accessible workspaces",builder:e=>e.option("owned",{type:"boolean",describe:"Only workspaces owned by the authenticated user"}).option("shared",{type:"boolean",describe:"Only workspaces shared with the authenticated user"}),handler:async e=>{try{let t=E(e);if(e.owned){let o=await t.getOwnedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else if(e.shared){let o=await t.getSharedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else{let o=await t.getAllWorkspaces();p(o.data)}}catch(t){d(t),process.exit(1)}}},Gf={command:"get <workspaceId>",describe:"Get a workspace by ID",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getWorkspaceDetails({workspaceId:e.workspaceId});p(o.data.workspaces)}catch(t){d(t),process.exit(1)}}};function Kf(e,t){if(!t)throw new Error(`Deleting a workspace cannot be undone. Re-run with --confirm ${e} to proceed.`);if(t!==e)throw new Error(`--confirm ${t} does not match the workspace being deleted (${e}).`);return e}var Vf={command:"delete <workspaceId>",describe:"Delete a workspace and everything in it. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("confirm",{type:"string",describe:"Repeat the workspace ID to confirm. Required"}),handler:async e=>{try{let t=Kf(e.workspaceId,e.confirm);await E(e).deleteWorkspace({workspaceId:t}),p({deleted:!0,workspaceId:t})}catch(t){d(t),process.exit(1)}}},ep={command:"workspaces",describe:"Analytics workspace operations",builder:e=>e.command(Lf).command(Gf).command(Vf).demandCommand(1).example([["$0 analytics workspaces list","List owned and shared workspaces"],["$0 analytics workspaces list --owned","List only owned workspaces"],["$0 analytics workspaces delete 1767024000000060001 --confirm 1767024000000060001","Delete a workspace, confirming the id"]]),handler:A};var zf={command:"list <workspaceId>",describe:"List the views of a workspace",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getViews({workspaceId:e.workspaceId});p(o.data.views,{count:o.data.views?.length})}catch(t){d(t),process.exit(1)}}},Jf={command:"get <viewId>",describe:"Get a view by ID",builder:e=>e.positional("viewId",{type:"string",demandOption:!0,describe:"View ID (globally unique, no workspace needed)"}),handler:async e=>{try{let o=await E(e).getViewDetails({viewId:e.viewId});p(o.data.views)}catch(t){d(t),process.exit(1)}}},Hf={command:"columns <workspaceId> <viewId>",describe:"List the columns of a table",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}),handler:async e=>{try{let o=await E(e).getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId});p(o.data.columns,{count:o.data.columns?.length})}catch(t){d(t),process.exit(1)}}},qf={command:"delete <workspaceId> <viewId>",describe:"Delete a view. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("dependent-views",{type:"boolean",default:!1,describe:"Also delete the reports, dashboards and query tables built on this view"}),handler:async e=>{try{await E(e).deleteView({workspaceId:e.workspaceId,viewId:e.viewId,config:{deleteDependentViews:e.dependentViews}}),p({deleted:!0,workspaceId:e.workspaceId,viewId:e.viewId,deletedDependentViews:e.dependentViews})}catch(t){d(t),process.exit(1)}}},tp={command:"views",describe:"Analytics view operations",builder:e=>e.command(zf).command(Jf).command(Hf).command(qf).demandCommand(1).example([["$0 analytics views list 1767024000000060001","List the views of a workspace"],["$0 analytics views columns 1767024000000060001 1767024000000149001","Inspect a table before importing into it"],["$0 analytics views delete 1767024000000060001 1767024000000149001",'Drop a table created by "import new-table"']]),handler:A};import{readFile as Wf}from"node:fs/promises";import{basename as jf,extname as op}from"node:path";var Bf=["append","truncateadd","updateadd"],$f=["abort","skiprow","setcolumnempty"];async function rp(e){let t=await Wf(e,"utf8"),o=jf(e),r=op(e).toLowerCase()===".json"?"application/json":"text/csv";return Ra({content:t,fileName:o,mimeType:r})}function Oo(e){let t=op(e).toLowerCase();return{".json":"json",".csv":"csv"}[t]}function Yf(e,t){let o=t?.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e==="updateadd"&&!o?.length)throw new Error("The updateadd mode requires --matching-columns.");return o?.length?o:void 0}function np(e){return e.option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file to import"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("on-error",{type:"string",choices:$f,describe:"What to do when a row cannot be imported"}).option("async",{type:"boolean",default:!1,describe:"Queue the import as a job and poll it, rather than waiting on one request"})}var Xf={command:"data <workspaceId> <viewId>",describe:"Import a file into an existing table",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("mode",{alias:"m",type:"string",choices:Bf,default:"append",describe:"append adds rows, truncateadd replaces every row, updateadd upserts on --matching-columns"}).option("matching-columns",{type:"string",describe:"Comma-separated columns to match on. Required for the updateadd mode"}),handler:async e=>{try{let t=E(e),o=e.mode,r=Yf(o,e.matchingColumns),n=await rp(e.file),a={importType:o,fileType:e.fileType??Oo(e.file),onError:e.onError,matchingColumns:r};if(e.async){let i=await t.importDataInTableAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:a}),{jobCode:s,jobStatus:c,jobInfo:u}=i.data;p({jobCode:s,jobStatus:c,...u},{complete:Pe(s)})}else{let i=await t.importDataInTable({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:a});p(i.data)}}catch(t){d(t),process.exit(1)}}},Qf={command:"new-table <workspaceId> <tableName>",describe:"Create a table in a workspace from an imported file",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("tableName",{type:"string",demandOption:!0,describe:"Name of the table to create"}),handler:async e=>{try{let t=E(e),o=await rp(e.file),r={tableName:e.tableName,fileType:e.fileType??Oo(e.file),onError:e.onError};if(e.async){let n=await t.createImportJobInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}else{let n=await t.importDataInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}}catch(t){d(t),process.exit(1)}}},eg={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous import job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Import job ID"}),handler:async e=>{try{let o=await E(e).getImportJob({workspaceId:e.workspaceId,jobId:e.jobId});p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ap={command:"import",describe:"Analytics import operations",builder:e=>e.command(Xf).command(Qf).command(eg).demandCommand(1).example([["$0 analytics import data WS VIEW -f rows.csv","Append the rows of a CSV to a table"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace every row in a table"],["$0 analytics import data WS VIEW -f big.csv --async","Queue a large import and poll it"],["$0 analytics import new-table WS Sales -f rows.csv","Create a table from a CSV"]]),handler:A};import{writeFile as tg}from"node:fs/promises";var og=["csv","json","xml","xls","pdf","html","image"];async function en(e,t){let o=await e.text(),r;return t?await tg(t,o,"utf8"):r=o,r}function ip(e){return e.option("format",{type:"string",choices:og,default:"csv",describe:"Format of the exported data"}).option("out",{alias:"o",type:"string",describe:"Write the export to this file instead of printing it"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("columns",{type:"string",describe:"Comma-separated columns to export"})}function rg(e){let t=e?.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t?.length?t:void 0}function sp(e){return{responseFormat:e.format,criteria:e.criteria,selectedColumns:rg(e.columns)}}var ng={command:"data <workspaceId> <viewId>",describe:"Export the data of a view",builder:e=>ip(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("async",{type:"boolean",default:!1,describe:"Queue the export as a job and poll it. Required for dashboards, query tables, and tables over a million rows"}),handler:async e=>{try{let t=E(e),o=sp(e);if(e.async){let r=await t.exportDataAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,config:o});if(Pe(r.data.jobCode)){let n=await t.downloadExport({workspaceId:e.workspaceId,jobId:r.data.jobId}),a=await en(n,e.out);p(a??{written:e.out,jobId:r.data.jobId})}else p(r.data,{complete:!1})}else{let r=await t.exportData({workspaceId:e.workspaceId,viewId:e.viewId,config:o}),n=await en(r,e.out);p(n??{written:e.out})}}catch(t){d(t),process.exit(1)}}},ag={command:"query <workspaceId>",describe:"Export the results of a SQL query",builder:e=>ip(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("sql",{type:"string",demandOption:!0,describe:"The SQL SELECT statement to run"}),handler:async e=>{try{let t=E(e),o={...sp(e),sqlQuery:e.sql},r=await t.createExportJobForSqlQuery({workspaceId:e.workspaceId,config:o}),n=await t.getExportJob({workspaceId:e.workspaceId,jobId:r.data.jobId});p(n.data,{complete:Pe(n.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ig={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous export job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Export job ID"}).option("download",{type:"boolean",default:!1,describe:"Download the export when the job has completed"}).option("out",{alias:"o",type:"string",describe:"Write the download to this file instead of printing it"}),handler:async e=>{try{let t=E(e),o=await t.getExportJob({workspaceId:e.workspaceId,jobId:e.jobId});if(e.download&&Pe(o.data.jobCode)){let r=await t.downloadExport({workspaceId:e.workspaceId,jobId:e.jobId}),n=await en(r,e.out);p(n??{written:e.out})}else p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},cp={command:"export",describe:"Analytics export operations",builder:e=>e.command(ng).command(ag).command(ig).demandCommand(1).example([["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"],["$0 analytics export data WS VIEW --format json","Print a table as JSON"],['$0 analytics export query WS --sql "select * from Sales"',"Queue an ad-hoc SQL export"]]),handler:A};import{readFile as sg}from"node:fs/promises";function cg(e,t){return{clean:t,rowCount:e.rowCount,matched:e.matchedColumns.length,dropped:e.droppedColumns.length,empty:e.emptyColumns.length,emptyRequired:e.emptyColumns.filter(o=>o.required).length,caseMismatched:e.caseMismatchedColumns.length,conflicts:e.conflicts.length,conflictingValues:e.conflicts.reduce((o,r)=>o+r.conflictCount,0)}}var ug={command:"schema <workspaceId> <viewId>",describe:"Compare a file against a table before importing it",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file that would be imported"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("delimiter",{type:"string",describe:"Field delimiter of the CSV. Defaults to a comma"}).option("max-samples",{type:"number",describe:"Offending values to report per conflict. Defaults to 3"}).option("strict",{type:"boolean",default:!1,describe:"Also treat a nullable column the file omits as drift"}).option("quiet",{type:"boolean",default:!1,describe:"Report only through the exit code, printing nothing"}),handler:async e=>{try{let t=E(e),o=e.fileType??Oo(e.file);if(o==null)throw new Error(`Cannot tell the format of "${e.file}" from its extension. Pass --file-type csv or --file-type json.`);let r=await sg(e.file,"utf8"),n=Uc({content:r,fileType:o,delimiter:e.delimiter}),{data:a}=await t.getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId}),i=Lc({...n,columns:a.columns??[],maxSamples:e.maxSamples}),s=Gc(i,{strict:e.strict});e.quiet||p(i,cg(i,s)),s||process.exit(1)}catch(t){d(t),process.exit(1)}}},up={command:"diff",describe:"Analytics comparison operations",builder:e=>e.command(ug).demandCommand(1).example([["$0 analytics diff schema WS VIEW -f rows.csv","Report what an import of the file would drop, leave empty, or mangle"],["$0 analytics diff schema WS VIEW -f rows.csv --strict","Also fail on a nullable column the file omits"],["$0 analytics diff schema WS VIEW -f rows.csv --quiet && zoho-cli analytics import data WS VIEW -f rows.csv","Gate an import on a clean diff"]]),handler:A};function tn(e){return e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Table view ID"})}var pg={command:"add <workspaceId> <viewId>",describe:"Add a single row to a table",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"Row as a JSON object of column name to value"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.addRow({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o}});p(r.data)}catch(t){d(t),process.exit(1)}}},lg={command:"update <workspaceId> <viewId>",describe:"Update the rows of a table matching a criteria expression",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"New values as a JSON object of column name to value"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Update every row. Required when no --criteria is given"}).option("add-if-not-exist",{type:"boolean",default:!1,describe:"Insert a row when the criteria matches nothing"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.updateRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o,criteria:e.criteria,updateAllRows:e.allRows,addIfNotExist:e.addIfNotExist}});p(r.data)}catch(t){d(t),process.exit(1)}}},dg={command:"delete <workspaceId> <viewId>",describe:"Delete the rows of a table matching a criteria expression",builder:e=>tn(e).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Delete every row. Required when no --criteria is given"}),handler:async e=>{try{let o=await E(e).deleteRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{criteria:e.criteria,deleteAllRows:e.allRows}});p(o.data)}catch(t){d(t),process.exit(1)}}},pp={command:"rows",describe:"Analytics row operations",builder:e=>e.command(pg).command(lg).command(dg).demandCommand(1).example([[`$0 analytics rows add WS VIEW --columns '{"Region":"East"}'`,"Add one row"],[`$0 analytics rows delete WS VIEW --criteria '"Sales"."Region"='"'"'West'"'"''`,"Delete the rows matching a filter"]]),handler:A};var lp={command:"analytics",describe:"Zoho Analytics operations",builder:e=>e.command(Qu).command(ep).command(tp).command(ap).command(cp).command(pp).command(up).demandCommand(1,"Please specify an analytics subcommand.").example([["$0 analytics orgs list","Find the org id every other command needs"],["$0 analytics workspaces list","List the accessible workspaces"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace a table with the rows of a CSV"],["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"]]),handler:A};var dp={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=oe(e).recruitContext;break;case"crm":n=re(e).crmContext;break;case"desk":n=Z(e).deskContext;break;case"sign":n=N(e).signContext;break;default:throw new Error(`Unknown product: ${t}`)}let a=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),l=a.includes("?")?"&":"?";a=`${a}${l}${u.toString()}`}let i={method:o};e.body&&(i.body=e.body,i.headers={"Content-Type":"application/json"});let s=await n.fetchJson(a,i);p(s)}catch(t){d(t),process.exit(1)}}};var yg=Ea({cliName:"zoho-cli",loadOutputConfig:async()=>(await B())?.output,mergeOutputConfig:e=>ae({output:e}),clearOutputConfig:Da}),fg=[_u,vu,ju,Xu,lp,dp],hp=[Pu,yg,Du];function gg(e){return e.command.split(" ")[0]}var mp=new Set(hp.map(gg)),Rg=Oa({cliName:"zoho-cli",skipCommands:mp,loadOutputConfig:async()=>(await B())?.output,saveCommandOutputConfig:async(e,t)=>{await ae({output:{commands:{[e]:t}}})}});async function Cg(){try{await hg(mg(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([wu(mp),Rg],!0).command(hp).command(fg).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){d(e),process.exit(1)}}await Cg();
|
|
4
|
+
var yp=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?fp(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&&yp(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as gp,mkdirSync as Rp,writeFileSync as Cp}from"node:fs";import{join as Tp}from"node:path";var nn=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],an=6e4,je={},sn=[...Po],Eo,xp=!1,Ap=an;function Do(e){je=e}function zt(){return je}function cn(e){xp=e}function un(e){Ap=e===void 0?an:e}function Mo(e){sn=e}function pn(e){Eo=e}function ge(e){let t=e;for(let o of sn)t=t.replace(o,"[REDACTED]");return t}function ln(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function Ct(e,t){let{dumpDir:o,commandPath:r}=je,n;if(o){gp(o)||Rp(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=ln(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=Tp(o,`${s}.${e}`)}else n=void 0;return n}function Zp(e,t){let o=Ct("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Cp(o,JSON.stringify(r,null,2))}function Me(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>rn(n,o)):e!=null&&typeof e=="object"?r=rn(e,o):r=e,r}function rn(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 dn(e){return je.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function p(e,t){Zp(e,t);let r={ok:!0,data:je.pick?Me(e,je.pick):e,...t?{meta:t}:{}};console.log(dn(r))}function hn(e){console.log(dn(wo(e)))}var Rt=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function wo(e){let t=Eo?Eo(e):void 0,o;return t?o=t:e instanceof Rt?o={ok:!1,error:ge(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:ge(e.message),code:"ERROR"}:o={ok:!1,error:ge(String(e)),code:"UNKNOWN_ERROR"},o}function Be(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 Tt(e){let t=!0;for(let o of e){t=!1;break}return t}function _o(e,t){for(let o of e)t(o)}function j(e,t,o=!1){e!=null&&(Be(e,o)?_o(e,t):t(e))}function mn(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 Sp(e){return e==null?[]:Fp(e)}var x=Sp;function Fp(e){return Array.isArray(e)?e:[e]}import{symmetricDifference as Eg}from"extra-set";function yn(e,t){j(t,o=>e.add(o))}function fn(e,t){j(t,o=>e.delete(o))}function gn(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function vo(e){return Object.keys(e).length===0}function Rn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Cn(e){return{...e}}function Tn(e){return e!=null}function Jt(e){return Be(e,!1)?!Tt(e):xn(e)}function No(e){let t;return Be(e,!0)?t=!Tt(e):xn(e)?t=typeof e=="object"?!vo(e):!0:t=!1,t}function xn(e){return e!=null&&e!==""}function Ip(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ce=Ip(Tn);function An({base:e,build:t}){let o=e??{};return t(o),o}var bp=(e=>e);function Zn(){return bp}function Uo(e,t){let o=new Set(e),r=kp(t,n=>n);return r.length&&fn(o,r),Array.from(o)}function kp(e,t){return ce(e==null?[]:Array.isArray(e)?e:Op(e,t))}function Op(e,t){let o=new Set(e.keys);return e.values&&yn(o,e.values.map(t)),Array.from(o)}function $e(e,t){let o=Ep(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Ep(e,t){return Rn(Pp(e,t))}function Pp(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 Sn(e,t,o){return x(t).forEach(r=>e.set(r,o)),e}function Lo(e){return Array.from(e.entries())}function Fn(e){return Dp(Lo(e))}function Dp(e){let t=[];return e.forEach(([o,r])=>{j(r,n=>{t.push([o,n])})}),t}function In(){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,mn(i));return{map:()=>e,entries:()=>Lo(e),tuples:()=>Fn(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 Mp(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function bn(e){let t=Mp(e);return t!=null&&t!=="class"}function kn(e){return bn(e)?e:()=>e}function On(e,t){return Math.log(t)/Math.log(e)}var En=",",wp=" ";function _p(e,t=En,o=!1){if(e==null)return e;let r=x(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Go(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 vp(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return _p(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Pn(e){let{joiner:t}=e,o=vp(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 Go(n,t,i)}}}var Ko=Pn({joiner:En}),Np=Pn({joiner:wp,trimByDefault:!0});var P=Ko.joinStrings,rR=Ko.splitStrings,nR=Ko.splitStringsToSet,iR=Np.joinStrings;var Dn=gn;function wn(e,{forEach:t,filter:o}){Up(e,o).forEach((n,i)=>t(n,i))}function Up(e,t){return Vo(t)(e)}function Vo(e){let t;if(e==null)t=Mn;else{let o=Lp(e);t=r=>Mn(r).filter((n,i)=>o(n,i))}return t}function Mn(e){return Object.entries(e)}function zo(e){return typeof e=="object"?e:{valueFilter:e}}function Lp(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])=>Jt(a);break;case 5:i=([,a])=>No(a);break;case 6:i=([,a])=>!!a&&Jt(a);break;case 7:i=([,a])=>!!a&&No(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 Dn(i,r)}function xt(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 _n(e){let t;return e==null||jp(e)?t=e:t=Gp(e),t}function Gp(e){return e==null?e:new Date(e)}var Kp=365,vn=24,Vp=60,zp=1440,Jp=60,hR=Kp*zp,Hp=Jp*Vp,z=1e3,Re=z*60,Jo=Re*60,qp=Jo*vn,mR=Hp*vn,Wp=7,yR=qp*Wp;function jp(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Nn(e){return e.getTime()<Date.now()}function Un(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function Bp(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:_n(n);function c(f){return f??r??new Date}function u(f,m=!1){let R=c(f),y=h(R),C;return y==null?C=m:C=y<=R,C}function l(f){let m=c(f);return h(m)}function h(f){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:a!=null&&(m=Un(s??(i===!1?null:f),a)),m}return{input:e,hasExpired:u,getExpirationDate:l}}function Ln(e,t){let o=!0;return e!=null&&(o=Bp(e).hasExpired(t,!0)),o}function $p({filter:e,copy:t,dynamic:o=!1}){let r=e==null?el:Ye({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:xt(i);return s=>{let c=a();return t&&(s=Cn(s)),Object.assign(s,c),s}}}function Gn(e,t){return Yp(t)(e)}function Yp(e){let t=$p({filter:e,copy:!1,dynamic:!0});return o=>t(ce(o))({})}function Kn(e,t=!1){return(t?Qp:Xp)(e)}var Xp=Ye({copy:!0,filter:{valueFilter:1}}),Qp=Ye({copy:!0,filter:{valueFilter:2}}),Vn=Ye({copy:!0,filter:{valueFilter:4}}),SR=Ye({copy:!0,filter:{valueFilter:6}}),FR=Ho({valueFilter:1}),IR=Ho({valueFilter:6}),bR=Ho({valueFilter:2});function Ho(e){let t=zn({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ye({copy:e=!1,filter:t={valueFilter:1}}={}){let o=zo(t);o.invertFilter=!o.invertFilter;let r=zn({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var el=Ye({copy:!1});function zn({forEach:e,filter:t}){let o=Vo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function Jn(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 Hn(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 qn(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 Ht(e,t,o){let[r,n]=qo(e,t,!1);return r+o+n}function qo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var tl=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],wR=new Set(tl);function Wn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=qt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=Ht(n,i[0],o(s));break}default:{let s=[],c=i.length,u=0,l=0;for(let h=0;h<c;h+=1){l=i[h];let f=n[l],R=n.substring(u,l)+o(f);s.push(R),u=l+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function ol(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of Array.from(t).entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function qt(e,t,o){return ol(e)(t,o)}function rl(e,t){return qt(e,t,1)[0]}function nl(e){return t=>{let r=rl(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=qo(t,r,!1),n}}function jn(e,t){return nl(t)(e)}var Xe="/",il=".";function al(e){let t=e.split(il,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Xe?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Bn(e){return al(e)!=="invalid"}var sl=/^\/+/,cl=/\/+$/;var ul=/\/{2,}/g;function $n(e){return e.startsWith(Xe)?e.replace(sl,Xe):`${Xe}${e}`}function Yn(e){return e.replaceAll(ul,Xe)}function Xn(e){return e.replace(cl,"")}function pl(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Qn=/:(\d+)/;function ll(e){return Qn.test(e)}function dl(e){let t=Qn.exec(e);return t?Number(t[1]):void 0}function hl(e){let t=ri(e),o=ml(t),{domain:r,path:n}=o,i=pl(r),a=ll(e),s=a?dl(e)??void 0:void 0,[c,u]=jn(o.path,"?"),l=i&&(c===""||Bn(c+"/")),h=fl(e);return{input:e,isWebsiteUrl:l,hasWebsiteDomain:i,hasHttpPrefix:h,hasPortNumber:a,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function ei(e){let t=hl(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function ti(e,t=!1){let o=qt(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=Ht(n,i,"&")),n}function ml(e){let t=ri(e);return yl(t)}function yl(e){let t=Go(e,"/",2),o=t[0],r=t[1];return{domain:o,path:$n(r??"/")}}var oi=/^https:\/\/|http:\/\//;function ri(e){return e.replace(oi,"")}function fl(e){return oi.test(e)}function A(){}async function ni(e){let t,o=e.initValue;if(o==null||await e.checkContinue(o,-1)){let n=0,i=o,a;do i=await e.next(n,i),n+=1,a=await e.checkContinue(i,n);while(a);t=i}else t=o;return t}function ii(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function At(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function gl(e){let n=Jo,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 l(){return{...i}}function h(){return u}function f(S){u=S}function m(S,O=!1){let q=Math.max(0,S.startLimitAt??1),I=S.cooldownRate??1,_=S.maxWaitTime??n,v=S.exponentRate??2;i={startLimitAt:q,cooldownRate:I,maxWaitTime:_,exponentRate:v},s=On(v,_/z+1),O&&R()}function R(){a=0,c=new Date}function y(S){let O;if(u){let{cooldownRate:q}=i,_=(Date.now()-c.getTime())*q/z,v=Math.max(a-_,0),W=Math.max(0,v-i.startLimitAt);S&&(a=v+S,c=new Date),O=W>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(W,0))-1)*z}else O=0;return O}function C(S){return y(S??0)}function g(){let S=y(1);return At(S)}return{waitForRateLimit:g,getNextWaitTime:C,getConfig:l,setConfig:m,getEnabled:h,setEnabled:f,reset:R}}function ai(e){let o=gl({exponentRate:1.5,maxWaitTime:z*8,...e}),r=Re,n=new Date,i=0,a=0,s=!0;g(e,!0);function c(){Nn(n)&&h()}function u(){return s}function l(I){s=I}function h(){a=i,n=new Date(Date.now()+r)}function f(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function R(I){n=I}function y(){return c(),a}function C(I){a=I}function g(I,_=!1){i=I.limit??i,r=I.resetPeriod??r;let v={cooldownRate:I.cooldownRate??Math.max(.1,r/z),exponentRate:I.exponentRate??1.5,maxWaitTime:I.maxWaitTime??z*8};o.setConfig(v,_),_&&h(),n=I.resetAt??n}function S(I){let _=0;if(s){let W=function(){return a-=I,o.getNextWaitTime(I)};var v=W;a>0?_=W():(c(),a>0?_=W():_=m())}return _}function O(I){return S(I??0)}function q(){let I=S(1);return At(I)}return{getRemainingLimit:y,setRemainingLimit:C,getTimeUntilNextReset:m,getResetAt:f,setNextResetAt:R,setConfig:g,reset:h,getNextWaitTime:O,waitForRateLimit:q,getEnabled:u,setEnabled:l}}var Rl="__CATCH_ALL_HANDLE_RESULT_KEY__";function si(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,i=new Map,a=u=>{n=u},s=(u,l)=>{u===Rl?a(l):Sn(i,u,l)},c=(u,l,h)=>{let f=h.bind(u);s(l,f)};return An({base:(u=>{let l=e(u),h=(l==null?void 0:i.get(l))??n,f;return h?f=Promise.resolve(h(u)).then(m=>m??o):f=Promise.resolve(r),f}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function Cl(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Tl(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function xl(e,t,o){let r=Tl(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function ci(e,t){return o=>xl(e,o,t)}function ui(e){return t=>(o,r)=>{let n=Cl(o,t),i=e.configurerForAccessor(n);r(i)}}var Al=-1,pi=0;function Zl(e){return e?.page??Al}function li(e){return Zl(e)+1}import{BaseError as di}from"make-error";var ne=class extends di{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}error};function hi(e){return(t,o)=>Sl(e(t,o))}var Se=class extends di{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}response};function Sl(e){return e.then(t=>{if(!t.ok)throw new Se(t);return t})}import{BaseError as cC}from"make-error";function mi(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 fi(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>gi({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>Il({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Fl=(e,t)=>t(e);function Il(e){let{makeFetch:t=fetch,fetchHandler:o=Fl,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=mi(a)),n&&(a=hi(a));let s=gi(e);return async(c,u)=>{let l=await s(c,u),h=o(l,a);return i&&(h=i(h)),h}}var bl=(e,t)=>new Request(e,t??void 0);function gi(e){let{makeRequest:t=bl,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 R,y=m.toString();if(!s&&ei(y))R=new URL(y);else{let C=c.origin+Yn("/"+c.pathname+"/"+m);R=new URL(C,c)}return R}:void 0;async function l(m){let R=ii(m)?await m:m;return yi(R)?R:t(R)}let h=u?async m=>{let R,y,C;if(typeof m=="string"?R=m:yi(m)?a?(R=m.url,y=m):C=m:C=await t(m),!C){let g=u(R);C=await t(g.href,y)}return C}:l,f;if(r!=null||n!=null){let m=kn(r);async function R(){let C=await m();return n?{...C,timeout:n}:C}async function y(C,g){let S=await R(),O=kl(S,await g),q=O.timeout===void 0?C.timeout:O.timeout;return{...O,timeout:q}}i?f=(C,g)=>i(C,y(C,g)):f=(C,g)=>y(C,g)}else i?f=i:f=(m,R)=>R;return async(m,R)=>{try{let y=await h(m);R=await f(y,R??void 0);let C=await t(y,R);return C.timeout=n,C}catch(y){throw y instanceof ne?y:new ne(y)}}}function kl(e,t){let o;if(t){let r=Ol([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Ol(e){let t=In();return ce(e).forEach(o=>{let r=El(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 El(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 yi(e){return!!e.url}import{safeParse as Pl}from"fast-content-type-parse";function Ri(e){let t={};return e.mimeType&&(t.type=e.mimeType),e.lastModified!=null&&(t.lastModified=e.lastModified),new File(x(e.content),e.fileName,t)}function Wt(e){let t=e.headers.get("content-type"),o=Pl(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ci(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 l,h;try{l=await s(a.clone())}catch(m){h=m,l=h.response}if(await t(l,h)&&u<r)l=await c(u+1);else if(h!=null)throw h;return l}return c(0)};return i._rateLimiter=n,i}var Wo=class extends ne{constructor(o){super("There was no next page for this.");this.page=o}page},jo=class extends ne{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}page;limit},Dl=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??{},l=u??i,h=c===null?Number.MAX_SAFE_INTEGER:c??Dl;function f(R,y=void 0){return async()=>{let C=await t(R),{cursor:g,nextPageCursor:S,hasNext:O}=await o(C),q=g??y?.cursor,I=O!==!1,_=y?y.page+1:pi,v=_>=h,W={input:R,result:C,page:_,previous:y,hasNext:I,isAtMaxPage:v,cursor:q,nextPageCursor:S,fetchNext:xt(async()=>{if(v)throw new jo(W,h);let on=I?await r(W,R,{maxPage:h,maxItemsPerPage:l}):void 0;if(!on)throw new Wo(W);return f({...R,...on},W)()})};return W}}return{input:a,fetchNext:xt(()=>f(a)())}}}function Ml(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 T(e,t){let{omitKeys:o,filterEmptyValues:r,useBracketNotation:n}=t??{},i=Array.isArray(e)?Gn(e):e,a=r??!0?Vn(i??{}):i,s=n?Ml(a):a,c=new URLSearchParams(s);return o!=null&&j(o,u=>c.delete(u),!1),c}function Bo(e){let t;if(typeof e=="string")t=e;else if(wl(e))t=e.href;else{let o=Bo(e.url);if(e.queryParams){let r=Nl(e.queryParams);Tt(r)?t=o:t=ti(o+`?${r.toString()}`)}else t=o}return t}function wl(e){return typeof e=="object"&&e instanceof URL}function _l(e){return typeof e=="object"&&e instanceof URLSearchParams}function vl(e){let t=[];return _o(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 Nl(e){let t;return _l(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Be(e)?t=new URLSearchParams(vl(e)):t=Ul(e),t}function Ul(e){let t=[];return wn(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&j(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var $o=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}response};function Ll(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Gl=e=>{throw new $o(e)},$=e=>null;function Y(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Gl};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=Ti(o);return(a,s,c)=>{let u=Bo(a),l=i(s,c),h=typeof s=="object"?s.interceptResponse:void 0;return e(u,l).then(m=>{let R=m.json().catch(r),y=n?R.then(C=>n(C,m)):R;return h?y.then(C=>h(C,m)):y})}}function Ti(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Zn()}=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:Ll(i.body)}}}var OC=Ti();var X=fi({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});import{createParamDecorator as Kl}from"@nestjs/common";var oT=Kl((e,t)=>Vl(t));function Vl(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Yo,BadRequestException as zl,InternalServerErrorException as Jl,Logger as Hl}from"@nestjs/common";import ql from"raw-body";import{parse as Wl}from"node:querystring";var xi=new Hl("RawBody"),sT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw xi.error("RawBody request was not readable. This is generally due to bad configuration."),new zl("Invalid body");return ql(o)}),Ai=Yo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw xi.error("RawBody expected a buffer set to req.body."),new Jl("failed parsing body");return r}),cT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=jl(o.body),o.body});function jl(e){let t=Bl(e);return Wl(t)}function Bl(e){return e.toString("utf8").trim()}import{Injectable as $l}from"@nestjs/common";import Yl from"body-parser";var et=class{use(t,o,r){Yl.json()(t,o,r)}};et=F([$l()],et);import{Injectable as Xl}from"@nestjs/common";import Ql from"body-parser";var tt=class{use(t,o,r){Ql.raw({type:"*/*"})(t,o,r)}};tt=F([Xl()],tt);import{Logger as ed,Module as td,RequestMethod as od}from"@nestjs/common";var rd="/webhook",nd={path:`${rd}/{*path}`,method:od.POST},Xo=class{configure(t){id(t)}},jt=class extends Xo{logger=new ed("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};jt=F([td({})],jt);function id(e){e.apply(tt).forRoutes(nd).apply(et).forRoutes("{*path}")}var Zi="CLIENT_WEB_APP_URL";var we=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as ad,Injectable as sd}from"@nestjs/common";var _e=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]}};_e=F([sd(),b(0,ad(we))],_e);import{Module as cd}from"@nestjs/common";import{ConfigModule as ud,ConfigService as pd}from"@nestjs/config";function ld(e){let t={client:{clientWebAppUrl:e.get(Zi)}};return we.assertValidConfig(t),t}var Bt=class{};Bt=F([cd({imports:[ud],providers:[{provide:we,inject:[pd],useFactory:ld},_e],exports:[_e]})],Bt);var Si="SERVER_ENV_TOKEN";import{Inject as dd,Injectable as hd}from"@nestjs/common";function Fi(){return process.env.NODE_ENV==="test"}var $t=class{constructor(t){this.env=t}env;get isTestingEnv(){return Fi()}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}};$t=F([hd(),b(0,dd(Si))],$t);import{dirname as Cd}from"node:path";import{chmod as md,mkdirSync as yd,readFile as fd,writeFile as gd}from"node:fs";import{rm as Rd}from"node:fs/promises";function Fe(e){return new Promise((t,o)=>{fd(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 Yt(e){return yd(e.dirPath,{recursive:!0}),new Promise((t,o)=>{gd(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():md(e.filePath,e.mode,n=>{n?o(n):t()})})})}function Zt(e){return Rd(e,{force:!0})}var Td=384;function Ii(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??Td;async function a(){let l=await Fe(t),h;if(l==null)h={};else if(r==null)h=l;else{h={};for(let f of Object.keys(l)){let m=r(l[f]);m!=null&&(h[f]=m)}}return h}async function s(l){let h=n==null?l:Object.fromEntries(Object.entries(l).map(([f,m])=>[f,n(m)]));await Yt({filePath:t,dirPath:Cd(t),data:h,mode:i})}let c=Promise.resolve();function u(l){let h=c.then(l,l);return c=h.catch(()=>{}),h}return{load:a,get:async l=>(await a())[l],set:(l,h)=>u(async()=>{let f=await a();await s({...f,[l]:h})}),remove:l=>u(async()=>{let f={...await a()};delete f[l],await s(f)}),clear:()=>u(async()=>{await Zt(t)})}}var Fx=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 bi(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 Xt(e,t=nn){return async o=>{try{await e(o)}catch(r){hn(r),process.exit(t)}}}var xd=["raw","page_by_line","data_by_line"],Ad=["replace","concat"],Zd=["meta","pages","merged_page"];function Qt(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:Zd,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:xd,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:Ad,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function St(e){return Fe(e.configFilePath)}function Sd(e){return Yt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function Ft(e){let t=await St({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:Qo(t.output,e.updates.output)};return await Sd({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Qo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Fd(e?.commands,t)}}function Fd(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 ki(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 Ie(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Id}from"node:os";import{join as eo}from"node:path";function to(e){let t=e.configDirOverride??eo(Id(),`.${e.cliName}`);return{configDir:t,configFilePath:eo(t,"config.json"),tokenCachePath:eo(t,".tokens.json"),firestoreSessionCachePath:eo(t,".firestore-sessions.json")}}function Oi(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{cn(!!n.verbose),un(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("."),R={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,R)}let l=a&&!e.skipCommands.has(a),h=l?await o():void 0,f=l?ki({outputConfig:h,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};Do({dumpDir:f.dumpDir,pick:n.pickAll?void 0:f.pick,commandPath:i,pretty:!!n.pretty})}}function bd(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>Ft({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 Ei(e){let t=bd(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:Xt(async i=>{let a=i.command,s=i.setDumpDir,c=i.setPick,u;if(a){let h={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[a]:h}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let l=await t.loadOutputConfig();p({saved:!0,output:l??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:Xt(async()=>{let i=await t.loadOutputConfig();p({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:Xt(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new Rt({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}),p({cleared:!0,command:a})}else await t.clearOutputConfig(),p({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:A}}import{writeFileSync as kd,appendFileSync as Od}from"node:fs";function Pi(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=zt(),n=t==="raw"?"json":"ndjson",i=Ct(n),a=r?Ct(n,"pick"):void 0,s;if(i){let c=0,u=y=>{let C;if(r){let g=Me(y.data,r);C={...y,data:g}}else C=y;return C},l=y=>{let C=y.append?Od:kd;C(i,y.mainContent),a&&y.pickContent!==void 0&&C(a,y.pickContent)},h=(y,C)=>{let g=JSON.stringify(y,null,2),S=a?JSON.stringify(u(y),null,2):void 0;l({mainContent:g,pickContent:S,append:C})},f=(y,C)=>{let g=JSON.stringify(y)+`
|
|
5
|
+
`,S=a?JSON.stringify(u(y))+`
|
|
6
|
+
`:void 0;l({mainContent:g,pickContent:S,append:C})},m=(y,C)=>{let g=y.data??[],S=a?Me(g,r):void 0;g.length===0?C||l({mainContent:"",pickContent:a?"":void 0,append:!1}):g.forEach((O,q)=>{let I=C||q>0,_=JSON.stringify(O)+`
|
|
7
|
+
`,v=a&&S?JSON.stringify(S[q])+`
|
|
8
|
+
`:void 0;l({mainContent:_,pickContent:v,append:I})})};s={mainPath:i,pickPath:a,writePage:y=>{let g=o==="concat"&&!(c===0);t==="raw"?h(y,g):t==="page_by_line"?f(y,g):m(y,g),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Ed(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 l=0;l<o;l++){let h=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(h),c.lastResult=h,c.lastInput=u,i.writePage(h),a)c.collectedPages.push(h);else if(s)for(let m of h.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,h);let f=n.nextInput(u,h);if(!f)break;u=f}return c}function Pd(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:Me(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?Me(r.collectedRecords,i):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...a,...o}}))}}async function k(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=zt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let l=Pi({dumpOutput:i,dumpMerge:a}),h;try{h=await Ed({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:l,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{l.close()}let f={pagesFetched:h.pagesFetched,totalRecords:h.totalRecords,hasMorePagesAvailable:h.hasMorePagesAvailable,dumpFile:l.mainPath??null};l.pickPath&&(f.dumpFilePick=l.pickPath),Pd({multiplePagesOutput:n,summaryMeta:f,state:h,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import hg from"yargs";import{hideBin as mg}from"yargs/helpers";import{writeFile as Dd,mkdirSync as Md}from"node:fs";import{join as er}from"node:path";import{homedir as wd}from"node:os";var It=["recruit","crm","desk","sign","analytics"],_d=new Set(["sign","analytics"]),Ne=new Set(["desk","analytics"]);function tr(){return er(wd(),".zoho-cli")}function bt(){return er(tr(),"config.json")}function kt(){return er(tr(),".tokens.json")}function ve(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function B(){let e=bt(),t=await Fe(e),o=ve("ACCOUNTS_CLIENT_ID"),r=ve("ACCOUNTS_CLIENT_SECRET"),n=ve("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:ve("ACCOUNTS_URL")??t?.shared?.region,apiMode:ve("API_URL")??t?.shared?.apiMode},c=u=>{let l=u.toUpperCase(),h=ve("API_URL",l),f=Ne.has(u)?ve("ORG_ID",l):void 0,m=t?.[u],R=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_ID`],y=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_SECRET`],C=process.env[`ZOHO_${l}_ACCOUNTS_REFRESH_TOKEN`],g=R||y||C,S;return!m&&!g&&!f?S=void 0:S={clientId:R??m?.clientId,clientSecret:y??m?.clientSecret,refreshToken:C??m?.refreshToken,apiUrl:h??m?.apiUrl,orgId:f??m?.orgId},S};a={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,sign:c("sign")??t?.sign,analytics:c("analytics")??t?.analytics,output:t?.output}}return a}function Ue(e,t){let o=e[t],r=e.shared,n=!_d.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 vd(e){let t=bt();return Md(tr(),{recursive:!0}),new Promise((o,r)=>{Dd(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}function ot(e,t){return t==null?e??void 0:{...e,...Kn(t)}}async function ie(e){let t=await B(),o={shared:ot(t?.shared,e.shared),recruit:ot(t?.recruit,e.recruit),crm:ot(t?.crm,e.crm),desk:ot(t?.desk,e.desk),sign:ot(t?.sign,e.sign),analytics:ot(t?.analytics,e.analytics),output:e.output===void 0?t?.output:Qo(t?.output,e.output)};return await vd(o),o}async function Di(){await ie({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Mi(){let e=bt(),t=kt();await Zt(e),await Zt(t)}function ue(e){return It.filter(t=>{let o=Ue(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as mu,Injectable as Tm}from"@nestjs/common";function rt(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function J(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:li(o),per_page:n.maxItemsPerPage??r.per_page}}})}function oo(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 nt="Candidates",wi="Job_Openings",ro="Notes",_i="Emails",Ot="Attachments";function no(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=io(o);break}default:break}return t}function io(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(or):a&&(s=io(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=ce(a.map(t)).flatMap(x);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 vi=Wn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function or(e){let t=vi(e.value);return`(${e.field}:${e.filter}:${t})`}var Ni=no;import{BaseError as Bd}from"make-error";import{BaseError as Ud}from"make-error";var Ld="__internal_data_array_blank_error";function Gd(e){return Array.isArray(e?.data)}var st="success";function ae(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var be=class extends Ud{constructor(o){super(o.message);this.error=o}error;get code(){return this.error.code}},L=class extends be{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}data;errorResponseData;responseError},it=class extends L{constructor(t,o){super({code:Ld,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function Q(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof it&&!o||(r instanceof L?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof be?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ee(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Se){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function pe(e){return(t,o)=>{if(t?.error!=null){let n=new Se(o),i=e(t,n);if(i)throw i}return t}}var Kd="INTERNAL_ERROR",Vd="INVALID_TOKEN",G=class extends L{},Ui="FAILURE",rr=class extends L{},zd="4834",at=class extends L{},Jd="INVALID_QUERY",nr=class extends L{get details(){return this.error.details}},ao="MANDATORY_NOT_FOUND",ke="DUPLICATE_DATA",so="INVALID_DATA",Hd="TOO_MANY_REQUESTS",ir=429,qd="X-RATELIMIT-LIMIT",Wd="X-RATELIMIT-REMAINING",jd="X-RATELIMIT-RESET",Li=100,Gi=Re;function ar(e){let t=e.get(qd),o=e.get(Wd),r=e.get(jd),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 Ce=class extends L{get headerDetails(){return ar(this.responseError.response.headers)}};function te(e,t){let o;if(Gd(e))o=new it(e,t);else{let r=Te(e,t);if(r){let n=ae(r);switch(n.code){case Kd:o=new rr(n,e,t);break;case Vd:o=new G(n,e,t);break;case zd:o=new at(n,e,t);break;case Jd:o=new nr(n,e,t);break;case Hd:o=new Ce(n,e,t);break;default:o=new L(n,e,t);break}}}return o}function Te(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var Ki="ALREADY_ASSOCIATED",sr=class extends Bd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}moduleName;recordId},ct=class extends be{},cr=class extends ct{},ur=class extends ct{},co=class extends ct{get invalidFieldDetails(){return this.error.details}},pr=class extends co{};function Vi(e){let t;switch(e.code){case so:{let o=new co(e);o.invalidFieldDetails.id?t=new pr(e):t=o;break}case ao:t=new cr(e);break;case ke:t=new ur(e);break;default:t=new ct(e);break}return t}function zi(e,t){return o=>{if(!o?.data?.length)throw new sr(e,t);return o}}var $d=Q("ZohoRecruit");async function Yd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ji(t,e)),o}function Ji(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Hi=pe(Ji),qi=ee(Yd,$d);import{BaseError as Xd}from"make-error";function dr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,K(o,{data:x(r)})).then(i=>{let a=Array.isArray(r),s=le(x(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Vi(l[0].result);c=u[0].result.details}return c}))}function Wi(e){return dr(e,"","POST")}function ji(e){return dr(e,"/upsert","POST")}function Bi(e){return dr(e,"","PUT")}function $i(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,K("DELETE")).then(Qd)}function Yi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,K("GET")).then(zi(t.module)).then(o=>o.data[0])}function Xi(e){return(t=>e.fetchJson(`/v2/${t.module}?${aa(t).toString()}`,K("GET")))}function hr(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 aa(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,K("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Qi(e){return J(hr(e))}function ut(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${fr(n).toString()}`,K("GET")).then(i=>i??(r===!1?i:rt()))}}function mr(e){return ut(e)({targetModule:_i})}function ea(e){return J(mr(e))}function yr(e){return ut(e)({targetModule:Ot})}function ta(e){return J(yr(e))}var zA=20*1024*1024;function oa(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${Ot}?${T(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}&${T({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function ra(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function na(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"DELETE"})}var lr=class extends Xd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}error};function ia(e){return t=>{let r=T(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?oo(t.apiUrl):""}${a}`;return e.fetchJson(c,K("POST")).then(u=>{if(u.code!=="success")throw new lr(u);return u.details})}}function aa(...e){return T(e,{omitKeys:"module"})}function fr(...e){return T(e,{omitKeys:["id","module"]})}function K(e,t){return{method:e,body:t??void 0}}function Qd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===st?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function le(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===st?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function sa(e){return t=>e.fetchJson(`/v2/${nt}/actions/associate`,K("PUT",{data:x(t)})).then(o=>{let r=o.data.map(()=>t),n=le(r,o.data),{included:i,excluded:a}=$e(n.errorItems,s=>s.result.code===Ui&&s.result.details.error[0].code===Ki);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function ca(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${fr(t).toString()}`,K("GET")).then(o=>o??rt())}function gr(e){let t=ca(e);return o=>t({...o,module:nt})}function ua(e){return J(gr(e))}function Rr(e,t=wi){let o=ca(e);return r=>o({...r,module:t})}function pa(e){return J(Rr(e))}function Cr(e){return t=>e.fetchJson(`/v2/${ro}`,K("POST",{data:t.data})).then(o=>le(x(t.data),o.data))}function la(e){return t=>e.fetchJson(`/v2/${ro}?${T({ids:t.ids})}`,K("DELETE")).then(o=>le(x(t.ids),o.data))}function Tr(e){return ut(e)({targetModule:ro})}function da(e){return J(Tr(e))}function ha(e){let t=Cr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:x(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function fa(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,K("POST",{tags:x(t.tags)})).then(o=>{let r=le(x(t.tags),o.tags),{included:n,excluded:i}=$e(r.errorItems,a=>a.result.code===ke);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ga(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,K("GET")).then(o=>({...o,data:o.tags}))}var ma=100;function Ra(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ma)throw new Error(`Cannot add tags to more than ${ma} records at once.`);return e.fetchJson(`/v2/${nt}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var ya=100;function Ca(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ya)throw new Error(`Cannot remove tags from more than ${ya} records at once.`);return e.fetchJson(`/v2/${nt}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var eh="invalid_code",th="invalid_client",xr=class extends ne{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}errorCode},pt=class extends ne{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}reason},oh=Q("ZohoAccounts");async function rh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ta(t,e)),o}function Ta(e,t){let o,r=e.error;if(r){let n=ae(r);switch(n.code){case eh:case th:o=new xr(n.code);break;default:o=te(e,t);break}}return o}var xa=pe(Ta),Aa=ee(rh,oh);function de(e){return async()=>{let t=await e();if(!t.accessToken)throw new pt;return t.accessToken}}var nh=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 Et(e){let{readRateLimitDetails:t,enabledWithoutRateLimitDetails:o=!1}=e,r=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??nh,n=e.maxRateLimit??Li,i=e.resetPeriod??Gi;function a(u,l){return{limit:u,startLimitAt:Math.ceil(u/10),cooldownRate:1.2*(u/(i/z)),exponentRate:1.08,maxWaitTime:z*10,resetPeriod:i,resetAt:l}}let s=a(n),c=ai(s);return Ci({rateLimiter:c,maxRetries:e.maxRetries,updateWithResponse:function(u,l){let h=t(u.headers),f=!1,m=o;if(h){let{remaining:R,limit:y,resetAt:C}=h;if(y!=null&&y!==n){let g=a(y,C??void 0);c.setConfig(g,!1)}if(c.setRemainingLimit(R),C&&c.setNextResetAt(C),m=!0,u.status===ir){f=!0;try{r?.(h,u,l)}catch{}}}else if(o&&u.status===ir){f=!0;try{r?.({remaining:0},u,l)}catch{}}return c.setEnabled(m),f}})}function xe(e){return Et({...e,readRateLimitDetails:Ar})}function Ar(e){let t=ar(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Za(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>X.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=oo(a.apiUrl),c=i({apiUrl:s}),u=qi(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Hi,handleFetchJsonParseErrorFunction:$});return{recruitContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function uo(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 po="Notes",Sa="Emails",Pt="Attachments";var Fa=no;import{BaseError as ih}from"make-error";var Zr=class extends ih{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}moduleName;recordId},lt=class extends be{},Sr=class extends lt{},Fr=class extends lt{},lo=class extends lt{get invalidFieldDetails(){return this.error.details}},Ir=class extends lo{};function Ia(e){let t;switch(e.code){case so:{let o=new lo(e);o.invalidFieldDetails.api_name==="id"?t=new Ir(e):t=o;break}case ao:t=new Sr(e);break;case ke:t=new Fr(e);break;default:t=new lt(e);break}return t}function ba(e,t){return o=>{if(!o?.data?.length)throw new Zr(e,t);return o}}var ah=Q("ZohoCrm",{logDataArrayErrors:!1});async function sh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ka(t,e)),o}function ka(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Oa=pe(ka),Ea=ee(sh,ah);import{BaseError as ch}from"make-error";function kr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,H(o,{data:x(r)})).catch(Ha).then(i=>{let a=Array.isArray(r),s=Oe(x(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Ia(l[0].result);c=u[0].result.details}return c}))}function Pa(e){return kr(e,"","POST")}function Da(e){return kr(e,"/upsert","POST")}function Ma(e){return kr(e,"","PUT")}function wa(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,H("DELETE")).catch(Ha).then(ph)}function _a(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,H("GET")).then(ba(t.module)).then(o=>o.data[0])}function va(e){return(t=>e.fetchJson(`/v8/${t.module}?${Ja(t).toString()}`,H("GET")))}function Or(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Fa(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 Ja(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,H("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Na(e){return J(Or(e))}function dt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${uh(n).toString()}`,H("GET")).then(i=>i??(r===!1?i:rt()))}}function Er(e){let t=dt(e)({targetModule:Sa});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Ua(e){return J(Er(e))}function Pr(e){return dt(e)({targetModule:Pt})}function La(e){return J(Pr(e))}var oS=20*1024*1024;function Ga(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let a=`/v8/${t.module}/${t.id}/${Pt}?${T(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function Ka(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function Va(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"DELETE"})}var br=class extends ch{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}error};function za(e){return t=>{let r=T(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?uo(t.apiUrl):""}${a}`;return e.fetchJson(c,H("POST")).then(u=>{if(u.code!=="success")throw new br(u);return u.details})}}function Ja(...e){return T(e,{omitKeys:"module"})}function uh(...e){return T(e,{omitKeys:["id","module"]})}function H(e,t){return{method:e,body:t??void 0}}function Ha(e){let t;if(e instanceof it)t={data:e.errorDataArray};else throw e;return t}function ph(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===st?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Oe(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===st?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Dr(e){return t=>e.fetchJson(`/v2/${po}`,H("POST",{data:t.data})).then(o=>Oe(x(t.data),o.data))}function qa(e){return t=>e.fetchJson(`/v2/${po}?${T({ids:t.ids})}`,H("DELETE")).then(o=>Oe(x(t.ids),o.data))}function Mr(e){return dt(e)({targetModule:po})}function Wa(e){return J(Mr(e))}function ja(e){let t=Dr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:x(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function $a(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,H("POST",{tags:x(t.tags)})).catch(o=>{let r;if(o instanceof L){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Oe(x(t.tags),o.tags),{included:n,excluded:i}=$e(r.errorItems,a=>a.result.code===ke);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ya(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,H("DELETE")).then(o=>o.tags)}function Xa(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,H("GET")).then(o=>({...o,data:o.tags}))}var Ba=100;function Qa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function es(e){if(Array.isArray(e.ids)&&e.ids.length>Ba)throw new Error(`Cannot add/remove tags from more than ${Ba} records at once.`);let t=[...x(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&x(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:x(e.ids)}}function ts(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function os(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>X.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=uo(a.apiUrl),c=i({apiUrl:s}),u=Ea(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Oa,handleFetchJsonParseErrorFunction:$});return{crmContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var rs="https://signsandbox.zoho.com/api/v1",lh="https://sign.zoho.com/api/v1";function wr(e){let t;switch(e){case"sandbox":t=rs;break;case"production":t=lh;break;default:t=e;break}return t}function ns(e){let t=wr(e),o;try{o=new URL(t).hostname!==new URL(rs).hostname}catch{o=!0}return o}function is(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 he(e,t){return{method:e,body:t??void 0}}function as(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,he("GET"))}function _r(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)}},he("GET"))}}function ss(e){let t=_r(e);return is(t)}function cs(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,he("GET"))}function us(e){return()=>e.fetchJson("/fieldtypes",he("GET"))}function ps(e){return({requestId:t,...o})=>{let n=T(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function ls(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function ds(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 hs(e){return({templateId:t,data:o,isQuickSend:r=!0})=>{let n=T({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 ms(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,he("GET"))}function ys(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)}},he("GET"))}}function fs(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,he("PUT",{requests:o}))}function gs(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,he("POST",r))}}function Rs(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,he("PUT",{expire_by:o}))}function Cs(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=T(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 Ts(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ns(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}},he("POST"))}}var dh=Q("ZohoSign",{logDataArrayErrors:!1});async function hh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=xs(t,e)),o}function xs(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var As=pe(xs),Zs=ee(hh,dh);function Ss(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>X.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=wr(a.apiUrl),c=i({apiUrl:s}),u=Zs(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:As,handleFetchJsonParseErrorFunction:$});return{signContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Fs(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var mh=Q("ZohoDesk",{logDataArrayErrors:!1});async function yh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Is(t,e)),o}function Is(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var bs=pe(Is),ks=ee(yh,mh);var fh="X-Rate-Limit-Remaining-v3",gh="Retry-After",Rh=200;function Ch(e){let t=e.get(fh),o;if(t!=null){let r=Number(t),n,i=e.get(gh);if(i!=null){let a=Number(i);Number.isNaN(a)||(n=new Date(Date.now()+a*z))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Os(e){return Et({maxRateLimit:Rh,...e,readRateLimitDetails:Ch})}function Es(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Os(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>X.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=Fs(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=ks(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:bs,handleFetchJsonParseErrorFunction:$});return{deskContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ps=25;function se(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ps}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Ps,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Le(e,t){return{method:e,body:t??void 0}}function ht(e,t){return T(e,{omitKeys:t})}function ho(e){let t;return e&&(t=P(x(e))),t}function vr(e){return t=>{let{include:o,...r}=t,n=ht([{...r,include:ho(o)}]);return e.fetchJson(`/tickets?${n}`,Le("GET")).then(i=>i??{data:[]})}}function Ds(e){return t=>{let{ticketId:o,include:r}=t,i=ht([{include:ho(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Le("GET"))}}function Nr(e){return t=>{let o=ht([t]);return e.fetchJson(`/tickets/search?${o}`,Le("GET")).then(r=>r??{data:[]})}}function Ms(e){return t=>{let{contactId:o,include:r,...n}=t,i=ht([{...n,include:ho(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Le("GET")).then(a=>a??{data:[]})}}function ws(e){return t=>{let{productId:o,include:r,...n}=t,i=ht([{...n,include:ho(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Le("GET")).then(a=>a??{data:[]})}}function _s(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Le("GET"))}function vs(e){return t=>{let o=ht([{agentIds:P(x(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Le("GET"))}}function Ns(e){return se(vr(e))}function Us(e){return se(Nr(e))}function Ls(e){return{method:e}}function Gs(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Ls("GET")).then(r=>r??{data:[]})}}function Ks(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ls("GET"))}function Ur(e){return{method:e}}function Vs(e){let t;return e&&(t=P(x(e))),t}function Lr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Vs(o)}]);return e.fetchJson(`/contacts?${n}`,Ur("GET")).then(i=>i??{data:[]})}}function zs(e){return t=>{let{contactId:o,include:r}=t,i=T([{include:Vs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,Ur("GET"))}}function Js(e){return t=>{let o=T([{contactIds:P(x(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Ur("GET")).then(r=>r??[])}}function Hs(e){return se(Lr(e))}function Dt(e,t){return{method:e,body:t??void 0}}function qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("GET")).then(o=>o??[])}function Ws(e){return t=>{let o={tags:x(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("POST",o)).then(r=>r??[])}}function js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Dt("DELETE"))}function Bs(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function $s(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function Gr(e,t){return{method:e,body:t??void 0}}function Ys(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("GET")).then(o=>o??[])}function Xs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("POST",o))}}function Qs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("DELETE",o))}}function ec(e,t){return{method:e,body:t??void 0}}function Th(e){let t;return e&&(t=P(x(e))),t}function tc(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:Th(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,ec("GET")).then(a=>a??{data:[]})}}function oc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,ec("DELETE"))}function mo(e,t){return{method:e,body:t??void 0}}function rc(e){let t;return e&&(t=P(x(e))),t}function nc(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:rc(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,mo("GET")).then(a=>a??{data:[]})}}function ic(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:rc(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,mo("GET"))}}function ac(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,mo("POST",r))}}function sc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,mo("DELETE"))}function Mt(e,t){return{method:e,body:t??void 0}}function cc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Mt("GET"))}function uc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Mt("POST",r))}}function pc(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Mt("GET")).then(i=>i??{data:[]})}}function lc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Mt("GET"))}function dc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Mt("GET"))}function hc(e){return{method:e}}function mc(e){let t;return e&&(t=P(x(e))),t}function Kr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:mc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,hc("GET")).then(a=>a??{data:[]})}}function yc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:mc(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,hc("GET"))}}function fc(e){return se(Kr(e))}function xh(e){return{method:e}}function Ah(e){let t;return e&&(t=P(x(e))),t}function Vr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:Ah(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,xh("GET")).then(a=>a??{data:[]})}}function gc(e){return se(Vr(e))}function yo(e){return{method:e}}function Rc(e){let t;return e&&(t=P(x(e))),t}function zr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Rc(o)}]);return e.fetchJson(`/agents?${n}`,yo("GET")).then(i=>i??{data:[]})}}function Cc(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:Rc(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,yo("GET"))}}function Tc(e){return t=>{let o=T([{agentIds:P(x(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,yo("GET")).then(r=>r?.data??[])}}function xc(e){return()=>e.fetchJson("/myinfo",yo("GET"))}function Ac(e){return se(zr(e))}var Zh="https://accounts.zoho.com",Sh="https://accounts.zoho.eu",Fh="https://accounts.zoho.in",Ih="https://accounts.zoho.com.au",bh="https://accounts.zoho.jp",kh="https://accounts.zoho.uk",Oh="https://accounts.zohocloud.ca",Eh="https://accounts.zoho.sa",Ph={us:Zh,eu:Sh,in:Fh,au:Ih,jp:bh,uk:kh,ca:Oh,sa:Eh};function Ge(e){return Ph[e]??e}var fo="/oauth/v2/token";function go(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,l=T({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`${fo}?${l}`,Jr("POST"))}}function Zc(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,refreshToken:i}=t,a=n?.clientId??o,s=n?.clientSecret??r,c=T({grant_type:"refresh_token",client_id:a,client_secret:s,refresh_token:i});return e.fetchJson(`${fo}?${c}`,Jr("POST"))}}function Sc(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=T({grant_type:"authorization_code",client_id:s,client_secret:c,code:i,redirect_uri:a});return e.fetchJson(`${fo}?${u}`,Jr("POST"))}}var Dh="/oauth/user/info";function Fc(e){return t=>e.fetchJson(Dh,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Jr(e,t){return{method:e,body:t}}function Ic(e){return t=>X.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function bc(e,t){let o=Aa(e,t),r=Y(o,{interceptJsonResponse:xa,handleFetchJsonParseErrorFunction:$});return{fetch:o,fetchJson:r}}function kc(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(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=Ge(n.apiUrl??"us"),a=r({apiUrl:i}),{fetch:s,fetchJson:c}=bc(a,o),u=async()=>{let m=Date.now(),{access_token:R,api_domain:y,scope:C,expires_in:g}=await go(h)();return{accessToken:R,apiDomain:y,expiresIn:g,expiresAt:new Date(m+g*z),scope:C}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let l=Mh({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),h={fetch:s,fetchJson:c,loadAccessToken:l,config:{...n,apiUrl:i}};return{accountsContext:h}}}function Oc(e){let t=e.fetchHandler??xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(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=Ge(n.apiUrl??"us"),a=r({apiUrl:i}),{fetchJson:s}=bc(a,o),c={...n,apiUrl:i};return{oauthClientContext:{fetchJson:s,config:c}}}}function Mh(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Re,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 pt("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}var Ec="ZANALYTICS-ORGID";function Pc(e){let t;switch(e){case"sandbox":case"production":t="https://analyticsapi.zoho.com/restapi/v2";break;default:t=e;break}return t}var wh="CONFIG",_h="application/x-www-form-urlencoded";function Dc(e){return e==null?"":T({[wh]:JSON.stringify(e)}).toString()}function Ee(e){let t=Dc(e);return t?`?${t}`:""}function V(e,t){return{method:e,body:t??void 0}}function Ro(e,t){return{method:e,headers:{"Content-Type":_h},body:Dc(t)}}var vh="failure",Nh="8535",Uh="8083",Lh="6045",Gh=["6043","6044"],Hr=class extends L{};function Mc(e){return e?.status===vh}function Kh(e){let{summary:t,data:o}=e,r=o?.errorCode;return{code:r==null?t??"":String(r),message:o?.errorMessage??t??"",details:{summary:t}}}function wc(e,t){let o;if(Mc(e)){let r=Kh(e),n={error:r};switch(r.code){case Nh:o=new G(r,n,t);break;case Uh:o=new Hr(r,n,t);break;case Lh:o=new Ce(r,n,t);break;default:o=Gh.includes(r.code)?new Ce(r,n,t):new L(r,n,t);break}}else o=te(e,t);return o}var Vh=Q("ZohoAnalytics",{logDataArrayErrors:!1});async function zh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=wc(t,e)),o}var _c=(e,t)=>{if(Mc(e)){let o=wc(e,new Se(t));if(o)throw o}return e},vc=ee(zh,Vh);var Jh=100;var Hh=Re;function Nc(e){return Et({maxRateLimit:Jh,resetPeriod:Hh,...e,readRateLimitDetails:Ar,enabledWithoutRateLimitDetails:!0})}var qh="1001",Wh="1002";var jh="1004";var Bh=z*2,$h=150;function Yh(e){return e===qh||e===Wh}function Pe(e){return e===jh}function Co(e){let{loadJob:t,readJobCode:o,pollWait:r=Bh,maxPolls:n=$h}=e;return ni({next:async i=>(i>0&&await At(r),t()),checkContinue:(i,a)=>i!=null&&Yh(o(i))&&a<n})}var Xh=65279;function Qh(e,t){let o=e.codePointAt(0)===Xh?e.slice(1):e,r=[],n=[],i="",a=!1,s=!1,c=0;for(;c<o.length;){let u=o[c];a?u==='"'?o[c+1]==='"'?(i+='"',c+=2):(a=!1,c+=1):(i+=u,c+=1):u==='"'&&i===""?(a=!0,s=!0,c+=1):u===t?(n.push(i),i="",s=!0,c+=1):u===`
|
|
9
|
+
`||u==="\r"?(n.push(i),r.push(n),n=[],i="",s=!1,c+=u==="\r"&&o[c+1]===`
|
|
10
|
+
`?2:1):(i+=u,s=!0,c+=1)}return(s||i!==""||n.length>0)&&(n.push(i),r.push(n)),r}function em(e,t){let o=Qh(e,t??","),[r,...n]=o,i;if(r==null)i={columnNames:[],rows:[]};else{let a=r.map(c=>c.trim()),s=n.map(c=>{let u={};return a.forEach((l,h)=>{l!==""&&(u[l]=c[h]??"")}),u});i={columnNames:Uo(a.filter(c=>c!=="")),rows:s}}return i}function tm(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`zohoAnalyticsRowDataFromJson(): the content is not valid JSON. ${i.message}`,{cause:i})}let o=i=>i!=null&&typeof i=="object"&&!Array.isArray(i),r=Array.isArray(t)?t:[t];if(!r.every(o))throw new Error("zohoAnalyticsRowDataFromJson(): the content must be an array of row objects, as a Zoho Analytics JSON import is.");let n=r;return{columnNames:Uo(n.flatMap(i=>Object.keys(i))),rows:n}}function Uc(e){let{content:t,fileType:o,delimiter:r}=e;return o==="json"?tm(t):em(t,r)}var om=3,rm=/[\s,%$£€¥]/g,nm=new Set(["true","false","yes","no","y","n","t","f","1","0"]),im=/^[\d\s/.:+-]+$/,am=new Set(["PLAIN","MULTI_LINE","EMAIL","URL"]);function qr(e){return e==null?"":String(e).trim()}var sm=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,cm=/^www\./i;function mt(e){let{text:t,allowNegative:o,allowFraction:r}=e,n=Number(t.replaceAll(rm,"")),i;return Number.isFinite(n)?!o&&n<0?i="negative":!r&&!Number.isInteger(n)&&(i="notAnInteger"):i="notANumber",i}var um={NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),AUTO_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),POSITIVE_NUMBER:e=>mt({text:e,allowNegative:!1,allowFraction:!1}),DECIMAL_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),CURRENCY:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),PERCENT:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),DATE:e=>Number.isNaN(Date.parse(e))&&!im.test(e)?"notADate":void 0,BOOLEAN:e=>nm.has(e.toLowerCase())?void 0:"notABoolean",EMAIL:e=>sm.test(e)?void 0:"notAnEmail",URL:e=>URL.canParse(e)||cm.test(e)?void 0:"notAUrl"};function pm(e,t,o){let r=o==null||am.has(o);return t.columnMaxSize!=null&&e.length>t.columnMaxSize&&r}function lm(e,t){let o=qr(e),r=t.dataType?.toUpperCase(),n;return o===""?n=t.isNullable===!1&&t.defaultValue==null?"emptyInNonNullable":void 0:pm(o,t,r)?n="tooLong":n=r==null?void 0:um[r]?.(o),n}function dm(e,t){return`${e}\0${t}`}function Lc(e){let{columns:t,columnNames:o,rows:r,maxSamples:n}=e,i=n??om,a=new Map(t.map(g=>[g.columnName,g])),s=new Map(t.map(g=>[g.columnName.trim().toLowerCase(),g.columnName])),c=new Set(o),u=[],l=[],h=[],f=new Set;o.forEach(g=>{let S=s.get(g.trim().toLowerCase());a.has(g)?u.push(g):S==null?l.push(g):(h.push({dataColumnName:g,tableColumnName:S}),f.add(S))});let m=l.map(g=>({columnName:g,valueCount:r.reduce((S,O)=>qr(O[g])===""?S:S+1,0)})),R=t.filter(g=>!c.has(g.columnName)&&!f.has(g.columnName)).map(g=>({columnName:g.columnName,dataType:g.dataType,isNullable:g.isNullable,required:g.isNullable===!1&&g.defaultValue==null})),y=new Map;r.forEach((g,S)=>{u.forEach(O=>{let q=a.get(O),I=lm(g[O],q);if(I!=null){let _=dm(O,I),v=y.get(_);if(v==null){let W=[];v={conflict:{columnName:O,dataType:q.dataType,reason:I,conflictCount:0,samples:W},count:0,samples:W},y.set(_,v)}v.count+=1,v.samples.length<i&&v.samples.push({row:S+1,value:qr(g[O])})}})});let C=Array.from(y.values()).map(g=>({...g.conflict,conflictCount:g.count}));return{matchedColumns:u,droppedColumns:m,emptyColumns:R,caseMismatchedColumns:h,conflicts:C,rowCount:r.length}}function Gc(e,t){let o=t?.strict?e.emptyColumns.length:e.emptyColumns.filter(r=>r.required).length;return e.droppedColumns.length===0&&e.caseMismatchedColumns.length===0&&e.conflicts.length===0&&o===0}function Kc(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Nc(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>X.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Zoho-oauthtoken ${await o()}`,...a.orgId?{[Ec]:a.orgId}:void 0}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoAnalyticsConfig missing api url.");let s=Pc(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=vc(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:_c,handleFetchJsonParseErrorFunction:$});return{analyticsContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Vc(e){return()=>e.fetchJson("/orgs",V("GET"))}function zc(e){return()=>e.fetchJson("/workspaces",V("GET"))}function Jc(e){return()=>e.fetchJson("/workspaces/owned",V("GET"))}function Hc(e){return()=>e.fetchJson("/workspaces/shared",V("GET"))}function qc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("GET"))}function Wc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views`,V("GET"))}function jc(e){return t=>e.fetchJson(`/views/${t.viewId}`,V("GET"))}function Bc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/metadata`,V("GET"))}var hm="import";function mm(e,t){let{file:o,data:r,rows:n}=e,i=new FormData;if(o!=null)i.append("FILE",o);else{if(r==null&&n==null)throw new Error("zohoAnalyticsImportFormData(): one of file, data, or rows must be provided.");{let a=r??JSON.stringify(n);if(t?.asFile){let s=t.fileType??(n==null?"csv":"json");i.append("FILE",new File([a],`${hm}.${s}`,{type:s==="json"?"application/json":"text/csv"}))}else i.append("DATA",a)}}return i}function Wr(e,t){let{file:o,rows:r}=e,n=t;if(n==null){if(r!=null)n="json";else if(o!=null){let i=o.name.split(".").pop()?.toLowerCase();n=i==="json"||i==="csv"?i:void 0}}return n}function To(e){return e??!0}function $c(e,t){let o=Wr(e,t);if(o==null)throw new Error("zohoAnalyticsCreateImportJob(): config.fileType is required for an async import job when the data is not rows or a file with a .csv/.json name.");return o}async function xo(e){let{context:t,url:o,config:r,dataInput:n,formDataOptions:i}=e,a=mm(n,i);return(await t.fetch(`${o}${Ee(r)}`,{method:"POST",headers:{"Content-Type":""},body:a})).json()}function Yc(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a={...n,autoIdentify:To(n.autoIdentify),fileType:Wr(i,n.fileType)};return xo({context:e,url:`/workspaces/${o}/views/${r}/data`,config:a,dataInput:i})}}function Xc(e){return t=>{let{workspaceId:o,config:r,...n}=t,i={...r,autoIdentify:To(r.autoIdentify),fileType:Wr(n,r.fileType)};return xo({context:e,url:`/workspaces/${o}/data`,config:i,dataInput:n})}}function jr(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a=$c(i,n.fileType),s={...n,autoIdentify:To(n.autoIdentify),fileType:a};return xo({context:e,url:`/bulk/workspaces/${o}/views/${r}/data`,config:s,dataInput:i,formDataOptions:{asFile:!0,fileType:a}})}}function Qc(e){return t=>{let{workspaceId:o,config:r,...n}=t,i=$c(n,r.fileType),a={...r,autoIdentify:To(r.autoIdentify),fileType:i};return xo({context:e,url:`/bulk/workspaces/${o}/data`,config:a,dataInput:n,formDataOptions:{asFile:!0,fileType:i}})}}function Br(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/importjobs/${t.jobId}`,{method:"GET"})}function eu(e){let t=jr(e),o=Br(e);return async r=>{let{poll:n,...i}=r,{data:a}=await t(i);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function tu(e){return t=>e.fetch(`/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,{method:"GET"})}function $r(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,V("GET"))}function ou(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/data${Ee(t.config)}`,V("GET"))}function Yr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}`,V("GET"))}function ru(e){return t=>e.fetch(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}/data`,{method:"GET"})}function nu(e){let t=$r(e),o=Yr(e);return async r=>{let{poll:n,...i}=r,{data:a}=await t(i);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function iu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("POST",t.config))}function au(e){return t=>{let{criteria:o,updateAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsUpdateRows(): either criteria or updateAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("PUT",t.config))}}function su(e){return t=>{let{criteria:o,deleteAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsDeleteRows(): either criteria or deleteAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("DELETE",t.config))}}function cu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}${Ee(t.config)}`,V("DELETE"))}function uu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("DELETE"))}function me(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Ae=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 ym}from"@nestjs/common";var yt=class{};yt=F([ym()],yt);function fm(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Ln(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function gm(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Rm(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function lu(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Rm;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(fm),c=qn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let l=await Promise.allSettled(a.map(h=>gm(h,u)));if(r!=null){let h=ce(l.map(f=>f.value));h.length&&r(h)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function du(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=Jn(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 Cm=".tmp/zoho-access-tokens.json";function pu(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 hu(e=Cm,t=!0){let o=Ii({filePath:e,reviver:pu}),r=t?Hn(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(l){console.error("Failed updating access token in file: ",l)}},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 l={};for(let h of Object.keys(c))l[h]=pu(c[h]);u=l}return u}async function a(c){await r.clear();for(let[u,l]of Object.entries(c))l!=null&&await r.set(u,l)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:i,writeTokenFile:a,deleteTokenFile:s}}var w=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=kc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}config;cacheService;zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return go(this.accountsContext)}};w=F([Tm(),b(0,mu(Ae)),b(1,mu(yt))],w);import{Inject as Zm,Injectable as Sm}from"@nestjs/common";var xm="ZOHO_ACCOUNTS_CLIENT_ID",Am="ZOHO_ACCOUNTS_CLIENT_SECRET",ft=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 (${xm}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${Am}).`)}};var _t=class{constructor(t){this.config=t;ft.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=Ge(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Oc(t.factoryConfig??{})}config;_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=Ge(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 Sc(i)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Zc(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Fc(n)({accessToken:o})}};_t=F([Sm(),b(0,Zm(ft))],_t);import{ConfigModule as Ek,ConfigService as Pk}from"@nestjs/config";import{Inject as yu,Injectable as Fm}from"@nestjs/common";var vt=class{zohoCrm;factoryConfig;static assertValidConfig(t){me(t.zohoCrm)}};var Ke=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=os({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}config;zohoAccountsApi;zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Pa(this.crmContext)}get upsertRecord(){return Da(this.crmContext)}get updateRecord(){return Ma(this.crmContext)}get deleteRecord(){return wa(this.crmContext)}get getRecordById(){return _a(this.crmContext)}get getRecords(){return va(this.crmContext)}get searchRecords(){return Or(this.crmContext)}get searchRecordsPageFactory(){return Na(this.crmContext)}get getRelatedRecordsFunctionFactory(){return dt(this.crmContext)}get getEmailsForRecord(){return Er(this.crmContext)}get getEmailsForRecordPageFactory(){return Ua(this.crmContext)}get getAttachmentsForRecord(){return Pr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return La(this.crmContext)}get uploadAttachmentForRecord(){return Ga(this.crmContext)}get downloadAttachmentForRecord(){return Ka(this.crmContext)}get deleteAttachmentFromRecord(){return Va(this.crmContext)}get createNotes(){return Dr(this.crmContext)}get deleteNotes(){return qa(this.crmContext)}get createNotesForRecord(){return ja(this.crmContext)}get getNotesForRecord(){return Mr(this.crmContext)}get getNotesForRecordPageFactory(){return Wa(this.crmContext)}get executeRestApiFunction(){return za(this.crmContext)}get createTagsForModule(){return $a(this.crmContext)}get deleteTag(){return Ya(this.crmContext)}get getTagsForModule(){return Xa(this.crmContext)}get addTagsToRecords(){return Qa(this.crmContext)}get removeTagsFromRecords(){return ts(this.crmContext)}};Ke=F([Fm(),b(0,yu(vt)),b(1,yu(w))],Ke);import{ConfigModule as Xk,ConfigService as Qk}from"@nestjs/config";import{Inject as fu,Injectable as Im}from"@nestjs/common";var Nt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){me(t.zohoRecruit)}};var Ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Za({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}config;zohoAccountsApi;zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Wi(this.recruitContext)}get upsertRecord(){return ji(this.recruitContext)}get updateRecord(){return Bi(this.recruitContext)}get deleteRecord(){return $i(this.recruitContext)}get getRecordById(){return Yi(this.recruitContext)}get getRecords(){return Xi(this.recruitContext)}get searchRecords(){return hr(this.recruitContext)}get searchRecordsPageFactory(){return Qi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ut(this.recruitContext)}get getEmailsForRecord(){return mr(this.recruitContext)}get getEmailsForRecordPageFactory(){return ea(this.recruitContext)}get getAttachmentsForRecord(){return yr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return ta(this.recruitContext)}get uploadAttachmentForRecord(){return oa(this.recruitContext)}get downloadAttachmentForRecord(){return ra(this.recruitContext)}get deleteAttachmentFromRecord(){return na(this.recruitContext)}get createNotes(){return Cr(this.recruitContext)}get deleteNotes(){return la(this.recruitContext)}get createNotesForRecord(){return ha(this.recruitContext)}get getNotesForRecord(){return Tr(this.recruitContext)}get getNotesForRecordPageFactory(){return da(this.recruitContext)}get executeRestApiFunction(){return ia(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return sa(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return gr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return ua(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Rr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return pa(this.recruitContext)}get createTagsForModule(){return fa(this.recruitContext)}get getTagsForModule(){return ga(this.recruitContext)}get addTagsToRecords(){return Ra(this.recruitContext)}get removeTagsFromRecords(){return Ca(this.recruitContext)}};Ve=F([Im(),b(0,fu(Nt)),b(1,fu(w))],Ve);import{ConfigModule as xO,ConfigService as AO}from"@nestjs/config";import{Inject as gu,Injectable as bm}from"@nestjs/common";var Ut=class{zohoSign;factoryConfig;static assertValidConfig(t){me(t.zohoSign)}};var ze=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ss({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}config;zohoAccountsApi;zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return as(this.signContext)}get getDocuments(){return _r(this.signContext)}get getDocumentsPageFactory(){return ss(this.signContext)}get getDocumentFormData(){return cs(this.signContext)}get retrieveFieldTypes(){return us(this.signContext)}get downloadPdf(){return ps(this.signContext)}get downloadCompletionCertificate(){return ls(this.signContext)}get createDocument(){return ds(this.signContext)}get createDocumentFromTemplate(){return hs(this.signContext)}get getTemplate(){return ms(this.signContext)}get getTemplates(){return ys(this.signContext)}get updateDocument(){return fs(this.signContext)}get sendDocumentForSignature(){return gs(this.signContext)}get extendDocument(){return Rs(this.signContext)}get deleteDocument(){return Cs(this.signContext)}get getEmbeddedSigningUrl(){return Ts(this.signContext)}};ze=F([bm(),b(0,gu(Ut)),b(1,gu(w))],ze);import{ConfigModule as JO,ConfigService as HO}from"@nestjs/config";function Ru(e){return{...e,operationType:e.notifications.operation_type}}var Cu=si(e=>e.operationType),Tu=ui({configurerForAccessor:e=>{let t=ci(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 xu="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Je=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as wm,Inject as _m,Post as vm,Req as Nm}from"@nestjs/common";import{Inject as Pm,Injectable as Dm,Logger as Mm}from"@nestjs/common";import{createHmac as km,timingSafeEqual as Om}from"node:crypto";var Em="x-zs-webhook-signature";function Au(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Em],i={valid:!1};if(n){let a=r.toString("utf-8"),s=km("sha256",t).update(a,"utf-8").digest("base64"),c=!1;try{let l=Buffer.from(n,"base64"),h=Buffer.from(s,"base64");l.length===h.length&&(c=Om(l,h))}catch{c=!1}let u;if(c)try{let l=JSON.parse(a);u=Ru(l)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var Ze=class{logger=new Mm("ZohoSignWebhookService");_verifier;handler=Cu();configure=Tu(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Au({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)}};Ze=F([Dm(),b(0,Pm(Je))],Ze);var He=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([vm(),b(0,Nm()),b(1,Ai())],He.prototype,"handleZohoSignWebhook",1),He=F([wm("/webhook/zoho/sign"),b(0,_m(Ze))],He);import{Module as Um}from"@nestjs/common";import{ConfigModule as Lm,ConfigService as Gm}from"@nestjs/config";function Km(e){let t={zohoSignWebhook:{webhookSecret:e.get(xu)}};return Je.assertValidConfig(t),t}var So=class{};So=F([Um({imports:[Lm],controllers:[He],providers:[{provide:Je,inject:[Gm],useFactory:Km},Ze],exports:[Ze]})],So);import{Inject as Zu,Injectable as Vm}from"@nestjs/common";var Lt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(me(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var qe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Es({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}config;zohoAccountsApi;zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return vr(this.deskContext)}get getTicketById(){return Ds(this.deskContext)}get searchTickets(){return Nr(this.deskContext)}get getTicketsForContact(){return Ms(this.deskContext)}get getTicketsForProduct(){return ws(this.deskContext)}get getTicketMetrics(){return _s(this.deskContext)}get getAgentsTicketsCount(){return vs(this.deskContext)}get getTicketsPageFactory(){return Ns(this.deskContext)}get searchTicketsPageFactory(){return Us(this.deskContext)}get getDepartments(){return Gs(this.deskContext)}get getDepartmentById(){return Ks(this.deskContext)}get getContacts(){return Lr(this.deskContext)}get getContactById(){return zs(this.deskContext)}get getContactsByIds(){return Js(this.deskContext)}get getContactsPageFactory(){return Hs(this.deskContext)}get getTicketTags(){return qs(this.deskContext)}get associateTicketTags(){return Ws(this.deskContext)}get dissociateTicketTag(){return js(this.deskContext)}get searchTags(){return Bs(this.deskContext)}get getAllTags(){return $s(this.deskContext)}get getTicketFollowers(){return Ys(this.deskContext)}get addTicketFollowers(){return Xs(this.deskContext)}get removeTicketFollowers(){return Qs(this.deskContext)}get getTicketAttachments(){return tc(this.deskContext)}get deleteTicketAttachment(){return oc(this.deskContext)}get getTicketComments(){return nc(this.deskContext)}get getTicketCommentById(){return ic(this.deskContext)}get createTicketComment(){return ac(this.deskContext)}get deleteTicketComment(){return sc(this.deskContext)}get getTicketTimer(){return cc(this.deskContext)}get performTicketTimerAction(){return uc(this.deskContext)}get getTicketTimeEntries(){return pc(this.deskContext)}get getTicketTimeEntryById(){return lc(this.deskContext)}get getTicketTimeEntrySummation(){return dc(this.deskContext)}get getTicketThreads(){return Kr(this.deskContext)}get getTicketThreadById(){return yc(this.deskContext)}get getTicketThreadsPageFactory(){return fc(this.deskContext)}get getTicketActivities(){return Vr(this.deskContext)}get getTicketActivitiesPageFactory(){return gc(this.deskContext)}get getAgents(){return zr(this.deskContext)}get getAgentById(){return Cc(this.deskContext)}get getAgentsByIds(){return Tc(this.deskContext)}get getMyInfo(){return xc(this.deskContext)}get getAgentsPageFactory(){return Ac(this.deskContext)}};qe=F([Vm(),b(0,Zu(Lt)),b(1,Zu(w))],qe);import{ConfigModule as HE,ConfigService as qE}from"@nestjs/config";import{Inject as Su,Injectable as zm}from"@nestjs/common";var Gt=class{zohoAnalytics;factoryConfig;static assertValidConfig(t){me(t.zohoAnalytics)}};var We=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoAnalytics=Kc({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoAnalytics)}config;zohoAccountsApi;zohoAnalytics;get analyticsContext(){return this.zohoAnalytics.analyticsContext}get zohoRateLimiter(){return this.zohoAnalytics.analyticsContext.zohoRateLimiter}get getOrgs(){return Vc(this.analyticsContext)}get getAllWorkspaces(){return zc(this.analyticsContext)}get getOwnedWorkspaces(){return Jc(this.analyticsContext)}get getSharedWorkspaces(){return Hc(this.analyticsContext)}get getWorkspaceDetails(){return qc(this.analyticsContext)}get getViews(){return Wc(this.analyticsContext)}get getViewDetails(){return jc(this.analyticsContext)}get getTableMetadata(){return Bc(this.analyticsContext)}get importDataInTable(){return Yc(this.analyticsContext)}get importDataInNewTable(){return Xc(this.analyticsContext)}get createImportJobInTable(){return jr(this.analyticsContext)}get createImportJobInNewTable(){return Qc(this.analyticsContext)}get getImportJob(){return Br(this.analyticsContext)}get importDataInTableAndAwaitJob(){return eu(this.analyticsContext)}get exportData(){return tu(this.analyticsContext)}get createExportJob(){return $r(this.analyticsContext)}get createExportJobForSqlQuery(){return ou(this.analyticsContext)}get getExportJob(){return Yr(this.analyticsContext)}get downloadExport(){return ru(this.analyticsContext)}get exportDataAndAwaitJob(){return nu(this.analyticsContext)}get addRow(){return iu(this.analyticsContext)}get updateRows(){return au(this.analyticsContext)}get deleteRows(){return su(this.analyticsContext)}get deleteView(){return cu(this.analyticsContext)}get deleteWorkspace(){return uu(this.analyticsContext)}};We=F([zm(),b(0,Su(Gt)),b(1,Su(w))],We);import{ConfigModule as mP,ConfigService as yP}from"@nestjs/config";function Fo(e){return{recruit:e.recruitApi,crm:e.crmApi,desk:e.deskApi,sign:e.signApi,analytics:e.analyticsApi}}function Jm(e){return`${e.clientId}:${e.refreshToken}`}function gt(e){let t=lu([du(),hu(kt())]),o=new Map;function r(R,y){let C=Jm(R),g=o.get(C),S;if(g)S=g;else{let O={zohoAccounts:{serviceAccessTokenKey:y,refreshToken:R.refreshToken,clientId:R.clientId,clientSecret:R.clientSecret,apiUrl:R.region??"us"}};S=new w(O,t),o.set(C,S)}return S}let n,i=Ue(e,"recruit");if(i){let R=r(i,"recruit"),y={zohoRecruit:{apiUrl:i.apiMode}};n=new Ve(y,R)}let a,s=Ue(e,"crm");if(s){let R=r(s,"crm"),y={zohoCrm:{apiUrl:s.apiMode}};a=new Ke(y,R)}let c,u=Ue(e,"desk");if(u?.orgId){let R=r(u,"desk"),y={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new qe(y,R)}let l,h=Ue(e,"sign");if(h){let R=r(h,"sign"),y={zohoSign:{apiUrl:h.apiMode}};l=new ze(y,R)}let f,m=Ue(e,"analytics");if(m){let R=r(m,"analytics"),y={zohoAnalytics:{apiUrl:m.apiMode,orgId:m.orgId}};f=new We(y,R)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:l,analyticsApi:f}}Mo([...Po,/1000\.\w{20,}/g]);function Fu(e){let t;return e instanceof G?t={ok:!1,error:ge(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof at?t={ok:!1,error:ge(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Ce?t={ok:!1,error:ge(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof L?t={ok:!1,error:ge(e.message),code:"API_ERROR"}:t=wo(e),t}pn(e=>e instanceof G||e instanceof at||e instanceof Ce||e instanceof L?Fu(e):void 0);function d(e){console.log(JSON.stringify(Fu(e)))}var Iu={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"},Xr={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"],analytics:["ZohoAnalytics.data.all","ZohoAnalytics.metadata.all","ZohoAnalytics.modeling.all"]},bu="http://localhost/oauth",ku=`Organization ID, for the products scoped by one (${Array.from(Ne).join(", ")})`;function Hm(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 qm={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:bu,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",defaultDescription:"--product when given, otherwise recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign,analytics)"}).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:[...It],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:ku}).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)"],["$0 auth setup --product analytics --client-id 1000.ANALYTICS --client-secret xyz --org-id 1234567","Analytics uses a separate OAuth client; --scopes defaults to analytics"]]),handler:async e=>{try{let t=await B(),o=Bm(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 $m(o,t):o.code?await Ym(o,t):await Qm(o,t)}catch(t){d(t),process.exit(1)}}},Wm="recruit,crm,desk";function jm(e,t){return(e??t??Wm).split(",").map(o=>o.trim())}function Bm(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??bu,region:o,scopes:jm(e.scopes,r),code:Hm(e.code),token:e.token,accountsUrl:Iu[o]??Iu.us,apiMode:e.apiMode,orgId:e.orgId}}function Qr({product:e,credentials:t,apiMode:o,orgId:r}){return{...t,apiUrl:o??void 0,orgId:Ne.has(e)?r??void 0:void 0}}async function Ou(e,t,o){return e.product?ie({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:Qr({product:e.product,credentials:t,apiMode:e.apiMode,orgId:e.orgId})}):ie({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function $m(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await Ou(e,o,t?.shared);p({success:!0,...e.product?{product:e.product}:{},refreshToken:Ie(e.token),configSaved:!0,configuredProducts:ue(r)})}async function Ym(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 Ou(e,s,t?.shared);p({step:2,success:!0,product:e.product??"shared",refreshToken:Ie(a),accessToken:i.access_token?Ie(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:ue(c)})}async function Xm(e,t){let o;return e.product?o=await ie({shared:{clientId:t?.shared?.clientId??"",clientSecret:t?.shared?.clientSecret??"",refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},[e.product]:Qr({product:e.product,credentials:{clientId:e.clientId,clientSecret:e.clientSecret},apiMode:e.apiMode,orgId:e.orgId})}):o=await ie({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}),o}async function Qm(e,t){let o=e.product?Xr[e.product]??[]:e.scopes.flatMap(i=>Xr[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Xr).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;await Xm(e,t);let n=e.product?`--product ${e.product} `:"";p({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 ey={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:[...It],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:ku}).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 ie({shared:(await B())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:Qr({product:t,credentials:o,apiMode:e.apiMode,orgId:e.orgId})}):r=await ie({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),p({saved:!0,product:t??"shared",configuredProducts:ue(r)})}catch(t){d(t),process.exit(1)}}};function Eu(e){return e?{clientId:e.clientId?Ie(e.clientId):void 0,clientSecret:e.clientSecret?Ie(e.clientSecret):void 0,refreshToken:e.refreshToken?Ie(e.refreshToken):void 0}:void 0}function ty(e,t){return t?{...Eu(t),apiUrl:t.apiUrl,...Ne.has(e)?{orgId:t.orgId}:{}}:null}function oy(e){let t=Object.fromEntries(It.map(o=>[o,ty(o,e[o])]));return{configured:!0,shared:{...Eu(e.shared),region:e.shared?.region??"us",apiMode:e.shared?.apiMode??"production"},...t,configuredProducts:ue(e)}}var ry={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let e=await B();p(e?oy(e):{configured:!1})}catch(e){d(e),process.exit(1)}}},ny={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await B();if(e){let t=ue(e);if(t.length===0)p({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=gt(e),r=Fo(o),n={};for(let i of t)try{let a=r[i];if(!a){n[i]={authenticated:!1,error:"Not configured"};continue}let s=await a.zohoAccountsApi.accessToken();n[i]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(a){let s=a instanceof Error?a.message:String(a);n[i]={authenticated:!1,error:s}}p({products:n})}}else p({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){d(e),process.exit(1)}}},iy={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Mi(),p({cleared:!0})}catch(e){d(e),process.exit(1)}}},Pu={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(qm).command(ey).command(ry).command(ny).command(iy).demandCommand(1,"Please specify an auth subcommand."),handler:A};import{access as ay,constants as sy}from"node:fs";import{dirname as cy}from"node:path";function uy(e){return e.every(t=>t.status==="pass")}var Du={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await B(),t=[];t.push(py(e));let o=ly(e);if(o&&t.push(o),t.push(await dy()),e){let n=ue(e);t.push(hy(n),...await my(e,n),...fy(e,n))}let r=uy(t);p({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function py(e){return e?{name:"config",status:"pass",message:`Config loaded from ${bt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function ly(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 dy(){let e=cy(kt());return await gy(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 hy(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 my(e,t){let o=Fo(gt(e)),r=[];for(let n of t)r.push(await yy(o[n],n));return r}async function yy(e,t){if(!e)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let o;try{let r=await e.zohoAccountsApi.accessToken();o={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${r.scope}`}}catch(r){let n=r instanceof Error?r.message:String(r);o={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${n}`}}return o}function fy(e,t){return Array.from(Ne).map(o=>{let r=e[o]?.orgId,n=`${o}-org-id`,i;return r?i={name:n,status:"pass",message:`${o}: Org ID configured: ${r}`}:t.includes(o)?i={name:n,status:"fail",message:`${o}: No org ID configured, but ${o} is reported as configured \u2014 every org-scoped ${o} command will fail. Run: zoho-cli auth set --product ${o} --org-id <ORG_ID>`}:i={name:n,status:"warn",message:`${o}: No org ID. ${o} commands unavailable.`},i})}function gy(e){return new Promise(t=>{ay(e,sy.W_OK,o=>{t(!o)})})}var Mu=bi({notInitializedMessage:"CLI context not initialized. This is a bug."});function wu(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await B();r||(d(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),ue(r).length===0&&(d(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Mu.set(gt(r))}catch(r){d(r),process.exit(4)}}}function Kt(e){return Mu.require()}function oe(e){let{recruitApi:t}=Kt(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 re(e){let{crmApi:t}=Kt(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 Z(e){let{deskApi:t}=Kt(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 N(e){let{signApi:t}=Kt(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 E(e){let{analyticsApi:t}=Kt(e);if(!t)throw new Error("Analytics not configured. Zoho Analytics requires its own OAuth client. Run: zoho-cli auth setup --product analytics --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function ye(e){return Qt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function D(e){return Qt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function Io(e){return Qt(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 U(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function De(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function Vt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function bo(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 Ry={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},M={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}},Cy={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 fe(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Ry,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;p(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}async function ko(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:async i=>{let a=await r(i);return{data:a.requests??[],page_context:a.page_context}},adapter:Cy,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;p(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 Ty={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)))),handler:async e=>{try{let t=oe(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},xy={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await oe(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Ay={command:"search",describe:"Search records in a module",builder:e=>ye(U(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=oe(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 fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Zy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Sy={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Fy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Iy={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=oe(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},by={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},ky={command:"attachments",describe:"Get attachments for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},_u={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(Ty).command(xy).command(Ay).command(Zy).command(Sy).command(Fy).command(Iy).command(by).command(ky).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:A};var Oy={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)),!0)),handler:async e=>{try{let t=re(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},Ey={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await re(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Py={command:"search",describe:"Search records in a module",builder:e=>ye(U(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=re(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 fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Dy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},My={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},wy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},_y={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=re(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},vy={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},Ny={command:"attachments",describe:"Get attachments for a record",builder:e=>Vt(ye(De(U(e))),!0),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},vu={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Oy).command(Ey).command(Py).command(Dy).command(My).command(wy).command(_y).command(vy).command(Ny).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:A};var Uy={command:"list",describe:"List tickets",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ly={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 Z(e).getTicketById({ticketId:e.ticketId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Gy={command:"search",describe:"Search tickets",builder:e=>D(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=Z(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 k({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ky={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>D(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=Z(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Vy={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 Z(e).getTicketMetrics({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},zy={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=Z(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});p(r)}catch(t){d(t),process.exit(1)}}},Nu={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Uy).command(Ly).command(Gy).command(Ky).command(Vy).command(zy).demandCommand(1),handler:A};var Jy={command:"list",describe:"List departments",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await k({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Hy={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 Z(e).getDepartmentById({departmentId:e.departmentId});p(o)}catch(t){d(t),process.exit(1)}}},Uu={command:"departments",describe:"Desk department operations",builder:e=>e.command(Jy).command(Hy).demandCommand(1),handler:A};var qy={command:"list",describe:"List contacts",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wy={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 Z(e).getContactById({contactId:e.contactId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Lu={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(qy).command(Wy).demandCommand(1),handler:A};var jy={command:"list",describe:"List agents",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},By={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 Z(e).getAgentById({agentId:e.agentId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},$y={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await Z(e).getMyInfo();p(o)}catch(t){d(t),process.exit(1)}}},Gu={command:"agents",describe:"Desk agent operations",builder:e=>e.command(jy).command(By).command($y).demandCommand(1),handler:A};var Yy={command:"list",describe:"List all tags",builder:e=>D(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await k({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Xy={command:"search",describe:"Search tags",builder:e=>D(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=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await k({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Qy={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 Z(e).getTicketTags({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},ef={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=Z(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});p(r)}catch(t){d(t),process.exit(1)}}},tf={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 Z(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ku={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Yy).command(Xy).command(Qy).command(ef).command(tf).demandCommand(1),handler:A};var of={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await k({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},rf={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 Z(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});p(o)}catch(t){d(t),process.exit(1)}}},nf={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 Z(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});p(o)}catch(t){d(t),process.exit(1)}}},af={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 Z(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},Vu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(of).command(rf).command(nf).command(af).demandCommand(1),handler:A};var sf={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},cf={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 Z(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},zu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(sf).command(cf).demandCommand(1),handler:A};var uf={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 Z(e).getTicketFollowers({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},pf={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=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({added:!0})}catch(t){d(t),process.exit(1)}}},lf={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=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ju={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(uf).command(pf).command(lf).demandCommand(1),handler:A};var df={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 Z(e).getTicketTimer({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},hf={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 Z(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});p(o)}catch(t){d(t),process.exit(1)}}},mf={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},yf={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 Z(e).getTicketTimeEntrySummation({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},Hu={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(df).command(hf).command(mf).command(yf).demandCommand(1),handler:A};var ff={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},gf={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 Z(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},qu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(ff).command(gf).demandCommand(1),handler:A};var Rf={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wu={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Rf).demandCommand(1),handler:A};var ju={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(Nu).command(Uu).command(Lu).command(Gu).command(Ku).command(Vu).command(zu).command(Ju).command(Hu).command(qu).command(Wu).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:A};import{readFile as Cf,writeFile as Bu}from"node:fs/promises";import{basename as Tf}from"node:path";function xf(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 Af={command:"list",describe:"List sign requests (documents)",builder:e=>Io(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=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:xf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){d(t),process.exit(1)}}},Zf={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 N(e).getDocument({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Sf={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 N(e).getDocumentFormData({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Ff={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=N(e),o=JSON.parse(e.data),r=await Cf(e.file),n=new File([r],Tf(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});p(i)}catch(t){d(t),process.exit(1)}}},If={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=N(e),o=JSON.parse(e.data),r=await t.createDocumentFromTemplate({templateId:e.templateId,data:o,isQuickSend:e.quickSend});p(r)}catch(t){d(t),process.exit(1)}}},bf={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=N(e),o=JSON.parse(e.data),r=await t.updateDocument({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},kf={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=N(e),o=e.data?JSON.parse(e.data):void 0,r=await t.sendDocumentForSignature({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Of={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 N(e).extendDocument({requestId:e.requestId,expire_by:e.expireBy});p(o)}catch(t){d(t),process.exit(1)}}},Ef={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 N(e).deleteDocument({requestId:e.requestId,recall_inprogress:e.recallInprogress,reason:e.reason});p(o)}catch(t){d(t),process.exit(1)}}},Pf={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 N(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 Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Df={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 N(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 Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Mf={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 N(e).getEmbeddedSigningUrl({requestId:e.requestId,actionId:e.actionId,host:e.host});p(o)}catch(t){d(t),process.exit(1)}}},$u={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Af).command(Zf).command(Sf).command(Ff).command(If).command(bf).command(kf).command(Of).command(Ef).command(Pf).command(Df).command(Mf).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:A};function wf(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 _f={command:"list",describe:"List templates",builder:e=>Io(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=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:wf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){d(t),process.exit(1)}}},vf={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 N(e).getTemplate({templateId:e.templateId});p(o)}catch(t){d(t),process.exit(1)}}},Yu={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(_f).command(vf).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:A};var Nf={command:"field-types",describe:"List available document field types",builder:e=>e,handler:async e=>{try{let o=await N(e).retrieveFieldTypes();p(o)}catch(t){d(t),process.exit(1)}}},Xu={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command($u).command(Yu).command(Nf).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:A};var Uf={command:"list",describe:"List the organizations available to the authenticated user",handler:async e=>{try{let o=await E(e).getOrgs();p(o.data.orgs,{count:o.data.orgs?.length})}catch(t){d(t),process.exit(1)}}},Qu={command:"orgs",describe:"Analytics organization operations",builder:e=>e.command(Uf).demandCommand(1).example([["$0 analytics orgs list","Find the org id needed by every other Analytics command"]]),handler:A};var Lf={command:"list",describe:"List all accessible workspaces",builder:e=>e.option("owned",{type:"boolean",describe:"Only workspaces owned by the authenticated user"}).option("shared",{type:"boolean",describe:"Only workspaces shared with the authenticated user"}),handler:async e=>{try{let t=E(e);if(e.owned){let o=await t.getOwnedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else if(e.shared){let o=await t.getSharedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else{let o=await t.getAllWorkspaces();p(o.data)}}catch(t){d(t),process.exit(1)}}},Gf={command:"get <workspaceId>",describe:"Get a workspace by ID",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getWorkspaceDetails({workspaceId:e.workspaceId});p(o.data.workspaces)}catch(t){d(t),process.exit(1)}}};function Kf(e,t){if(!t)throw new Error(`Deleting a workspace cannot be undone. Re-run with --confirm ${e} to proceed.`);if(t!==e)throw new Error(`--confirm ${t} does not match the workspace being deleted (${e}).`);return e}var Vf={command:"delete <workspaceId>",describe:"Delete a workspace and everything in it. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("confirm",{type:"string",describe:"Repeat the workspace ID to confirm. Required"}),handler:async e=>{try{let t=Kf(e.workspaceId,e.confirm);await E(e).deleteWorkspace({workspaceId:t}),p({deleted:!0,workspaceId:t})}catch(t){d(t),process.exit(1)}}},ep={command:"workspaces",describe:"Analytics workspace operations",builder:e=>e.command(Lf).command(Gf).command(Vf).demandCommand(1).example([["$0 analytics workspaces list","List owned and shared workspaces"],["$0 analytics workspaces list --owned","List only owned workspaces"],["$0 analytics workspaces delete 1767024000000060001 --confirm 1767024000000060001","Delete a workspace, confirming the id"]]),handler:A};var zf={command:"list <workspaceId>",describe:"List the views of a workspace",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getViews({workspaceId:e.workspaceId});p(o.data.views,{count:o.data.views?.length})}catch(t){d(t),process.exit(1)}}},Jf={command:"get <viewId>",describe:"Get a view by ID",builder:e=>e.positional("viewId",{type:"string",demandOption:!0,describe:"View ID (globally unique, no workspace needed)"}),handler:async e=>{try{let o=await E(e).getViewDetails({viewId:e.viewId});p(o.data.views)}catch(t){d(t),process.exit(1)}}},Hf={command:"columns <workspaceId> <viewId>",describe:"List the columns of a table",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}),handler:async e=>{try{let o=await E(e).getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId});p(o.data.columns,{count:o.data.columns?.length})}catch(t){d(t),process.exit(1)}}},qf={command:"delete <workspaceId> <viewId>",describe:"Delete a view. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("dependent-views",{type:"boolean",default:!1,describe:"Also delete the reports, dashboards and query tables built on this view"}),handler:async e=>{try{await E(e).deleteView({workspaceId:e.workspaceId,viewId:e.viewId,config:{deleteDependentViews:e.dependentViews}}),p({deleted:!0,workspaceId:e.workspaceId,viewId:e.viewId,deletedDependentViews:e.dependentViews})}catch(t){d(t),process.exit(1)}}},tp={command:"views",describe:"Analytics view operations",builder:e=>e.command(zf).command(Jf).command(Hf).command(qf).demandCommand(1).example([["$0 analytics views list 1767024000000060001","List the views of a workspace"],["$0 analytics views columns 1767024000000060001 1767024000000149001","Inspect a table before importing into it"],["$0 analytics views delete 1767024000000060001 1767024000000149001",'Drop a table created by "import new-table"']]),handler:A};import{readFile as Wf}from"node:fs/promises";import{basename as jf,extname as op}from"node:path";var Bf=["append","truncateadd","updateadd"],$f=["abort","skiprow","setcolumnempty"];async function rp(e){let t=await Wf(e,"utf8"),o=jf(e),r=op(e).toLowerCase()===".json"?"application/json":"text/csv";return Ri({content:t,fileName:o,mimeType:r})}function Oo(e){let t=op(e).toLowerCase();return{".json":"json",".csv":"csv"}[t]}function Yf(e,t){let o=t?.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e==="updateadd"&&!o?.length)throw new Error("The updateadd mode requires --matching-columns.");return o?.length?o:void 0}function np(e){return e.option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file to import"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("on-error",{type:"string",choices:$f,describe:"What to do when a row cannot be imported"}).option("async",{type:"boolean",default:!1,describe:"Queue the import as a job and poll it, rather than waiting on one request"})}var Xf={command:"data <workspaceId> <viewId>",describe:"Import a file into an existing table",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("mode",{alias:"m",type:"string",choices:Bf,default:"append",describe:"append adds rows, truncateadd replaces every row, updateadd upserts on --matching-columns"}).option("matching-columns",{type:"string",describe:"Comma-separated columns to match on. Required for the updateadd mode"}),handler:async e=>{try{let t=E(e),o=e.mode,r=Yf(o,e.matchingColumns),n=await rp(e.file),i={importType:o,fileType:e.fileType??Oo(e.file),onError:e.onError,matchingColumns:r};if(e.async){let a=await t.importDataInTableAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:i}),{jobCode:s,jobStatus:c,jobInfo:u}=a.data;p({jobCode:s,jobStatus:c,...u},{complete:Pe(s)})}else{let a=await t.importDataInTable({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:i});p(a.data)}}catch(t){d(t),process.exit(1)}}},Qf={command:"new-table <workspaceId> <tableName>",describe:"Create a table in a workspace from an imported file",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("tableName",{type:"string",demandOption:!0,describe:"Name of the table to create"}),handler:async e=>{try{let t=E(e),o=await rp(e.file),r={tableName:e.tableName,fileType:e.fileType??Oo(e.file),onError:e.onError};if(e.async){let n=await t.createImportJobInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}else{let n=await t.importDataInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}}catch(t){d(t),process.exit(1)}}},eg={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous import job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Import job ID"}),handler:async e=>{try{let o=await E(e).getImportJob({workspaceId:e.workspaceId,jobId:e.jobId});p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ip={command:"import",describe:"Analytics import operations",builder:e=>e.command(Xf).command(Qf).command(eg).demandCommand(1).example([["$0 analytics import data WS VIEW -f rows.csv","Append the rows of a CSV to a table"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace every row in a table"],["$0 analytics import data WS VIEW -f big.csv --async","Queue a large import and poll it"],["$0 analytics import new-table WS Sales -f rows.csv","Create a table from a CSV"]]),handler:A};import{writeFile as tg}from"node:fs/promises";var og=["csv","json","xml","xls","pdf","html","image"];async function en(e,t){let o=await e.text(),r;return t?await tg(t,o,"utf8"):r=o,r}function ap(e){return e.option("format",{type:"string",choices:og,default:"csv",describe:"Format of the exported data"}).option("out",{alias:"o",type:"string",describe:"Write the export to this file instead of printing it"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("columns",{type:"string",describe:"Comma-separated columns to export"})}function rg(e){let t=e?.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t?.length?t:void 0}function sp(e){return{responseFormat:e.format,criteria:e.criteria,selectedColumns:rg(e.columns)}}var ng={command:"data <workspaceId> <viewId>",describe:"Export the data of a view",builder:e=>ap(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("async",{type:"boolean",default:!1,describe:"Queue the export as a job and poll it. Required for dashboards, query tables, and tables over a million rows"}),handler:async e=>{try{let t=E(e),o=sp(e);if(e.async){let r=await t.exportDataAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,config:o});if(Pe(r.data.jobCode)){let n=await t.downloadExport({workspaceId:e.workspaceId,jobId:r.data.jobId}),i=await en(n,e.out);p(i??{written:e.out,jobId:r.data.jobId})}else p(r.data,{complete:!1})}else{let r=await t.exportData({workspaceId:e.workspaceId,viewId:e.viewId,config:o}),n=await en(r,e.out);p(n??{written:e.out})}}catch(t){d(t),process.exit(1)}}},ig={command:"query <workspaceId>",describe:"Export the results of a SQL query",builder:e=>ap(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("sql",{type:"string",demandOption:!0,describe:"The SQL SELECT statement to run"}),handler:async e=>{try{let t=E(e),o={...sp(e),sqlQuery:e.sql},r=await t.createExportJobForSqlQuery({workspaceId:e.workspaceId,config:o}),n=await t.getExportJob({workspaceId:e.workspaceId,jobId:r.data.jobId});p(n.data,{complete:Pe(n.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ag={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous export job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Export job ID"}).option("download",{type:"boolean",default:!1,describe:"Download the export when the job has completed"}).option("out",{alias:"o",type:"string",describe:"Write the download to this file instead of printing it"}),handler:async e=>{try{let t=E(e),o=await t.getExportJob({workspaceId:e.workspaceId,jobId:e.jobId});if(e.download&&Pe(o.data.jobCode)){let r=await t.downloadExport({workspaceId:e.workspaceId,jobId:e.jobId}),n=await en(r,e.out);p(n??{written:e.out})}else p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},cp={command:"export",describe:"Analytics export operations",builder:e=>e.command(ng).command(ig).command(ag).demandCommand(1).example([["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"],["$0 analytics export data WS VIEW --format json","Print a table as JSON"],['$0 analytics export query WS --sql "select * from Sales"',"Queue an ad-hoc SQL export"]]),handler:A};import{readFile as sg}from"node:fs/promises";function cg(e,t){return{clean:t,rowCount:e.rowCount,matched:e.matchedColumns.length,dropped:e.droppedColumns.length,empty:e.emptyColumns.length,emptyRequired:e.emptyColumns.filter(o=>o.required).length,caseMismatched:e.caseMismatchedColumns.length,conflicts:e.conflicts.length,conflictingValues:e.conflicts.reduce((o,r)=>o+r.conflictCount,0)}}var ug={command:"schema <workspaceId> <viewId>",describe:"Compare a file against a table before importing it",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file that would be imported"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("delimiter",{type:"string",describe:"Field delimiter of the CSV. Defaults to a comma"}).option("max-samples",{type:"number",describe:"Offending values to report per conflict. Defaults to 3"}).option("strict",{type:"boolean",default:!1,describe:"Also treat a nullable column the file omits as drift"}).option("quiet",{type:"boolean",default:!1,describe:"Report only through the exit code, printing nothing"}),handler:async e=>{try{let t=E(e),o=e.fileType??Oo(e.file);if(o==null)throw new Error(`Cannot tell the format of "${e.file}" from its extension. Pass --file-type csv or --file-type json.`);let r=await sg(e.file,"utf8"),n=Uc({content:r,fileType:o,delimiter:e.delimiter}),{data:i}=await t.getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId}),a=Lc({...n,columns:i.columns??[],maxSamples:e.maxSamples}),s=Gc(a,{strict:e.strict});e.quiet||p(a,cg(a,s)),s||process.exit(1)}catch(t){d(t),process.exit(1)}}},up={command:"diff",describe:"Analytics comparison operations",builder:e=>e.command(ug).demandCommand(1).example([["$0 analytics diff schema WS VIEW -f rows.csv","Report what an import of the file would drop, leave empty, or mangle"],["$0 analytics diff schema WS VIEW -f rows.csv --strict","Also fail on a nullable column the file omits"],["$0 analytics diff schema WS VIEW -f rows.csv --quiet && zoho-cli analytics import data WS VIEW -f rows.csv","Gate an import on a clean diff"]]),handler:A};function tn(e){return e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Table view ID"})}var pg={command:"add <workspaceId> <viewId>",describe:"Add a single row to a table",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"Row as a JSON object of column name to value"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.addRow({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o}});p(r.data)}catch(t){d(t),process.exit(1)}}},lg={command:"update <workspaceId> <viewId>",describe:"Update the rows of a table matching a criteria expression",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"New values as a JSON object of column name to value"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Update every row. Required when no --criteria is given"}).option("add-if-not-exist",{type:"boolean",default:!1,describe:"Insert a row when the criteria matches nothing"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.updateRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o,criteria:e.criteria,updateAllRows:e.allRows,addIfNotExist:e.addIfNotExist}});p(r.data)}catch(t){d(t),process.exit(1)}}},dg={command:"delete <workspaceId> <viewId>",describe:"Delete the rows of a table matching a criteria expression",builder:e=>tn(e).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Delete every row. Required when no --criteria is given"}),handler:async e=>{try{let o=await E(e).deleteRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{criteria:e.criteria,deleteAllRows:e.allRows}});p(o.data)}catch(t){d(t),process.exit(1)}}},pp={command:"rows",describe:"Analytics row operations",builder:e=>e.command(pg).command(lg).command(dg).demandCommand(1).example([[`$0 analytics rows add WS VIEW --columns '{"Region":"East"}'`,"Add one row"],[`$0 analytics rows delete WS VIEW --criteria '"Sales"."Region"='"'"'West'"'"''`,"Delete the rows matching a filter"]]),handler:A};var lp={command:"analytics",describe:"Zoho Analytics operations",builder:e=>e.command(Qu).command(ep).command(tp).command(ip).command(cp).command(pp).command(up).demandCommand(1,"Please specify an analytics subcommand.").example([["$0 analytics orgs list","Find the org id every other command needs"],["$0 analytics workspaces list","List the accessible workspaces"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace a table with the rows of a CSV"],["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"]]),handler:A};var dp={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=oe(e).recruitContext;break;case"crm":n=re(e).crmContext;break;case"desk":n=Z(e).deskContext;break;case"sign":n=N(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),l=i.includes("?")?"&":"?";i=`${i}${l}${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);p(s)}catch(t){d(t),process.exit(1)}}};var yg=Ei({cliName:"zoho-cli",loadOutputConfig:async()=>(await B())?.output,mergeOutputConfig:e=>ie({output:e}),clearOutputConfig:Di}),fg=[_u,vu,ju,Xu,lp,dp],hp=[Pu,yg,Du];function gg(e){return e.command.split(" ")[0]}var mp=new Set(hp.map(gg)),Rg=Oi({cliName:"zoho-cli",skipCommands:mp,loadOutputConfig:async()=>(await B())?.output,saveCommandOutputConfig:async(e,t)=>{await ie({output:{commands:{[e]:t}}})}});async function Cg(){try{await hg(mg(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([wu(mp),Rg],!0).command(hp).command(fg).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){d(e),process.exit(1)}}await Cg();
|