@dereekb/zoho 14.0.1 → 14.1.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 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,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)+`
4
+ var fp=Object.defineProperty;var gp=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?gp(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&&fp(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Rp,mkdirSync as Cp,writeFileSync as Tp}from"node:fs";import{join as xp}from"node:path";var an=1;var wo=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],sn=6e4,je={},cn=[...wo],Mo,Ap=!1,Zp=sn;function _o(e){je=e}function Jt(){return je}function un(e){Ap=e}function pn(e){Zp=e===void 0?sn:e}function vo(e){cn=e}function ln(e){Mo=e}function ge(e){let t=e;for(let o of cn)t=t.replace(o,"[REDACTED]");return t}function dn(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function Tt(e,t){let{dumpDir:o,commandPath:r}=je,n;if(o){Rp(o)||Cp(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=dn(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=xp(o,`${s}.${e}`)}else n=void 0;return n}function Sp(e,t){let o=Tt("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Tp(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=>nn(n,o)):e!=null&&typeof e=="object"?r=nn(e,o):r=e,r}function nn(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 hn(e){return je.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function p(e,t){Sp(e,t);let r={ok:!0,data:je.pick?Me(e,je.pick):e,...t?{meta:t}:{}};console.log(hn(r))}function mn(e){console.log(hn(No(e)))}var Ct=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function No(e){let t=Mo?Mo(e):void 0,o;return t?o=t:e instanceof Ct?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 xt(e){let t=!0;for(let o of e){t=!1;break}return t}function Uo(e,t){for(let o of e)t(o)}function W(e,t,o=!1){e!=null&&(Be(e,o)?Uo(e,t):t(e))}function yn(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 Fp(e){return e==null?[]:Ip(e)}var x=Fp;function Ip(e){return Array.isArray(e)?e:[e]}import{symmetricDifference as Pg}from"extra-set";function fn(e,t){W(t,o=>e.add(o))}function gn(e,t){W(t,o=>e.delete(o))}function Rn(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function Lo(e){return Object.keys(e).length===0}function Cn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Tn(e){return{...e}}function xn(e){return e!=null}function Ht(e){return Be(e,!1)?!xt(e):An(e)}function Go(e){let t;return Be(e,!0)?t=!xt(e):An(e)?t=typeof e=="object"?!Lo(e):!0:t=!1,t}function An(e){return e!=null&&e!==""}function bp(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ce=bp(xn);function Zn({base:e,build:t}){let o=e??{};return t(o),o}var kp=(e=>e);function Sn(){return kp}function Ko(e,t){let o=new Set(e),r=Op(t,n=>n);return r.length&&gn(o,r),Array.from(o)}function Op(e,t){return ce(e==null?[]:Array.isArray(e)?e:Ep(e,t))}function Ep(e,t){let o=new Set(e.keys);return e.values&&fn(o,e.values.map(t)),Array.from(o)}function $e(e,t){let o=Pp(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Pp(e,t){return Cn(Dp(e,t))}function Dp(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 Fn(e,t,o){return x(t).forEach(r=>e.set(r,o)),e}function Vo(e){return Array.from(e.entries())}function In(e){return Mp(Vo(e))}function Mp(e){let t=[];return e.forEach(([o,r])=>{W(r,n=>{t.push([o,n])})}),t}function bn(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),W(i,s=>a.push(s))},o=(n,i)=>t(n,yn(i));return{map:()=>e,entries:()=>Vo(e),tuples:()=>In(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>W(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>W(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function wp(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function kn(e){let t=wp(e);return t!=null&&t!=="class"}function On(e){return kn(e)?e:()=>e}function En(e,t){return Math.log(t)/Math.log(e)}var Pn=",",_p=" ";function vp(e,t=Pn,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 zo(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 Np(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return vp(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Dn(e){let{joiner:t}=e,o=Np(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 zo(n,t,i)}}}var Jo=Dn({joiner:Pn}),Up=Dn({joiner:_p,trimByDefault:!0});var P=Jo.joinStrings,nR=Jo.splitStrings,iR=Jo.splitStringsToSet,aR=Up.joinStrings;var Mn=Rn;function _n(e,{forEach:t,filter:o}){Lp(e,o).forEach((n,i)=>t(n,i))}function Lp(e,t){return Ho(t)(e)}function Ho(e){let t;if(e==null)t=wn;else{let o=Gp(e);t=r=>wn(r).filter((n,i)=>o(n,i))}return t}function wn(e){return Object.entries(e)}function qo(e){return typeof e=="object"?e:{valueFilter:e}}function Gp(e){let t=qo(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])=>Ht(a);break;case 5:i=([,a])=>Go(a);break;case 6:i=([,a])=>!!a&&Ht(a);break;case 7:i=([,a])=>!!a&&Go(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 Mn(i,r)}function At(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 vn(e){let t;return e==null||Bp(e)?t=e:t=Kp(e),t}function Kp(e){return e==null?e:new Date(e)}var Vp=365,Nn=24,zp=60,Jp=1440,Hp=60,mR=Vp*Jp,qp=Hp*zp,z=1e3,Re=z*60,Wo=Re*60,Wp=Wo*Nn,yR=qp*Nn,jp=7,fR=Wp*jp;function Bp(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Un(e){return e.getTime()<Date.now()}function Ln(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function $p(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:vn(n);function c(f){return f??r??new Date}function u(f,m=!1){let C=c(f),y=h(C),R;return y==null?R=m:R=y<=C,R}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=Ln(s??(i===!1?null:f),a)),m}return{input:e,hasExpired:u,getExpirationDate:l}}function Gn(e,t){let o=!0;return e!=null&&(o=$p(e).hasExpired(t,!0)),o}function Yp({filter:e,copy:t,dynamic:o=!1}){let r=e==null?tl: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:At(i);return s=>{let c=a();return t&&(s=Tn(s)),Object.assign(s,c),s}}}function Kn(e,t){return Xp(t)(e)}function Xp(e){let t=Yp({filter:e,copy:!1,dynamic:!0});return o=>t(ce(o))({})}function Vn(e,t=!1){return(t?el:Qp)(e)}var Qp=Ye({copy:!0,filter:{valueFilter:1}}),el=Ye({copy:!0,filter:{valueFilter:2}}),zn=Ye({copy:!0,filter:{valueFilter:4}}),FR=Ye({copy:!0,filter:{valueFilter:6}}),IR=jo({valueFilter:1}),bR=jo({valueFilter:6}),kR=jo({valueFilter:2});function jo(e){let t=Jn({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=qo(t);o.invertFilter=!o.invertFilter;let r=Jn({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var tl=Ye({copy:!1});function Jn({forEach:e,filter:t}){let o=Ho(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function Hn(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function qn(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 Wn(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 qt(e,t,o){let[r,n]=Bo(e,t,!1);return r+o+n}function Bo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var ol=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],_R=new Set(ol);function jn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=Wt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=qt(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],C=n.substring(u,l)+o(f);s.push(C),u=l+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function rl(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 Wt(e,t,o){return rl(e)(t,o)}function nl(e,t){return Wt(e,t,1)[0]}function il(e){return t=>{let r=nl(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=Bo(t,r,!1),n}}function Bn(e,t){return il(t)(e)}var Xe="/",al=".";function sl(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 $n(e){return sl(e)!=="invalid"}var cl=/^\/+/,ul=/\/+$/;var pl=/\/{2,}/g;function Yn(e){return e.startsWith(Xe)?e.replace(cl,Xe):`${Xe}${e}`}function Xn(e){return e.replaceAll(pl,Xe)}function Qn(e){return e.replace(ul,"")}function ll(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var ei=/:(\d+)/;function dl(e){return ei.test(e)}function hl(e){let t=ei.exec(e);return t?Number(t[1]):void 0}function ml(e){let t=ni(e),o=yl(t),{domain:r,path:n}=o,i=ll(r),a=dl(e),s=a?hl(e)??void 0:void 0,[c,u]=Bn(o.path,"?"),l=i&&(c===""||$n(c+"/")),h=gl(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 ti(e){let t=ml(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function oi(e,t=!1){let o=Wt(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=qt(n,i,"&")),n}function yl(e){let t=ni(e);return fl(t)}function fl(e){let t=zo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Yn(r??"/")}}var ri=/^https:\/\/|http:\/\//;function ni(e){return e.replace(ri,"")}function gl(e){return ri.test(e)}function A(){}async function ii(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 ai(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function Zt(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Rl(e){let n=Wo,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=En(v,_/z+1),O&&C()}function C(){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),B=Math.max(0,v-i.startLimitAt);S&&(a=v+S,c=new Date),O=B>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(B,0))-1)*z}else O=0;return O}function R(S){return y(S??0)}function g(){let S=y(1);return Zt(S)}return{waitForRateLimit:g,getNextWaitTime:R,getConfig:l,setConfig:m,getEnabled:h,setEnabled:f,reset:C}}function si(e){let o=Rl({exponentRate:1.5,maxWaitTime:z*8,...e}),r=Re,n=new Date,i=0,a=0,s=!0;g(e,!0);function c(){Un(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 C(I){n=I}function y(){return c(),a}function R(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 B=function(){return a-=I,o.getNextWaitTime(I)};var v=B;a>0?_=B():(c(),a>0?_=B():_=m())}return _}function O(I){return S(I??0)}function q(){let I=S(1);return Zt(I)}return{getRemainingLimit:y,setRemainingLimit:R,getTimeUntilNextReset:m,getResetAt:f,setNextResetAt:C,setConfig:g,reset:h,getNextWaitTime:O,waitForRateLimit:q,getEnabled:u,setEnabled:l}}var Cl="__CATCH_ALL_HANDLE_RESULT_KEY__";function ci(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===Cl?a(l):Fn(i,u,l)},c=(u,l,h)=>{let f=h.bind(u);s(l,f)};return Zn({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 Tl(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function xl(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Al(e,t,o){let r=xl(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function ui(e,t){return o=>Al(e,o,t)}function pi(e){return t=>(o,r)=>{let n=Tl(o,t),i=e.configurerForAccessor(n);r(i)}}var Zl=-1,li=0;function Sl(e){return e?.page??Zl}function di(e){return Sl(e)+1}import{BaseError as hi}from"make-error";var ne=class extends hi{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}error};function mi(e){return(t,o)=>Fl(e(t,o))}var Se=class extends hi{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}response};function Fl(e){return e.then(t=>{if(!t.ok)throw new Se(t);return t})}import{BaseError as uC}from"make-error";function yi(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 gi(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Ri({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>bl({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Il=(e,t)=>t(e);function bl(e){let{makeFetch:t=fetch,fetchHandler:o=Il,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=yi(a)),n&&(a=mi(a));let s=Ri(e);return async(c,u)=>{let l=await s(c,u),h=o(l,a);return i&&(h=i(h)),h}}var kl=(e,t)=>new Request(e,t??void 0);function Ri(e){let{makeRequest:t=kl,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(Qn(o)):void 0,u=c?m=>{let C,y=m.toString();if(!s&&ti(y))C=new URL(y);else{let R=c.origin+Xn("/"+c.pathname+"/"+m);C=new URL(R,c)}return C}:void 0;async function l(m){let C=ai(m)?await m:m;return fi(C)?C:t(C)}let h=u?async m=>{let C,y,R;if(typeof m=="string"?C=m:fi(m)?a?(C=m.url,y=m):R=m:R=await t(m),!R){let g=u(C);R=await t(g.href,y)}return R}:l,f;if(r!=null||n!=null){let m=On(r);async function C(){let R=await m();return n?{...R,timeout:n}:R}async function y(R,g){let S=await C(),O=Ol(S,await g),q=O.timeout===void 0?R.timeout:O.timeout;return{...O,timeout:q}}i?f=(R,g)=>i(R,y(R,g)):f=(R,g)=>y(R,g)}else i?f=i:f=(m,C)=>C;return async(m,C)=>{try{let y=await h(m);C=await f(y,C??void 0);let R=await t(y,C);return R.timeout=n,R}catch(y){throw y instanceof ne?y:new ne(y)}}}function Ol(e,t){let o;if(t){let r=El([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function El(e){let t=bn();return ce(e).forEach(o=>{let r=Pl(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 Pl(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 fi(e){return!!e.url}import{safeParse as Dl}from"fast-content-type-parse";function Ci(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 jt(e){let t=e.headers.get("content-type"),o=Dl(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ti(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 Bt=class extends ne{constructor(o){super("There was no next page for this.");this.page=o}page},$t=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},Ml=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??Ml,f={maxPage:h,maxItemsPerPage:l};function m(y,R=void 0){return async()=>{let g=await t(y),{cursor:S,nextPageCursor:O,hasNext:q}=await o(g,y,f),I=S??R?.cursor,_=q!==!1,v=R?R.page+1:li,B=v>=h,Rt={input:y,result:g,page:v,previous:R,hasNext:_,isAtMaxPage:B,cursor:I,nextPageCursor:O,fetchNext:At(async()=>{if(B)throw new $t(Rt,h);let rn=_?await r(Rt,y,f):void 0;if(!rn)throw new Bt(Rt);return m({...y,...rn},Rt)()})};return Rt}}return{input:a,fetchNext:At(()=>m(a)())}}}function wl(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)?Kn(e):e,a=r??!0?zn(i??{}):i,s=n?wl(a):a,c=new URLSearchParams(s);return o!=null&&W(o,u=>c.delete(u),!1),c}function $o(e){let t;if(typeof e=="string")t=e;else if(_l(e))t=e.href;else{let o=$o(e.url);if(e.queryParams){let r=Ul(e.queryParams);xt(r)?t=o:t=oi(o+`?${r.toString()}`)}else t=o}return t}function _l(e){return typeof e=="object"&&e instanceof URL}function vl(e){return typeof e=="object"&&e instanceof URLSearchParams}function Nl(e){let t=[];return Uo(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);W(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Ul(e){let t;return vl(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Be(e)?t=new URLSearchParams(Nl(e)):t=Ll(e),t}function Ll(e){let t=[];return _n(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&W(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var Yo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}response};function Gl(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Kl=e=>{throw new Yo(e)},$=e=>null;function Y(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Kl};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=xi(o);return(a,s,c)=>{let u=$o(a),l=i(s,c),h=typeof s=="object"?s.interceptResponse:void 0;return e(u,l).then(m=>{let C=m.json().catch(r),y=n?C.then(R=>n(R,m)):C;return h?y.then(R=>h(R,m)):y})}}function xi(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Sn()}=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:Gl(i.body)}}}var PC=xi();var X=gi({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});import{createParamDecorator as Vl}from"@nestjs/common";var nT=Vl((e,t)=>zl(t));function zl(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Xo,BadRequestException as Jl,InternalServerErrorException as Hl,Logger as ql}from"@nestjs/common";import Wl from"raw-body";import{parse as jl}from"node:querystring";var Ai=new ql("RawBody"),uT=Xo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Ai.error("RawBody request was not readable. This is generally due to bad configuration."),new Jl("Invalid body");return Wl(o)}),Zi=Xo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Ai.error("RawBody expected a buffer set to req.body."),new Hl("failed parsing body");return r}),pT=Xo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Bl(o.body),o.body});function Bl(e){let t=$l(e);return jl(t)}function $l(e){return e.toString("utf8").trim()}import{Injectable as Yl}from"@nestjs/common";import Xl from"body-parser";var et=class{use(t,o,r){Xl.json()(t,o,r)}};et=F([Yl()],et);import{Injectable as Ql}from"@nestjs/common";import ed from"body-parser";var tt=class{use(t,o,r){ed.raw({type:"*/*"})(t,o,r)}};tt=F([Ql()],tt);import{Logger as td,Module as od,RequestMethod as rd}from"@nestjs/common";var nd="/webhook",id={path:`${nd}/{*path}`,method:rd.POST},Qo=class{configure(t){ad(t)}},Yt=class extends Qo{logger=new td("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Yt=F([od({})],Yt);function ad(e){e.apply(tt).forRoutes(id).apply(et).forRoutes("{*path}")}var Si="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 sd,Injectable as cd}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([cd(),b(0,sd(we))],_e);import{Module as ud}from"@nestjs/common";import{ConfigModule as pd,ConfigService as ld}from"@nestjs/config";function dd(e){let t={client:{clientWebAppUrl:e.get(Si)}};return we.assertValidConfig(t),t}var Xt=class{};Xt=F([ud({imports:[pd],providers:[{provide:we,inject:[ld],useFactory:dd},_e],exports:[_e]})],Xt);var Fi="SERVER_ENV_TOKEN";import{Inject as hd,Injectable as md}from"@nestjs/common";function Ii(){return process.env.NODE_ENV==="test"}var Qt=class{constructor(t){this.env=t}env;get isTestingEnv(){return Ii()}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}};Qt=F([md(),b(0,hd(Fi))],Qt);import{dirname as Td}from"node:path";import{chmod as yd,mkdirSync as fd,readFile as gd,writeFile as Rd}from"node:fs";import{rm as Cd}from"node:fs/promises";function Fe(e){return new Promise((t,o)=>{gd(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 eo(e){return fd(e.dirPath,{recursive:!0}),new Promise((t,o)=>{Rd(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():yd(e.filePath,e.mode,n=>{n?o(n):t()})})})}function St(e){return Cd(e,{force:!0})}var xd=384;function bi(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??xd;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 eo({filePath:t,dirPath:Td(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 St(t)})}}var bx=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 ki(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 to(e,t=an){return async o=>{try{await e(o)}catch(r){mn(r),process.exit(t)}}}var Ad=["raw","page_by_line","data_by_line"],Zd=["replace","concat"],Sd=["meta","pages","merged_page"];function oo(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:Sd,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:Ad,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:Zd,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function Ft(e){return Fe(e.configFilePath)}function Fd(e){return eo({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function It(e){let t=await Ft({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:er(t.output,e.updates.output)};return await Fd({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function er(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Id(e?.commands,t)}}function Id(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 Oi(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 bd}from"node:os";import{join as ro}from"node:path";function no(e){let t=e.configDirOverride??ro(bd(),`.${e.cliName}`);return{configDir:t,configFilePath:ro(t,"config.json"),tokenCachePath:ro(t,".tokens.json"),firestoreSessionCachePath:ro(t,".firestore-sessions.json")}}function Ei(e){let t=no({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await Ft({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await It({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{un(!!n.verbose),pn(typeof n.timeout=="number"?n.timeout*1e3:void 0);let i=n._?n._.map(String):[],a=i[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&a&&!e.skipCommands.has(a)){let m=i.join("."),C={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,C)}let l=a&&!e.skipCommands.has(a),h=l?await o():void 0,f=l?Oi({outputConfig:h,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};_o({dumpDir:f.dumpDir,pick:n.pickAll?void 0:f.pick,commandPath:i,pretty:!!n.pretty})}}function kd(e){let t=no({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await Ft({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>It({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>It({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 Pi(e){let t=kd(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:to(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:to(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:to(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new Ct({message:`No per-command output config for "${a}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[a],await t.mergeOutputConfig({...s,commands:c}),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 Od,appendFileSync as Ed}from"node:fs";function Di(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=Jt(),n=t==="raw"?"json":"ndjson",i=Tt(n),a=r?Tt(n,"pick"):void 0,s;if(i){let c=0,u=y=>{let R;if(r){let g=Me(y.data,r);R={...y,data:g}}else R=y;return R},l=y=>{let R=y.append?Ed:Od;R(i,y.mainContent),a&&y.pickContent!==void 0&&R(a,y.pickContent)},h=(y,R)=>{let g=JSON.stringify(y,null,2),S=a?JSON.stringify(u(y),null,2):void 0;l({mainContent:g,pickContent:S,append:R})},f=(y,R)=>{let g=JSON.stringify(y)+`
5
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)+`
6
+ `:void 0;l({mainContent:g,pickContent:S,append:R})},m=(y,R)=>{let g=y.data??[],S=a?Me(g,r):void 0;g.length===0?R||l({mainContent:"",pickContent:a?"":void 0,append:!1}):g.forEach((O,q)=>{let I=R||q>0,_=JSON.stringify(O)+`
7
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===`
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 Pd(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 Dd(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=Jt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let l=Di({dumpOutput:i,dumpMerge:a}),h;try{h=await Pd({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),Dd({multiplePagesOutput:n,summaryMeta:f,state:h,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import mg from"yargs";import{hideBin as yg}from"yargs/helpers";import{writeFile as Md,mkdirSync as wd}from"node:fs";import{join as tr}from"node:path";import{homedir as _d}from"node:os";var bt=["recruit","crm","desk","sign","analytics"],vd=new Set(["sign","analytics"]),Ne=new Set(["desk","analytics"]);function or(){return tr(_d(),".zoho-cli")}function kt(){return tr(or(),"config.json")}function Ot(){return tr(or(),".tokens.json")}function ve(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function j(){let e=kt(),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],C=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_ID`],y=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${l}_ACCOUNTS_REFRESH_TOKEN`],g=C||y||R,S;return!m&&!g&&!f?S=void 0:S={clientId:C??m?.clientId,clientSecret:y??m?.clientSecret,refreshToken:R??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=!vd.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 Nd(e){let t=kt();return wd(or(),{recursive:!0}),new Promise((o,r)=>{Md(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}function ot(e,t){return t==null?e??void 0:{...e,...Vn(t)}}async function ie(e){let t=await j(),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:er(t?.output,e.output)};return await Nd(o),o}async function Mi(){await ie({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function wi(){let e=kt(),t=Ot();await St(e),await St(t)}function ue(e){return bt.filter(t=>{let o=Ue(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as yu,Injectable as xm}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:di(o),per_page:n.maxItemsPerPage??r.per_page}}})}function io(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",_i="Job_Openings",ao="Notes",vi="Emails",Et="Attachments";function so(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=co(o);break}default:break}return t}function co(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(rr):a&&(s=co(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 Ni=jn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function rr(e){let t=Ni(e.value);return`(${e.field}:${e.filter}:${t})`}var Ui=so;import{BaseError as $d}from"make-error";import{BaseError as Ld}from"make-error";var Gd="__internal_data_array_blank_error";function Kd(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 Ld{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:Gd,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 Vd="INTERNAL_ERROR",zd="INVALID_TOKEN",G=class extends L{},Li="FAILURE",nr=class extends L{},Jd="4834",at=class extends L{},Hd="INVALID_QUERY",ir=class extends L{get details(){return this.error.details}},uo="MANDATORY_NOT_FOUND",ke="DUPLICATE_DATA",po="INVALID_DATA",qd="TOO_MANY_REQUESTS",ar=429,Wd="X-RATELIMIT-LIMIT",jd="X-RATELIMIT-REMAINING",Bd="X-RATELIMIT-RESET",Gi=100,Ki=Re;function sr(e){let t=e.get(Wd),o=e.get(jd),r=e.get(Bd),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 sr(this.responseError.response.headers)}};function te(e,t){let o;if(Kd(e))o=new it(e,t);else{let r=Te(e,t);if(r){let n=ae(r);switch(n.code){case Vd:o=new nr(n,e,t);break;case zd:o=new G(n,e,t);break;case Jd:o=new at(n,e,t);break;case Hd:o=new ir(n,e,t);break;case qd: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 Vi="ALREADY_ASSOCIATED",cr=class extends $d{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{},ur=class extends ct{},pr=class extends ct{},lo=class extends ct{get invalidFieldDetails(){return this.error.details}},lr=class extends lo{};function zi(e){let t;switch(e.code){case po:{let o=new lo(e);o.invalidFieldDetails.id?t=new lr(e):t=o;break}case uo:t=new ur(e);break;case ke:t=new pr(e);break;default:t=new ct(e);break}return t}function Ji(e,t){return o=>{if(!o?.data?.length)throw new cr(e,t);return o}}var Yd=Q("ZohoRecruit");async function Xd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Hi(t,e)),o}function Hi(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var qi=pe(Hi),Wi=ee(Xd,Yd);import{BaseError as Qd}from"make-error";function hr(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 zi(l[0].result);c=u[0].result.details}return c}))}function ji(e){return hr(e,"","POST")}function Bi(e){return hr(e,"/upsert","POST")}function $i(e){return hr(e,"","PUT")}function Yi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,K("DELETE")).then(eh)}function Xi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,K("GET")).then(Ji(t.module)).then(o=>o.data[0])}function Qi(e){return(t=>e.fetchJson(`/v2/${t.module}?${sa(t).toString()}`,K("GET")))}function mr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ui(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return sa(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,K("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function ea(e){return J(mr(e))}function ut(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${gr(n).toString()}`,K("GET")).then(i=>i??(r===!1?i:rt()))}}function yr(e){return ut(e)({targetModule:vi})}function ta(e){return J(yr(e))}function fr(e){return ut(e)({targetModule:Et})}function oa(e){return J(fr(e))}var HA=20*1024*1024;function ra(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}/${Et}?${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 na(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Et}/${t.attachment_id}`,{method:"GET"}).then(jt)}function ia(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Et}/${t.attachment_id}`,{method:"DELETE"})}var dr=class extends Qd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}error};function aa(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?io(t.apiUrl):""}${a}`;return e.fetchJson(c,K("POST")).then(u=>{if(u.code!=="success")throw new dr(u);return u.details})}}function sa(...e){return T(e,{omitKeys:"module"})}function gr(...e){return T(e,{omitKeys:["id","module"]})}function K(e,t){return{method:e,body:t??void 0}}function eh(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 ca(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===Li&&s.result.details.error[0].code===Vi);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function ua(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${gr(t).toString()}`,K("GET")).then(o=>o??rt())}function Rr(e){let t=ua(e);return o=>t({...o,module:nt})}function pa(e){return J(Rr(e))}function Cr(e,t=_i){let o=ua(e);return r=>o({...r,module:t})}function la(e){return J(Cr(e))}function Tr(e){return t=>e.fetchJson(`/v2/${ao}`,K("POST",{data:t.data})).then(o=>le(x(t.data),o.data))}function da(e){return t=>e.fetchJson(`/v2/${ao}?${T({ids:t.ids})}`,K("DELETE")).then(o=>le(x(t.ids),o.data))}function xr(e){return ut(e)({targetModule:ao})}function ha(e){return J(xr(e))}function ma(e){let t=Tr(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 ga(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 Ra(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 ya=100;function Ca(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ya)throw new Error(`Cannot add tags to more than ${ya} 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 fa=100;function Ta(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>fa)throw new Error(`Cannot remove tags from more than ${fa} 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 th="invalid_code",oh="invalid_client",Ar=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},rh=Q("ZohoAccounts");async function nh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=xa(t,e)),o}function xa(e,t){let o,r=e.error;if(r){let n=ae(r);switch(n.code){case th:case oh:o=new Ar(n.code);break;default:o=te(e,t);break}}return o}var Aa=pe(xa),Za=ee(nh,rh);function de(e){return async()=>{let t=await e();if(!t.accessToken)throw new pt;return t.accessToken}}var ih=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 Pt(e){let{readRateLimitDetails:t,enabledWithoutRateLimitDetails:o=!1}=e,r=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??ih,n=e.maxRateLimit??Gi,i=e.resetPeriod??Ki;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=si(s);return Ti({rateLimiter:c,maxRetries:e.maxRetries,updateWithResponse:function(u,l){let h=t(u.headers),f=!1,m=o;if(h){let{remaining:C,limit:y,resetAt:R}=h;if(y!=null&&y!==n){let g=a(y,R??void 0);c.setConfig(g,!1)}if(c.setRemainingLimit(C),R&&c.setNextResetAt(R),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 Pt({...e,readRateLimitDetails:Zr})}function Zr(e){let t=sr(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Sa(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=io(a.apiUrl),c=i({apiUrl:s}),u=Wi(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:qi,handleFetchJsonParseErrorFunction:$});return{recruitContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ho(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 mo="Notes",Fa="Emails",Dt="Attachments";var Ia=so;import{BaseError as ah}from"make-error";var Sr=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}moduleName;recordId},lt=class extends be{},Fr=class extends lt{},Ir=class extends lt{},yo=class extends lt{get invalidFieldDetails(){return this.error.details}},br=class extends yo{};function ba(e){let t;switch(e.code){case po:{let o=new yo(e);o.invalidFieldDetails.api_name==="id"?t=new br(e):t=o;break}case uo:t=new Fr(e);break;case ke:t=new Ir(e);break;default:t=new lt(e);break}return t}function ka(e,t){return o=>{if(!o?.data?.length)throw new Sr(e,t);return o}}var sh=Q("ZohoCrm",{logDataArrayErrors:!1});async function ch(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Oa(t,e)),o}function Oa(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Ea=pe(Oa),Pa=ee(ch,sh);import{BaseError as uh}from"make-error";function Or(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,H(o,{data:x(r)})).catch(qa).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 ba(l[0].result);c=u[0].result.details}return c}))}function Da(e){return Or(e,"","POST")}function Ma(e){return Or(e,"/upsert","POST")}function wa(e){return Or(e,"","PUT")}function _a(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,H("DELETE")).catch(qa).then(lh)}function va(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,H("GET")).then(ka(t.module)).then(o=>o.data[0])}function Na(e){return(t=>e.fetchJson(`/v8/${t.module}?${Ha(t).toString()}`,H("GET")))}function Er(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ia(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 Ha(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,H("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Ua(e){return J(Er(e))}function dt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${ph(n).toString()}`,H("GET")).then(i=>i??(r===!1?i:rt()))}}function Pr(e){let t=dt(e)({targetModule:Fa});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function La(e){return J(Pr(e))}function Dr(e){return dt(e)({targetModule:Dt})}function Ga(e){return J(Dr(e))}var nS=20*1024*1024;function Ka(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}/${Dt}?${T(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function Va(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Dt}/${t.attachment_id}`,{method:"GET"}).then(jt)}function za(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Dt}/${t.attachment_id}`,{method:"DELETE"})}var kr=class extends uh{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}error};function Ja(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?ho(t.apiUrl):""}${a}`;return e.fetchJson(c,H("POST")).then(u=>{if(u.code!=="success")throw new kr(u);return u.details})}}function Ha(...e){return T(e,{omitKeys:"module"})}function ph(...e){return T(e,{omitKeys:["id","module"]})}function H(e,t){return{method:e,body:t??void 0}}function qa(e){let t;if(e instanceof it)t={data:e.errorDataArray};else throw e;return t}function lh(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 Mr(e){return t=>e.fetchJson(`/v2/${mo}`,H("POST",{data:t.data})).then(o=>Oe(x(t.data),o.data))}function Wa(e){return t=>e.fetchJson(`/v2/${mo}?${T({ids:t.ids})}`,H("DELETE")).then(o=>Oe(x(t.ids),o.data))}function wr(e){return dt(e)({targetModule:mo})}function ja(e){return J(wr(e))}function Ba(e){let t=Mr(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 Ya(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 Xa(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,H("DELETE")).then(o=>o.tags)}function Qa(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 $a=100;function es(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,H("POST",ts(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function ts(e){if(Array.isArray(e.ids)&&e.ids.length>$a)throw new Error(`Cannot add/remove tags from more than ${$a} 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 os(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,H("POST",ts(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function rs(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=ho(a.apiUrl),c=i({apiUrl:s}),u=Pa(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Ea,handleFetchJsonParseErrorFunction:$});return{crmContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var ns="https://signsandbox.zoho.com/api/v1",dh="https://sign.zoho.com/api/v1";function _r(e){let t;switch(e){case"sandbox":t=ns;break;case"production":t=dh;break;default:t=e;break}return t}function is(e){let t=_r(e),o;try{o=new URL(t).hostname!==new URL(ns).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 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 ss(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,he("GET"))}function vr(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 cs(e){let t=vr(e);return as(t)}function us(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,he("GET"))}function ps(e){return()=>e.fetchJson("/fieldtypes",he("GET"))}function ls(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 ds(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function hs(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 ms(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 ys(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,he("GET"))}function fs(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 gs(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,he("PUT",{requests:o}))}function Rs(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,he("POST",r))}}function Cs(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,he("PUT",{expire_by:o}))}function Ts(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 xs(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&is(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 hh=Q("ZohoSign",{logDataArrayErrors:!1});async function mh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=As(t,e)),o}function As(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Zs=pe(As),Ss=ee(mh,hh);function Fs(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=_r(a.apiUrl),c=i({apiUrl:s}),u=Ss(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Zs,handleFetchJsonParseErrorFunction:$});return{signContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Is(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var yh=Q("ZohoDesk",{logDataArrayErrors:!1});async function fh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=bs(t,e)),o}function bs(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var ks=pe(bs),Os=ee(fh,yh);var gh="X-Rate-Limit-Remaining-v3",Rh="Retry-After",Ch=200;function Th(e){let t=e.get(gh),o;if(t!=null){let r=Number(t),n,i=e.get(Rh);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 Es(e){return Pt({maxRateLimit:Ch,...e,readRateLimitDetails:Th})}function Ps(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Es(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=Is(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Os(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:ks,handleFetchJsonParseErrorFunction:$});return{deskContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ds=25;function se(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ds}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Ds,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 fo(e){let t;return e&&(t=P(x(e))),t}function Nr(e){return t=>{let{include:o,...r}=t,n=ht([{...r,include:fo(o)}]);return e.fetchJson(`/tickets?${n}`,Le("GET")).then(i=>i??{data:[]})}}function Ms(e){return t=>{let{ticketId:o,include:r}=t,i=ht([{include:fo(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Le("GET"))}}function Ur(e){return t=>{let o=ht([t]);return e.fetchJson(`/tickets/search?${o}`,Le("GET")).then(r=>r??{data:[]})}}function ws(e){return t=>{let{contactId:o,include:r,...n}=t,i=ht([{...n,include:fo(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Le("GET")).then(a=>a??{data:[]})}}function _s(e){return t=>{let{productId:o,include:r,...n}=t,i=ht([{...n,include:fo(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Le("GET")).then(a=>a??{data:[]})}}function vs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Le("GET"))}function Ns(e){return t=>{let o=ht([{agentIds:P(x(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Le("GET"))}}function Us(e){return se(Nr(e))}function Ls(e){return se(Ur(e))}function Gs(e){return{method:e}}function Ks(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Gs("GET")).then(r=>r??{data:[]})}}function Vs(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Gs("GET"))}function Lr(e){return{method:e}}function zs(e){let t;return e&&(t=P(x(e))),t}function Gr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:zs(o)}]);return e.fetchJson(`/contacts?${n}`,Lr("GET")).then(i=>i??{data:[]})}}function Js(e){return t=>{let{contactId:o,include:r}=t,i=T([{include:zs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,Lr("GET"))}}function Hs(e){return t=>{let o=T([{contactIds:P(x(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Lr("GET")).then(r=>r??[])}}function qs(e){return se(Gr(e))}function Mt(e,t){return{method:e,body:t??void 0}}function Ws(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Mt("GET")).then(o=>o??[])}function js(e){return t=>{let o={tags:x(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Mt("POST",o)).then(r=>r??[])}}function Bs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Mt("DELETE"))}function $s(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,Mt("GET")).then(r=>r??{data:[]})}}function Ys(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,Mt("GET")).then(r=>r??{data:[]})}}function Kr(e,t){return{method:e,body:t??void 0}}function Xs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Kr("GET")).then(o=>o??[])}function Qs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Kr("POST",o))}}function ec(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Kr("DELETE",o))}}function tc(e,t){return{method:e,body:t??void 0}}function xh(e){let t;return e&&(t=P(x(e))),t}function oc(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:xh(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,tc("GET")).then(a=>a??{data:[]})}}function rc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,tc("DELETE"))}function go(e,t){return{method:e,body:t??void 0}}function nc(e){let t;return e&&(t=P(x(e))),t}function ic(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:nc(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,go("GET")).then(a=>a??{data:[]})}}function ac(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:nc(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,go("GET"))}}function sc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,go("POST",r))}}function cc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,go("DELETE"))}function wt(e,t){return{method:e,body:t??void 0}}function uc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,wt("GET"))}function pc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,wt("POST",r))}}function lc(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,wt("GET")).then(i=>i??{data:[]})}}function dc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,wt("GET"))}function hc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,wt("GET"))}function mc(e){return{method:e}}function yc(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:yc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,mc("GET")).then(a=>a??{data:[]})}}function fc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:yc(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,mc("GET"))}}function gc(e){return se(Vr(e))}function Ah(e){return{method:e}}function Zh(e){let t;return e&&(t=P(x(e))),t}function zr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:Zh(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,Ah("GET")).then(a=>a??{data:[]})}}function Rc(e){return se(zr(e))}function Ro(e){return{method:e}}function Cc(e){let t;return e&&(t=P(x(e))),t}function Jr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Cc(o)}]);return e.fetchJson(`/agents?${n}`,Ro("GET")).then(i=>i??{data:[]})}}function Tc(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:Cc(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Ro("GET"))}}function xc(e){return t=>{let o=T([{agentIds:P(x(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Ro("GET")).then(r=>r?.data??[])}}function Ac(e){return()=>e.fetchJson("/myinfo",Ro("GET"))}function Zc(e){return se(Jr(e))}var Sh="https://accounts.zoho.com",Fh="https://accounts.zoho.eu",Ih="https://accounts.zoho.in",bh="https://accounts.zoho.com.au",kh="https://accounts.zoho.jp",Oh="https://accounts.zoho.uk",Eh="https://accounts.zohocloud.ca",Ph="https://accounts.zoho.sa",Dh={us:Sh,eu:Fh,in:Ih,au:bh,jp:kh,uk:Oh,ca:Eh,sa:Ph};function Ge(e){return Dh[e]??e}var Co="/oauth/v2/token";function To(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(`${Co}?${l}`,Hr("POST"))}}function Sc(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(`${Co}?${c}`,Hr("POST"))}}function Fc(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(`${Co}?${u}`,Hr("POST"))}}var Mh="/oauth/user/info";function Ic(e){return t=>e.fetchJson(Mh,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Hr(e,t){return{method:e,body:t}}function bc(e){return t=>X.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function kc(e,t){let o=Za(e,t),r=Y(o,{interceptJsonResponse:Aa,handleFetchJsonParseErrorFunction:$});return{fetch:o,fetchJson:r}}function Oc(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=bc(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}=kc(a,o),u=async()=>{let m=Date.now(),{access_token:C,api_domain:y,scope:R,expires_in:g}=await To(h)();return{accessToken:C,apiDomain:y,expiresIn:g,expiresAt:new Date(m+g*z),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let l=wh({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),h={fetch:s,fetchJson:c,loadAccessToken:l,config:{...n,apiUrl:i}};return{accountsContext:h}}}function Ec(e){let t=e.fetchHandler??xe(),{logZohoServerErrorFunction:o,fetchFactory:r=bc(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}=kc(a,o),c={...n,apiUrl:i};return{oauthClientContext:{fetchJson:s,config:c}}}}function wh(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 Pc="ZANALYTICS-ORGID";function Dc(e){let t;switch(e){case"sandbox":case"production":t="https://analyticsapi.zoho.com/restapi/v2";break;default:t=e;break}return t}var _h="CONFIG",vh="application/x-www-form-urlencoded";function Mc(e){return e==null?"":T({[_h]:JSON.stringify(e)}).toString()}function Ee(e){let t=Mc(e);return t?`?${t}`:""}function V(e,t){return{method:e,body:t??void 0}}function xo(e,t){return{method:e,headers:{"Content-Type":vh},body:Mc(t)}}var Nh="failure",Uh="8535",Lh="8083",Gh="6045",Kh=["6043","6044"],qr=class extends L{};function wc(e){return e?.status===Nh}function Vh(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 _c(e,t){let o;if(wc(e)){let r=Vh(e),n={error:r};switch(r.code){case Uh:o=new G(r,n,t);break;case Lh:o=new qr(r,n,t);break;case Gh:o=new Ce(r,n,t);break;default:o=Kh.includes(r.code)?new Ce(r,n,t):new L(r,n,t);break}}else o=te(e,t);return o}var zh=Q("ZohoAnalytics",{logDataArrayErrors:!1});async function Jh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=_c(t,e)),o}var vc=(e,t)=>{if(wc(e)){let o=_c(e,new Se(t));if(o)throw o}return e},Nc=ee(Jh,zh);var Hh=100;var qh=Re;function Uc(e){return Pt({maxRateLimit:Hh,resetPeriod:qh,...e,readRateLimitDetails:Zr,enabledWithoutRateLimitDetails:!0})}var Wh="1001",jh="1002";var Bh="1004";var $h=z*2,Yh=150;function Xh(e){return e===Wh||e===jh}function Pe(e){return e===Bh}function Ao(e){let{loadJob:t,readJobCode:o,pollWait:r=$h,maxPolls:n=Yh}=e;return ii({next:async i=>(i>0&&await Zt(r),t()),checkContinue:(i,a)=>i!=null&&Xh(o(i))&&a<n})}var Qh=65279;function em(e,t){let o=e.codePointAt(0)===Qh?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
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();
10
+ `?2:1):(i+=u,s=!0,c+=1)}return(s||i!==""||n.length>0)&&(n.push(i),r.push(n)),r}function tm(e,t){let o=em(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:Ko(a.filter(c=>c!=="")),rows:s}}return i}function om(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:Ko(n.flatMap(i=>Object.keys(i))),rows:n}}function Lc(e){let{content:t,fileType:o,delimiter:r}=e;return o==="json"?om(t):tm(t,r)}var rm=3,nm=/[\s,%$£€¥]/g,im=new Set(["true","false","yes","no","y","n","t","f","1","0"]),am=/^[\d\s/.:+-]+$/,sm=new Set(["PLAIN","MULTI_LINE","EMAIL","URL"]);function Wr(e){return e==null?"":String(e).trim()}var cm=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,um=/^www\./i;function mt(e){let{text:t,allowNegative:o,allowFraction:r}=e,n=Number(t.replaceAll(nm,"")),i;return Number.isFinite(n)?!o&&n<0?i="negative":!r&&!Number.isInteger(n)&&(i="notAnInteger"):i="notANumber",i}var pm={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=>im.has(e.toLowerCase())?void 0:"notABoolean",EMAIL:e=>cm.test(e)?void 0:"notAnEmail",URL:e=>URL.canParse(e)||um.test(e)?void 0:"notAUrl"};function lm(e,t,o){let r=o==null||sm.has(o);return t.columnMaxSize!=null&&e.length>t.columnMaxSize&&r}function dm(e,t){let o=Wr(e),r=t.dataType?.toUpperCase(),n;return o===""?n=t.isNullable===!1&&t.defaultValue==null?"emptyInNonNullable":void 0:lm(o,t,r)?n="tooLong":n=r==null?void 0:pm[r]?.(o),n}function hm(e,t){return`${e}\0${t}`}function Gc(e){let{columns:t,columnNames:o,rows:r,maxSamples:n}=e,i=n??rm,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)=>Wr(O[g])===""?S:S+1,0)})),C=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=dm(g[O],q);if(I!=null){let _=hm(O,I),v=y.get(_);if(v==null){let B=[];v={conflict:{columnName:O,dataType:q.dataType,reason:I,conflictCount:0,samples:B},count:0,samples:B},y.set(_,v)}v.count+=1,v.samples.length<i&&v.samples.push({row:S+1,value:Wr(g[O])})}})});let R=Array.from(y.values()).map(g=>({...g.conflict,conflictCount:g.count}));return{matchedColumns:u,droppedColumns:m,emptyColumns:C,caseMismatchedColumns:h,conflicts:R,rowCount:r.length}}function Kc(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 Vc(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Uc(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?{[Pc]: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=Dc(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Nc(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:vc,handleFetchJsonParseErrorFunction:$});return{analyticsContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function zc(e){return()=>e.fetchJson("/orgs",V("GET"))}function Jc(e){return()=>e.fetchJson("/workspaces",V("GET"))}function Hc(e){return()=>e.fetchJson("/workspaces/owned",V("GET"))}function qc(e){return()=>e.fetchJson("/workspaces/shared",V("GET"))}function Wc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("GET"))}function jc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views`,V("GET"))}function Bc(e){return t=>e.fetchJson(`/views/${t.viewId}`,V("GET"))}function $c(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/metadata`,V("GET"))}var mm="import";function ym(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],`${mm}.${s}`,{type:s==="json"?"application/json":"text/csv"}))}else i.append("DATA",a)}}return i}function jr(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 Zo(e){return e??!0}function Yc(e,t){let o=jr(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 So(e){let{context:t,url:o,config:r,dataInput:n,formDataOptions:i}=e,a=ym(n,i);return(await t.fetch(`${o}${Ee(r)}`,{method:"POST",headers:{"Content-Type":""},body:a})).json()}function Xc(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a={...n,autoIdentify:Zo(n.autoIdentify),fileType:jr(i,n.fileType)};return So({context:e,url:`/workspaces/${o}/views/${r}/data`,config:a,dataInput:i})}}function Qc(e){return t=>{let{workspaceId:o,config:r,...n}=t,i={...r,autoIdentify:Zo(r.autoIdentify),fileType:jr(n,r.fileType)};return So({context:e,url:`/workspaces/${o}/data`,config:i,dataInput:n})}}function Br(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a=Yc(i,n.fileType),s={...n,autoIdentify:Zo(n.autoIdentify),fileType:a};return So({context:e,url:`/bulk/workspaces/${o}/views/${r}/data`,config:s,dataInput:i,formDataOptions:{asFile:!0,fileType:a}})}}function eu(e){return t=>{let{workspaceId:o,config:r,...n}=t,i=Yc(n,r.fileType),a={...r,autoIdentify:Zo(r.autoIdentify),fileType:i};return So({context:e,url:`/bulk/workspaces/${o}/data`,config:a,dataInput:n,formDataOptions:{asFile:!0,fileType:i}})}}function $r(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/importjobs/${t.jobId}`,{method:"GET"})}function tu(e){let t=Br(e),o=$r(e);return async r=>{let{poll:n,...i}=r,{data:a}=await t(i);return Ao({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function ou(e){return t=>e.fetch(`/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,{method:"GET"})}function Yr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,V("GET"))}function ru(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/data${Ee(t.config)}`,V("GET"))}function Xr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}`,V("GET"))}function nu(e){return t=>e.fetch(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}/data`,{method:"GET"})}function iu(e){let t=Yr(e),o=Xr(e);return async r=>{let{poll:n,...i}=r,{data:a}=await t(i);return Ao({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function au(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,xo("POST",t.config))}function su(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`,xo("PUT",t.config))}}function cu(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`,xo("DELETE",t.config))}}function uu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}${Ee(t.config)}`,V("DELETE"))}function pu(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 fm}from"@nestjs/common";var yt=class{};yt=F([fm()],yt);function gm(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Gn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function Rm(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Cm(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function du(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Cm;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(gm),c=Wn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let l=await Promise.allSettled(a.map(h=>Rm(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 hu(e,t){let o={};if(e!=null)for(let i of Object.keys(e)){let a=e[i];a!=null&&(o[i]=a)}let r=Hn(o);function n(i){return{loadCachedToken:async()=>{let a=await r.get(i);return t&&console.log("retrieving access token from memory: ",{service:i,hit:a!=null,expiresAt:a?.expiresAt}),a},updateCachedToken:async a=>{await r.set(i,a),t&&console.log("updating access token in memory: ",{service:i,expiresAt:a?.expiresAt})},clearCachedToken:async()=>{await r.remove(i),t&&console.log("clearing access token in memory: ",{service:i})}}}return{loadZohoAccessTokenCache:n}}var Tm=".tmp/zoho-access-tokens.json";function lu(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 mu(e=Tm,t=!0){let o=bi({filePath:e,reviver:lu}),r=t?qn(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]=lu(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=Oc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}config;cacheService;zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return To(this.accountsContext)}};w=F([xm(),b(0,yu(Ae)),b(1,yu(yt))],w);import{Inject as Sm,Injectable as Fm}from"@nestjs/common";var Am="ZOHO_ACCOUNTS_CLIENT_ID",Zm="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 (${Am}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${Zm}).`)}};var vt=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=Ec(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 Fc(i)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Sc(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Ic(n)({accessToken:o})}};vt=F([Fm(),b(0,Sm(ft))],vt);import{ConfigModule as Dk,ConfigService as Mk}from"@nestjs/config";import{Inject as fu,Injectable as Im}from"@nestjs/common";var Nt=class{zohoCrm;factoryConfig;static assertValidConfig(t){me(t.zohoCrm)}};var Ke=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=rs({...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 Da(this.crmContext)}get upsertRecord(){return Ma(this.crmContext)}get updateRecord(){return wa(this.crmContext)}get deleteRecord(){return _a(this.crmContext)}get getRecordById(){return va(this.crmContext)}get getRecords(){return Na(this.crmContext)}get searchRecords(){return Er(this.crmContext)}get searchRecordsPageFactory(){return Ua(this.crmContext)}get getRelatedRecordsFunctionFactory(){return dt(this.crmContext)}get getEmailsForRecord(){return Pr(this.crmContext)}get getEmailsForRecordPageFactory(){return La(this.crmContext)}get getAttachmentsForRecord(){return Dr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Ga(this.crmContext)}get uploadAttachmentForRecord(){return Ka(this.crmContext)}get downloadAttachmentForRecord(){return Va(this.crmContext)}get deleteAttachmentFromRecord(){return za(this.crmContext)}get createNotes(){return Mr(this.crmContext)}get deleteNotes(){return Wa(this.crmContext)}get createNotesForRecord(){return Ba(this.crmContext)}get getNotesForRecord(){return wr(this.crmContext)}get getNotesForRecordPageFactory(){return ja(this.crmContext)}get executeRestApiFunction(){return Ja(this.crmContext)}get createTagsForModule(){return Ya(this.crmContext)}get deleteTag(){return Xa(this.crmContext)}get getTagsForModule(){return Qa(this.crmContext)}get addTagsToRecords(){return es(this.crmContext)}get removeTagsFromRecords(){return os(this.crmContext)}};Ke=F([Im(),b(0,fu(Nt)),b(1,fu(w))],Ke);import{ConfigModule as eO,ConfigService as tO}from"@nestjs/config";import{Inject as gu,Injectable as bm}from"@nestjs/common";var Ut=class{zohoRecruit;factoryConfig;static assertValidConfig(t){me(t.zohoRecruit)}};var Ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Sa({...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 ji(this.recruitContext)}get upsertRecord(){return Bi(this.recruitContext)}get updateRecord(){return $i(this.recruitContext)}get deleteRecord(){return Yi(this.recruitContext)}get getRecordById(){return Xi(this.recruitContext)}get getRecords(){return Qi(this.recruitContext)}get searchRecords(){return mr(this.recruitContext)}get searchRecordsPageFactory(){return ea(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ut(this.recruitContext)}get getEmailsForRecord(){return yr(this.recruitContext)}get getEmailsForRecordPageFactory(){return ta(this.recruitContext)}get getAttachmentsForRecord(){return fr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return oa(this.recruitContext)}get uploadAttachmentForRecord(){return ra(this.recruitContext)}get downloadAttachmentForRecord(){return na(this.recruitContext)}get deleteAttachmentFromRecord(){return ia(this.recruitContext)}get createNotes(){return Tr(this.recruitContext)}get deleteNotes(){return da(this.recruitContext)}get createNotesForRecord(){return ma(this.recruitContext)}get getNotesForRecord(){return xr(this.recruitContext)}get getNotesForRecordPageFactory(){return ha(this.recruitContext)}get executeRestApiFunction(){return aa(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return ca(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Rr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return pa(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Cr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return la(this.recruitContext)}get createTagsForModule(){return ga(this.recruitContext)}get getTagsForModule(){return Ra(this.recruitContext)}get addTagsToRecords(){return Ca(this.recruitContext)}get removeTagsFromRecords(){return Ta(this.recruitContext)}};Ve=F([bm(),b(0,gu(Ut)),b(1,gu(w))],Ve);import{ConfigModule as ZO,ConfigService as SO}from"@nestjs/config";import{Inject as Ru,Injectable as km}from"@nestjs/common";var Lt=class{zohoSign;factoryConfig;static assertValidConfig(t){me(t.zohoSign)}};var ze=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Fs({...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 ss(this.signContext)}get getDocuments(){return vr(this.signContext)}get getDocumentsPageFactory(){return cs(this.signContext)}get getDocumentFormData(){return us(this.signContext)}get retrieveFieldTypes(){return ps(this.signContext)}get downloadPdf(){return ls(this.signContext)}get downloadCompletionCertificate(){return ds(this.signContext)}get createDocument(){return hs(this.signContext)}get createDocumentFromTemplate(){return ms(this.signContext)}get getTemplate(){return ys(this.signContext)}get getTemplates(){return fs(this.signContext)}get updateDocument(){return gs(this.signContext)}get sendDocumentForSignature(){return Rs(this.signContext)}get extendDocument(){return Cs(this.signContext)}get deleteDocument(){return Ts(this.signContext)}get getEmbeddedSigningUrl(){return xs(this.signContext)}};ze=F([km(),b(0,Ru(Lt)),b(1,Ru(w))],ze);import{ConfigModule as qO,ConfigService as WO}from"@nestjs/config";function Cu(e){return{...e,operationType:e.notifications.operation_type}}var Tu=ci(e=>e.operationType),xu=pi({configurerForAccessor:e=>{let t=ui(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 Au="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 _m,Inject as vm,Post as Nm,Req as Um}from"@nestjs/common";import{Inject as Dm,Injectable as Mm,Logger as wm}from"@nestjs/common";import{createHmac as Om,timingSafeEqual as Em}from"node:crypto";var Pm="x-zs-webhook-signature";function Zu(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Pm],i={valid:!1};if(n){let a=r.toString("utf-8"),s=Om("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=Em(l,h))}catch{c=!1}let u;if(c)try{let l=JSON.parse(a);u=Cu(l)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var Ze=class{logger=new wm("ZohoSignWebhookService");_verifier;handler=Tu();configure=xu(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Zu({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([Mm(),b(0,Dm(Je))],Ze);var He=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([Nm(),b(0,Um()),b(1,Zi())],He.prototype,"handleZohoSignWebhook",1),He=F([_m("/webhook/zoho/sign"),b(0,vm(Ze))],He);import{Module as Lm}from"@nestjs/common";import{ConfigModule as Gm,ConfigService as Km}from"@nestjs/config";function Vm(e){let t={zohoSignWebhook:{webhookSecret:e.get(Au)}};return Je.assertValidConfig(t),t}var bo=class{};bo=F([Lm({imports:[Gm],controllers:[He],providers:[{provide:Je,inject:[Km],useFactory:Vm},Ze],exports:[Ze]})],bo);import{Inject as Su,Injectable as zm}from"@nestjs/common";var Gt=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=Ps({...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 Nr(this.deskContext)}get getTicketById(){return Ms(this.deskContext)}get searchTickets(){return Ur(this.deskContext)}get getTicketsForContact(){return ws(this.deskContext)}get getTicketsForProduct(){return _s(this.deskContext)}get getTicketMetrics(){return vs(this.deskContext)}get getAgentsTicketsCount(){return Ns(this.deskContext)}get getTicketsPageFactory(){return Us(this.deskContext)}get searchTicketsPageFactory(){return Ls(this.deskContext)}get getDepartments(){return Ks(this.deskContext)}get getDepartmentById(){return Vs(this.deskContext)}get getContacts(){return Gr(this.deskContext)}get getContactById(){return Js(this.deskContext)}get getContactsByIds(){return Hs(this.deskContext)}get getContactsPageFactory(){return qs(this.deskContext)}get getTicketTags(){return Ws(this.deskContext)}get associateTicketTags(){return js(this.deskContext)}get dissociateTicketTag(){return Bs(this.deskContext)}get searchTags(){return $s(this.deskContext)}get getAllTags(){return Ys(this.deskContext)}get getTicketFollowers(){return Xs(this.deskContext)}get addTicketFollowers(){return Qs(this.deskContext)}get removeTicketFollowers(){return ec(this.deskContext)}get getTicketAttachments(){return oc(this.deskContext)}get deleteTicketAttachment(){return rc(this.deskContext)}get getTicketComments(){return ic(this.deskContext)}get getTicketCommentById(){return ac(this.deskContext)}get createTicketComment(){return sc(this.deskContext)}get deleteTicketComment(){return cc(this.deskContext)}get getTicketTimer(){return uc(this.deskContext)}get performTicketTimerAction(){return pc(this.deskContext)}get getTicketTimeEntries(){return lc(this.deskContext)}get getTicketTimeEntryById(){return dc(this.deskContext)}get getTicketTimeEntrySummation(){return hc(this.deskContext)}get getTicketThreads(){return Vr(this.deskContext)}get getTicketThreadById(){return fc(this.deskContext)}get getTicketThreadsPageFactory(){return gc(this.deskContext)}get getTicketActivities(){return zr(this.deskContext)}get getTicketActivitiesPageFactory(){return Rc(this.deskContext)}get getAgents(){return Jr(this.deskContext)}get getAgentById(){return Tc(this.deskContext)}get getAgentsByIds(){return xc(this.deskContext)}get getMyInfo(){return Ac(this.deskContext)}get getAgentsPageFactory(){return Zc(this.deskContext)}};qe=F([zm(),b(0,Su(Gt)),b(1,Su(w))],qe);import{ConfigModule as WE,ConfigService as jE}from"@nestjs/config";import{Inject as Fu,Injectable as Jm}from"@nestjs/common";var Kt=class{zohoAnalytics;factoryConfig;static assertValidConfig(t){me(t.zohoAnalytics)}};var We=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoAnalytics=Vc({...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 zc(this.analyticsContext)}get getAllWorkspaces(){return Jc(this.analyticsContext)}get getOwnedWorkspaces(){return Hc(this.analyticsContext)}get getSharedWorkspaces(){return qc(this.analyticsContext)}get getWorkspaceDetails(){return Wc(this.analyticsContext)}get getViews(){return jc(this.analyticsContext)}get getViewDetails(){return Bc(this.analyticsContext)}get getTableMetadata(){return $c(this.analyticsContext)}get importDataInTable(){return Xc(this.analyticsContext)}get importDataInNewTable(){return Qc(this.analyticsContext)}get createImportJobInTable(){return Br(this.analyticsContext)}get createImportJobInNewTable(){return eu(this.analyticsContext)}get getImportJob(){return $r(this.analyticsContext)}get importDataInTableAndAwaitJob(){return tu(this.analyticsContext)}get exportData(){return ou(this.analyticsContext)}get createExportJob(){return Yr(this.analyticsContext)}get createExportJobForSqlQuery(){return ru(this.analyticsContext)}get getExportJob(){return Xr(this.analyticsContext)}get downloadExport(){return nu(this.analyticsContext)}get exportDataAndAwaitJob(){return iu(this.analyticsContext)}get addRow(){return au(this.analyticsContext)}get updateRows(){return su(this.analyticsContext)}get deleteRows(){return cu(this.analyticsContext)}get deleteView(){return uu(this.analyticsContext)}get deleteWorkspace(){return pu(this.analyticsContext)}};We=F([Jm(),b(0,Fu(Kt)),b(1,Fu(w))],We);import{ConfigModule as fP,ConfigService as gP}from"@nestjs/config";function ko(e){return{recruit:e.recruitApi,crm:e.crmApi,desk:e.deskApi,sign:e.signApi,analytics:e.analyticsApi}}function Hm(e){return`${e.clientId}:${e.refreshToken}`}function gt(e){let t=du([hu(),mu(Ot())]),o=new Map;function r(C,y){let R=Hm(C),g=o.get(R),S;if(g)S=g;else{let O={zohoAccounts:{serviceAccessTokenKey:y,refreshToken:C.refreshToken,clientId:C.clientId,clientSecret:C.clientSecret,apiUrl:C.region??"us"}};S=new w(O,t),o.set(R,S)}return S}let n,i=Ue(e,"recruit");if(i){let C=r(i,"recruit"),y={zohoRecruit:{apiUrl:i.apiMode}};n=new Ve(y,C)}let a,s=Ue(e,"crm");if(s){let C=r(s,"crm"),y={zohoCrm:{apiUrl:s.apiMode}};a=new Ke(y,C)}let c,u=Ue(e,"desk");if(u?.orgId){let C=r(u,"desk"),y={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new qe(y,C)}let l,h=Ue(e,"sign");if(h){let C=r(h,"sign"),y={zohoSign:{apiUrl:h.apiMode}};l=new ze(y,C)}let f,m=Ue(e,"analytics");if(m){let C=r(m,"analytics"),y={zohoAnalytics:{apiUrl:m.apiMode,orgId:m.orgId}};f=new We(y,C)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:l,analyticsApi:f}}vo([...wo,/1000\.\w{20,}/g]);function Iu(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=No(e),t}ln(e=>e instanceof G||e instanceof at||e instanceof Ce||e instanceof L?Iu(e):void 0);function d(e){console.log(JSON.stringify(Iu(e)))}var bu={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"},Qr={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"]},ku="http://localhost/oauth",Ou=`Organization ID, for the products scoped by one (${Array.from(Ne).join(", ")})`;function qm(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 Wm={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:ku,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:[...bt],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:Ou}).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 j(),o=$m(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 Ym(o,t):o.code?await Xm(o,t):await ey(o,t)}catch(t){d(t),process.exit(1)}}},jm="recruit,crm,desk";function Bm(e,t){return(e??t??jm).split(",").map(o=>o.trim())}function $m(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??ku,region:o,scopes:Bm(e.scopes,r),code:qm(e.code),token:e.token,accountsUrl:bu[o]??bu.us,apiMode:e.apiMode,orgId:e.orgId}}function en({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 Eu(e,t,o){return e.product?ie({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:en({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 Ym(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await Eu(e,o,t?.shared);p({success:!0,...e.product?{product:e.product}:{},refreshToken:Ie(e.token),configSaved:!0,configuredProducts:ue(r)})}async function Xm(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 Eu(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 Qm(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]:en({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 ey(e,t){let o=e.product?Qr[e.product]??[]:e.scopes.flatMap(i=>Qr[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Qr).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 Qm(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 ty={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:[...bt],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:Ou}).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 j())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:en({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 Pu(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 oy(e,t){return t?{...Pu(t),apiUrl:t.apiUrl,...Ne.has(e)?{orgId:t.orgId}:{}}:null}function ry(e){let t=Object.fromEntries(bt.map(o=>[o,oy(o,e[o])]));return{configured:!0,shared:{...Pu(e.shared),region:e.shared?.region??"us",apiMode:e.shared?.apiMode??"production"},...t,configuredProducts:ue(e)}}var ny={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let e=await j();p(e?ry(e):{configured:!1})}catch(e){d(e),process.exit(1)}}},iy={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await j();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=ko(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)}}},ay={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await wi(),p({cleared:!0})}catch(e){d(e),process.exit(1)}}},Du={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Wm).command(ty).command(ny).command(iy).command(ay).demandCommand(1,"Please specify an auth subcommand."),handler:A};import{access as sy,constants as cy}from"node:fs";import{dirname as uy}from"node:path";function py(e){return e.every(t=>t.status==="pass")}var Mu={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await j(),t=[];t.push(ly(e));let o=dy(e);if(o&&t.push(o),t.push(await hy()),e){let n=ue(e);t.push(my(n),...await yy(e,n),...gy(e,n))}let r=py(t);p({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function ly(e){return e?{name:"config",status:"pass",message:`Config loaded from ${kt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function dy(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 hy(){let e=uy(Ot());return await Ry(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 my(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 yy(e,t){let o=ko(gt(e)),r=[];for(let n of t)r.push(await fy(o[n],n));return r}async function fy(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 gy(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 Ry(e){return new Promise(t=>{sy(e,cy.W_OK,o=>{t(!o)})})}var wu=ki({notInitializedMessage:"CLI context not initialized. This is a bug."});function _u(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await j();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)),wu.set(gt(r))}catch(r){d(r),process.exit(4)}}}function Vt(e){return wu.require()}function oe(e){let{recruitApi:t}=Vt(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}=Vt(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}=Vt(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}=Vt(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}=Vt(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 oo(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 oo(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function Oo(e){return oo(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 zt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Eo(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 Cy={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}},Ty={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:Cy,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 Po(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:Ty,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 xy={command:"list",describe:"List records from a module",builder:e=>Eo(zt(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)}}},Ay={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)}}},Zy={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)}}},Sy={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)}}},Fy={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)}}},Iy={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)}}},by={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)}}},ky={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)}}},Oy={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)}}},vu={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(xy).command(Ay).command(Zy).command(Sy).command(Fy).command(Iy).command(by).command(ky).command(Oy).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 Ey={command:"list",describe:"List records from a module",builder:e=>Eo(zt(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)}}},Py={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)}}},Dy={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)}}},My={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)}}},wy={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)}}},_y={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)}}},vy={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)}}},Ny={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)}}},Uy={command:"attachments",describe:"Get attachments for a record",builder:e=>zt(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)}}},Nu={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Ey).command(Py).command(Dy).command(My).command(wy).command(_y).command(vy).command(Ny).command(Uy).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 Ly={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)}}},Gy={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)}}},Ky={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)}}},Vy={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)}}},zy={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)}}},Jy={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)}}},Uu={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Ly).command(Gy).command(Ky).command(Vy).command(zy).command(Jy).demandCommand(1),handler:A};var Hy={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)}}},qy={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)}}},Lu={command:"departments",describe:"Desk department operations",builder:e=>e.command(Hy).command(qy).demandCommand(1),handler:A};var Wy={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)}}},jy={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)}}},Gu={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Wy).command(jy).demandCommand(1),handler:A};var By={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)}}},$y={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)}}},Yy={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)}}},Ku={command:"agents",describe:"Desk agent operations",builder:e=>e.command(By).command($y).command(Yy).demandCommand(1),handler:A};var Xy={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)}}},Qy={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)}}},ef={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)}}},tf={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)}}},of={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)}}},Vu={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Xy).command(Qy).command(ef).command(tf).command(of).demandCommand(1),handler:A};var rf={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)}}},nf={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)}}},af={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)}}},sf={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)}}},zu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(rf).command(nf).command(af).command(sf).demandCommand(1),handler:A};var cf={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)}}},uf={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)}}},Ju={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(cf).command(uf).demandCommand(1),handler:A};var pf={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)}}},lf={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)}}},df={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)}}},Hu={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(pf).command(lf).command(df).demandCommand(1),handler:A};var hf={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)}}},mf={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)}}},yf={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)}}},ff={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)}}},qu={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(hf).command(mf).command(yf).command(ff).demandCommand(1),handler:A};var gf={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)}}},Rf={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)}}},Wu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(gf).command(Rf).demandCommand(1),handler:A};var Cf={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)}}},ju={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Cf).demandCommand(1),handler:A};var Bu={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(Uu).command(Lu).command(Gu).command(Ku).command(Vu).command(zu).command(Ju).command(Hu).command(qu).command(Wu).command(ju).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 Tf,writeFile as $u}from"node:fs/promises";import{basename as xf}from"node:path";function Af(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 Zf={command:"list",describe:"List sign requests (documents)",builder:e=>Oo(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. request_name, created_time, recipient_email)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("request-name",{type:"string",describe:"Filter by request name"}).option("folder-name",{type:"string",describe:"Filter by folder name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}).option("recipient-email",{type:"string",describe:"Filter by recipient email"}).option("recipient-name",{type:"string",describe:"Filter by recipient name"}).option("form-name",{type:"string",describe:"Filter by form name"}),handler:async e=>{try{let t=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:Af(e)};await Po({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){d(t),process.exit(1)}}},Sf={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)}}},Ff={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)}}},If={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 Tf(e.file),n=new File([r],xf(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});p(i)}catch(t){d(t),process.exit(1)}}},bf={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)}}},kf={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)}}},Of={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)}}},Ef={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)}}},Pf={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)}}},Df={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 $u(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Mf={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 $u(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},wf={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)}}},Yu={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Zf).command(Sf).command(Ff).command(If).command(bf).command(kf).command(Of).command(Ef).command(Pf).command(Df).command(Mf).command(wf).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 _f(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 vf={command:"list",describe:"List templates",builder:e=>Oo(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. template_name, created_time)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("template-name",{type:"string",describe:"Filter by template name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}),handler:async e=>{try{let t=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:_f(e)};await Po({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){d(t),process.exit(1)}}},Nf={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)}}},Xu={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(vf).command(Nf).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 Uf={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)}}},Qu={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command(Yu).command(Xu).command(Uf).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 Lf={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)}}},ep={command:"orgs",describe:"Analytics organization operations",builder:e=>e.command(Lf).demandCommand(1).example([["$0 analytics orgs list","Find the org id needed by every other Analytics command"]]),handler:A};var Gf={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)}}},Kf={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 Vf(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 zf={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=Vf(e.workspaceId,e.confirm);await E(e).deleteWorkspace({workspaceId:t}),p({deleted:!0,workspaceId:t})}catch(t){d(t),process.exit(1)}}},tp={command:"workspaces",describe:"Analytics workspace operations",builder:e=>e.command(Gf).command(Kf).command(zf).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 Jf={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)}}},Hf={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)}}},qf={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)}}},Wf={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)}}},op={command:"views",describe:"Analytics view operations",builder:e=>e.command(Jf).command(Hf).command(qf).command(Wf).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 jf}from"node:fs/promises";import{basename as Bf,extname as rp}from"node:path";var $f=["append","truncateadd","updateadd"],Yf=["abort","skiprow","setcolumnempty"];async function np(e){let t=await jf(e,"utf8"),o=Bf(e),r=rp(e).toLowerCase()===".json"?"application/json":"text/csv";return Ci({content:t,fileName:o,mimeType:r})}function Do(e){let t=rp(e).toLowerCase();return{".json":"json",".csv":"csv"}[t]}function Xf(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 ip(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:Yf,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 Qf={command:"data <workspaceId> <viewId>",describe:"Import a file into an existing table",builder:e=>ip(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:$f,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=Xf(o,e.matchingColumns),n=await np(e.file),i={importType:o,fileType:e.fileType??Do(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)}}},eg={command:"new-table <workspaceId> <tableName>",describe:"Create a table in a workspace from an imported file",builder:e=>ip(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 np(e.file),r={tableName:e.tableName,fileType:e.fileType??Do(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)}}},tg={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(Qf).command(eg).command(tg).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 og}from"node:fs/promises";var rg=["csv","json","xml","xls","pdf","html","image"];async function tn(e,t){let o=await e.text(),r;return t?await og(t,o,"utf8"):r=o,r}function sp(e){return e.option("format",{type:"string",choices:rg,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 ng(e){let t=e?.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t?.length?t:void 0}function cp(e){return{responseFormat:e.format,criteria:e.criteria,selectedColumns:ng(e.columns)}}var ig={command:"data <workspaceId> <viewId>",describe:"Export the data of a view",builder:e=>sp(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=cp(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 tn(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 tn(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=>sp(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={...cp(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)}}},sg={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 tn(r,e.out);p(n??{written:e.out})}else p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},up={command:"export",describe:"Analytics export operations",builder:e=>e.command(ig).command(ag).command(sg).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 cg}from"node:fs/promises";function ug(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 pg={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??Do(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 cg(e.file,"utf8"),n=Lc({content:r,fileType:o,delimiter:e.delimiter}),{data:i}=await t.getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId}),a=Gc({...n,columns:i.columns??[],maxSamples:e.maxSamples}),s=Kc(a,{strict:e.strict});e.quiet||p(a,ug(a,s)),s||process.exit(1)}catch(t){d(t),process.exit(1)}}},pp={command:"diff",describe:"Analytics comparison operations",builder:e=>e.command(pg).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 on(e){return e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Table view ID"})}var lg={command:"add <workspaceId> <viewId>",describe:"Add a single row to a table",builder:e=>on(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)}}},dg={command:"update <workspaceId> <viewId>",describe:"Update the rows of a table matching a criteria expression",builder:e=>on(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)}}},hg={command:"delete <workspaceId> <viewId>",describe:"Delete the rows of a table matching a criteria expression",builder:e=>on(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)}}},lp={command:"rows",describe:"Analytics row operations",builder:e=>e.command(lg).command(dg).command(hg).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 dp={command:"analytics",describe:"Zoho Analytics operations",builder:e=>e.command(ep).command(tp).command(op).command(ap).command(up).command(lp).command(pp).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 hp={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 fg=Pi({cliName:"zoho-cli",loadOutputConfig:async()=>(await j())?.output,mergeOutputConfig:e=>ie({output:e}),clearOutputConfig:Mi}),gg=[vu,Nu,Bu,Qu,dp,hp],mp=[Du,fg,Mu];function Rg(e){return e.command.split(" ")[0]}var yp=new Set(mp.map(Rg)),Cg=Ei({cliName:"zoho-cli",skipCommands:yp,loadOutputConfig:async()=>(await j())?.output,saveCommandOutputConfig:async(e,t)=>{await ie({output:{commands:{[e]:t}}})}});async function Tg(){try{await mg(yg(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([_u(yp),Cg],!0).command(mp).command(gg).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 Tg();
package/cli/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@dereekb/zoho/cli",
3
- "version": "14.0.1",
3
+ "version": "14.1.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "zoho-cli": "index.js"
7
7
  },
8
8
  "peerDependencies": {
9
- "@dereekb/dbx-cli": "14.0.1",
10
- "@dereekb/nestjs": "14.0.1",
11
- "@dereekb/rxjs": "14.0.1",
12
- "@dereekb/util": "14.0.1",
13
- "@dereekb/zoho": "14.0.1",
14
- "@dereekb/zoho/nestjs": "14.0.1",
9
+ "@dereekb/dbx-cli": "14.1.0",
10
+ "@dereekb/nestjs": "14.1.0",
11
+ "@dereekb/rxjs": "14.1.0",
12
+ "@dereekb/util": "14.1.0",
13
+ "@dereekb/zoho": "14.1.0",
14
+ "@dereekb/zoho/nestjs": "14.1.0",
15
15
  "yargs": "^18.0.0"
16
16
  },
17
17
  "devDependencies": {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@dereekb/zoho/nestjs",
3
- "version": "14.0.1",
3
+ "version": "14.1.0",
4
4
  "type": "module",
5
5
  "peerDependencies": {
6
- "@dereekb/nestjs": "14.0.1",
7
- "@dereekb/rxjs": "14.0.1",
8
- "@dereekb/util": "14.0.1",
9
- "@dereekb/zoho": "14.0.1",
6
+ "@dereekb/nestjs": "14.1.0",
7
+ "@dereekb/rxjs": "14.1.0",
8
+ "@dereekb/util": "14.1.0",
9
+ "@dereekb/zoho": "14.1.0",
10
10
  "@nestjs/common": "^12.0.1",
11
11
  "@nestjs/config": "^12.0.0",
12
12
  "express": "^5.2.1"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dereekb/zoho",
3
- "version": "14.0.1",
3
+ "version": "14.1.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "zoho-cli": "cli/index.js"
@@ -22,13 +22,13 @@
22
22
  }
23
23
  },
24
24
  "peerDependencies": {
25
- "@dereekb/date": "14.0.1",
26
- "@dereekb/dbx-cli": "14.0.1",
27
- "@dereekb/firebase": "14.0.1",
28
- "@dereekb/model": "14.0.1",
29
- "@dereekb/nestjs": "14.0.1",
30
- "@dereekb/rxjs": "14.0.1",
31
- "@dereekb/util": "14.0.1",
25
+ "@dereekb/date": "14.1.0",
26
+ "@dereekb/dbx-cli": "14.1.0",
27
+ "@dereekb/firebase": "14.1.0",
28
+ "@dereekb/model": "14.1.0",
29
+ "@dereekb/nestjs": "14.1.0",
30
+ "@dereekb/rxjs": "14.1.0",
31
+ "@dereekb/util": "14.1.0",
32
32
  "@nestjs/common": "^12.0.1",
33
33
  "@nestjs/config": "^12.0.0",
34
34
  "express": "^5.2.1",