@dereekb/zoho 13.41.0 → 13.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/index.js +7 -7
- package/cli/package.json +7 -7
- package/nestjs/package.json +5 -5
- package/package.json +8 -8
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 up=Object.defineProperty;var pp=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?pp(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&&up(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as lp,mkdirSync as dp,writeFileSync as hp}from"node:fs";import{join as mp}from"node:path";var on=1;var Eo=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],rn=6e4,We={},nn=[...Eo],Oo,yp=!1,fp=rn;function Po(e){We=e}function Gt(){return We}function an(e){yp=e}function sn(e){fp=e===void 0?rn:e}function Do(e){nn=e}function cn(e){Oo=e}function ge(e){let t=e;for(let o of nn)t=t.replace(o,"[REDACTED]");return t}function un(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function gt(e,t){let{dumpDir:o,commandPath:r}=We,n;if(o){lp(o)||dp(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=un(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=mp(o,`${s}.${e}`)}else n=void 0;return n}function gp(e,t){let o=gt("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};hp(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=>tn(n,o)):e!=null&&typeof e=="object"?r=tn(e,o):r=e,r}function tn(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 pn(e){return We.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function p(e,t){gp(e,t);let r={ok:!0,data:We.pick?Me(e,We.pick):e,...t?{meta:t}:{}};console.log(pn(r))}function ln(e){console.log(pn(Mo(e)))}var ft=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function Mo(e){let t=Oo?Oo(e):void 0,o;return t?o=t:e instanceof ft?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 je(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 Rt(e){let t=!0;for(let o of e){t=!1;break}return t}function wo(e,t){for(let o of e)t(o)}function j(e,t,o=!1){e!=null&&(je(e,o)?wo(e,t):t(e))}function dn(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 Rp(e){return e==null?[]:Cp(e)}var x=Rp;function Cp(e){return Array.isArray(e)?e:[e]}import{symmetricDifference as fg}from"extra-set";function hn(e,t){j(t,o=>e.add(o))}function mn(e,t){j(t,o=>e.delete(o))}function yn(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function _o(e){return Object.keys(e).length===0}function fn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function gn(e){return{...e}}function Rn(e){return e!=null}function Kt(e){return je(e,!1)?!Rt(e):Cn(e)}function vo(e){let t;return je(e,!0)?t=!Rt(e):Cn(e)?t=typeof e=="object"?!_o(e):!0:t=!1,t}function Cn(e){return e!=null&&e!==""}function Tp(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,i)=>e(r,n,i)),o}}var ce=Tp(Rn);function Tn({base:e,build:t}){let o=e??{};return t(o),o}var xp=(e=>e);function xn(){return xp}function No(e,t){let o=new Set(e),r=Ap(t,n=>n);return r.length&&mn(o,r),Array.from(o)}function Ap(e,t){return ce(e==null?[]:Array.isArray(e)?e:Zp(e,t))}function Zp(e,t){let o=new Set(e.keys);return e.values&&hn(o,e.values.map(t)),Array.from(o)}function Be(e,t){let o=Sp(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Sp(e,t){return fn(Fp(e,t))}function Fp(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 An(e,t,o){return x(t).forEach(r=>e.set(r,o)),e}function Uo(e){return Array.from(e.entries())}function Zn(e){return Ip(Uo(e))}function Ip(e){let t=[];return e.forEach(([o,r])=>{j(r,n=>{t.push([o,n])})}),t}function Sn(){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,dn(i));return{map:()=>e,entries:()=>Uo(e),tuples:()=>Zn(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 bp(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function Fn(e){let t=bp(e);return t!=null&&t!=="class"}function In(e){return Fn(e)?e:()=>e}function bn(e,t){return Math.log(t)/Math.log(e)}var kn=",",kp=" ";function Op(e,t=kn,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 Lo(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 Ep(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return Op(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function On(e){let{joiner:t}=e,o=Ep(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 Lo(n,t,i)}}}var Go=On({joiner:kn}),Pp=On({joiner:kp,trimByDefault:!0});var P=Go.joinStrings,zg=Go.splitStrings,Jg=Go.splitStringsToSet,Hg=Pp.joinStrings;var En=yn;function Dn(e,{forEach:t,filter:o}){Dp(e,o).forEach((n,i)=>t(n,i))}function Dp(e,t){return Ko(t)(e)}function Ko(e){let t;if(e==null)t=Pn;else{let o=Mp(e);t=r=>Pn(r).filter((n,i)=>o(n,i))}return t}function Pn(e){return Object.entries(e)}function Vo(e){return typeof e=="object"?e:{valueFilter:e}}function Mp(e){let t=Vo(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])=>Kt(a);break;case 5:i=([,a])=>vo(a);break;case 6:i=([,a])=>!!a&&Kt(a);break;case 7:i=([,a])=>!!a&&vo(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 En(i,r)}function Ct(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function Mn(e){let t;return e==null||Gp(e)?t=e:t=wp(e),t}function wp(e){return e==null?e:new Date(e)}var wn=24,_p=60;var vp=60,Np=vp*_p,z=1e3,Re=z*60,zo=Re*60,Up=zo*wn,Qg=Np*wn,Lp=7,eR=Up*Lp;function Gp(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function _n(e){return e.getTime()<Date.now()}function vn(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function Kp(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:Mn(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=vn(s??(i===!1?null:f),a)),m}return{input:e,hasExpired:u,getExpirationDate:l}}function Nn(e,t){let o=!0;return e!=null&&(o=Kp(e).hasExpired(t,!0)),o}function Vp({filter:e,copy:t,dynamic:o=!1}){let r=e==null?Jp:$e({filter:e,copy:!1});return n=>{let i=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},a=o?i:Ct(i);return s=>{let c=a();return t&&(s=gn(s)),Object.assign(s,c),s}}}function Un(e,t){return zp(t)(e)}function zp(e){let t=Vp({filter:e,copy:!1,dynamic:!0});return o=>t(ce(o))({})}var uR=$e({copy:!0,filter:{valueFilter:1}}),pR=$e({copy:!0,filter:{valueFilter:2}}),Ln=$e({copy:!0,filter:{valueFilter:4}}),lR=$e({copy:!0,filter:{valueFilter:6}}),dR=Jo({valueFilter:1}),hR=Jo({valueFilter:6}),mR=Jo({valueFilter:2});function Jo(e){let t=Gn({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function $e({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Vo(t);o.invertFilter=!o.invertFilter;let r=Gn({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var Jp=$e({copy:!1});function Gn({forEach:e,filter:t}){let o=Ko(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function Kn(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 Vn(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 zn(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 Vt(e,t,o){let[r,n]=Ho(e,t,!1);return r+o+n}function Ho(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var Hp=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],xR=new Set(Hp);function Jn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=zt(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=Vt(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 qp(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of[...t].entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function zt(e,t,o){return qp(e)(t,o)}function Wp(e,t){return zt(e,t,1)[0]}function jp(e){return t=>{let r=Wp(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=Ho(t,r,!1),n}}function Hn(e,t){return jp(t)(e)}var Ye="/",Bp=".";function $p(e){let t=e.split(Bp,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ye?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function qn(e){return $p(e)!=="invalid"}var Yp=/^\/+/,Xp=/\/+$/;var Qp=/\/{2,}/g;function Wn(e){return e.startsWith(Ye)?e.replace(Yp,Ye):`${Ye}${e}`}function jn(e){return e.replaceAll(Qp,Ye)}function Bn(e){return e.replace(Xp,"")}function el(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var $n=/:(\d+)/;function tl(e){return $n.test(e)}function ol(e){let t=$n.exec(e);return t?Number(t[1]):void 0}function rl(e){let t=ei(e),o=nl(t),{domain:r,path:n}=o,i=el(r),a=tl(e),s=a?ol(e)??void 0:void 0,[c,u]=Hn(o.path,"?"),l=i&&(c===""||qn(c+"/")),h=al(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 Yn(e){let t=rl(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Xn(e,t=!1){let o=zt(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=Vt(n,i,"&")),n}function nl(e){let t=ei(e);return il(t)}function il(e){let t=Lo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Wn(r??"/")}}var Qn=/^https:\/\/|http:\/\//;function ei(e){return e.replace(Qn,"")}function al(e){return Qn.test(e)}function A(){}async function ti(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 oi(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function Tt(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function sl(e){let n=zo,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=bn(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 Tt(S)}return{waitForRateLimit:g,getNextWaitTime:C,getConfig:l,setConfig:m,getEnabled:h,setEnabled:f,reset:R}}function ri(e){let o=sl({exponentRate:1.5,maxWaitTime:z*8,...e}),r=Re,n=new Date,i=0,a=0,s=!0;g(e,!0);function c(){_n(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 Tt(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 cl="__CATCH_ALL_HANDLE_RESULT_KEY__";function ni(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):An(i,u,l)},c=(u,l,h)=>{let f=h.bind(u);s(l,f)};return Tn({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 ul(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function pl(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function ll(e,t,o){let r=pl(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function ii(e,t){return o=>ll(e,o,t)}function ai(e){return t=>(o,r)=>{let n=ul(o,t),i=e.configurerForAccessor(n);r(i)}}var dl=-1,si=0;function hl(e){return e?.page??dl}function ci(e){return hl(e)+1}import{BaseError as ui}from"make-error";var ne=class extends ui{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function pi(e){return(t,o)=>ml(e(t,o))}var Se=class extends ui{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function ml(e){return e.then(t=>{if(!t.ok)throw new Se(t);return t})}import{BaseError as BR}from"make-error";function li(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 hi(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>mi({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>fl({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var yl=(e,t)=>t(e);function fl(e){let{makeFetch:t=fetch,fetchHandler:o=yl,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=li(a)),n&&(a=pi(a));let s=mi(e);return async(c,u)=>{let l=await s(c,u),h=o(l,a);return i&&(h=i(h)),h}}var gl=(e,t)=>new Request(e,t??void 0);function mi(e){let{makeRequest:t=gl,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(Bn(o)):void 0,u=c?m=>{let R,y=m.toString();if(!s&&Yn(y))R=new URL(y);else{let C=c.origin+jn("/"+c.pathname+"/"+m);R=new URL(C,c)}return R}:void 0;async function l(m){let R=oi(m)?await m:m;return di(R)?R:t(R)}let h=u?async m=>{let R,y,C;if(typeof m=="string"?R=m:di(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=In(r);async function R(){let C=await m();return n?{...C,timeout:n}:C}async function y(C,g){let S=await R(),O=Rl(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 Rl(e,t){let o;if(t){let r=Cl([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Cl(e){let t=Sn();return ce(e).forEach(o=>{let r=Tl(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 Tl(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 di(e){return!!e.url}import{safeParse as xl}from"fast-content-type-parse";function yi(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=xl(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function fi(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 qo=class extends ne{constructor(o){super("There was no next page for this.");this.page=o}},Wo=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}},Al=100;function Xe(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??Al;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:si,v=_>=h,W={input:R,result:C,page:_,previous:y,hasNext:I,isAtMaxPage:v,cursor:q,nextPageCursor:S,fetchNext:Ct(async()=>{if(v)throw new Wo(W,h);let en=I?await r(W,R,{maxPage:h,maxItemsPerPage:l}):void 0;if(!en)throw new qo(W);return f({...R,...en},W)()})};return W}}return{input:a,fetchNext:Ct(()=>f(a)())}}}function Zl(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)?Un(e):e,a=r??!0?Ln(i??{}):i,s=n?Zl(a):a,c=new URLSearchParams(s);return o!=null&&j(o,u=>c.delete(u),!1),c}function jo(e){let t;if(typeof e=="string")t=e;else if(Sl(e))t=e.href;else{let o=jo(e.url);if(e.queryParams){let r=bl(e.queryParams);Rt(r)?t=o:t=Xn(o+`?${r.toString()}`)}else t=o}return t}function Sl(e){return typeof e=="object"&&e instanceof URL}function Fl(e){return typeof e=="object"&&e instanceof URLSearchParams}function Il(e){let t=[];return wo(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 bl(e){let t;return Fl(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):je(e)?t=new URLSearchParams(Il(e)):t=kl(e),t}function kl(e){let t=[];return Dn(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&j(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var Bo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Ol(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var El=e=>{throw new Bo(e)},$=e=>null;function Y(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??El};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=gi(o);return(a,s,c)=>{let u=jo(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 gi(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=xn()}=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:Ol(i.body)}}}var fC=gi();var X=hi({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});import{createParamDecorator as Pl}from"@nestjs/common";var zC=Pl((e,t)=>Dl(t));function Dl(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as $o,BadRequestException as Ml,InternalServerErrorException as wl,Logger as _l}from"@nestjs/common";import vl from"raw-body";import{parse as Nl}from"node:querystring";var Ri=new _l("RawBody"),jC=$o(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Ri.error("RawBody request was not readable. This is generally due to bad configuration."),new Ml("Invalid body");return vl(o)}),Ci=$o(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Ri.error("RawBody expected a buffer set to req.body."),new wl("failed parsing body");return r}),BC=$o(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Ul(o.body),o.body});function Ul(e){let t=Ll(e);return Nl(t)}function Ll(e){return e.toString("utf8").trim()}import{Injectable as Gl}from"@nestjs/common";import Kl from"body-parser";var Qe=class{use(t,o,r){Kl.json()(t,o,r)}};Qe=F([Gl()],Qe);import{Injectable as Vl}from"@nestjs/common";import zl from"body-parser";var et=class{use(t,o,r){zl.raw({type:"*/*"})(t,o,r)}};et=F([Vl()],et);import{Logger as Jl,Module as Hl,RequestMethod as ql}from"@nestjs/common";var Wl="/webhook",jl={path:`${Wl}/{*path}`,method:ql.POST},Yo=class{configure(t){Bl(t)}},Ht=class extends Yo{logger=new Jl("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Ht=F([Hl({})],Ht);function Bl(e){e.apply(et).forRoutes(jl).apply(Qe).forRoutes("{*path}")}var Ti="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 $l,Injectable as Yl}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([Yl(),b(0,$l(we))],_e);import{Module as Xl}from"@nestjs/common";import{ConfigModule as Ql,ConfigService as ed}from"@nestjs/config";function td(e){let t={client:{clientWebAppUrl:e.get(Ti)}};return we.assertValidConfig(t),t}var qt=class{};qt=F([Xl({imports:[Ql],providers:[{provide:we,inject:[ed],useFactory:td},_e],exports:[_e]})],qt);var xi="SERVER_ENV_TOKEN";import{Inject as od,Injectable as rd}from"@nestjs/common";function Ai(){return process.env.NODE_ENV==="test"}var Wt=class{constructor(t){this.env=t}get isTestingEnv(){return Ai()}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}};Wt=F([rd(),b(0,od(xi))],Wt);import{dirname as ud}from"node:path";import{chmod as nd,mkdirSync as id,readFile as ad,writeFile as sd}from"node:fs";import{rm as cd}from"node:fs/promises";function Fe(e){return new Promise((t,o)=>{ad(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 jt(e){return id(e.dirPath,{recursive:!0}),new Promise((t,o)=>{sd(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():nd(e.filePath,e.mode,n=>{n?o(n):t()})})})}function xt(e){return cd(e,{force:!0})}var pd=384;function Zi(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??pd;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 jt({filePath:t,dirPath:ud(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 xt(t)})}}var dx=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 Si(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 Bt(e,t=on){return async o=>{try{await e(o)}catch(r){ln(r),process.exit(t)}}}var ld=["raw","page_by_line","data_by_line"],dd=["replace","concat"],hd=["meta","pages","merged_page"];function $t(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:hd,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:ld,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:dd,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function At(e){return Fe(e.configFilePath)}function md(e){return jt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function Zt(e){let t=await At({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:Xo(t.output,e.updates.output)};return await md({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Xo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:yd(e?.commands,t)}}function yd(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 Fi(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 fd}from"node:os";import{join as Yt}from"node:path";function Xt(e){let t=e.configDirOverride??Yt(fd(),`.${e.cliName}`);return{configDir:t,configFilePath:Yt(t,"config.json"),tokenCachePath:Yt(t,".tokens.json"),firestoreSessionCachePath:Yt(t,".firestore-sessions.json")}}function Ii(e){let t=Xt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await At({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await Zt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{an(!!n.verbose),sn(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?Fi({outputConfig:h,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};Po({dumpDir:f.dumpDir,pick:n.pickAll?void 0:f.pick,commandPath:i,pretty:!!n.pretty})}}function gd(e){let t=Xt({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await At({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>Zt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>Zt({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 bi(e){let t=gd(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:Bt(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:Bt(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:Bt(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new ft({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 Rd,appendFileSync as Cd}from"node:fs";function ki(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=Gt(),n=t==="raw"?"json":"ndjson",i=gt(n),a=r?gt(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?Cd:Rd;C(i,y.mainContent),a&&y.pickContent!==void 0&&C(a,y.pickContent)},h=(y,C)=>{let g=JSON.stringify(y,null,2),S=a?JSON.stringify(u(y),null,2):void 0;l({mainContent:g,pickContent:S,append:C})},f=(y,C)=>{let g=JSON.stringify(y)+`
|
|
5
|
-
`,S=
|
|
6
|
-
`:void 0;l({mainContent:g,pickContent:S,append:C})},m=(y,C)=>{let g=y.data??[],S=
|
|
7
|
-
`,v=
|
|
8
|
-
`:void 0;l({mainContent:_,pickContent:v,append:I})})};s={mainPath: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 Td(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 xd(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=Gt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let l=ki({dumpOutput:i,dumpMerge:a}),h;try{h=await Td({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),xd({multiplePagesOutput:n,summaryMeta:f,state:h,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import Qf from"yargs";import{hideBin as eg}from"yargs/helpers";import{writeFile as Ad,mkdirSync as Zd}from"node:fs";import{join as Qo}from"node:path";import{homedir as Sd}from"node:os";var Qt=["recruit","crm","desk","sign","analytics"],Fd=new Set(["sign","analytics"]),eo=new Set(["desk","analytics"]);function er(){return Qo(Sd(),".zoho-cli")}function St(){return Qo(er(),"config.json")}function Ft(){return Qo(er(),".tokens.json")}function ve(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function B(){let e=St(),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=eo.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 Ne(e,t){let o=e[t],r=e.shared,n=!Fd.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 Id(e){let t=St();return Zd(er(),{recursive:!0}),new Promise((o,r)=>{Ad(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function ie(e){let t=await B(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit===void 0?t?.recruit:{...t?.recruit,...e.recruit},crm:e.crm===void 0?t?.crm:{...t?.crm,...e.crm},desk:e.desk===void 0?t?.desk:{...t?.desk,...e.desk},sign:e.sign===void 0?t?.sign:{...t?.sign,...e.sign},analytics:e.analytics===void 0?t?.analytics:{...t?.analytics,...e.analytics},output:e.output===void 0?t?.output:Xo(t?.output,e.output)};return await Id(o),o}async function Oi(){await ie({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Ei(){let e=St(),t=Ft();await xt(e),await xt(t)}function ue(e){return Qt.filter(t=>{let o=Ne(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as lu,Injectable as pm}from"@nestjs/common";function tt(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function J(e,t){return Xe({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:ci(o),per_page:n.maxItemsPerPage??r.per_page}}})}function to(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 ot="Candidates",Pi="Job_Openings",oo="Notes",Di="Emails",It="Attachments";function ro(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=no(o);break}default:break}return t}function no(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(tr):a&&(s=no(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 Mi=Jn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function tr(e){let t=Mi(e.value);return`(${e.field}:${e.filter}:${t})`}var wi=ro;import{BaseError as Ld}from"make-error";import{BaseError as kd}from"make-error";var Od="__internal_data_array_blank_error";function Ed(e){return Array.isArray(e?.data)}var it="success";function ae(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var be=class extends kd{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},L=class extends be{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},rt=class extends L{constructor(t,o){super({code:Od,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 rt&&!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 Pd="INTERNAL_ERROR",Dd="INVALID_TOKEN",G=class extends L{},_i="FAILURE",or=class extends L{},Md="4834",nt=class extends L{},wd="INVALID_QUERY",rr=class extends L{get details(){return this.error.details}},io="MANDATORY_NOT_FOUND",ke="DUPLICATE_DATA",ao="INVALID_DATA",_d="TOO_MANY_REQUESTS",nr=429,vd="X-RATELIMIT-LIMIT",Nd="X-RATELIMIT-REMAINING",Ud="X-RATELIMIT-RESET",vi=100,Ni=Re;function ir(e){let t=e.get(vd),o=e.get(Nd),r=e.get(Ud),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 ir(this.responseError.response.headers)}};function te(e,t){let o;if(Ed(e))o=new rt(e,t);else{let r=Te(e,t);if(r){let n=ae(r);switch(n.code){case Pd:o=new or(n,e,t);break;case Dd:o=new G(n,e,t);break;case Md:o=new nt(n,e,t);break;case wd:o=new rr(n,e,t);break;case _d: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 Ui="ALREADY_ASSOCIATED",ar=class extends Ld{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},at=class extends be{},sr=class extends at{},cr=class extends at{},so=class extends at{get invalidFieldDetails(){return this.error.details}},ur=class extends so{};function Li(e){let t;switch(e.code){case ao:{let o=new so(e);o.invalidFieldDetails.id?t=new ur(e):t=o;break}case io:t=new sr(e);break;case ke:t=new cr(e);break;default:t=new at(e);break}return t}function Gi(e,t){return o=>{if(!o?.data?.length)throw new ar(e,t);return o}}var Gd=Q("ZohoRecruit");async function Kd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ki(t,e)),o}function Ki(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Vi=pe(Ki),zi=ee(Kd,Gd);import{BaseError as Vd}from"make-error";function lr(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 Li(l[0].result);c=u[0].result.details}return c}))}function Ji(e){return lr(e,"","POST")}function Hi(e){return lr(e,"/upsert","POST")}function qi(e){return lr(e,"","PUT")}function Wi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,K("DELETE")).then(zd)}function ji(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,K("GET")).then(Gi(t.module)).then(o=>o.data[0])}function Bi(e){return(t=>e.fetchJson(`/v2/${t.module}?${ra(t).toString()}`,K("GET")))}function dr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=wi(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return ra(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,K("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function $i(e){return J(dr(e))}function st(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${yr(n,n.filter).toString()}`,K("GET")).then(i=>i??(r===!1?i:tt()))}}function hr(e){return st(e)({targetModule:Di})}function Yi(e){return J(hr(e))}function mr(e){return st(e)({targetModule:It})}function Xi(e){return J(mr(e))}var OA=20*1024*1024;function Qi(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}/${It}?${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 ea(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${It}/${t.attachment_id}`,{method:"GET"}).then(Jt)}function ta(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${It}/${t.attachment_id}`,{method:"DELETE"})}var pr=class extends Vd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function oa(e){return t=>{let r=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?to(t.apiUrl):""}${a}`;return e.fetchJson(c,K("POST")).then(u=>{if(u.code!=="success")throw new pr(u);return u.details})}}function ra(...e){return T(e,{omitKeys:"module"})}function yr(...e){return T(e,{omitKeys:["id","module"]})}function K(e,t){return{method:e,body:t??void 0}}function zd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===it?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===it?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function na(e){return t=>e.fetchJson(`/v2/${ot}/actions/associate`,K("PUT",{data:x(t)})).then(o=>{let r=o.data.map(()=>t),n=le(r,o.data),{included:i,excluded:a}=Be(n.errorItems,s=>s.result.code===_i&&s.result.details.error[0].code===Ui);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function ia(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${yr(t).toString()}`,K("GET")).then(o=>o??tt())}function fr(e){let t=ia(e);return o=>t({...o,module:ot})}function aa(e){return J(fr(e))}function gr(e,t=Pi){let o=ia(e);return r=>o({...r,module:t})}function sa(e){return J(gr(e))}function Rr(e){return t=>e.fetchJson(`/v2/${oo}`,K("POST",{data:t.data})).then(o=>le(x(t.data),o.data))}function ca(e){return t=>e.fetchJson(`/v2/${oo}?${T({ids:t.ids})}`,K("DELETE")).then(o=>le(x(t.ids),o.data))}function Cr(e){return st(e)({targetModule:oo})}function ua(e){return J(Cr(e))}function pa(e){let t=Rr(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 ha(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}=Be(r.errorItems,a=>a.result.code===ke);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ma(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 la=100;function ya(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>la)throw new Error(`Cannot add tags to more than ${la} records at once.`);return e.fetchJson(`/v2/${ot}/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 da=100;function fa(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>da)throw new Error(`Cannot remove tags from more than ${da} records at once.`);return e.fetchJson(`/v2/${ot}/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 Jd="invalid_code",Hd="invalid_client",Tr=class extends ne{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},ct=class extends ne{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},qd=Q("ZohoAccounts");async function Wd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ga(t,e)),o}function ga(e,t){let o,r=e.error;if(r){let n=ae(r);switch(n.code){case Jd:case Hd:o=new Tr(n.code);break;default:o=te(e,t);break}}return o}var Ra=pe(ga),Ca=ee(Wd,qd);function de(e){return async()=>{let t=await e();if(!t.accessToken)throw new ct;return t.accessToken}}var jd=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 bt(e){let{readRateLimitDetails:t,enabledWithoutRateLimitDetails:o=!1}=e,r=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??jd,n=e.maxRateLimit??vi,i=e.resetPeriod??Ni;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=ri(s);return fi({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===nr){f=!0;try{r?.(h,u,l)}catch{}}}else if(o&&u.status===nr){f=!0;try{r?.({remaining:0},u,l)}catch{}}return c.setEnabled(m),f}})}function xe(e){return bt({...e,readRateLimitDetails:xr})}function xr(e){let t=ir(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Ta(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=to(a.apiUrl),c=i({apiUrl:s}),u=zi(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Vi,handleFetchJsonParseErrorFunction:$});return{recruitContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function co(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 uo="Notes",xa="Emails",kt="Attachments";var Aa=ro;import{BaseError as Bd}from"make-error";var Ar=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}},ut=class extends be{},Zr=class extends ut{},Sr=class extends ut{},po=class extends ut{get invalidFieldDetails(){return this.error.details}},Fr=class extends po{};function Za(e){let t;switch(e.code){case ao:{let o=new po(e);o.invalidFieldDetails.api_name==="id"?t=new Fr(e):t=o;break}case io:t=new Zr(e);break;case ke:t=new Sr(e);break;default:t=new ut(e);break}return t}function Sa(e,t){return o=>{if(!o?.data?.length)throw new Ar(e,t);return o}}var $d=Q("ZohoCrm",{logDataArrayErrors:!1});async function Yd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Fa(t,e)),o}function Fa(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Ia=pe(Fa),ba=ee(Yd,$d);import{BaseError as Xd}from"make-error";function br(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,H(o,{data:x(r)})).catch(Va).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 Za(l[0].result);c=u[0].result.details}return c}))}function ka(e){return br(e,"","POST")}function Oa(e){return br(e,"/upsert","POST")}function Ea(e){return br(e,"","PUT")}function Pa(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,H("DELETE")).catch(Va).then(eh)}function Da(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,H("GET")).then(Sa(t.module)).then(o=>o.data[0])}function Ma(e){return(t=>e.fetchJson(`/v8/${t.module}?${Ka(t).toString()}`,H("GET")))}function kr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Aa(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 Ka(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,H("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function wa(e){return J(kr(e))}function pt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${Qd(n,n.filter).toString()}`,H("GET")).then(i=>i??(r===!1?i:tt()))}}function Or(e){let t=pt(e)({targetModule:xa});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function _a(e){return J(Or(e))}function Er(e){return pt(e)({targetModule:kt})}function va(e){return J(Er(e))}var VZ=20*1024*1024;function Na(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}/${kt}?${T(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function Ua(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${kt}/${t.attachment_id}`,{method:"GET"}).then(Jt)}function La(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${kt}/${t.attachment_id}`,{method:"DELETE"})}var Ir=class extends Xd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Ga(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?co(t.apiUrl):""}${a}`;return e.fetchJson(c,H("POST")).then(u=>{if(u.code!=="success")throw new Ir(u);return u.details})}}function Ka(...e){return T(e,{omitKeys:"module"})}function Qd(...e){return T(e,{omitKeys:["id","module"]})}function H(e,t){return{method:e,body:t??void 0}}function Va(e){let t;if(e instanceof rt)t={data:e.errorDataArray};else throw e;return t}function eh(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===it?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===it?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Pr(e){return t=>e.fetchJson(`/v2/${uo}`,H("POST",{data:t.data})).then(o=>Oe(x(t.data),o.data))}function za(e){return t=>e.fetchJson(`/v2/${uo}?${T({ids:t.ids})}`,H("DELETE")).then(o=>Oe(x(t.ids),o.data))}function Dr(e){return pt(e)({targetModule:uo})}function Ja(e){return J(Dr(e))}function Ha(e){let t=Pr(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 Wa(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}=Be(r.errorItems,a=>a.result.code===ke);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ja(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,H("DELETE")).then(o=>o.tags)}function Ba(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 qa=100;function $a(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,H("POST",Ya(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function Ya(e){if(Array.isArray(e.ids)&&e.ids.length>qa)throw new Error(`Cannot add/remove tags from more than ${qa} 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 Xa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,H("POST",Ya(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function Qa(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=co(a.apiUrl),c=i({apiUrl:s}),u=ba(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Ia,handleFetchJsonParseErrorFunction:$});return{crmContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var es="https://signsandbox.zoho.com/api/v1",th="https://sign.zoho.com/api/v1";function Mr(e){let t;switch(e){case"sandbox":t=es;break;case"production":t=th;break;default:t=e;break}return t}function ts(e){let t=Mr(e),o;try{o=new URL(t).hostname!==new URL(es).hostname}catch{o=!0}return o}function os(e,t){return Xe({...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 rs(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,he("GET"))}function wr(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 ns(e){let t=wr(e);return os(t)}function is(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,he("GET"))}function as(e){return()=>e.fetchJson("/fieldtypes",he("GET"))}function ss(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 cs(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function us(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 ps(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 ls(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,he("GET"))}function ds(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 hs(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,he("PUT",{requests:o}))}function ms(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,he("POST",r))}}function ys(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,he("PUT",{expire_by:o}))}function fs(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 gs(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ts(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 oh=Q("ZohoSign",{logDataArrayErrors:!1});async function rh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Rs(t,e)),o}function Rs(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Cs=pe(Rs),Ts=ee(rh,oh);function xs(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=Mr(a.apiUrl),c=i({apiUrl:s}),u=Ts(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Cs,handleFetchJsonParseErrorFunction:$});return{signContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function As(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var nh=Q("ZohoDesk",{logDataArrayErrors:!1});async function ih(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Zs(t,e)),o}function Zs(e,t){let o,r=Te(e,t);if(r)switch(ae(r).code){default:o=te(e,t);break}return o}var Ss=pe(Zs),Fs=ee(ih,nh);var ah="X-Rate-Limit-Remaining-v3",sh="Retry-After",ch=200;function uh(e){let t=e.get(ah),o;if(t!=null){let r=Number(t),n,i=e.get(sh);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 Is(e){return bt({maxRateLimit:ch,...e,readRateLimitDetails:uh})}function bs(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Is(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=As(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Fs(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Ss,handleFetchJsonParseErrorFunction:$});return{deskContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var ks=25;function se(e,t){return Xe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=ks}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??ks,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ue(e,t){return{method:e,body:t??void 0}}function lt(e,t){return T(e,{omitKeys:t})}function lo(e){let t;return e&&(t=P(x(e))),t}function _r(e){return t=>{let{include:o,...r}=t,n=lt([{...r,include:lo(o)}]);return e.fetchJson(`/tickets?${n}`,Ue("GET")).then(i=>i??{data:[]})}}function Os(e){return t=>{let{ticketId:o,include:r}=t,i=lt([{include:lo(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ue("GET"))}}function vr(e){return t=>{let o=lt([t]);return e.fetchJson(`/tickets/search?${o}`,Ue("GET")).then(r=>r??{data:[]})}}function Es(e){return t=>{let{contactId:o,include:r,...n}=t,i=lt([{...n,include:lo(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ue("GET")).then(a=>a??{data:[]})}}function Ps(e){return t=>{let{productId:o,include:r,...n}=t,i=lt([{...n,include:lo(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ue("GET")).then(a=>a??{data:[]})}}function Ds(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ue("GET"))}function Ms(e){return t=>{let o=lt([{agentIds:P(x(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ue("GET"))}}function ws(e){return se(_r(e))}function _s(e){return se(vr(e))}function vs(e){return{method:e}}function Ns(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,vs("GET")).then(r=>r??{data:[]})}}function Us(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,vs("GET"))}function Nr(e){return{method:e}}function Ls(e){let t;return e&&(t=P(x(e))),t}function Ur(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Ls(o)}]);return e.fetchJson(`/contacts?${n}`,Nr("GET")).then(i=>i??{data:[]})}}function Gs(e){return t=>{let{contactId:o,include:r}=t,i=T([{include:Ls(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,Nr("GET"))}}function Ks(e){return t=>{let o=T([{contactIds:P(x(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Nr("GET")).then(r=>r??[])}}function Vs(e){return se(Ur(e))}function Ot(e,t){return{method:e,body:t??void 0}}function zs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Ot("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`,Ot("POST",o)).then(r=>r??[])}}function Hs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Ot("DELETE"))}function qs(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,Ot("GET")).then(r=>r??{data:[]})}}function Ws(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,Ot("GET")).then(r=>r??{data:[]})}}function Lr(e,t){return{method:e,body:t??void 0}}function js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Lr("GET")).then(o=>o??[])}function Bs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Lr("POST",o))}}function $s(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Lr("DELETE",o))}}function Ys(e,t){return{method:e,body:t??void 0}}function ph(e){let t;return e&&(t=P(x(e))),t}function Xs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:ph(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,Ys("GET")).then(a=>a??{data:[]})}}function Qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,Ys("DELETE"))}function ho(e,t){return{method:e,body:t??void 0}}function ec(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:ec(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,ho("GET")).then(a=>a??{data:[]})}}function oc(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:ec(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,ho("GET"))}}function rc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,ho("POST",r))}}function nc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,ho("DELETE"))}function Et(e,t){return{method:e,body:t??void 0}}function ic(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Et("GET"))}function ac(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Et("POST",r))}}function sc(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Et("GET")).then(i=>i??{data:[]})}}function cc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Et("GET"))}function uc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Et("GET"))}function pc(e){return{method:e}}function lc(e){let t;return e&&(t=P(x(e))),t}function Gr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:lc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,pc("GET")).then(a=>a??{data:[]})}}function dc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:lc(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,pc("GET"))}}function hc(e){return se(Gr(e))}function lh(e){return{method:e}}function dh(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:dh(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,lh("GET")).then(a=>a??{data:[]})}}function mc(e){return se(Kr(e))}function mo(e){return{method:e}}function yc(e){let t;return e&&(t=P(x(e))),t}function Vr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:yc(o)}]);return e.fetchJson(`/agents?${n}`,mo("GET")).then(i=>i??{data:[]})}}function fc(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:yc(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,mo("GET"))}}function gc(e){return t=>{let o=T([{agentIds:P(x(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,mo("GET")).then(r=>r?.data??[])}}function Rc(e){return()=>e.fetchJson("/myinfo",mo("GET"))}function Cc(e){return se(Vr(e))}var hh="https://accounts.zoho.com",mh="https://accounts.zoho.eu",yh="https://accounts.zoho.in",fh="https://accounts.zoho.com.au",gh="https://accounts.zoho.jp",Rh="https://accounts.zoho.uk",Ch="https://accounts.zohocloud.ca",Th="https://accounts.zoho.sa",xh={us:hh,eu:mh,in:yh,au:fh,jp:gh,uk:Rh,ca:Ch,sa:Th};function Le(e){return xh[e]??e}var yo="/oauth/v2/token";function fo(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(`${yo}?${l}`,zr("POST"))}}function Tc(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(`${yo}?${c}`,zr("POST"))}}function xc(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(`${yo}?${u}`,zr("POST"))}}var Ah="/oauth/user/info";function Ac(e){return t=>e.fetchJson(Ah,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function zr(e,t){return{method:e,body:t}}function Zc(e){return t=>X.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function Sc(e,t){let o=Ca(e,t),r=Y(o,{interceptJsonResponse:Ra,handleFetchJsonParseErrorFunction:$});return{fetch:o,fetchJson:r}}function Fc(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Zc(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=Le(n.apiUrl??"us"),a=r({apiUrl:i}),{fetch:s,fetchJson:c}=Sc(a,o),u=async()=>{let m=Date.now(),{access_token:R,api_domain:y,scope:C,expires_in:g}=await fo(h)();return{accessToken:R,apiDomain:y,expiresIn:g,expiresAt:new Date(m+g*z),scope:C}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let l=Zh({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),h={fetch:s,fetchJson:c,loadAccessToken:l,config:{...n,apiUrl:i}};return{accountsContext:h}}}function Ic(e){let t=e.fetchHandler??xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Zc(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=Le(n.apiUrl??"us"),a=r({apiUrl:i}),{fetchJson:s}=Sc(a,o),c={...n,apiUrl:i};return{oauthClientContext:{fetchJson:s,config:c}}}}function Zh(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 ct("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}var bc="ZANALYTICS-ORGID";function kc(e){let t;switch(e){case"sandbox":case"production":t="https://analyticsapi.zoho.com/restapi/v2";break;default:t=e;break}return t}var Sh="CONFIG",Fh="application/x-www-form-urlencoded";function Oc(e){return e==null?"":T({[Sh]:JSON.stringify(e)}).toString()}function Ee(e){let t=Oc(e);return t?`?${t}`:""}function V(e,t){return{method:e,body:t??void 0}}function go(e,t){return{method:e,headers:{"Content-Type":Fh},body:Oc(t)}}var Ih="failure",bh="8535",kh="8083",Oh="6045",Eh=["6043","6044"],Jr=class extends L{};function Ec(e){return e?.status===Ih}function Ph(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 Pc(e,t){let o;if(Ec(e)){let r=Ph(e),n={error:r};switch(r.code){case bh:o=new G(r,n,t);break;case kh:o=new Jr(r,n,t);break;case Oh:o=new Ce(r,n,t);break;default:o=Eh.includes(r.code)?new Ce(r,n,t):new L(r,n,t);break}}else o=te(e,t);return o}var Dh=Q("ZohoAnalytics",{logDataArrayErrors:!1});async function Mh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Pc(t,e)),o}var Dc=(e,t)=>{if(Ec(e)){let o=Pc(e,new Se(t));if(o)throw o}return e},Mc=ee(Mh,Dh);var wh=100;var _h=Re;function wc(e){return bt({maxRateLimit:wh,resetPeriod:_h,...e,readRateLimitDetails:xr,enabledWithoutRateLimitDetails:!0})}var vh="1001",Nh="1002";var Uh="1004";var Lh=z*2,Gh=150;function Kh(e){return e===vh||e===Nh}function Pe(e){return e===Uh}function Ro(e){let{loadJob:t,readJobCode:o,pollWait:r=Lh,maxPolls:n=Gh}=e;return ti({next:async i=>(i>0&&await Tt(r),t()),checkContinue:(i,a)=>i!=null&&Kh(o(i))&&a<n})}var Vh=65279;function zh(e,t){let o=e.codePointAt(0)===Vh?e.slice(1):e,r=[],n=[],i="",a=!1,s=!1,c=0;for(;c<o.length;){let u=o[c];a?u==='"'?o[c+1]==='"'?(i+='"',c+=2):(a=!1,c+=1):(i+=u,c+=1):u==='"'&&i===""?(a=!0,s=!0,c+=1):u===t?(n.push(i),i="",s=!0,c+=1):u===`
|
|
9
|
-
`||u==="\r"?(n.push(
|
|
10
|
-
`?2:1):(i+=u,s=!0,c+=1)}return(s||i!==""||n.length>0)&&(n.push(i),r.push(n)),r}function Jh(e,t){let o=zh(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:No(a.filter(c=>c!=="")),rows:s}}return i}function Hh(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:No(n.flatMap(i=>Object.keys(i))),rows:n}}function _c(e){let{content:t,fileType:o,delimiter:r}=e;return o==="json"?Hh(t):Jh(t,r)}var qh=3,Wh=/[\s,%$£€¥]/g,jh=new Set(["true","false","yes","no","y","n","t","f","1","0"]),Bh=/^[\d\s/.:+-]+$/,$h=new Set(["PLAIN","MULTI_LINE","EMAIL","URL"]);function Hr(e){return e==null?"":String(e).trim()}var Yh=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Xh=/^www\./i;function dt(e){let{text:t,allowNegative:o,allowFraction:r}=e,n=Number(t.replaceAll(Wh,"")),i;return Number.isFinite(n)?!o&&n<0?i="negative":!r&&!Number.isInteger(n)&&(i="notAnInteger"):i="notANumber",i}var Qh={NUMBER:e=>dt({text:e,allowNegative:!0,allowFraction:!1}),AUTO_NUMBER:e=>dt({text:e,allowNegative:!0,allowFraction:!1}),POSITIVE_NUMBER:e=>dt({text:e,allowNegative:!1,allowFraction:!1}),DECIMAL_NUMBER:e=>dt({text:e,allowNegative:!0,allowFraction:!0}),CURRENCY:e=>dt({text:e,allowNegative:!0,allowFraction:!0}),PERCENT:e=>dt({text:e,allowNegative:!0,allowFraction:!0}),DATE:e=>Number.isNaN(Date.parse(e))&&!Bh.test(e)?"notADate":void 0,BOOLEAN:e=>jh.has(e.toLowerCase())?void 0:"notABoolean",EMAIL:e=>Yh.test(e)?void 0:"notAnEmail",URL:e=>URL.canParse(e)||Xh.test(e)?void 0:"notAUrl"};function em(e,t,o){let r=o==null||$h.has(o);return t.columnMaxSize!=null&&e.length>t.columnMaxSize&&r}function tm(e,t){let o=Hr(e),r=t.dataType?.toUpperCase(),n;return o===""?n=t.isNullable===!1&&t.defaultValue==null?"emptyInNonNullable":void 0:em(o,t,r)?n="tooLong":n=r==null?void 0:Qh[r]?.(o),n}function om(e,t){return`${e}\0${t}`}function vc(e){let{columns:t,columnNames:o,rows:r,maxSamples:n}=e,i=n??qh,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)=>Hr(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=tm(g[O],q);if(I!=null){let _=om(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:Hr(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 Nc(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 Uc(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=wc(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?{[bc]: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=kc(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Mc(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Dc,handleFetchJsonParseErrorFunction:$});return{analyticsContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Lc(e){return()=>e.fetchJson("/orgs",V("GET"))}function Gc(e){return()=>e.fetchJson("/workspaces",V("GET"))}function Kc(e){return()=>e.fetchJson("/workspaces/owned",V("GET"))}function Vc(e){return()=>e.fetchJson("/workspaces/shared",V("GET"))}function zc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("GET"))}function Jc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views`,V("GET"))}function Hc(e){return t=>e.fetchJson(`/views/${t.viewId}`,V("GET"))}function qc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/metadata`,V("GET"))}var rm="import";function nm(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],`${rm}.${s}`,{type:s==="json"?"application/json":"text/csv"}))}else i.append("DATA",a)}}return i}function qr(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 Co(e){return e??!0}function Wc(e,t){let o=qr(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 To(e){let{context:t,url:o,config:r,dataInput:n,formDataOptions:i}=e,a=nm(n,i);return(await t.fetch(`${o}${Ee(r)}`,{method:"POST",headers:{"Content-Type":""},body:a})).json()}function jc(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a={...n,autoIdentify:Co(n.autoIdentify),fileType:qr(i,n.fileType)};return To({context:e,url:`/workspaces/${o}/views/${r}/data`,config:a,dataInput:i})}}function Bc(e){return t=>{let{workspaceId:o,config:r,...n}=t,i={...r,autoIdentify:Co(r.autoIdentify),fileType:qr(n,r.fileType)};return To({context:e,url:`/workspaces/${o}/data`,config:i,dataInput:n})}}function Wr(e){return t=>{let{workspaceId:o,viewId:r,config:n,...i}=t,a=Wc(i,n.fileType),s={...n,autoIdentify:Co(n.autoIdentify),fileType:a};return To({context:e,url:`/bulk/workspaces/${o}/views/${r}/data`,config:s,dataInput:i,formDataOptions:{asFile:!0,fileType:a}})}}function $c(e){return t=>{let{workspaceId:o,config:r,...n}=t,i=Wc(n,r.fileType),a={...r,autoIdentify:Co(r.autoIdentify),fileType:i};return To({context:e,url:`/bulk/workspaces/${o}/data`,config:a,dataInput:n,formDataOptions:{asFile:!0,fileType:i}})}}function jr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/importjobs/${t.jobId}`,{method:"GET"})}function Yc(e){let t=Wr(e),o=jr(e);return async r=>{let{poll:n,...i}=r,{data:a}=await t(i);return Ro({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function Xc(e){return t=>e.fetch(`/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,{method:"GET"})}function Br(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,V("GET"))}function Qc(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/data${Ee(t.config)}`,V("GET"))}function $r(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}`,V("GET"))}function eu(e){return t=>e.fetch(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}/data`,{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 Ro({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:a.jobId}),readJobCode:s=>s.data.jobCode})}}function ou(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,go("POST",t.config))}function ru(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`,go("PUT",t.config))}}function nu(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`,go("DELETE",t.config))}}function iu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}${Ee(t.config)}`,V("DELETE"))}function au(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 im}from"@nestjs/common";var ht=class{};ht=F([im()],ht);function am(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Nn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function sm(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 cu(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(am),c=zn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let l=await Promise.allSettled(a.map(h=>sm(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 uu(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=Kn(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 um=".tmp/zoho-access-tokens.json";function su(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 pu(e=um,t=!0){let o=Zi({filePath:e,reviver:su}),r=t?Vn(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]=su(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=Fc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return fo(this.accountsContext)}};w=F([pm(),b(0,lu(Ae)),b(1,lu(ht))],w);import{Inject as hm,Injectable as mm}from"@nestjs/common";var lm="ZOHO_ACCOUNTS_CLIENT_ID",dm="ZOHO_ACCOUNTS_CLIENT_SECRET",mt=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 (${lm}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${dm}).`)}};var Dt=class{constructor(t){this.config=t;mt.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=Le(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Ic(t.factoryConfig??{})}_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=Le(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 xc(i)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Tc(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Ac(n)({accessToken:o})}};Dt=F([mm(),b(0,hm(mt))],Dt);import{ConfigModule as fk,ConfigService as gk}from"@nestjs/config";import{Inject as du,Injectable as ym}from"@nestjs/common";var Mt=class{zohoCrm;factoryConfig;static assertValidConfig(t){me(t.zohoCrm)}};var Ge=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=Qa({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return ka(this.crmContext)}get upsertRecord(){return Oa(this.crmContext)}get updateRecord(){return Ea(this.crmContext)}get deleteRecord(){return Pa(this.crmContext)}get getRecordById(){return Da(this.crmContext)}get getRecords(){return Ma(this.crmContext)}get searchRecords(){return kr(this.crmContext)}get searchRecordsPageFactory(){return wa(this.crmContext)}get getRelatedRecordsFunctionFactory(){return pt(this.crmContext)}get getEmailsForRecord(){return Or(this.crmContext)}get getEmailsForRecordPageFactory(){return _a(this.crmContext)}get getAttachmentsForRecord(){return Er(this.crmContext)}get getAttachmentsForRecordPageFactory(){return va(this.crmContext)}get uploadAttachmentForRecord(){return Na(this.crmContext)}get downloadAttachmentForRecord(){return Ua(this.crmContext)}get deleteAttachmentFromRecord(){return La(this.crmContext)}get createNotes(){return Pr(this.crmContext)}get deleteNotes(){return za(this.crmContext)}get createNotesForRecord(){return Ha(this.crmContext)}get getNotesForRecord(){return Dr(this.crmContext)}get getNotesForRecordPageFactory(){return Ja(this.crmContext)}get executeRestApiFunction(){return Ga(this.crmContext)}get createTagsForModule(){return Wa(this.crmContext)}get deleteTag(){return ja(this.crmContext)}get getTagsForModule(){return Ba(this.crmContext)}get addTagsToRecords(){return $a(this.crmContext)}get removeTagsFromRecords(){return Xa(this.crmContext)}};Ge=F([ym(),b(0,du(Mt)),b(1,du(w))],Ge);import{ConfigModule as Uk,ConfigService as Lk}from"@nestjs/config";import{Inject as hu,Injectable as fm}from"@nestjs/common";var wt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){me(t.zohoRecruit)}};var Ke=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Ta({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Ji(this.recruitContext)}get upsertRecord(){return Hi(this.recruitContext)}get updateRecord(){return qi(this.recruitContext)}get deleteRecord(){return Wi(this.recruitContext)}get getRecordById(){return ji(this.recruitContext)}get getRecords(){return Bi(this.recruitContext)}get searchRecords(){return dr(this.recruitContext)}get searchRecordsPageFactory(){return $i(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return st(this.recruitContext)}get getEmailsForRecord(){return hr(this.recruitContext)}get getEmailsForRecordPageFactory(){return Yi(this.recruitContext)}get getAttachmentsForRecord(){return mr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Xi(this.recruitContext)}get uploadAttachmentForRecord(){return Qi(this.recruitContext)}get downloadAttachmentForRecord(){return ea(this.recruitContext)}get deleteAttachmentFromRecord(){return ta(this.recruitContext)}get createNotes(){return Rr(this.recruitContext)}get deleteNotes(){return ca(this.recruitContext)}get createNotesForRecord(){return pa(this.recruitContext)}get getNotesForRecord(){return Cr(this.recruitContext)}get getNotesForRecordPageFactory(){return ua(this.recruitContext)}get executeRestApiFunction(){return oa(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return na(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return fr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return aa(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return gr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return sa(this.recruitContext)}get createTagsForModule(){return ha(this.recruitContext)}get getTagsForModule(){return ma(this.recruitContext)}get addTagsToRecords(){return ya(this.recruitContext)}get removeTagsFromRecords(){return fa(this.recruitContext)}};Ke=F([fm(),b(0,hu(wt)),b(1,hu(w))],Ke);import{ConfigModule as sO,ConfigService as cO}from"@nestjs/config";import{Inject as mu,Injectable as gm}from"@nestjs/common";var _t=class{zohoSign;factoryConfig;static assertValidConfig(t){me(t.zohoSign)}};var Ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=xs({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return rs(this.signContext)}get getDocuments(){return wr(this.signContext)}get getDocumentsPageFactory(){return ns(this.signContext)}get getDocumentFormData(){return is(this.signContext)}get retrieveFieldTypes(){return as(this.signContext)}get downloadPdf(){return ss(this.signContext)}get downloadCompletionCertificate(){return cs(this.signContext)}get createDocument(){return us(this.signContext)}get createDocumentFromTemplate(){return ps(this.signContext)}get getTemplate(){return ls(this.signContext)}get getTemplates(){return ds(this.signContext)}get updateDocument(){return hs(this.signContext)}get sendDocumentForSignature(){return ms(this.signContext)}get extendDocument(){return ys(this.signContext)}get deleteDocument(){return fs(this.signContext)}get getEmbeddedSigningUrl(){return gs(this.signContext)}};Ve=F([gm(),b(0,mu(_t)),b(1,mu(w))],Ve);import{ConfigModule as EO,ConfigService as PO}from"@nestjs/config";function yu(e){return{...e,operationType:e.notifications.operation_type}}var fu=ni(e=>e.operationType),gu=ai({configurerForAccessor:e=>{let t=ii(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 Ru="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",ze=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as Sm,Inject as Fm,Post as Im,Req as bm}from"@nestjs/common";import{Inject as xm,Injectable as Am,Logger as Zm}from"@nestjs/common";import{createHmac as Rm,timingSafeEqual as Cm}from"node:crypto";var Tm="x-zs-webhook-signature";function Cu(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Tm],i={valid:!1};if(n){let a=r.toString("utf-8"),s=Rm("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=Cm(l,h))}catch{c=!1}let u;if(c)try{let l=JSON.parse(a);u=yu(l)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var Ze=class{logger=new Zm("ZohoSignWebhookService");_verifier;handler=fu();configure=gu(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Cu({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([Am(),b(0,xm(ze))],Ze);var Je=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([Im(),b(0,bm()),b(1,Ci())],Je.prototype,"handleZohoSignWebhook",1),Je=F([Sm("/webhook/zoho/sign"),b(0,Fm(Ze))],Je);import{Module as km}from"@nestjs/common";import{ConfigModule as Om,ConfigService as Em}from"@nestjs/config";function Pm(e){let t={zohoSignWebhook:{webhookSecret:e.get(Ru)}};return ze.assertValidConfig(t),t}var Zo=class{};Zo=F([km({imports:[Om],controllers:[Je],providers:[{provide:ze,inject:[Em],useFactory:Pm},Ze],exports:[Ze]})],Zo);import{Inject as Tu,Injectable as Dm}from"@nestjs/common";var vt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(me(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var He=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=bs({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return _r(this.deskContext)}get getTicketById(){return Os(this.deskContext)}get searchTickets(){return vr(this.deskContext)}get getTicketsForContact(){return Es(this.deskContext)}get getTicketsForProduct(){return Ps(this.deskContext)}get getTicketMetrics(){return Ds(this.deskContext)}get getAgentsTicketsCount(){return Ms(this.deskContext)}get getTicketsPageFactory(){return ws(this.deskContext)}get searchTicketsPageFactory(){return _s(this.deskContext)}get getDepartments(){return Ns(this.deskContext)}get getDepartmentById(){return Us(this.deskContext)}get getContacts(){return Ur(this.deskContext)}get getContactById(){return Gs(this.deskContext)}get getContactsByIds(){return Ks(this.deskContext)}get getContactsPageFactory(){return Vs(this.deskContext)}get getTicketTags(){return zs(this.deskContext)}get associateTicketTags(){return Js(this.deskContext)}get dissociateTicketTag(){return Hs(this.deskContext)}get searchTags(){return qs(this.deskContext)}get getAllTags(){return Ws(this.deskContext)}get getTicketFollowers(){return js(this.deskContext)}get addTicketFollowers(){return Bs(this.deskContext)}get removeTicketFollowers(){return $s(this.deskContext)}get getTicketAttachments(){return Xs(this.deskContext)}get deleteTicketAttachment(){return Qs(this.deskContext)}get getTicketComments(){return tc(this.deskContext)}get getTicketCommentById(){return oc(this.deskContext)}get createTicketComment(){return rc(this.deskContext)}get deleteTicketComment(){return nc(this.deskContext)}get getTicketTimer(){return ic(this.deskContext)}get performTicketTimerAction(){return ac(this.deskContext)}get getTicketTimeEntries(){return sc(this.deskContext)}get getTicketTimeEntryById(){return cc(this.deskContext)}get getTicketTimeEntrySummation(){return uc(this.deskContext)}get getTicketThreads(){return Gr(this.deskContext)}get getTicketThreadById(){return dc(this.deskContext)}get getTicketThreadsPageFactory(){return hc(this.deskContext)}get getTicketActivities(){return Kr(this.deskContext)}get getTicketActivitiesPageFactory(){return mc(this.deskContext)}get getAgents(){return Vr(this.deskContext)}get getAgentById(){return fc(this.deskContext)}get getAgentsByIds(){return gc(this.deskContext)}get getMyInfo(){return Rc(this.deskContext)}get getAgentsPageFactory(){return Cc(this.deskContext)}};He=F([Dm(),b(0,Tu(vt)),b(1,Tu(w))],He);import{ConfigModule as PE,ConfigService as DE}from"@nestjs/config";import{Inject as xu,Injectable as Mm}from"@nestjs/common";var Nt=class{zohoAnalytics;factoryConfig;static assertValidConfig(t){me(t.zohoAnalytics)}};var qe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoAnalytics=Uc({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoAnalytics)}zohoAnalytics;get analyticsContext(){return this.zohoAnalytics.analyticsContext}get zohoRateLimiter(){return this.zohoAnalytics.analyticsContext.zohoRateLimiter}get getOrgs(){return Lc(this.analyticsContext)}get getAllWorkspaces(){return Gc(this.analyticsContext)}get getOwnedWorkspaces(){return Kc(this.analyticsContext)}get getSharedWorkspaces(){return Vc(this.analyticsContext)}get getWorkspaceDetails(){return zc(this.analyticsContext)}get getViews(){return Jc(this.analyticsContext)}get getViewDetails(){return Hc(this.analyticsContext)}get getTableMetadata(){return qc(this.analyticsContext)}get importDataInTable(){return jc(this.analyticsContext)}get importDataInNewTable(){return Bc(this.analyticsContext)}get createImportJobInTable(){return Wr(this.analyticsContext)}get createImportJobInNewTable(){return $c(this.analyticsContext)}get getImportJob(){return jr(this.analyticsContext)}get importDataInTableAndAwaitJob(){return Yc(this.analyticsContext)}get exportData(){return Xc(this.analyticsContext)}get createExportJob(){return Br(this.analyticsContext)}get createExportJobForSqlQuery(){return Qc(this.analyticsContext)}get getExportJob(){return $r(this.analyticsContext)}get downloadExport(){return eu(this.analyticsContext)}get exportDataAndAwaitJob(){return tu(this.analyticsContext)}get addRow(){return ou(this.analyticsContext)}get updateRows(){return ru(this.analyticsContext)}get deleteRows(){return nu(this.analyticsContext)}get deleteView(){return iu(this.analyticsContext)}get deleteWorkspace(){return au(this.analyticsContext)}};qe=F([Mm(),b(0,xu(Nt)),b(1,xu(w))],qe);import{ConfigModule as eP,ConfigService as tP}from"@nestjs/config";function So(e){return{recruit:e.recruitApi,crm:e.crmApi,desk:e.deskApi,sign:e.signApi,analytics:e.analyticsApi}}function wm(e){return`${e.clientId}:${e.refreshToken}`}function yt(e){let t=cu([uu(),pu(Ft())]),o=new Map;function r(R,y){let C=wm(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=Ne(e,"recruit");if(i){let R=r(i,"recruit"),y={zohoRecruit:{apiUrl:i.apiMode}};n=new Ke(y,R)}let a,s=Ne(e,"crm");if(s){let R=r(s,"crm"),y={zohoCrm:{apiUrl:s.apiMode}};a=new Ge(y,R)}let c,u=Ne(e,"desk");if(u?.orgId){let R=r(u,"desk"),y={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new He(y,R)}let l,h=Ne(e,"sign");if(h){let R=r(h,"sign"),y={zohoSign:{apiUrl:h.apiMode}};l=new Ve(y,R)}let f,m=Ne(e,"analytics");if(m){let R=r(m,"analytics"),y={zohoAnalytics:{apiUrl:m.apiMode,orgId:m.orgId}};f=new qe(y,R)}return{recruitApi:n,crmApi:a,deskApi:c,signApi:l,analyticsApi:f}}Do([...Eo,/1000\.\w{20,}/g]);function Au(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 nt?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=Mo(e),t}cn(e=>e instanceof G||e instanceof nt||e instanceof Ce||e instanceof L?Au(e):void 0);function d(e){console.log(JSON.stringify(Au(e)))}var Zu={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"},Yr={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"]};function _m(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 vm={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:"http://localhost/oauth",describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",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:[...Qt],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:"Organization ID, for the products scoped by one (desk, analytics)"}).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=Lm(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 Gm(o,t):o.code?await Km(o,t):await Vm(o,t)}catch(t){d(t),process.exit(1)}}},Nm="recruit,crm,desk";function Um(e,t){return(e??t??Nm).split(",").map(o=>o.trim())}function Lm(e,t){let o=e.region??t?.shared?.region??"us",r=e.product,n=r?t?.[r]:void 0;return{product:r,clientId:e.clientId??n?.clientId??t?.shared?.clientId,clientSecret:e.clientSecret??n?.clientSecret??t?.shared?.clientSecret,redirectUri:e.redirectUri,region:o,scopes:Um(e.scopes,r),code:_m(e.code),token:e.token,accountsUrl:Zu[o]??Zu.us,apiMode:e.apiMode,orgId:e.orgId}}async function Su(e,t,o){return e.product?ie({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:{...t,apiUrl:e.apiMode,orgId:eo.has(e.product)?e.orgId:void 0}}):ie({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function Gm(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await Su(e,o,t?.shared);p({success:!0,...e.product?{product:e.product}:{},refreshToken:Ie(e.token),configSaved:!0,configuredProducts:ue(r)})}async function Km(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 Su(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 Vm(e,t){let o=e.product?Yr[e.product]??[]:e.scopes.flatMap(i=>Yr[i]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Yr).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;e.product?await 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]:{clientId:e.clientId,clientSecret:e.clientSecret,apiUrl:e.apiMode,orgId:e.product==="desk"?e.orgId:void 0}}):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});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 zm={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:[...Qt],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:"Organization ID, for the products scoped by one (desk, analytics)"}).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]:{...o,apiUrl:e.apiMode,orgId:eo.has(t)?e.orgId:void 0}}):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)}}},Jm={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?Ie(r.clientId):void 0,clientSecret:r.clientSecret?Ie(r.clientSecret):void 0,refreshToken:r.refreshToken?Ie(r.refreshToken):void 0}:void 0};var e=o;let t=await B();if(!t){p({configured:!1});return}p({configured:!0,shared:{...o(t.shared),region:t.shared?.region??"us",apiMode:t.shared?.apiMode??"production"},recruit:t.recruit?{...o(t.recruit),apiUrl:t.recruit.apiUrl}:null,crm:t.crm?{...o(t.crm),apiUrl:t.crm.apiUrl}:null,desk:t.desk?{...o(t.desk),apiUrl:t.desk.apiUrl,orgId:t.desk.orgId}:null,sign:t.sign?{...o(t.sign),apiUrl:t.sign.apiUrl}:null,configuredProducts:ue(t)})}catch(t){d(t),process.exit(1)}}},Hm={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=yt(e),r=So(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)}}},qm={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Ei(),p({cleared:!0})}catch(e){d(e),process.exit(1)}}},Fu={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(vm).command(zm).command(Jm).command(Hm).command(qm).demandCommand(1,"Please specify an auth subcommand."),handler:A};import{access as Wm,constants as jm}from"node:fs";import{dirname as Bm}from"node:path";var Iu={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await B(),t=[];t.push($m(e));let o=Ym(e);if(o&&t.push(o),t.push(await Xm()),e){let n=ue(e);t.push(Qm(n),...await ey(e,n));let i=oy(e,n);i&&t.push(i)}let r=t.every(n=>n.status==="pass");p({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function $m(e){return e?{name:"config",status:"pass",message:`Config loaded from ${St()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function Ym(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 Xm(){let e=Bm(Ft());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 Qm(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 ey(e,t){let o=So(yt(e)),r=[];for(let n of t)r.push(await ty(o[n],n));return r}async function ty(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 oy(e,t){if(e.desk?.orgId)return{name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${e.desk.orgId}`};if(!t.includes("desk"))return{name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."}}function ry(e){return new Promise(t=>{Wm(e,jm.W_OK,o=>{t(!o)})})}var bu=Si({notInitializedMessage:"CLI context not initialized. This is a bug."});function ku(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)),bu.set(yt(r))}catch(r){d(r),process.exit(4)}}}function Ut(e){return bu.require()}function oe(e){let{recruitApi:t}=Ut(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}=Ut(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}=Ut(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}=Ut(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}=Ut(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 $t(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 $t(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function Fo(e){return $t(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 Lt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Io(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 ny={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}},iy={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:ny,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 bo(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:iy,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 ay={command:"list",describe:"List records from a module",builder:e=>Io(Lt(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)}}},sy={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)}}},cy={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)}}},uy={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)}}},py={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)}}},ly={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)}}},dy={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)}}},hy={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)}}},my={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)}}},Ou={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(ay).command(sy).command(cy).command(uy).command(py).command(ly).command(dy).command(hy).command(my).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 yy={command:"list",describe:"List records from a module",builder:e=>Io(Lt(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)}}},fy={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)}}},gy={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)}}},Ry={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)}}},Cy={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)}}},Ty={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)}}},xy={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)}}},Ay={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)}}},Zy={command:"attachments",describe:"Get attachments for a record",builder:e=>Lt(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)}}},Eu={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(yy).command(fy).command(gy).command(Ry).command(Cy).command(Ty).command(xy).command(Ay).command(Zy).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 Sy={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)}}},Fy={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)}}},Iy={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)}}},by={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)}}},ky={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)}}},Oy={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)}}},Pu={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Sy).command(Fy).command(Iy).command(by).command(ky).command(Oy).demandCommand(1),handler:A};var Ey={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)}}},Py={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)}}},Du={command:"departments",describe:"Desk department operations",builder:e=>e.command(Ey).command(Py).demandCommand(1),handler:A};var Dy={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)}}},My={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)}}},Mu={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Dy).command(My).demandCommand(1),handler:A};var wy={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)}}},vy={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)}}},wu={command:"agents",describe:"Desk agent operations",builder:e=>e.command(wy).command(_y).command(vy).demandCommand(1),handler:A};var Ny={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)}}},Uy={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)}}},Ly={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)}}},Gy={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)}}},Ky={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)}}},_u={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Ny).command(Uy).command(Ly).command(Gy).command(Ky).demandCommand(1),handler:A};var Vy={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)}}},zy={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)}}},Jy={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)}}},Hy={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(Vy).command(zy).command(Jy).command(Hy).demandCommand(1),handler:A};var qy={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)}}},Wy={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)}}},Nu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(qy).command(Wy).demandCommand(1),handler:A};var jy={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)}}},By={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)}}},$y={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)}}},Uu={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(jy).command(By).command($y).demandCommand(1),handler:A};var Yy={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)}}},Xy={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)}}},Qy={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)}}},ef={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)}}},Lu={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Yy).command(Xy).command(Qy).command(ef).demandCommand(1),handler:A};var tf={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)}}},of={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)}}},Gu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(tf).command(of).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)}}},Ku={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(rf).demandCommand(1),handler:A};var Vu={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(Pu).command(Du).command(Mu).command(wu).command(_u).command(vu).command(Nu).command(Uu).command(Lu).command(Gu).command(Ku).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 nf,writeFile as zu}from"node:fs/promises";import{basename as af}from"node:path";function sf(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 cf={command:"list",describe:"List sign requests (documents)",builder:e=>Fo(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:sf(e)};await bo({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){d(t),process.exit(1)}}},uf={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)}}},pf={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)}}},lf={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 nf(e.file),n=new File([r],af(e.file),{type:e.contentType}),i=await t.createDocument({requestData:o,file:n});p(i)}catch(t){d(t),process.exit(1)}}},df={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)}}},hf={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)}}},mf={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)}}},yf={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)}}},ff={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)}}},gf={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 zu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Rf={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 zu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Cf={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)}}},Ju={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(cf).command(uf).command(pf).command(lf).command(df).command(hf).command(mf).command(yf).command(ff).command(gf).command(Rf).command(Cf).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 Tf(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 xf={command:"list",describe:"List templates",builder:e=>Fo(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:Tf(e)};await bo({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){d(t),process.exit(1)}}},Af={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)}}},Hu={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(xf).command(Af).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 Zf={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(Ju).command(Hu).command(Zf).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 Sf={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)}}},Wu={command:"orgs",describe:"Analytics organization operations",builder:e=>e.command(Sf).demandCommand(1).example([["$0 analytics orgs list","Find the org id needed by every other Analytics command"]]),handler:A};var Ff={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)}}},If={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 bf(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 kf={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=bf(e.workspaceId,e.confirm);await E(e).deleteWorkspace({workspaceId:t}),p({deleted:!0,workspaceId:t})}catch(t){d(t),process.exit(1)}}},ju={command:"workspaces",describe:"Analytics workspace operations",builder:e=>e.command(Ff).command(If).command(kf).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 Of={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)}}},Ef={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)}}},Pf={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)}}},Df={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)}}},Bu={command:"views",describe:"Analytics view operations",builder:e=>e.command(Of).command(Ef).command(Pf).command(Df).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 Mf}from"node:fs/promises";import{basename as wf,extname as $u}from"node:path";var _f=["append","truncateadd","updateadd"],vf=["abort","skiprow","setcolumnempty"];async function Yu(e){let t=await Mf(e,"utf8"),o=wf(e),r=$u(e).toLowerCase()===".json"?"application/json":"text/csv";return yi({content:t,fileName:o,mimeType:r})}function ko(e){let t=$u(e).toLowerCase();return{".json":"json",".csv":"csv"}[t]}function Nf(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 Xu(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:vf,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 Uf={command:"data <workspaceId> <viewId>",describe:"Import a file into an existing table",builder:e=>Xu(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=Nf(o,e.matchingColumns),n=await Yu(e.file),i={importType:o,fileType:e.fileType??ko(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)}}},Lf={command:"new-table <workspaceId> <tableName>",describe:"Create a table in a workspace from an imported file",builder:e=>Xu(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 Yu(e.file),r={tableName:e.tableName,fileType:e.fileType??ko(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)}}},Gf={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)}}},Qu={command:"import",describe:"Analytics import operations",builder:e=>e.command(Uf).command(Lf).command(Gf).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 Kf}from"node:fs/promises";var Vf=["csv","json","xml","xls","pdf","html","image"];async function Xr(e,t){let o=await e.text(),r;return t?await Kf(t,o,"utf8"):r=o,r}function ep(e){return e.option("format",{type:"string",choices:Vf,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 zf(e){let t=e?.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t?.length?t:void 0}function tp(e){return{responseFormat:e.format,criteria:e.criteria,selectedColumns:zf(e.columns)}}var Jf={command:"data <workspaceId> <viewId>",describe:"Export the data of a view",builder:e=>ep(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=tp(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 Xr(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 Xr(r,e.out);p(n??{written:e.out})}}catch(t){d(t),process.exit(1)}}},Hf={command:"query <workspaceId>",describe:"Export the results of a SQL query",builder:e=>ep(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={...tp(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)}}},qf={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 Xr(r,e.out);p(n??{written:e.out})}else p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},op={command:"export",describe:"Analytics export operations",builder:e=>e.command(Jf).command(Hf).command(qf).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 Wf}from"node:fs/promises";function jf(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 Bf={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??ko(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 Wf(e.file,"utf8"),n=_c({content:r,fileType:o,delimiter:e.delimiter}),{data:i}=await t.getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId}),a=vc({...n,columns:i.columns??[],maxSamples:e.maxSamples}),s=Nc(a,{strict:e.strict});e.quiet||p(a,jf(a,s)),s||process.exit(1)}catch(t){d(t),process.exit(1)}}},rp={command:"diff",describe:"Analytics comparison operations",builder:e=>e.command(Bf).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 Qr(e){return e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Table view ID"})}var $f={command:"add <workspaceId> <viewId>",describe:"Add a single row to a table",builder:e=>Qr(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)}}},Yf={command:"update <workspaceId> <viewId>",describe:"Update the rows of a table matching a criteria expression",builder:e=>Qr(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)}}},Xf={command:"delete <workspaceId> <viewId>",describe:"Delete the rows of a table matching a criteria expression",builder:e=>Qr(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)}}},np={command:"rows",describe:"Analytics row operations",builder:e=>e.command($f).command(Yf).command(Xf).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 ip={command:"analytics",describe:"Zoho Analytics operations",builder:e=>e.command(Wu).command(ju).command(Bu).command(Qu).command(op).command(np).command(rp).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 ap={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 tg=bi({cliName:"zoho-cli",loadOutputConfig:async()=>(await B())?.output,mergeOutputConfig:e=>ie({output:e}),clearOutputConfig:Oi}),og=[Ou,Eu,Vu,qu,ip,ap],sp=[Fu,tg,Iu];function rg(e){return e.command.split(" ")[0]}var cp=new Set(sp.map(rg)),ng=Ii({cliName:"zoho-cli",skipCommands:cp,loadOutputConfig:async()=>(await B())?.output,saveCommandOutputConfig:async(e,t)=>{await ie({output:{commands:{[e]:t}}})}});async function ig(){try{await Qf(eg(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([ku(cp),ng],!0).command(sp).command(og).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 ig();
|
|
4
|
+
var yp=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var F=(e,t,o,r)=>{for(var n=r>1?void 0:r?fp(t,o):t,a=e.length-1,i;a>=0;a--)(i=e[a])&&(n=(r?i(t,o,n):i(n))||n);return r&&n&&yp(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as gp,mkdirSync as Rp,writeFileSync as Cp}from"node:fs";import{join as Tp}from"node:path";var nn=1;var Po=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],an=6e4,je={},sn=[...Po],Eo,xp=!1,Ap=an;function Do(e){je=e}function zt(){return je}function cn(e){xp=e}function un(e){Ap=e===void 0?an:e}function Mo(e){sn=e}function pn(e){Eo=e}function ge(e){let t=e;for(let o of sn)t=t.replace(o,"[REDACTED]");return t}function ln(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function Ct(e,t){let{dumpDir:o,commandPath:r}=je,n;if(o){gp(o)||Rp(o,{recursive:!0});let a=r?.length?r.join("_"):"response",i=ln(),s=t?`${a}_${i}_${t}`:`${a}_${i}`;n=Tp(o,`${s}.${e}`)}else n=void 0;return n}function Zp(e,t){let o=Ct("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Cp(o,JSON.stringify(r,null,2))}function Me(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>rn(n,o)):e!=null&&typeof e=="object"?r=rn(e,o):r=e,r}function rn(e,t){let o;if(e==null||typeof e!="object")o=e;else{let r={};for(let n of t)n in e&&(r[n]=e[n]);o=r}return o}function dn(e){return je.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function p(e,t){Zp(e,t);let r={ok:!0,data:je.pick?Me(e,je.pick):e,...t?{meta:t}:{}};console.log(dn(r))}function hn(e){console.log(dn(wo(e)))}var Rt=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function wo(e){let t=Eo?Eo(e):void 0,o;return t?o=t:e instanceof Rt?o={ok:!1,error:ge(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:ge(e.message),code:"ERROR"}:o={ok:!1,error:ge(String(e)),code:"UNKNOWN_ERROR"},o}function Be(e,t=!1){let o;return typeof e=="string"?o=t:e!=null&&typeof e=="object"&&Symbol.iterator in e?o=!0:o=!1,o}function Tt(e){let t=!0;for(let o of e){t=!1;break}return t}function _o(e,t){for(let o of e)t(o)}function j(e,t,o=!1){e!=null&&(Be(e,o)?_o(e,t):t(e))}function mn(e){if(!Array.isArray(e))throw new TypeError("Input is not an array/tuple...");let t;if(e.length>0){let o=e[0],r=!1;if(Array.isArray(o)){let n=o.length;r=e.findIndex(i=>Array.isArray(i)?i.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Sp(e){return e==null?[]:Fp(e)}var x=Sp;function Fp(e){return Array.isArray(e)?e:[e]}import{symmetricDifference as Eg}from"extra-set";function yn(e,t){j(t,o=>e.add(o))}function fn(e,t){j(t,o=>e.delete(o))}function gn(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function vo(e){return Object.keys(e).length===0}function Rn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Cn(e){return{...e}}function Tn(e){return e!=null}function Jt(e){return Be(e,!1)?!Tt(e):xn(e)}function No(e){let t;return Be(e,!0)?t=!Tt(e):xn(e)?t=typeof e=="object"?!vo(e):!0:t=!1,t}function xn(e){return e!=null&&e!==""}function Ip(e){return t=>{let o;return t==null?o=[]:o=t.filter((r,n,a)=>e(r,n,a)),o}}var ce=Ip(Tn);function An({base:e,build:t}){let o=e??{};return t(o),o}var bp=(e=>e);function Zn(){return bp}function Uo(e,t){let o=new Set(e),r=kp(t,n=>n);return r.length&&fn(o,r),Array.from(o)}function kp(e,t){return ce(e==null?[]:Array.isArray(e)?e:Op(e,t))}function Op(e,t){let o=new Set(e.keys);return e.values&&yn(o,e.values.map(t)),Array.from(o)}function $e(e,t){let o=Ep(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Ep(e,t){return Rn(Pp(e,t))}function Pp(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),a=o.get(n);a==null?o.set(n,[r]):a.push(r)}),o}function Sn(e,t,o){return x(t).forEach(r=>e.set(r,o)),e}function Lo(e){return Array.from(e.entries())}function Fn(e){return Dp(Lo(e))}function Dp(e){let t=[];return e.forEach(([o,r])=>{j(r,n=>{t.push([o,n])})}),t}function In(){let e=new Map,t=(n,a)=>{let i=e.get(n);i==null&&(i=[],e.set(n,i)),j(a,s=>i.push(s))},o=(n,a)=>t(n,mn(a));return{map:()=>e,entries:()=>Lo(e),tuples:()=>Fn(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,a)=>j(n,i=>t(i,a)),addTuplesToKeys:(n,a)=>j(n,i=>o(i,a)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Mp(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function bn(e){let t=Mp(e);return t!=null&&t!=="class"}function kn(e){return bn(e)?e:()=>e}function On(e,t){return Math.log(t)/Math.log(e)}var En=",",wp=" ";function _p(e,t=En,o=!1){if(e==null)return e;let r=x(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Go(e,t,o){let r;switch(o){case 1:r=[e];break;case 2:{let n=e.indexOf(t);r=n<0?[e]:[e.slice(0,n),e.slice(n+t.length)];break}default:{let n=e.split(t),a=[];if(n.length>1){let i=n.length>o,s=i?o-1:n.length;for(let c=0;c<s;c+=1)a.push(n[c]);i&&a.push(n.slice(s).join(t))}else a.push(n[0]);r=a;break}}return r}function vp(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,a=o){return _p(n,t,a)};return r.joiner=t,r.trimByDefault=o,r}function Pn(e){let{joiner:t}=e,o=vp(e),r=(n,a=i=>i)=>n.split(t).map(s=>a(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,a){return Go(n,t,a)}}}var Ko=Pn({joiner:En}),Np=Pn({joiner:wp,trimByDefault:!0});var P=Ko.joinStrings,rR=Ko.splitStrings,nR=Ko.splitStringsToSet,aR=Np.joinStrings;var Dn=gn;function wn(e,{forEach:t,filter:o}){Up(e,o).forEach((n,a)=>t(n,a))}function Up(e,t){return Vo(t)(e)}function Vo(e){let t;if(e==null)t=Mn;else{let o=Lp(e);t=r=>Mn(r).filter((n,a)=>o(n,a))}return t}function Mn(e){return Object.entries(e)}function zo(e){return typeof e=="object"?e:{valueFilter:e}}function Lp(e){let t=zo(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,a;switch(o){case 1:a=([,i])=>i!==void 0;break;case 2:a=([,i])=>i!=null;break;case 3:a=([,i])=>!!i;break;case 4:a=([,i])=>Jt(i);break;case 5:a=([,i])=>No(i);break;case 6:a=([,i])=>!!i&&Jt(i);break;case 7:a=([,i])=>!!i&&No(i);break;default:a=()=>!0;break}if(n){let i=a,s=new Set(n.map(c=>c.toString()));a=(c,u)=>i(c,u)&&s.has(c[0])}return Dn(a,r)}function xt(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function _n(e){let t;return e==null||jp(e)?t=e:t=Gp(e),t}function Gp(e){return e==null?e:new Date(e)}var Kp=365,vn=24,Vp=60,zp=1440,Jp=60,hR=Kp*zp,Hp=Jp*Vp,z=1e3,Re=z*60,Jo=Re*60,qp=Jo*vn,mR=Hp*vn,Wp=7,yR=qp*Wp;function jp(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Nn(e){return e.getTime()<Date.now()}function Un(e,t){return e==null?e:new Date(e.getTime()+(t??0))}function Bp(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:a,expiresIn:i}=e,s=n==null?null:_n(n);function c(f){return f??r??new Date}function u(f,m=!1){let R=c(f),y=h(R),C;return y==null?C=m:C=y<=R,C}function l(f){let m=c(f);return h(m)}function h(f){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:i!=null&&(m=Un(s??(a===!1?null:f),i)),m}return{input:e,hasExpired:u,getExpirationDate:l}}function Ln(e,t){let o=!0;return e!=null&&(o=Bp(e).hasExpired(t,!0)),o}function $p({filter:e,copy:t,dynamic:o=!1}){let r=e==null?el:Ye({filter:e,copy:!1});return n=>{let a=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},i=o?a:xt(a);return s=>{let c=i();return t&&(s=Cn(s)),Object.assign(s,c),s}}}function Gn(e,t){return Yp(t)(e)}function Yp(e){let t=$p({filter:e,copy:!1,dynamic:!0});return o=>t(ce(o))({})}function Kn(e,t=!1){return(t?Qp:Xp)(e)}var Xp=Ye({copy:!0,filter:{valueFilter:1}}),Qp=Ye({copy:!0,filter:{valueFilter:2}}),Vn=Ye({copy:!0,filter:{valueFilter:4}}),SR=Ye({copy:!0,filter:{valueFilter:6}}),FR=Ho({valueFilter:1}),IR=Ho({valueFilter:6}),bR=Ho({valueFilter:2});function Ho(e){let t=zn({filter:e,forEach:([o],r,n,a)=>{a.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ye({copy:e=!1,filter:t={valueFilter:1}}={}){let o=zo(t);o.invertFilter=!o.invertFilter;let r=zn({filter:o,forEach:([n],a,i)=>{delete i[n]}});return(n,a)=>((typeof a=="boolean"?a:e)&&(n={...n}),r(n),n)}var el=Ye({copy:!1});function zn({forEach:e,filter:t}){let o=Vo(t);return((r,n)=>{o(r).forEach((i,s)=>e(i,s,r,n))})}function Jn(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function Hn(e){let t,o,r=0;function n(){let a;if(t==null){if(o==null){let i=r;o=e.load().then(s=>(r===i&&(t={entries:s},o=void 0),s),s=>{throw r===i&&(o=void 0),s})}a=o}else a=Promise.resolve(t.entries);return a}return{load:async()=>({...await n()}),get:async a=>(await n())[a],set:async(a,i)=>{let s=await n();r+=1,o=void 0,await e.set(a,i),t={entries:{...s,[a]:i}}},remove:async a=>{let i=await n();r+=1,o=void 0,await e.remove(a);let s={...i};delete s[a],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function qn(e){return{load:async()=>{let t;for(let o of e){let r=await o.load();if(r!=null){t=r;break}}return t},update:async t=>{for(let o=e.length-1;o>=0;o-=1)await e[o].update(t)},clear:async()=>{for(let t=e.length-1;t>=0;t-=1)await e[t].clear()}}}function Ht(e,t,o){let[r,n]=qo(e,t,!1);return r+o+n}function qo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var tl=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],wR=new Set(tl);function Wn(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let a=qt(r,n),i;switch(a.length){case 0:i=n;break;case 1:{let s=n[a[0]];i=Ht(n,a[0],o(s));break}default:{let s=[],c=a.length,u=0,l=0;for(let h=0;h<c;h+=1){l=a[h];let f=n[l],R=n.substring(u,l)+o(f);s.push(R),u=l+1}s.push(n.substring(u)),i=s.join("");break}}return i}}function ol(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[a,i]of Array.from(t).entries())if(e.has(i)&&(n.push(a),n.length>=r))break;return n}}function qt(e,t,o){return ol(e)(t,o)}function rl(e,t){return qt(e,t,1)[0]}function nl(e){return t=>{let r=rl(typeof e=="string"?new Set([e]):e,t),n;return r==null?n=[t,void 0]:n=qo(t,r,!1),n}}function jn(e,t){return nl(t)(e)}var Xe="/",al=".";function il(e){let t=e.split(al,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Xe?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Bn(e){return il(e)!=="invalid"}var sl=/^\/+/,cl=/\/+$/;var ul=/\/{2,}/g;function $n(e){return e.startsWith(Xe)?e.replace(sl,Xe):`${Xe}${e}`}function Yn(e){return e.replaceAll(ul,Xe)}function Xn(e){return e.replace(cl,"")}function pl(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Qn=/:(\d+)/;function ll(e){return Qn.test(e)}function dl(e){let t=Qn.exec(e);return t?Number(t[1]):void 0}function hl(e){let t=ra(e),o=ml(t),{domain:r,path:n}=o,a=pl(r),i=ll(e),s=i?dl(e)??void 0:void 0,[c,u]=jn(o.path,"?"),l=a&&(c===""||Bn(c+"/")),h=fl(e);return{input:e,isWebsiteUrl:l,hasWebsiteDomain:a,hasHttpPrefix:h,hasPortNumber:i,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function ea(e){let t=hl(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function ta(e,t=!1){let o=qt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(a=>n=Ht(n,a,"&")),n}function ml(e){let t=ra(e);return yl(t)}function yl(e){let t=Go(e,"/",2),o=t[0],r=t[1];return{domain:o,path:$n(r??"/")}}var oa=/^https:\/\/|http:\/\//;function ra(e){return e.replace(oa,"")}function fl(e){return oa.test(e)}function A(){}async function na(e){let t,o=e.initValue;if(o==null||await e.checkContinue(o,-1)){let n=0,a=o,i;do a=await e.next(n,a),n+=1,i=await e.checkContinue(a,n);while(i);t=a}else t=o;return t}function aa(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function At(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function gl(e){let n=Jo,a={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},i=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;m(e??a);function l(){return{...a}}function h(){return u}function f(S){u=S}function m(S,O=!1){let q=Math.max(0,S.startLimitAt??1),I=S.cooldownRate??1,_=S.maxWaitTime??n,v=S.exponentRate??2;a={startLimitAt:q,cooldownRate:I,maxWaitTime:_,exponentRate:v},s=On(v,_/z+1),O&&R()}function R(){i=0,c=new Date}function y(S){let O;if(u){let{cooldownRate:q}=a,_=(Date.now()-c.getTime())*q/z,v=Math.max(i-_,0),W=Math.max(0,v-a.startLimitAt);S&&(i=v+S,c=new Date),O=W>=s?a.maxWaitTime:(Math.pow(a.exponentRate,Math.max(W,0))-1)*z}else O=0;return O}function C(S){return y(S??0)}function g(){let S=y(1);return At(S)}return{waitForRateLimit:g,getNextWaitTime:C,getConfig:l,setConfig:m,getEnabled:h,setEnabled:f,reset:R}}function ia(e){let o=gl({exponentRate:1.5,maxWaitTime:z*8,...e}),r=Re,n=new Date,a=0,i=0,s=!0;g(e,!0);function c(){Nn(n)&&h()}function u(){return s}function l(I){s=I}function h(){i=a,n=new Date(Date.now()+r)}function f(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function R(I){n=I}function y(){return c(),i}function C(I){i=I}function g(I,_=!1){a=I.limit??a,r=I.resetPeriod??r;let v={cooldownRate:I.cooldownRate??Math.max(.1,r/z),exponentRate:I.exponentRate??1.5,maxWaitTime:I.maxWaitTime??z*8};o.setConfig(v,_),_&&h(),n=I.resetAt??n}function S(I){let _=0;if(s){let W=function(){return i-=I,o.getNextWaitTime(I)};var v=W;i>0?_=W():(c(),i>0?_=W():_=m())}return _}function O(I){return S(I??0)}function q(){let I=S(1);return At(I)}return{getRemainingLimit:y,setRemainingLimit:C,getTimeUntilNextReset:m,getResetAt:f,setNextResetAt:R,setConfig:g,reset:h,getNextWaitTime:O,waitForRateLimit:q,getEnabled:u,setEnabled:l}}var Rl="__CATCH_ALL_HANDLE_RESULT_KEY__";function sa(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,a=new Map,i=u=>{n=u},s=(u,l)=>{u===Rl?i(l):Sn(a,u,l)},c=(u,l,h)=>{let f=h.bind(u);s(l,f)};return An({base:(u=>{let l=e(u),h=(l==null?void 0:a.get(l))??n,f;return h?f=Promise.resolve(h(u)).then(m=>m??o):f=Promise.resolve(r),f}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=i}})}}function Cl(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function Tl(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function xl(e,t,o){let r=Tl(e,t);return n=>{r(function(a){let i=o(a);return n.call(this,i)})}}function ca(e,t){return o=>xl(e,o,t)}function ua(e){return t=>(o,r)=>{let n=Cl(o,t),a=e.configurerForAccessor(n);r(a)}}var Al=-1,pa=0;function Zl(e){return e?.page??Al}function la(e){return Zl(e)+1}import{BaseError as da}from"make-error";var ne=class extends da{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function ha(e){return(t,o)=>Sl(e(t,o))}var Se=class extends da{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Sl(e){return e.then(t=>{if(!t.ok)throw new Se(t);return t})}import{BaseError as cC}from"make-error";function ma(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let i=new AbortController;r=i,o={...o,signal:i.signal}}let a=e(t,o??void 0);if(n){let i=setTimeout(()=>{r?.abort()},n);a=a.finally(()=>{clearTimeout(i)})}return a}}function fa(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>ga({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>Il({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Fl=(e,t)=>t(e);function Il(e){let{makeFetch:t=fetch,fetchHandler:o=Fl,useTimeout:r,requireOkResponse:n,mapResponse:a}=e,i=t;r&&(i=ma(i)),n&&(i=ha(i));let s=ga(e);return async(c,u)=>{let l=await s(c,u),h=o(l,i);return a&&(h=a(h)),h}}var bl=(e,t)=>new Request(e,t??void 0);function ga(e){let{makeRequest:t=bl,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:a,useBaseUrlForConfiguredFetchRequests:i=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=i}=e,c=o?new URL(Xn(o)):void 0,u=c?m=>{let R,y=m.toString();if(!s&&ea(y))R=new URL(y);else{let C=c.origin+Yn("/"+c.pathname+"/"+m);R=new URL(C,c)}return R}:void 0;async function l(m){let R=aa(m)?await m:m;return ya(R)?R:t(R)}let h=u?async m=>{let R,y,C;if(typeof m=="string"?R=m:ya(m)?i?(R=m.url,y=m):C=m:C=await t(m),!C){let g=u(R);C=await t(g.href,y)}return C}:l,f;if(r!=null||n!=null){let m=kn(r);async function R(){let C=await m();return n?{...C,timeout:n}:C}async function y(C,g){let S=await R(),O=kl(S,await g),q=O.timeout===void 0?C.timeout:O.timeout;return{...O,timeout:q}}a?f=(C,g)=>a(C,y(C,g)):f=(C,g)=>y(C,g)}else a?f=a:f=(m,R)=>R;return async(m,R)=>{try{let y=await h(m);R=await f(y,R??void 0);let C=await t(y,R);return C.timeout=n,C}catch(y){throw y instanceof ne?y:new ne(y)}}}function kl(e,t){let o;if(t){let r=Ol([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Ol(e){let t=In();return ce(e).forEach(o=>{let r=El(o),n=new Set;r.forEach(([a,i])=>{n.has(a)||(t.delete(a),n.add(a)),i&&t.add(a,i)})}),t.tuples()}function El(e){let t=[];return Array.isArray(e)?t=e:typeof e.forEach=="function"?e.forEach((o,r)=>{t.push([r,o])}):typeof e=="object"&&(t=Object.entries(e)),t}function ya(e){return!!e.url}import{safeParse as Pl}from"fast-content-type-parse";function Ra(e){let t={};return e.mimeType&&(t.type=e.mimeType),e.lastModified!=null&&(t.lastModified=e.lastModified),new File(x(e.content),e.fileName,t)}function Wt(e){let t=e.headers.get("content-type"),o=Pl(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ca(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,a=async(i,s)=>{async function c(u){await n.waitForRateLimit();let l,h;try{l=await s(i.clone())}catch(m){h=m,l=h.response}if(await t(l,h)&&u<r)l=await c(u+1);else if(h!=null)throw h;return l}return c(0)};return a._rateLimiter=n,a}var Wo=class extends ne{constructor(o){super("There was no next page for this.");this.page=o}},jo=class extends ne{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},Dl=100;function Qe(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:a}=e;return(i,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},l=u??a,h=c===null?Number.MAX_SAFE_INTEGER:c??Dl;function f(R,y=void 0){return async()=>{let C=await t(R),{cursor:g,nextPageCursor:S,hasNext:O}=await o(C),q=g??y?.cursor,I=O!==!1,_=y?y.page+1:pa,v=_>=h,W={input:R,result:C,page:_,previous:y,hasNext:I,isAtMaxPage:v,cursor:q,nextPageCursor:S,fetchNext:xt(async()=>{if(v)throw new jo(W,h);let on=I?await r(W,R,{maxPage:h,maxItemsPerPage:l}):void 0;if(!on)throw new Wo(W);return f({...R,...on},W)()})};return W}}return{input:i,fetchNext:xt(()=>f(i)())}}}function Ml(e){let t=[];function o(r,n){n!=null&&(Array.isArray(n)?n.forEach((a,i)=>o(`${r}[${i}]`,a)):typeof n=="object"?Object.entries(n).forEach(([a,i])=>o(`${r}[${a}]`,i)):t.push([r,String(n)]))}return Object.entries(e??{}).forEach(([r,n])=>o(r,n)),t}function T(e,t){let{omitKeys:o,filterEmptyValues:r,useBracketNotation:n}=t??{},a=Array.isArray(e)?Gn(e):e,i=r??!0?Vn(a??{}):a,s=n?Ml(i):i,c=new URLSearchParams(s);return o!=null&&j(o,u=>c.delete(u),!1),c}function Bo(e){let t;if(typeof e=="string")t=e;else if(wl(e))t=e.href;else{let o=Bo(e.url);if(e.queryParams){let r=Nl(e.queryParams);Tt(r)?t=o:t=ta(o+`?${r.toString()}`)}else t=o}return t}function wl(e){return typeof e=="object"&&e instanceof URL}function _l(e){return typeof e=="object"&&e instanceof URLSearchParams}function vl(e){let t=[];return _o(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let a=String(r);j(n,i=>{i!=null&&t.push([a,String(i)])})}}),t}function Nl(e){let t;return _l(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):Be(e)?t=new URLSearchParams(vl(e)):t=Ul(e),t}function Ul(e){let t=[];return wn(e,{forEach:o=>{let[r,n]=o,a=String(r);n!=null&&j(n,i=>{t.push([a,String(i)])})}}),new URLSearchParams(t)}var $o=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Ll(e){return e==null?void 0:typeof e=="string"?e:JSON.stringify(e)}var Gl=e=>{throw new $o(e)},$=e=>null;function Y(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Gl};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,a=Ta(o);return(i,s,c)=>{let u=Bo(i),l=a(s,c),h=typeof s=="object"?s.interceptResponse:void 0;return e(u,l).then(m=>{let R=m.json().catch(r),y=n?R.then(C=>n(C,m)):R;return h?y.then(C=>h(C,m)):y})}}function Ta(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Zn()}=e;return(r=t,n)=>{let a;return typeof r=="string"?a={method:r,body:n}:a=r??{method:t,body:n},a=o(a),{...a,method:a.method,body:Ll(a.body)}}}var OC=Ta();var X=fa({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});import{createParamDecorator as Kl}from"@nestjs/common";var oT=Kl((e,t)=>Vl(t));function Vl(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Yo,BadRequestException as zl,InternalServerErrorException as Jl,Logger as Hl}from"@nestjs/common";import ql from"raw-body";import{parse as Wl}from"node:querystring";var xa=new Hl("RawBody"),sT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw xa.error("RawBody request was not readable. This is generally due to bad configuration."),new zl("Invalid body");return ql(o)}),Aa=Yo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw xa.error("RawBody expected a buffer set to req.body."),new Jl("failed parsing body");return r}),cT=Yo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=jl(o.body),o.body});function jl(e){let t=Bl(e);return Wl(t)}function Bl(e){return e.toString("utf8").trim()}import{Injectable as $l}from"@nestjs/common";import Yl from"body-parser";var et=class{use(t,o,r){Yl.json()(t,o,r)}};et=F([$l()],et);import{Injectable as Xl}from"@nestjs/common";import Ql from"body-parser";var tt=class{use(t,o,r){Ql.raw({type:"*/*"})(t,o,r)}};tt=F([Xl()],tt);import{Logger as ed,Module as td,RequestMethod as od}from"@nestjs/common";var rd="/webhook",nd={path:`${rd}/{*path}`,method:od.POST},Xo=class{configure(t){ad(t)}},jt=class extends Xo{logger=new ed("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};jt=F([td({})],jt);function ad(e){e.apply(tt).forRoutes(nd).apply(et).forRoutes("{*path}")}var Za="CLIENT_WEB_APP_URL";var we=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as id,Injectable as sd}from"@nestjs/common";var _e=class{_config;constructor(t){this._config=t}get config(){return this._config}get webAppUrl(){return this.config.client.clientWebAppUrl}get webAppHost(){return this.webAppUrl.split("://",2)[1]}};_e=F([sd(),b(0,id(we))],_e);import{Module as cd}from"@nestjs/common";import{ConfigModule as ud,ConfigService as pd}from"@nestjs/config";function ld(e){let t={client:{clientWebAppUrl:e.get(Za)}};return we.assertValidConfig(t),t}var Bt=class{};Bt=F([cd({imports:[ud],providers:[{provide:we,inject:[pd],useFactory:ld},_e],exports:[_e]})],Bt);var Sa="SERVER_ENV_TOKEN";import{Inject as dd,Injectable as hd}from"@nestjs/common";function Fa(){return process.env.NODE_ENV==="test"}var $t=class{constructor(t){this.env=t}get isTestingEnv(){return Fa()}get isProduction(){return this.env.production}get isStaging(){return!!this.env.staging}get developerToolsEnabled(){return!!(!this.isProduction&&this.env.developerToolsEnabled)}get appUrl(){return this.env.appUrl}get appApiUrl(){return this.env.appApiUrl}};$t=F([hd(),b(0,dd(Sa))],$t);import{dirname as Cd}from"node:path";import{chmod as md,mkdirSync as yd,readFile as fd,writeFile as gd}from"node:fs";import{rm as Rd}from"node:fs/promises";function Fe(e){return new Promise((t,o)=>{fd(e,{encoding:"utf-8"},(r,n)=>{if(r){r.code==="ENOENT"?t(void 0):o(r);return}try{t(JSON.parse(n))}catch{t(void 0)}})})}function Yt(e){return yd(e.dirPath,{recursive:!0}),new Promise((t,o)=>{gd(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():md(e.filePath,e.mode,n=>{n?o(n):t()})})})}function Zt(e){return Rd(e,{force:!0})}var Td=384;function Ia(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,a=o??Td;async function i(){let l=await Fe(t),h;if(l==null)h={};else if(r==null)h=l;else{h={};for(let f of Object.keys(l)){let m=r(l[f]);m!=null&&(h[f]=m)}}return h}async function s(l){let h=n==null?l:Object.fromEntries(Object.entries(l).map(([f,m])=>[f,n(m)]));await Yt({filePath:t,dirPath:Cd(t),data:h,mode:a})}let c=Promise.resolve();function u(l){let h=c.then(l,l);return c=h.catch(()=>{}),h}return{load:i,get:async l=>(await i())[l],set:(l,h)=>u(async()=>{let f=await i();await s({...f,[l]:h})}),remove:l=>u(async()=>{let f={...await i()};delete f[l],await s(f)}),clear:()=>u(async()=>{await Zt(t)})}}var Fx=Buffer.from([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function ba(e){let t,o=e?.notInitializedMessage??"Context slot has not been initialized.";return{set:r=>{t=r},get:()=>t,require:()=>{if(t==null)throw new Error(o);return t}}}function Xt(e,t=nn){return async o=>{try{await e(o)}catch(r){hn(r),process.exit(t)}}}var xd=["raw","page_by_line","data_by_line"],Ad=["replace","concat"],Zd=["meta","pages","merged_page"];function Qt(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from the per-API page/offset flag."}).option("multiple-pages-output",{type:"string",choices:Zd,default:"meta",describe:"Stdout shape when multiple-pages > 1: meta (summary, low memory), pages (array of page responses, WARNING: holds all pages in memory), merged_page (concat all records into one array, WARNING: holds all records in memory)."}).option("dump-output",{type:"string",choices:xd,default:"raw",describe:"Dump file format when --dump-dir is set. raw: one full JSON page response (concatenated JSON when --dump-merge=concat, not standard JSON). page_by_line: NDJSON of page responses. data_by_line: NDJSON of records."}).option("dump-merge",{type:"string",choices:Ad,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function St(e){return Fe(e.configFilePath)}function Sd(e){return Yt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function Ft(e){let t=await St({configFilePath:e.configFilePath})??{},o={activeEnv:e.updates.activeEnv??t.activeEnv,envs:e.updates.envs?{...t.envs,...e.updates.envs}:t.envs,output:e.updates.output===void 0?t.output:Qo(t.output,e.updates.output)};return await Sd({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Qo(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:Fd(e?.commands,t)}}function Fd(e,t){let o;if("commands"in t)if(t.commands){let r={...e};for(let n of Object.keys(t.commands))r[n]={...e?.[n],...t.commands[n]};o=r}else o=void 0;else o=e;return o}function ka(e){let t=e.commandPath.join("."),o=t?e.outputConfig?.commands?.[t]:void 0;return{dumpDir:e.cliFlags.dumpDir??o?.dumpDir??e.outputConfig?.dumpDir,pick:e.cliFlags.pick??o?.pick??e.outputConfig?.pick}}function Ie(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Id}from"node:os";import{join as eo}from"node:path";function to(e){let t=e.configDirOverride??eo(Id(),`.${e.cliName}`);return{configDir:t,configFilePath:eo(t,"config.json"),tokenCachePath:eo(t,".tokens.json"),firestoreSessionCachePath:eo(t,".firestore-sessions.json")}}function Oa(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,a)=>{await Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:a}}}})});return async n=>{cn(!!n.verbose),un(typeof n.timeout=="number"?n.timeout*1e3:void 0);let a=n._?n._.map(String):[],i=a[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&i&&!e.skipCommands.has(i)){let m=a.join("."),R={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,R)}let l=i&&!e.skipCommands.has(i),h=l?await o():void 0,f=l?ka({outputConfig:h,commandPath:a,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};Do({dumpDir:f.dumpDir,pick:n.pickAll?void 0:f.pick,commandPath:a,pretty:!!n.pretty})}}function bd(e){let t=to({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await St({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(a=>Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:a}})),n=e.clearOutputConfig??(()=>Ft({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{dumpDir:void 0,pick:void 0,commands:void 0}}}));return{loadOutputConfig:o,mergeOutputConfig:r,clearOutputConfig:n}}function Ea(e){let t=bd(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:a=>a.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(i=>{if(i.setDumpDir==null&&i.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:Xt(async a=>{let i=a.command,s=a.setDumpDir,c=a.setPick,u;if(i){let h={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[i]:h}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let l=await t.loadOutputConfig();p({saved:!0,output:l??{}})})},r={command:"show",describe:"Show current output configuration",builder:a=>a,handler:Xt(async()=>{let a=await t.loadOutputConfig();p({output:a??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:a=>a.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:Xt(async a=>{let i=a.command;if(i){let s=await t.loadOutputConfig();if(!s?.commands?.[i])throw new Rt({message:`No per-command output config for "${i}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[i],await t.mergeOutputConfig({...s,commands:c}),p({cleared:!0,command:i})}else await t.clearOutputConfig(),p({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:a=>a.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:A}}import{writeFileSync as kd,appendFileSync as Od}from"node:fs";function Pa(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=zt(),n=t==="raw"?"json":"ndjson",a=Ct(n),i=r?Ct(n,"pick"):void 0,s;if(a){let c=0,u=y=>{let C;if(r){let g=Me(y.data,r);C={...y,data:g}}else C=y;return C},l=y=>{let C=y.append?Od:kd;C(a,y.mainContent),i&&y.pickContent!==void 0&&C(i,y.pickContent)},h=(y,C)=>{let g=JSON.stringify(y,null,2),S=i?JSON.stringify(u(y),null,2):void 0;l({mainContent:g,pickContent:S,append:C})},f=(y,C)=>{let g=JSON.stringify(y)+`
|
|
5
|
+
`,S=i?JSON.stringify(u(y))+`
|
|
6
|
+
`:void 0;l({mainContent:g,pickContent:S,append:C})},m=(y,C)=>{let g=y.data??[],S=i?Me(g,r):void 0;g.length===0?C||l({mainContent:"",pickContent:i?"":void 0,append:!1}):g.forEach((O,q)=>{let I=C||q>0,_=JSON.stringify(O)+`
|
|
7
|
+
`,v=i&&S?JSON.stringify(S[q])+`
|
|
8
|
+
`:void 0;l({mainContent:_,pickContent:v,append:I})})};s={mainPath:a,pickPath:i,writePage:y=>{let g=o==="concat"&&!(c===0);t==="raw"?h(y,g):t==="page_by_line"?f(y,g):m(y,g),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Ed(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:a,shouldCollectPages:i,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let l=0;l<o;l++){let h=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(h),c.lastResult=h,c.lastInput=u,a.writePage(h),i)c.collectedPages.push(h);else if(s)for(let m of h.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,h);let f=n.nextInput(u,h);if(!f)break;u=f}return c}function Pd(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:a}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let i=a?r.collectedPages.map(s=>({...s,data:Me(s.data,a)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:i,meta:o}))}else{let i=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=a?Me(r.collectedRecords,a):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...i,...o}}))}}async function k(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:a,dumpMerge:i}=e,s=Math.max(1,Math.floor(e.multiplePages||1)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=zt();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let l=Pa({dumpOutput:a,dumpMerge:i}),h;try{h=await Ed({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:l,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{l.close()}let f={pagesFetched:h.pagesFetched,totalRecords:h.totalRecords,hasMorePagesAvailable:h.hasMorePagesAvailable,dumpFile:l.mainPath??null};l.pickPath&&(f.dumpFilePick=l.pickPath),Pd({multiplePagesOutput:n,summaryMeta:f,state:h,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import hg from"yargs";import{hideBin as mg}from"yargs/helpers";import{writeFile as Dd,mkdirSync as Md}from"node:fs";import{join as er}from"node:path";import{homedir as wd}from"node:os";var It=["recruit","crm","desk","sign","analytics"],_d=new Set(["sign","analytics"]),Ne=new Set(["desk","analytics"]);function tr(){return er(wd(),".zoho-cli")}function bt(){return er(tr(),"config.json")}function kt(){return er(tr(),".tokens.json")}function ve(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function B(){let e=bt(),t=await Fe(e),o=ve("ACCOUNTS_CLIENT_ID"),r=ve("ACCOUNTS_CLIENT_SECRET"),n=ve("ACCOUNTS_REFRESH_TOKEN"),a=o&&r&&n,i;if(!t&&!a)i=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:ve("ACCOUNTS_URL")??t?.shared?.region,apiMode:ve("API_URL")??t?.shared?.apiMode},c=u=>{let l=u.toUpperCase(),h=ve("API_URL",l),f=Ne.has(u)?ve("ORG_ID",l):void 0,m=t?.[u],R=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_ID`],y=process.env[`ZOHO_${l}_ACCOUNTS_CLIENT_SECRET`],C=process.env[`ZOHO_${l}_ACCOUNTS_REFRESH_TOKEN`],g=R||y||C,S;return!m&&!g&&!f?S=void 0:S={clientId:R??m?.clientId,clientSecret:y??m?.clientSecret,refreshToken:C??m?.refreshToken,apiUrl:h??m?.apiUrl,orgId:f??m?.orgId},S};i={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,sign:c("sign")??t?.sign,analytics:c("analytics")??t?.analytics,output:t?.output}}return i}function Ue(e,t){let o=e[t],r=e.shared,n=!_d.has(t),a=o?.clientId??(n?r.clientId:void 0),i=o?.clientSecret??(n?r.clientSecret:void 0),s=o?.refreshToken??(n?r.refreshToken:void 0),c;return!a||!i||!s?c=void 0:c={clientId:a,clientSecret:i,refreshToken:s,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},c}async function vd(e){let t=bt();return Md(tr(),{recursive:!0}),new Promise((o,r)=>{Dd(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}function ot(e,t){return t==null?e??void 0:{...e,...Kn(t)}}async function ae(e){let t=await B(),o={shared:ot(t?.shared,e.shared),recruit:ot(t?.recruit,e.recruit),crm:ot(t?.crm,e.crm),desk:ot(t?.desk,e.desk),sign:ot(t?.sign,e.sign),analytics:ot(t?.analytics,e.analytics),output:e.output===void 0?t?.output:Qo(t?.output,e.output)};return await vd(o),o}async function Da(){await ae({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Ma(){let e=bt(),t=kt();await Zt(e),await Zt(t)}function ue(e){return It.filter(t=>{let o=Ue(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as mu,Injectable as Tm}from"@nestjs/common";function rt(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function J(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:la(o),per_page:n.maxItemsPerPage??r.per_page}}})}function oo(e){let t;switch(e){case"sandbox":t="https://recruitsandbox.zoho.com/recruit";break;case"production":t="https://recruit.zoho.com/recruit";break;default:t=e;break}return t}var nt="Candidates",wa="Job_Openings",ro="Notes",_a="Emails",Ot="Attachments";function no(e){let t;if(e!=null)switch(typeof e){case"string":t=e;break;case"object":{let o;Array.isArray(e)?o={and:[e]}:o=e,t=ao(o);break}default:break}return t}function ao(e){function t(i){let s;return typeof i=="object"?Array.isArray(i)?s=i.map(or):i&&(s=ao(i)):s=i,s}function o(i,s){return i.length>1?`(${i.join(s)})`:i[0]}function r(i,s){let c=ce(i.map(t)).flatMap(x);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,a=n;return e.and&&(a=r([r(e.and,"and"),n],"and")),a}var va=Wn({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function or(e){let t=va(e.value);return`(${e.field}:${e.filter}:${t})`}var Na=no;import{BaseError as Bd}from"make-error";import{BaseError as Ud}from"make-error";var Ld="__internal_data_array_blank_error";function Gd(e){return Array.isArray(e?.data)}var st="success";function ie(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var be=class extends Ud{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},L=class extends be{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},at=class extends L{constructor(t,o){super({code:Ld,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function Q(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof at&&!o||(r instanceof L?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof be?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ee(e,t){return(o,r=t,n)=>async(a,i)=>{try{return await o(a,i)}catch(s){if(s instanceof Se){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function pe(e){return(t,o)=>{if(t?.error!=null){let n=new Se(o),a=e(t,n);if(a)throw a}return t}}var Kd="INTERNAL_ERROR",Vd="INVALID_TOKEN",G=class extends L{},Ua="FAILURE",rr=class extends L{},zd="4834",it=class extends L{},Jd="INVALID_QUERY",nr=class extends L{get details(){return this.error.details}},io="MANDATORY_NOT_FOUND",ke="DUPLICATE_DATA",so="INVALID_DATA",Hd="TOO_MANY_REQUESTS",ar=429,qd="X-RATELIMIT-LIMIT",Wd="X-RATELIMIT-REMAINING",jd="X-RATELIMIT-RESET",La=100,Ga=Re;function ir(e){let t=e.get(qd),o=e.get(Wd),r=e.get(jd),n=null;if(t!=null&&o!=null&&r!=null){let a=Number(t),i=Number(o),s=Number(r),c=new Date(s);n={limit:a,remaining:i,reset:s,resetAt:c}}return n}var Ce=class extends L{get headerDetails(){return ir(this.responseError.response.headers)}};function te(e,t){let o;if(Gd(e))o=new at(e,t);else{let r=Te(e,t);if(r){let n=ie(r);switch(n.code){case Kd:o=new rr(n,e,t);break;case Vd:o=new G(n,e,t);break;case zd:o=new it(n,e,t);break;case Jd:o=new nr(n,e,t);break;case Hd:o=new Ce(n,e,t);break;default:o=new L(n,e,t);break}}}return o}function Te(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var Ka="ALREADY_ASSOCIATED",sr=class extends Bd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},ct=class extends be{},cr=class extends ct{},ur=class extends ct{},co=class extends ct{get invalidFieldDetails(){return this.error.details}},pr=class extends co{};function Va(e){let t;switch(e.code){case so:{let o=new co(e);o.invalidFieldDetails.id?t=new pr(e):t=o;break}case io:t=new cr(e);break;case ke:t=new ur(e);break;default:t=new ct(e);break}return t}function za(e,t){return o=>{if(!o?.data?.length)throw new sr(e,t);return o}}var $d=Q("ZohoRecruit");async function Yd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ja(t,e)),o}function Ja(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var Ha=pe(Ja),qa=ee(Yd,$d);import{BaseError as Xd}from"make-error";function dr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,K(o,{data:x(r)})).then(a=>{let i=Array.isArray(r),s=le(x(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Va(l[0].result);c=u[0].result.details}return c}))}function Wa(e){return dr(e,"","POST")}function ja(e){return dr(e,"/upsert","POST")}function Ba(e){return dr(e,"","PUT")}function $a(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,K("DELETE")).then(Qd)}function Ya(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,K("GET")).then(za(t.module)).then(o=>o.data[0])}function Xa(e){return(t=>e.fetchJson(`/v2/${t.module}?${ii(t).toString()}`,K("GET")))}function hr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Na(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return ii(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,K("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Qa(e){return J(hr(e))}function ut(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${fr(n,n.filter).toString()}`,K("GET")).then(a=>a??(r===!1?a:rt()))}}function mr(e){return ut(e)({targetModule:_a})}function ei(e){return J(mr(e))}function yr(e){return ut(e)({targetModule:Ot})}function ti(e){return J(yr(e))}var zA=20*1024*1024;function oi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:a}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${Ot}?${T(i).toString()}`,c;if(n!=null){let u=new FormData;u.append("file",n),c=e.fetch(s,{method:"POST",headers:{"Content-Type":""},body:u})}else if(a){let u=`${s}&${T({attachment_url:a}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function ri(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function ni(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"DELETE"})}var lr=class extends Xd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function ai(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v2/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?oo(t.apiUrl):""}${i}`;return e.fetchJson(c,K("POST")).then(u=>{if(u.code!=="success")throw new lr(u);return u.details})}}function ii(...e){return T(e,{omitKeys:"module"})}function fr(...e){return T(e,{omitKeys:["id","module"]})}function K(e,t){return{method:e,body:t??void 0}}function Qd(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===st?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function le(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===st?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function si(e){return t=>e.fetchJson(`/v2/${nt}/actions/associate`,K("PUT",{data:x(t)})).then(o=>{let r=o.data.map(()=>t),n=le(r,o.data),{included:a,excluded:i}=$e(n.errorItems,s=>s.result.code===Ua&&s.result.details.error[0].code===Ka);return{...n,errorItems:i,alreadyAssociatedErrorItems:a,allErrorItems:n.errorItems}})}function ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${fr(t).toString()}`,K("GET")).then(o=>o??rt())}function gr(e){let t=ci(e);return o=>t({...o,module:nt})}function ui(e){return J(gr(e))}function Rr(e,t=wa){let o=ci(e);return r=>o({...r,module:t})}function pi(e){return J(Rr(e))}function Cr(e){return t=>e.fetchJson(`/v2/${ro}`,K("POST",{data:t.data})).then(o=>le(x(t.data),o.data))}function li(e){return t=>e.fetchJson(`/v2/${ro}?${T({ids:t.ids})}`,K("DELETE")).then(o=>le(x(t.ids),o.data))}function Tr(e){return ut(e)({targetModule:ro})}function di(e){return J(Tr(e))}function hi(e){let t=Cr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:x(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function fi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,K("POST",{tags:x(t.tags)})).then(o=>{let r=le(x(t.tags),o.tags),{included:n,excluded:a}=$e(r.errorItems,i=>i.result.code===ke);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function gi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,K("GET")).then(o=>({...o,data:o.tags}))}var mi=100;function Ri(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>mi)throw new Error(`Cannot add tags to more than ${mi} records at once.`);return e.fetchJson(`/v2/${nt}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var yi=100;function Ci(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>yi)throw new Error(`Cannot remove tags from more than ${yi} records at once.`);return e.fetchJson(`/v2/${nt}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,K("POST")).then(o=>{let r=o.data.map(()=>t);return le(r,o.data)})}}var eh="invalid_code",th="invalid_client",xr=class extends ne{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},pt=class extends ne{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},oh=Q("ZohoAccounts");async function rh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ti(t,e)),o}function Ti(e,t){let o,r=e.error;if(r){let n=ie(r);switch(n.code){case eh:case th:o=new xr(n.code);break;default:o=te(e,t);break}}return o}var xi=pe(Ti),Ai=ee(rh,oh);function de(e){return async()=>{let t=await e();if(!t.accessToken)throw new pt;return t.accessToken}}var nh=e=>{let t="limit"in e?e.limit:void 0,o="resetAt"in e?e.resetAt:void 0,r=t==null?"":" The limit is "+String(t)+" requests per reset period.",n=o==null?"":" Will be reset at "+String(o)+".";console.warn("zohoRateLimitedFetchHandler(): Too many requests made."+r+n)};function Et(e){let{readRateLimitDetails:t,enabledWithoutRateLimitDetails:o=!1}=e,r=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??nh,n=e.maxRateLimit??La,a=e.resetPeriod??Ga;function i(u,l){return{limit:u,startLimitAt:Math.ceil(u/10),cooldownRate:1.2*(u/(a/z)),exponentRate:1.08,maxWaitTime:z*10,resetPeriod:a,resetAt:l}}let s=i(n),c=ia(s);return Ca({rateLimiter:c,maxRetries:e.maxRetries,updateWithResponse:function(u,l){let h=t(u.headers),f=!1,m=o;if(h){let{remaining:R,limit:y,resetAt:C}=h;if(y!=null&&y!==n){let g=i(y,C??void 0);c.setConfig(g,!1)}if(c.setRemainingLimit(R),C&&c.setNextResetAt(C),m=!0,u.status===ar){f=!0;try{r?.(h,u,l)}catch{}}}else if(o&&u.status===ar){f=!0;try{r?.({remaining:0},u,l)}catch{}}return c.setEnabled(m),f}})}function xe(e){return Et({...e,readRateLimitDetails:Ar})}function Ar(e){let t=ir(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Zi(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=oo(i.apiUrl),c=a({apiUrl:s}),u=qa(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Ha,handleFetchJsonParseErrorFunction:$});return{recruitContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function uo(e){let t;switch(e){case"sandbox":t="https://crmsandbox.zoho.com/crm";break;case"production":t="https://www.zohoapis.com/crm";break;default:t=e;break}return t}var po="Notes",Si="Emails",Pt="Attachments";var Fi=no;import{BaseError as ah}from"make-error";var Zr=class extends ah{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},lt=class extends be{},Sr=class extends lt{},Fr=class extends lt{},lo=class extends lt{get invalidFieldDetails(){return this.error.details}},Ir=class extends lo{};function Ii(e){let t;switch(e.code){case so:{let o=new lo(e);o.invalidFieldDetails.api_name==="id"?t=new Ir(e):t=o;break}case io:t=new Sr(e);break;case ke:t=new Fr(e);break;default:t=new lt(e);break}return t}function bi(e,t){return o=>{if(!o?.data?.length)throw new Zr(e,t);return o}}var ih=Q("ZohoCrm",{logDataArrayErrors:!1});async function sh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ki(t,e)),o}function ki(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var Oi=pe(ki),Ei=ee(sh,ih);import{BaseError as ch}from"make-error";function kr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,H(o,{data:x(r)})).catch(Hi).then(a=>{let i=Array.isArray(r),s=Oe(x(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:l}=s;if(l[0]!=null)throw Ii(l[0].result);c=u[0].result.details}return c}))}function Pi(e){return kr(e,"","POST")}function Di(e){return kr(e,"/upsert","POST")}function Mi(e){return kr(e,"","PUT")}function wi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,H("DELETE")).catch(Hi).then(ph)}function _i(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,H("GET")).then(bi(t.module)).then(o=>o.data[0])}function vi(e){return(t=>e.fetchJson(`/v8/${t.module}?${Ji(t).toString()}`,H("GET")))}function Or(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Fi(o.criteria);r.criteria=n}if(!r.word&&!o.cvid&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, cvid, criteria, email, or phone must be provided");return Ji(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,H("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function Ni(e){return J(Or(e))}function dt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${uh(n,n.filter).toString()}`,H("GET")).then(a=>a??(r===!1?a:rt()))}}function Er(e){let t=dt(e)({targetModule:Si});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Ui(e){return J(Er(e))}function Pr(e){return dt(e)({targetModule:Pt})}function Li(e){return J(Pr(e))}var oS=20*1024*1024;function Gi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let i=`/v8/${t.module}/${t.id}/${Pt}?${T(a).toString()}`,s=new FormData;return s.append("file",n),e.fetch(i,{method:"POST",headers:{"Content-Type":""},body:s})}}function Ki(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"GET"}).then(Wt)}function Vi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${Pt}/${t.attachment_id}`,{method:"DELETE"})}var br=class extends ch{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function zi(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v8/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?uo(t.apiUrl):""}${i}`;return e.fetchJson(c,H("POST")).then(u=>{if(u.code!=="success")throw new br(u);return u.details})}}function Ji(...e){return T(e,{omitKeys:"module"})}function uh(...e){return T(e,{omitKeys:["id","module"]})}function H(e,t){return{method:e,body:t??void 0}}function Hi(e){let t;if(e instanceof at)t={data:e.errorDataArray};else throw e;return t}function ph(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===st?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function Oe(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===st?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function Dr(e){return t=>e.fetchJson(`/v2/${po}`,H("POST",{data:t.data})).then(o=>Oe(x(t.data),o.data))}function qi(e){return t=>e.fetchJson(`/v2/${po}?${T({ids:t.ids})}`,H("DELETE")).then(o=>Oe(x(t.ids),o.data))}function Mr(e){return dt(e)({targetModule:po})}function Wi(e){return J(Mr(e))}function ji(e){let t=Dr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:x(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function $i(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,H("POST",{tags:x(t.tags)})).catch(o=>{let r;if(o instanceof L){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Oe(x(t.tags),o.tags),{included:n,excluded:a}=$e(r.errorItems,i=>i.result.code===ke);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Yi(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,H("DELETE")).then(o=>o.tags)}function Xi(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,H("GET")).then(o=>({...o,data:o.tags}))}var Bi=100;function Qi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function es(e){if(Array.isArray(e.ids)&&e.ids.length>Bi)throw new Error(`Cannot add/remove tags from more than ${Bi} records at once.`);let t=[...x(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&x(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:x(e.ids)}}function ts(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,H("POST",es(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function os(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=uo(i.apiUrl),c=a({apiUrl:s}),u=Ei(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:Oi,handleFetchJsonParseErrorFunction:$});return{crmContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var rs="https://signsandbox.zoho.com/api/v1",lh="https://sign.zoho.com/api/v1";function wr(e){let t;switch(e){case"sandbox":t=rs;break;case"production":t=lh;break;default:t=e;break}return t}function ns(e){let t=wr(e),o;try{o=new URL(t).hostname!==new URL(rs).hostname}catch{o=!0}return o}function as(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let i=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??i?.row_count??20,c=(i?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function he(e,t){return{method:e,body:t??void 0}}function is(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,he("GET"))}function _r(e){return t=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/requests",queryParams:{data:JSON.stringify(n)}},he("GET"))}}function ss(e){let t=_r(e);return as(t)}function cs(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,he("GET"))}function us(e){return()=>e.fetchJson("/fieldtypes",he("GET"))}function ps(e){return({requestId:t,...o})=>{let n=T(o).toString(),a=n?`?${n}`:"",i=`/requests/${t}/pdf${a}`;return e.fetch(i,{method:"GET"})}}function ls(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function ds(e){return({requestData:t,file:o})=>{let r=new FormData;return r.append("data",JSON.stringify({requests:t})),r.append("file",o),e.fetch("/requests",{method:"POST",headers:{"Content-Type":""},body:r}).then(n=>n.json())}}function hs(e){return({templateId:t,data:o,isQuickSend:r=!0})=>{let n=T({data:JSON.stringify({templates:o})});return e.fetchJson({url:`/templates/${t}/createdocument`,queryParams:{is_quicksend:String(r)}},{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()})}}function ms(e){return({templateId:t})=>e.fetchJson(`/templates/${t}`,he("GET"))}function ys(e){return(t={})=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/templates",queryParams:{data:JSON.stringify(n)}},he("GET"))}}function fs(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,he("PUT",{requests:o}))}function gs(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,he("POST",r))}}function Rs(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,he("PUT",{expire_by:o}))}function Cs(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let a=T(n),i=a.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...i?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()}:{}})}}function Ts(e){return async({requestId:t,actionId:o,host:r})=>{let n=e.config.apiUrl;if(n!=null&&ns(n)&&!/^https:\/\//i.test(r))throw new Error(`Zoho Sign requires an https embedded-signing host for this environment, but received "${r}".`);return e.fetchJson({url:`/requests/${t}/actions/${o}/embedtoken`,queryParams:{host:r}},he("POST"))}}var dh=Q("ZohoSign",{logDataArrayErrors:!1});async function hh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=xs(t,e)),o}function xs(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var As=pe(xs),Zs=ee(hh,dh);function Ss(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=xe(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=wr(i.apiUrl),c=a({apiUrl:s}),u=Zs(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:As,handleFetchJsonParseErrorFunction:$});return{signContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Fs(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var mh=Q("ZohoDesk",{logDataArrayErrors:!1});async function yh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Is(t,e)),o}function Is(e,t){let o,r=Te(e,t);if(r)switch(ie(r).code){default:o=te(e,t);break}return o}var bs=pe(Is),ks=ee(yh,mh);var fh="X-Rate-Limit-Remaining-v3",gh="Retry-After",Rh=200;function Ch(e){let t=e.get(fh),o;if(t!=null){let r=Number(t),n,a=e.get(gh);if(a!=null){let i=Number(a);Number.isNaN(i)||(n=new Date(Date.now()+i*z))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Os(e){return Et({maxRateLimit:Rh,...e,readRateLimitDetails:Ch})}function Es(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Os(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:i.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!i.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=Fs(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=ks(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:bs,handleFetchJsonParseErrorFunction:$});return{deskContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ps=25;function se(e,t){return Qe({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ps}},buildInputForNextPage:function(o,r,n){let a=n.maxItemsPerPage??r.limit??Ps,s=(r.from??1)+a;return{...r,from:s,limit:a}}})}function Le(e,t){return{method:e,body:t??void 0}}function ht(e,t){return T(e,{omitKeys:t})}function ho(e){let t;return e&&(t=P(x(e))),t}function vr(e){return t=>{let{include:o,...r}=t,n=ht([{...r,include:ho(o)}]);return e.fetchJson(`/tickets?${n}`,Le("GET")).then(a=>a??{data:[]})}}function Ds(e){return t=>{let{ticketId:o,include:r}=t,a=ht([{include:ho(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/tickets/${o}${i}`,Le("GET"))}}function Nr(e){return t=>{let o=ht([t]);return e.fetchJson(`/tickets/search?${o}`,Le("GET")).then(r=>r??{data:[]})}}function Ms(e){return t=>{let{contactId:o,include:r,...n}=t,a=ht([{...n,include:ho(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${a}`,Le("GET")).then(i=>i??{data:[]})}}function ws(e){return t=>{let{productId:o,include:r,...n}=t,a=ht([{...n,include:ho(r)}]);return e.fetchJson(`/products/${o}/tickets?${a}`,Le("GET")).then(i=>i??{data:[]})}}function _s(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Le("GET"))}function vs(e){return t=>{let o=ht([{agentIds:P(x(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Le("GET"))}}function Ns(e){return se(vr(e))}function Us(e){return se(Nr(e))}function Ls(e){return{method:e}}function Gs(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Ls("GET")).then(r=>r??{data:[]})}}function Ks(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ls("GET"))}function Ur(e){return{method:e}}function Vs(e){let t;return e&&(t=P(x(e))),t}function Lr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Vs(o)}]);return e.fetchJson(`/contacts?${n}`,Ur("GET")).then(a=>a??{data:[]})}}function zs(e){return t=>{let{contactId:o,include:r}=t,a=T([{include:Vs(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/contacts/${o}${i}`,Ur("GET"))}}function Js(e){return t=>{let o=T([{contactIds:P(x(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Ur("GET")).then(r=>r??[])}}function Hs(e){return se(Lr(e))}function Dt(e,t){return{method:e,body:t??void 0}}function qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("GET")).then(o=>o??[])}function Ws(e){return t=>{let o={tags:x(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Dt("POST",o)).then(r=>r??[])}}function js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Dt("DELETE"))}function Bs(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function $s(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,Dt("GET")).then(r=>r??{data:[]})}}function Gr(e,t){return{method:e,body:t??void 0}}function Ys(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("GET")).then(o=>o??[])}function Xs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("POST",o))}}function Qs(e){return t=>{let o={ids:x(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("DELETE",o))}}function ec(e,t){return{method:e,body:t??void 0}}function Th(e){let t;return e&&(t=P(x(e))),t}function tc(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:Th(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${a}`,ec("GET")).then(i=>i??{data:[]})}}function oc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,ec("DELETE"))}function mo(e,t){return{method:e,body:t??void 0}}function rc(e){let t;return e&&(t=P(x(e))),t}function nc(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:rc(r)}]);return e.fetchJson(`/tickets/${o}/comments?${a}`,mo("GET")).then(i=>i??{data:[]})}}function ac(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,i=T([{include:rc(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,mo("GET"))}}function ic(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,mo("POST",r))}}function sc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,mo("DELETE"))}function Mt(e,t){return{method:e,body:t??void 0}}function cc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Mt("GET"))}function uc(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Mt("POST",r))}}function pc(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Mt("GET")).then(a=>a??{data:[]})}}function lc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Mt("GET"))}function dc(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Mt("GET"))}function hc(e){return{method:e}}function mc(e){let t;return e&&(t=P(x(e))),t}function Kr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:mc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${a}`,hc("GET")).then(i=>i??{data:[]})}}function yc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,i=T([{include:mc(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,hc("GET"))}}function fc(e){return se(Kr(e))}function xh(e){return{method:e}}function Ah(e){let t;return e&&(t=P(x(e))),t}function Vr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=T([{...n,include:Ah(r)}]);return e.fetchJson(`/tickets/${o}/activities?${a}`,xh("GET")).then(i=>i??{data:[]})}}function gc(e){return se(Vr(e))}function yo(e){return{method:e}}function Rc(e){let t;return e&&(t=P(x(e))),t}function zr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Rc(o)}]);return e.fetchJson(`/agents?${n}`,yo("GET")).then(a=>a??{data:[]})}}function Cc(e){return t=>{let{agentId:o,include:r}=t,a=T([{include:Rc(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/agents/${o}${i}`,yo("GET"))}}function Tc(e){return t=>{let o=T([{agentIds:P(x(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,yo("GET")).then(r=>r?.data??[])}}function xc(e){return()=>e.fetchJson("/myinfo",yo("GET"))}function Ac(e){return se(zr(e))}var Zh="https://accounts.zoho.com",Sh="https://accounts.zoho.eu",Fh="https://accounts.zoho.in",Ih="https://accounts.zoho.com.au",bh="https://accounts.zoho.jp",kh="https://accounts.zoho.uk",Oh="https://accounts.zohocloud.ca",Eh="https://accounts.zoho.sa",Ph={us:Zh,eu:Sh,in:Fh,au:Ih,jp:bh,uk:kh,ca:Oh,sa:Eh};function Ge(e){return Ph[e]??e}var fo="/oauth/v2/token";function go(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:a,refreshToken:i}=t??{},s=a?.clientId??o,c=a?.clientSecret??r,l=T({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:i??n});return e.fetchJson(`${fo}?${l}`,Jr("POST"))}}function Zc(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,refreshToken:a}=t,i=n?.clientId??o,s=n?.clientSecret??r,c=T({grant_type:"refresh_token",client_id:i,client_secret:s,refresh_token:a});return e.fetchJson(`${fo}?${c}`,Jr("POST"))}}function Sc(e){return t=>{let{clientId:o,clientSecret:r}=e.config,{client:n,code:a,redirectUri:i}=t,s=n?.clientId??o,c=n?.clientSecret??r,u=T({grant_type:"authorization_code",client_id:s,client_secret:c,code:a,redirect_uri:i});return e.fetchJson(`${fo}?${u}`,Jr("POST"))}}var Dh="/oauth/user/info";function Fc(e){return t=>e.fetchJson(Dh,{method:"GET",headers:{Authorization:`Zoho-oauthtoken ${t.accessToken}`}})}function Jr(e,t){return{method:e,body:t}}function Ic(e){return t=>X.makeFetch({baseUrl:t.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:e,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}function bc(e,t){let o=Ai(e,t),r=Y(o,{interceptJsonResponse:xi,handleFetchJsonParseErrorFunction:$});return{fetch:o,fetchJson:r}}function kc(e){let t=xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(t)}=e;return n=>{if(n.refreshToken)if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsConfig missing clientSecret.")}else throw new Error("ZohoAccountsConfig missing clientId.");else throw new Error("ZohoAccountsConfig missing refreshToken.");let a=Ge(n.apiUrl??"us"),i=r({apiUrl:a}),{fetch:s,fetchJson:c}=bc(i,o),u=async()=>{let m=Date.now(),{access_token:R,api_domain:y,scope:C,expires_in:g}=await go(h)();return{accessToken:R,apiDomain:y,expiresIn:g,expiresAt:new Date(m+g*z),scope:C}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let l=Mh({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),h={fetch:s,fetchJson:c,loadAccessToken:l,config:{...n,apiUrl:a}};return{accountsContext:h}}}function Oc(e){let t=e.fetchHandler??xe(),{logZohoServerErrorFunction:o,fetchFactory:r=Ic(t)}=e;return n=>{if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsOAuthClientConfig missing clientSecret.")}else throw new Error("ZohoAccountsOAuthClientConfig missing clientId.");let a=Ge(n.apiUrl??"us"),i=r({apiUrl:a}),{fetchJson:s}=bc(i,o),c={...n,apiUrl:a};return{oauthClientContext:{fetchJson:s,config:c}}}}function Mh(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Re,a=null,i=async()=>{a=null},s=async()=>{if(!a){let c=await o?.loadCachedToken();c&&(a=c)}if(a!=null&&Date.now()+n>=a.expiresAt.getTime()&&(a=null),!a){try{a=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new pt("Token Refresh Failed")}try{await o?.updateCachedToken(a)}catch{}}return a};return s.resetAccessToken=i,s}var Ec="ZANALYTICS-ORGID";function Pc(e){let t;switch(e){case"sandbox":case"production":t="https://analyticsapi.zoho.com/restapi/v2";break;default:t=e;break}return t}var wh="CONFIG",_h="application/x-www-form-urlencoded";function Dc(e){return e==null?"":T({[wh]:JSON.stringify(e)}).toString()}function Ee(e){let t=Dc(e);return t?`?${t}`:""}function V(e,t){return{method:e,body:t??void 0}}function Ro(e,t){return{method:e,headers:{"Content-Type":_h},body:Dc(t)}}var vh="failure",Nh="8535",Uh="8083",Lh="6045",Gh=["6043","6044"],Hr=class extends L{};function Mc(e){return e?.status===vh}function Kh(e){let{summary:t,data:o}=e,r=o?.errorCode;return{code:r==null?t??"":String(r),message:o?.errorMessage??t??"",details:{summary:t}}}function wc(e,t){let o;if(Mc(e)){let r=Kh(e),n={error:r};switch(r.code){case Nh:o=new G(r,n,t);break;case Uh:o=new Hr(r,n,t);break;case Lh:o=new Ce(r,n,t);break;default:o=Gh.includes(r.code)?new Ce(r,n,t):new L(r,n,t);break}}else o=te(e,t);return o}var Vh=Q("ZohoAnalytics",{logDataArrayErrors:!1});async function zh(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=wc(t,e)),o}var _c=(e,t)=>{if(Mc(e)){let o=wc(e,new Se(t));if(o)throw o}return e},vc=ee(zh,Vh);var Jh=100;var Hh=Re;function Nc(e){return Et({maxRateLimit:Jh,resetPeriod:Hh,...e,readRateLimitDetails:Ar,enabledWithoutRateLimitDetails:!0})}var qh="1001",Wh="1002";var jh="1004";var Bh=z*2,$h=150;function Yh(e){return e===qh||e===Wh}function Pe(e){return e===jh}function Co(e){let{loadJob:t,readJobCode:o,pollWait:r=Bh,maxPolls:n=$h}=e;return na({next:async a=>(a>0&&await At(r),t()),checkContinue:(a,i)=>a!=null&&Yh(o(a))&&i<n})}var Xh=65279;function Qh(e,t){let o=e.codePointAt(0)===Xh?e.slice(1):e,r=[],n=[],a="",i=!1,s=!1,c=0;for(;c<o.length;){let u=o[c];i?u==='"'?o[c+1]==='"'?(a+='"',c+=2):(i=!1,c+=1):(a+=u,c+=1):u==='"'&&a===""?(i=!0,s=!0,c+=1):u===t?(n.push(a),a="",s=!0,c+=1):u===`
|
|
9
|
+
`||u==="\r"?(n.push(a),r.push(n),n=[],a="",s=!1,c+=u==="\r"&&o[c+1]===`
|
|
10
|
+
`?2:1):(a+=u,s=!0,c+=1)}return(s||a!==""||n.length>0)&&(n.push(a),r.push(n)),r}function em(e,t){let o=Qh(e,t??","),[r,...n]=o,a;if(r==null)a={columnNames:[],rows:[]};else{let i=r.map(c=>c.trim()),s=n.map(c=>{let u={};return i.forEach((l,h)=>{l!==""&&(u[l]=c[h]??"")}),u});a={columnNames:Uo(i.filter(c=>c!=="")),rows:s}}return a}function tm(e){let t;try{t=JSON.parse(e)}catch(a){throw new Error(`zohoAnalyticsRowDataFromJson(): the content is not valid JSON. ${a.message}`,{cause:a})}let o=a=>a!=null&&typeof a=="object"&&!Array.isArray(a),r=Array.isArray(t)?t:[t];if(!r.every(o))throw new Error("zohoAnalyticsRowDataFromJson(): the content must be an array of row objects, as a Zoho Analytics JSON import is.");let n=r;return{columnNames:Uo(n.flatMap(a=>Object.keys(a))),rows:n}}function Uc(e){let{content:t,fileType:o,delimiter:r}=e;return o==="json"?tm(t):em(t,r)}var om=3,rm=/[\s,%$£€¥]/g,nm=new Set(["true","false","yes","no","y","n","t","f","1","0"]),am=/^[\d\s/.:+-]+$/,im=new Set(["PLAIN","MULTI_LINE","EMAIL","URL"]);function qr(e){return e==null?"":String(e).trim()}var sm=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,cm=/^www\./i;function mt(e){let{text:t,allowNegative:o,allowFraction:r}=e,n=Number(t.replaceAll(rm,"")),a;return Number.isFinite(n)?!o&&n<0?a="negative":!r&&!Number.isInteger(n)&&(a="notAnInteger"):a="notANumber",a}var um={NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),AUTO_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!1}),POSITIVE_NUMBER:e=>mt({text:e,allowNegative:!1,allowFraction:!1}),DECIMAL_NUMBER:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),CURRENCY:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),PERCENT:e=>mt({text:e,allowNegative:!0,allowFraction:!0}),DATE:e=>Number.isNaN(Date.parse(e))&&!am.test(e)?"notADate":void 0,BOOLEAN:e=>nm.has(e.toLowerCase())?void 0:"notABoolean",EMAIL:e=>sm.test(e)?void 0:"notAnEmail",URL:e=>URL.canParse(e)||cm.test(e)?void 0:"notAUrl"};function pm(e,t,o){let r=o==null||im.has(o);return t.columnMaxSize!=null&&e.length>t.columnMaxSize&&r}function lm(e,t){let o=qr(e),r=t.dataType?.toUpperCase(),n;return o===""?n=t.isNullable===!1&&t.defaultValue==null?"emptyInNonNullable":void 0:pm(o,t,r)?n="tooLong":n=r==null?void 0:um[r]?.(o),n}function dm(e,t){return`${e}\0${t}`}function Lc(e){let{columns:t,columnNames:o,rows:r,maxSamples:n}=e,a=n??om,i=new Map(t.map(g=>[g.columnName,g])),s=new Map(t.map(g=>[g.columnName.trim().toLowerCase(),g.columnName])),c=new Set(o),u=[],l=[],h=[],f=new Set;o.forEach(g=>{let S=s.get(g.trim().toLowerCase());i.has(g)?u.push(g):S==null?l.push(g):(h.push({dataColumnName:g,tableColumnName:S}),f.add(S))});let m=l.map(g=>({columnName:g,valueCount:r.reduce((S,O)=>qr(O[g])===""?S:S+1,0)})),R=t.filter(g=>!c.has(g.columnName)&&!f.has(g.columnName)).map(g=>({columnName:g.columnName,dataType:g.dataType,isNullable:g.isNullable,required:g.isNullable===!1&&g.defaultValue==null})),y=new Map;r.forEach((g,S)=>{u.forEach(O=>{let q=i.get(O),I=lm(g[O],q);if(I!=null){let _=dm(O,I),v=y.get(_);if(v==null){let W=[];v={conflict:{columnName:O,dataType:q.dataType,reason:I,conflictCount:0,samples:W},count:0,samples:W},y.set(_,v)}v.count+=1,v.samples.length<a&&v.samples.push({row:S+1,value:qr(g[O])})}})});let C=Array.from(y.values()).map(g=>({...g.conflict,conflictCount:g.count}));return{matchedColumns:u,droppedColumns:m,emptyColumns:R,caseMismatchedColumns:h,conflicts:C,rowCount:r.length}}function Gc(e,t){let o=t?.strict?e.emptyColumns.length:e.emptyColumns.filter(r=>r.required).length;return e.droppedColumns.length===0&&e.caseMismatchedColumns.length===0&&e.conflicts.length===0&&o===0}function Kc(e){let{accountsContext:t}=e,o=de(t.loadAccessToken),r=Nc(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>X.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Zoho-oauthtoken ${await o()}`,...i.orgId?{[Ec]:i.orgId}:void 0}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoAnalyticsConfig missing api url.");let s=Pc(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=vc(c,n,m=>{m instanceof G&&t.loadAccessToken.resetAccessToken()}),l=Y(u,{interceptJsonResponse:_c,handleFetchJsonParseErrorFunction:$});return{analyticsContext:{fetch:u,fetchJson:l,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Vc(e){return()=>e.fetchJson("/orgs",V("GET"))}function zc(e){return()=>e.fetchJson("/workspaces",V("GET"))}function Jc(e){return()=>e.fetchJson("/workspaces/owned",V("GET"))}function Hc(e){return()=>e.fetchJson("/workspaces/shared",V("GET"))}function qc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("GET"))}function Wc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views`,V("GET"))}function jc(e){return t=>e.fetchJson(`/views/${t.viewId}`,V("GET"))}function Bc(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/metadata`,V("GET"))}var hm="import";function mm(e,t){let{file:o,data:r,rows:n}=e,a=new FormData;if(o!=null)a.append("FILE",o);else{if(r==null&&n==null)throw new Error("zohoAnalyticsImportFormData(): one of file, data, or rows must be provided.");{let i=r??JSON.stringify(n);if(t?.asFile){let s=t.fileType??(n==null?"csv":"json");a.append("FILE",new File([i],`${hm}.${s}`,{type:s==="json"?"application/json":"text/csv"}))}else a.append("DATA",i)}}return a}function Wr(e,t){let{file:o,rows:r}=e,n=t;if(n==null){if(r!=null)n="json";else if(o!=null){let a=o.name.split(".").pop()?.toLowerCase();n=a==="json"||a==="csv"?a:void 0}}return n}function To(e){return e??!0}function $c(e,t){let o=Wr(e,t);if(o==null)throw new Error("zohoAnalyticsCreateImportJob(): config.fileType is required for an async import job when the data is not rows or a file with a .csv/.json name.");return o}async function xo(e){let{context:t,url:o,config:r,dataInput:n,formDataOptions:a}=e,i=mm(n,a);return(await t.fetch(`${o}${Ee(r)}`,{method:"POST",headers:{"Content-Type":""},body:i})).json()}function Yc(e){return t=>{let{workspaceId:o,viewId:r,config:n,...a}=t,i={...n,autoIdentify:To(n.autoIdentify),fileType:Wr(a,n.fileType)};return xo({context:e,url:`/workspaces/${o}/views/${r}/data`,config:i,dataInput:a})}}function Xc(e){return t=>{let{workspaceId:o,config:r,...n}=t,a={...r,autoIdentify:To(r.autoIdentify),fileType:Wr(n,r.fileType)};return xo({context:e,url:`/workspaces/${o}/data`,config:a,dataInput:n})}}function jr(e){return t=>{let{workspaceId:o,viewId:r,config:n,...a}=t,i=$c(a,n.fileType),s={...n,autoIdentify:To(n.autoIdentify),fileType:i};return xo({context:e,url:`/bulk/workspaces/${o}/views/${r}/data`,config:s,dataInput:a,formDataOptions:{asFile:!0,fileType:i}})}}function Qc(e){return t=>{let{workspaceId:o,config:r,...n}=t,a=$c(n,r.fileType),i={...r,autoIdentify:To(r.autoIdentify),fileType:a};return xo({context:e,url:`/bulk/workspaces/${o}/data`,config:i,dataInput:n,formDataOptions:{asFile:!0,fileType:a}})}}function Br(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/importjobs/${t.jobId}`,{method:"GET"})}function eu(e){let t=jr(e),o=Br(e);return async r=>{let{poll:n,...a}=r,{data:i}=await t(a);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:i.jobId}),readJobCode:s=>s.data.jobCode})}}function tu(e){return t=>e.fetch(`/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,{method:"GET"})}function $r(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/views/${t.viewId}/data${Ee(t.config)}`,V("GET"))}function ou(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/data${Ee(t.config)}`,V("GET"))}function Yr(e){return t=>e.fetchJson(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}`,V("GET"))}function ru(e){return t=>e.fetch(`/bulk/workspaces/${t.workspaceId}/exportjobs/${t.jobId}/data`,{method:"GET"})}function nu(e){let t=$r(e),o=Yr(e);return async r=>{let{poll:n,...a}=r,{data:i}=await t(a);return Co({...n,loadJob:()=>o({workspaceId:r.workspaceId,jobId:i.jobId}),readJobCode:s=>s.data.jobCode})}}function au(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("POST",t.config))}function iu(e){return t=>{let{criteria:o,updateAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsUpdateRows(): either criteria or updateAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("PUT",t.config))}}function su(e){return t=>{let{criteria:o,deleteAllRows:r}=t.config;if(!o&&!r)throw new Error("zohoAnalyticsDeleteRows(): either criteria or deleteAllRows must be provided.");return e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}/rows`,Ro("DELETE",t.config))}}function cu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}/views/${t.viewId}${Ee(t.config)}`,V("DELETE"))}function uu(e){return t=>e.fetchJson(`/workspaces/${t.workspaceId}`,V("DELETE"))}function me(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Ae=class{zohoAccounts;factoryConfig;static assertValidConfig(t){let{zohoAccounts:o}=t;if(o)if(o.serviceAccessTokenKey)if(o.refreshToken)if(o.apiUrl){if(!o.clientId)throw new Error("ZohoAccountsServiceConfig.zohoAccounts.clientId is required")}else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.apiUrl is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.refreshToken is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.serviceAccessTokenKey is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts is required")}};import{Injectable as ym}from"@nestjs/common";var yt=class{};yt=F([ym()],yt);function fm(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!Ln(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function gm(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Rm(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function lu(e,t){let o=[...e],r=typeof t=="function"?t:t===!1?void 0:Rm;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(a){let i=o.map(u=>u.loadZohoAccessTokenCache(a)),s=i.map(fm),c=qn(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let l=await Promise.allSettled(i.map(h=>gm(h,u)));if(r!=null){let h=ce(l.map(f=>f.value));h.length&&r(h)}},clearCachedToken:async()=>{await Promise.allSettled(i.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function du(e,t){let o={};if(e!=null)for(let a of Object.keys(e)){let i=e[a];i!=null&&(o[a]=i)}let r=Jn(o);function n(a){return{loadCachedToken:async()=>{let i=await r.get(a);return t&&console.log("retrieving access token from memory: ",{service:a,hit:i!=null,expiresAt:i?.expiresAt}),i},updateCachedToken:async i=>{await r.set(a,i),t&&console.log("updating access token in memory: ",{service:a,expiresAt:i?.expiresAt})},clearCachedToken:async()=>{await r.remove(a),t&&console.log("clearing access token in memory: ",{service:a})}}}return{loadZohoAccessTokenCache:n}}var Cm=".tmp/zoho-access-tokens.json";function pu(e){let t;if(e==null||typeof e!="object")t=void 0;else{let o=e,r=o.expiresAt,n=r!=null&&!(r instanceof Date)?new Date(r):r;t={...o,expiresAt:n}}return t}function hu(e=Cm,t=!0){let o=Ia({filePath:e,reviver:pu}),r=t?Hn(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(l){console.error("Failed updating access token in file: ",l)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function a(){let c=await Fe(e),u;if(c==null)u=void 0;else{let l={};for(let h of Object.keys(c))l[h]=pu(c[h]);u=l}return u}async function i(c){await r.clear();for(let[u,l]of Object.entries(c))l!=null&&await r.set(u,l)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:a,writeTokenFile:i,deleteTokenFile:s}}var w=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=kc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return go(this.accountsContext)}};w=F([Tm(),b(0,mu(Ae)),b(1,mu(yt))],w);import{Inject as Zm,Injectable as Sm}from"@nestjs/common";var xm="ZOHO_ACCOUNTS_CLIENT_ID",Am="ZOHO_ACCOUNTS_CLIENT_SECRET",ft=class{zohoAccountsOAuth;factoryConfig;static assertValidConfig(t){let{zohoAccountsOAuth:o}=t;if(!o)throw new Error("ZohoAccountsOAuthServiceConfig.zohoAccountsOAuth is required");if(!o.clientId)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientId (${xm}).`);if(!o.clientSecret)throw new Error(`ZohoAccountsOAuthServiceConfig requires a clientSecret (${Am}).`)}};var _t=class{constructor(t){this.config=t;ft.assertValidConfig(t);let{apiUrl:o,clientId:r,clientSecret:n}=t.zohoAccountsOAuth;this.apiUrl=Ge(o??"us"),this.clientId=r,this._clientSecret=n,this._clientFactory=Oc(t.factoryConfig??{})}_clientFactory;_clients=new Map;apiUrl;clientId;_clientSecret;get oauthClientContext(){return this.oauthClientContextForApiUrl(this.apiUrl)}oauthClientContextForApiUrl(t){let o=Ge(t),r=this._clients.get(o);return r==null&&(r=this._clientFactory({clientId:this.clientId,clientSecret:this._clientSecret,apiUrl:o}).oauthClientContext,this._clients.set(o,r)),r}exchangeAuthorizationCode(t){let{code:o,redirectUri:r,accountsApiUrl:n}=t,a=this.oauthClientContextForApiUrl(n??this.apiUrl);return Sc(a)({code:o,redirectUri:r})}refreshUserAccessToken(t){let{refreshToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Zc(n)({refreshToken:o})}userInfo(t){let{accessToken:o,accountsApiUrl:r}=t,n=this.oauthClientContextForApiUrl(r??this.apiUrl);return Fc(n)({accessToken:o})}};_t=F([Sm(),b(0,Zm(ft))],_t);import{ConfigModule as Ek,ConfigService as Pk}from"@nestjs/config";import{Inject as yu,Injectable as Fm}from"@nestjs/common";var vt=class{zohoCrm;factoryConfig;static assertValidConfig(t){me(t.zohoCrm)}};var Ke=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=os({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Pi(this.crmContext)}get upsertRecord(){return Di(this.crmContext)}get updateRecord(){return Mi(this.crmContext)}get deleteRecord(){return wi(this.crmContext)}get getRecordById(){return _i(this.crmContext)}get getRecords(){return vi(this.crmContext)}get searchRecords(){return Or(this.crmContext)}get searchRecordsPageFactory(){return Ni(this.crmContext)}get getRelatedRecordsFunctionFactory(){return dt(this.crmContext)}get getEmailsForRecord(){return Er(this.crmContext)}get getEmailsForRecordPageFactory(){return Ui(this.crmContext)}get getAttachmentsForRecord(){return Pr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Li(this.crmContext)}get uploadAttachmentForRecord(){return Gi(this.crmContext)}get downloadAttachmentForRecord(){return Ki(this.crmContext)}get deleteAttachmentFromRecord(){return Vi(this.crmContext)}get createNotes(){return Dr(this.crmContext)}get deleteNotes(){return qi(this.crmContext)}get createNotesForRecord(){return ji(this.crmContext)}get getNotesForRecord(){return Mr(this.crmContext)}get getNotesForRecordPageFactory(){return Wi(this.crmContext)}get executeRestApiFunction(){return zi(this.crmContext)}get createTagsForModule(){return $i(this.crmContext)}get deleteTag(){return Yi(this.crmContext)}get getTagsForModule(){return Xi(this.crmContext)}get addTagsToRecords(){return Qi(this.crmContext)}get removeTagsFromRecords(){return ts(this.crmContext)}};Ke=F([Fm(),b(0,yu(vt)),b(1,yu(w))],Ke);import{ConfigModule as Xk,ConfigService as Qk}from"@nestjs/config";import{Inject as fu,Injectable as Im}from"@nestjs/common";var Nt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){me(t.zohoRecruit)}};var Ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Zi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Wa(this.recruitContext)}get upsertRecord(){return ja(this.recruitContext)}get updateRecord(){return Ba(this.recruitContext)}get deleteRecord(){return $a(this.recruitContext)}get getRecordById(){return Ya(this.recruitContext)}get getRecords(){return Xa(this.recruitContext)}get searchRecords(){return hr(this.recruitContext)}get searchRecordsPageFactory(){return Qa(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return ut(this.recruitContext)}get getEmailsForRecord(){return mr(this.recruitContext)}get getEmailsForRecordPageFactory(){return ei(this.recruitContext)}get getAttachmentsForRecord(){return yr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return ti(this.recruitContext)}get uploadAttachmentForRecord(){return oi(this.recruitContext)}get downloadAttachmentForRecord(){return ri(this.recruitContext)}get deleteAttachmentFromRecord(){return ni(this.recruitContext)}get createNotes(){return Cr(this.recruitContext)}get deleteNotes(){return li(this.recruitContext)}get createNotesForRecord(){return hi(this.recruitContext)}get getNotesForRecord(){return Tr(this.recruitContext)}get getNotesForRecordPageFactory(){return di(this.recruitContext)}get executeRestApiFunction(){return ai(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return si(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return gr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return ui(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Rr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return pi(this.recruitContext)}get createTagsForModule(){return fi(this.recruitContext)}get getTagsForModule(){return gi(this.recruitContext)}get addTagsToRecords(){return Ri(this.recruitContext)}get removeTagsFromRecords(){return Ci(this.recruitContext)}};Ve=F([Im(),b(0,fu(Nt)),b(1,fu(w))],Ve);import{ConfigModule as xO,ConfigService as AO}from"@nestjs/config";import{Inject as gu,Injectable as bm}from"@nestjs/common";var Ut=class{zohoSign;factoryConfig;static assertValidConfig(t){me(t.zohoSign)}};var ze=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ss({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return is(this.signContext)}get getDocuments(){return _r(this.signContext)}get getDocumentsPageFactory(){return ss(this.signContext)}get getDocumentFormData(){return cs(this.signContext)}get retrieveFieldTypes(){return us(this.signContext)}get downloadPdf(){return ps(this.signContext)}get downloadCompletionCertificate(){return ls(this.signContext)}get createDocument(){return ds(this.signContext)}get createDocumentFromTemplate(){return hs(this.signContext)}get getTemplate(){return ms(this.signContext)}get getTemplates(){return ys(this.signContext)}get updateDocument(){return fs(this.signContext)}get sendDocumentForSignature(){return gs(this.signContext)}get extendDocument(){return Rs(this.signContext)}get deleteDocument(){return Cs(this.signContext)}get getEmbeddedSigningUrl(){return Ts(this.signContext)}};ze=F([bm(),b(0,gu(Ut)),b(1,gu(w))],ze);import{ConfigModule as JO,ConfigService as HO}from"@nestjs/config";function Ru(e){return{...e,operationType:e.notifications.operation_type}}var Cu=sa(e=>e.operationType),Tu=ua({configurerForAccessor:e=>{let t=ca(e,r=>r);return{...e,handleRequestSubmitted:t("RequestSubmitted"),handleRequestViewed:t("RequestViewed"),handleRequestSigningSuccess:t("RequestSigningSuccess"),handleRequestCompleted:t("RequestCompleted"),handleRequestRejected:t("RequestRejected"),handleRequestRecalled:t("RequestRecalled"),handleRequestForwarded:t("RequestForwarded"),handleRequestExpired:t("RequestExpired")}}});var xu="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Je=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as wm,Inject as _m,Post as vm,Req as Nm}from"@nestjs/common";import{Inject as Pm,Injectable as Dm,Logger as Mm}from"@nestjs/common";import{createHmac as km,timingSafeEqual as Om}from"node:crypto";var Em="x-zs-webhook-signature";function Au(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Em],a={valid:!1};if(n){let i=r.toString("utf-8"),s=km("sha256",t).update(i,"utf-8").digest("base64"),c=!1;try{let l=Buffer.from(n,"base64"),h=Buffer.from(s,"base64");l.length===h.length&&(c=Om(l,h))}catch{c=!1}let u;if(c)try{let l=JSON.parse(i);u=Ru(l)}catch{c=!1}c&&u&&(a={valid:!0,event:u})}return a}}var Ze=class{logger=new Mm("ZohoSignWebhookService");_verifier;handler=Cu();configure=Tu(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Au({secret:o})}async updateForWebhook(t,o){let r=await this._verifier(t,o);r.valid?await this.updateForZohoSignEvent(r.event):this.logger.warn("Received invalid Zoho Sign webhook event.",t)}async updateForZohoSignEvent(t){await this.handler(t)||this.logger.warn("Received unexpected/unhandled Zoho Sign webhook event.",t)}};Ze=F([Dm(),b(0,Pm(Je))],Ze);var He=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};F([vm(),b(0,Nm()),b(1,Aa())],He.prototype,"handleZohoSignWebhook",1),He=F([wm("/webhook/zoho/sign"),b(0,_m(Ze))],He);import{Module as Um}from"@nestjs/common";import{ConfigModule as Lm,ConfigService as Gm}from"@nestjs/config";function Km(e){let t={zohoSignWebhook:{webhookSecret:e.get(xu)}};return Je.assertValidConfig(t),t}var So=class{};So=F([Um({imports:[Lm],controllers:[He],providers:[{provide:Je,inject:[Gm],useFactory:Km},Ze],exports:[Ze]})],So);import{Inject as Zu,Injectable as Vm}from"@nestjs/common";var Lt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(me(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var qe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Es({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return vr(this.deskContext)}get getTicketById(){return Ds(this.deskContext)}get searchTickets(){return Nr(this.deskContext)}get getTicketsForContact(){return Ms(this.deskContext)}get getTicketsForProduct(){return ws(this.deskContext)}get getTicketMetrics(){return _s(this.deskContext)}get getAgentsTicketsCount(){return vs(this.deskContext)}get getTicketsPageFactory(){return Ns(this.deskContext)}get searchTicketsPageFactory(){return Us(this.deskContext)}get getDepartments(){return Gs(this.deskContext)}get getDepartmentById(){return Ks(this.deskContext)}get getContacts(){return Lr(this.deskContext)}get getContactById(){return zs(this.deskContext)}get getContactsByIds(){return Js(this.deskContext)}get getContactsPageFactory(){return Hs(this.deskContext)}get getTicketTags(){return qs(this.deskContext)}get associateTicketTags(){return Ws(this.deskContext)}get dissociateTicketTag(){return js(this.deskContext)}get searchTags(){return Bs(this.deskContext)}get getAllTags(){return $s(this.deskContext)}get getTicketFollowers(){return Ys(this.deskContext)}get addTicketFollowers(){return Xs(this.deskContext)}get removeTicketFollowers(){return Qs(this.deskContext)}get getTicketAttachments(){return tc(this.deskContext)}get deleteTicketAttachment(){return oc(this.deskContext)}get getTicketComments(){return nc(this.deskContext)}get getTicketCommentById(){return ac(this.deskContext)}get createTicketComment(){return ic(this.deskContext)}get deleteTicketComment(){return sc(this.deskContext)}get getTicketTimer(){return cc(this.deskContext)}get performTicketTimerAction(){return uc(this.deskContext)}get getTicketTimeEntries(){return pc(this.deskContext)}get getTicketTimeEntryById(){return lc(this.deskContext)}get getTicketTimeEntrySummation(){return dc(this.deskContext)}get getTicketThreads(){return Kr(this.deskContext)}get getTicketThreadById(){return yc(this.deskContext)}get getTicketThreadsPageFactory(){return fc(this.deskContext)}get getTicketActivities(){return Vr(this.deskContext)}get getTicketActivitiesPageFactory(){return gc(this.deskContext)}get getAgents(){return zr(this.deskContext)}get getAgentById(){return Cc(this.deskContext)}get getAgentsByIds(){return Tc(this.deskContext)}get getMyInfo(){return xc(this.deskContext)}get getAgentsPageFactory(){return Ac(this.deskContext)}};qe=F([Vm(),b(0,Zu(Lt)),b(1,Zu(w))],qe);import{ConfigModule as HE,ConfigService as qE}from"@nestjs/config";import{Inject as Su,Injectable as zm}from"@nestjs/common";var Gt=class{zohoAnalytics;factoryConfig;static assertValidConfig(t){me(t.zohoAnalytics)}};var We=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoAnalytics=Kc({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoAnalytics)}zohoAnalytics;get analyticsContext(){return this.zohoAnalytics.analyticsContext}get zohoRateLimiter(){return this.zohoAnalytics.analyticsContext.zohoRateLimiter}get getOrgs(){return Vc(this.analyticsContext)}get getAllWorkspaces(){return zc(this.analyticsContext)}get getOwnedWorkspaces(){return Jc(this.analyticsContext)}get getSharedWorkspaces(){return Hc(this.analyticsContext)}get getWorkspaceDetails(){return qc(this.analyticsContext)}get getViews(){return Wc(this.analyticsContext)}get getViewDetails(){return jc(this.analyticsContext)}get getTableMetadata(){return Bc(this.analyticsContext)}get importDataInTable(){return Yc(this.analyticsContext)}get importDataInNewTable(){return Xc(this.analyticsContext)}get createImportJobInTable(){return jr(this.analyticsContext)}get createImportJobInNewTable(){return Qc(this.analyticsContext)}get getImportJob(){return Br(this.analyticsContext)}get importDataInTableAndAwaitJob(){return eu(this.analyticsContext)}get exportData(){return tu(this.analyticsContext)}get createExportJob(){return $r(this.analyticsContext)}get createExportJobForSqlQuery(){return ou(this.analyticsContext)}get getExportJob(){return Yr(this.analyticsContext)}get downloadExport(){return ru(this.analyticsContext)}get exportDataAndAwaitJob(){return nu(this.analyticsContext)}get addRow(){return au(this.analyticsContext)}get updateRows(){return iu(this.analyticsContext)}get deleteRows(){return su(this.analyticsContext)}get deleteView(){return cu(this.analyticsContext)}get deleteWorkspace(){return uu(this.analyticsContext)}};We=F([zm(),b(0,Su(Gt)),b(1,Su(w))],We);import{ConfigModule as mP,ConfigService as yP}from"@nestjs/config";function Fo(e){return{recruit:e.recruitApi,crm:e.crmApi,desk:e.deskApi,sign:e.signApi,analytics:e.analyticsApi}}function Jm(e){return`${e.clientId}:${e.refreshToken}`}function gt(e){let t=lu([du(),hu(kt())]),o=new Map;function r(R,y){let C=Jm(R),g=o.get(C),S;if(g)S=g;else{let O={zohoAccounts:{serviceAccessTokenKey:y,refreshToken:R.refreshToken,clientId:R.clientId,clientSecret:R.clientSecret,apiUrl:R.region??"us"}};S=new w(O,t),o.set(C,S)}return S}let n,a=Ue(e,"recruit");if(a){let R=r(a,"recruit"),y={zohoRecruit:{apiUrl:a.apiMode}};n=new Ve(y,R)}let i,s=Ue(e,"crm");if(s){let R=r(s,"crm"),y={zohoCrm:{apiUrl:s.apiMode}};i=new Ke(y,R)}let c,u=Ue(e,"desk");if(u?.orgId){let R=r(u,"desk"),y={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new qe(y,R)}let l,h=Ue(e,"sign");if(h){let R=r(h,"sign"),y={zohoSign:{apiUrl:h.apiMode}};l=new ze(y,R)}let f,m=Ue(e,"analytics");if(m){let R=r(m,"analytics"),y={zohoAnalytics:{apiUrl:m.apiMode,orgId:m.orgId}};f=new We(y,R)}return{recruitApi:n,crmApi:i,deskApi:c,signApi:l,analyticsApi:f}}Mo([...Po,/1000\.\w{20,}/g]);function Fu(e){let t;return e instanceof G?t={ok:!1,error:ge(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof it?t={ok:!1,error:ge(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Ce?t={ok:!1,error:ge(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof L?t={ok:!1,error:ge(e.message),code:"API_ERROR"}:t=wo(e),t}pn(e=>e instanceof G||e instanceof it||e instanceof Ce||e instanceof L?Fu(e):void 0);function d(e){console.log(JSON.stringify(Fu(e)))}var Iu={us:"https://accounts.zoho.com",eu:"https://accounts.zoho.eu",in:"https://accounts.zoho.in",au:"https://accounts.zoho.com.au",jp:"https://accounts.zoho.jp"},Xr={recruit:["ZohoRecruit.modules.ALL","ZohoRecruit.settings.all","ZohoRecruit.functions.execute.READ","ZohoRecruit.functions.execute.CREATE"],crm:["ZohoCRM.modules.ALL","ZohoCRM.settings.ALL","ZohoCRM.functions.execute.READ","ZohoCRM.functions.execute.CREATE"],desk:["Desk.tickets.ALL","Desk.tasks.ALL","Desk.contacts.ALL","Desk.settings.ALL","Desk.events.ALL","Desk.search.READ","Desk.articles.READ","Desk.basic.READ"],sign:["ZohoSign.documents.ALL","ZohoSign.templates.ALL"],analytics:["ZohoAnalytics.data.all","ZohoAnalytics.metadata.all","ZohoAnalytics.modeling.all"]},bu="http://localhost/oauth",ku=`Organization ID, for the products scoped by one (${Array.from(Ne).join(", ")})`;function Hm(e){let t;if(!e)t=void 0;else if(e.startsWith("http://")||e.startsWith("https://"))try{let r=new URL(e).searchParams.get("code");if(!r)throw new Error('No "code" parameter found in the provided URL.');t=r}catch(o){throw o instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`,{cause:o}):o}else t=e;return t}var qm={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:bu,describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",defaultDescription:"--product when given, otherwise recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign,analytics)"}).option("code",{type:"string",describe:"Authorization code or the full redirect URL (code is extracted automatically)"}).option("token",{type:"string",describe:"Set a refresh token directly (skips OAuth code exchange)"}).option("product",{type:"string",choices:[...It],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:ku}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth setup --client-id 1000.ABC --client-secret xyz","Step 1: Get OAuth URL (saves shared credentials)"],["$0 auth setup --code 1000.AUTH.CODE","Step 2: Exchange code for refresh token"],['$0 auth setup --code "http://localhost/oauth?code=1000.AUTH.CODE&location=us"',"Step 2: Paste the full redirect URL"],["$0 auth setup --client-id 1000.ABC --client-secret xyz --token 1000.REFRESH.TOKEN","Set shared refresh token directly"],["$0 auth setup --product crm --client-id 1000.CRM --client-secret xyz --token 1000.CRM.TOKEN","Set CRM-specific credentials"],["$0 auth setup --product sign --client-id 1000.SIGN --client-secret xyz","Sign uses a separate OAuth client (sign-only scopes)"],["$0 auth setup --product analytics --client-id 1000.ANALYTICS --client-secret xyz --org-id 1234567","Analytics uses a separate OAuth client; --scopes defaults to analytics"]]),handler:async e=>{try{let t=await B(),o=Bm(e,t);if(!o.clientId||!o.clientSecret)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");o.token?await $m(o,t):o.code?await Ym(o,t):await Qm(o,t)}catch(t){d(t),process.exit(1)}}},Wm="recruit,crm,desk";function jm(e,t){return(e??t??Wm).split(",").map(o=>o.trim())}function Bm(e,t){let o=e.region??t?.shared?.region??"us",r=e.product,n=r?t?.[r]:void 0;return{product:r,clientId:e.clientId??n?.clientId??t?.shared?.clientId,clientSecret:e.clientSecret??n?.clientSecret??t?.shared?.clientSecret,redirectUri:e.redirectUri??bu,region:o,scopes:jm(e.scopes,r),code:Hm(e.code),token:e.token,accountsUrl:Iu[o]??Iu.us,apiMode:e.apiMode,orgId:e.orgId}}function Qr({product:e,credentials:t,apiMode:o,orgId:r}){return{...t,apiUrl:o??void 0,orgId:Ne.has(e)?r??void 0:void 0}}async function Ou(e,t,o){return e.product?ae({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:Qr({product:e.product,credentials:t,apiMode:e.apiMode,orgId:e.orgId})}):ae({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function $m(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await Ou(e,o,t?.shared);p({success:!0,...e.product?{product:e.product}:{},refreshToken:Ie(e.token),configSaved:!0,configuredProducts:ue(r)})}async function Ym(e,t){let o=`${e.accountsUrl}/oauth/v2/token`,r=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUri,code:e.code}),a=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()})).json();if(a.error)throw new Error(`Token exchange failed: ${a.error}`);let i=a.refresh_token;if(!i)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let s={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:i},c=await Ou(e,s,t?.shared);p({step:2,success:!0,product:e.product??"shared",refreshToken:Ie(i),accessToken:a.access_token?Ie(a.access_token):null,scope:a.scope,configSaved:!0,configuredProducts:ue(c)})}async function Xm(e,t){let o;return e.product?o=await ae({shared:{clientId:t?.shared?.clientId??"",clientSecret:t?.shared?.clientSecret??"",refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},[e.product]:Qr({product:e.product,credentials:{clientId:e.clientId,clientSecret:e.clientSecret},apiMode:e.apiMode,orgId:e.orgId})}):o=await ae({shared:{clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),o}async function Qm(e,t){let o=e.product?Xr[e.product]??[]:e.scopes.flatMap(a=>Xr[a]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Xr).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;await Xm(e,t);let n=e.product?`--product ${e.product} `:"";p({step:1,product:e.product??"shared",instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:r,redirectUri:e.redirectUri,scopes:o,credentialsSaved:!0,nextStep:`zoho-cli auth setup ${n}--code "PASTE_REDIRECT_URL_OR_AUTH_CODE"`})}var ey={command:"set",describe:"Save Zoho API credentials directly",builder:e=>e.option("client-id",{type:"string",demandOption:!0,describe:"OAuth client ID"}).option("client-secret",{type:"string",demandOption:!0,describe:"OAuth client secret"}).option("refresh-token",{type:"string",demandOption:!0,describe:"OAuth refresh token"}).option("product",{type:"string",choices:[...It],describe:"Store for a specific product instead of shared"}).option("region",{type:"string",default:"us",describe:"Zoho region (us, eu, in, au, jp)"}).option("org-id",{type:"string",describe:ku}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth set --client-id abc --client-secret xyz --refresh-token 1000.abc.xyz","Set shared credentials"],["$0 auth set --product crm --client-id abc --client-secret xyz --refresh-token 1000.crm.xyz","Set CRM-specific credentials"]]),handler:async e=>{try{let t=e.product,o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken},r;t?r=await ae({shared:(await B())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:Qr({product:t,credentials:o,apiMode:e.apiMode,orgId:e.orgId})}):r=await ae({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),p({saved:!0,product:t??"shared",configuredProducts:ue(r)})}catch(t){d(t),process.exit(1)}}};function Eu(e){return e?{clientId:e.clientId?Ie(e.clientId):void 0,clientSecret:e.clientSecret?Ie(e.clientSecret):void 0,refreshToken:e.refreshToken?Ie(e.refreshToken):void 0}:void 0}function ty(e,t){return t?{...Eu(t),apiUrl:t.apiUrl,...Ne.has(e)?{orgId:t.orgId}:{}}:null}function oy(e){let t=Object.fromEntries(It.map(o=>[o,ty(o,e[o])]));return{configured:!0,shared:{...Eu(e.shared),region:e.shared?.region??"us",apiMode:e.shared?.apiMode??"production"},...t,configuredProducts:ue(e)}}var ry={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let e=await B();p(e?oy(e):{configured:!1})}catch(e){d(e),process.exit(1)}}},ny={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await B();if(e){let t=ue(e);if(t.length===0)p({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=gt(e),r=Fo(o),n={};for(let a of t)try{let i=r[a];if(!i){n[a]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();n[a]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let s=i instanceof Error?i.message:String(i);n[a]={authenticated:!1,error:s}}p({products:n})}}else p({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){d(e),process.exit(1)}}},ay={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Ma(),p({cleared:!0})}catch(e){d(e),process.exit(1)}}},Pu={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(qm).command(ey).command(ry).command(ny).command(ay).demandCommand(1,"Please specify an auth subcommand."),handler:A};import{access as iy,constants as sy}from"node:fs";import{dirname as cy}from"node:path";function uy(e){return e.every(t=>t.status==="pass")}var Du={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await B(),t=[];t.push(py(e));let o=ly(e);if(o&&t.push(o),t.push(await dy()),e){let n=ue(e);t.push(hy(n),...await my(e,n),...fy(e,n))}let r=uy(t);p({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function py(e){return e?{name:"config",status:"pass",message:`Config loaded from ${bt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function ly(e){if(e?.shared?.clientId&&e?.shared?.clientSecret&&e?.shared?.refreshToken)return{name:"shared-credentials",status:"pass",message:"Shared credentials present"};if(e)return{name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."}}async function dy(){let e=cy(kt());return await gy(e)?{name:"token-cache",status:"pass",message:`Token cache directory writable: ${e}`}:{name:"token-cache",status:"warn",message:`Token cache directory not writable: ${e}`}}function hy(e){return e.length>0?{name:"products",status:"pass",message:`Configured products: ${e.join(", ")}`}:{name:"products",status:"fail",message:"No products have complete credentials"}}async function my(e,t){let o=Fo(gt(e)),r=[];for(let n of t)r.push(await yy(o[n],n));return r}async function yy(e,t){if(!e)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let o;try{let r=await e.zohoAccountsApi.accessToken();o={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${r.scope}`}}catch(r){let n=r instanceof Error?r.message:String(r);o={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${n}`}}return o}function fy(e,t){return Array.from(Ne).map(o=>{let r=e[o]?.orgId,n=`${o}-org-id`,a;return r?a={name:n,status:"pass",message:`${o}: Org ID configured: ${r}`}:t.includes(o)?a={name:n,status:"fail",message:`${o}: No org ID configured, but ${o} is reported as configured \u2014 every org-scoped ${o} command will fail. Run: zoho-cli auth set --product ${o} --org-id <ORG_ID>`}:a={name:n,status:"warn",message:`${o}: No org ID. ${o} commands unavailable.`},a})}function gy(e){return new Promise(t=>{iy(e,sy.W_OK,o=>{t(!o)})})}var Mu=ba({notInitializedMessage:"CLI context not initialized. This is a bug."});function wu(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await B();r||(d(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),ue(r).length===0&&(d(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Mu.set(gt(r))}catch(r){d(r),process.exit(4)}}}function Kt(e){return Mu.require()}function oe(e){let{recruitApi:t}=Kt(e);if(!t)throw new Error("Recruit not configured. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z");return t}function re(e){let{crmApi:t}=Kt(e);if(!t)throw new Error("CRM not configured. Run: zoho-cli auth setup --product crm --client-id X --client-secret Y --token Z");return t}function Z(e){let{deskApi:t}=Kt(e);if(!t)throw new Error("Desk not configured. Run: zoho-cli auth setup --product desk --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function N(e){let{signApi:t}=Kt(e);if(!t)throw new Error("Sign not configured. Zoho Sign requires its own OAuth client. Run: zoho-cli auth setup --product sign --client-id X --client-secret Y --token Z");return t}function E(e){let{analyticsApi:t}=Kt(e);if(!t)throw new Error("Analytics not configured. Zoho Analytics requires its own OAuth client. Run: zoho-cli auth setup --product analytics --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function ye(e){return Qt(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function D(e){return Qt(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function Io(e){return Qt(e.option("start-index",{type:"number",default:1,describe:"Start index (1-based)"}).option("row-count",{type:"number",default:20,describe:"Records per page"}))}function U(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function De(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function Vt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function bo(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}var Ry={nextInput:(e,t)=>{let o;if(t.info?.more_records){let r=e.page??1;o={...e,page:r+1}}else o=void 0;return o},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},M={nextInput:(e,t)=>{let o=e.limit??25,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let a=e.from??1;n={...e,from:a+o}}return n},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25,r=t.data?.length??0;return o>0&&r>=o}},Cy={nextInput:(e,t)=>{let o;if(t.page_context?.has_more_rows){let r=e.row_count??t.page_context?.row_count??20,n=e.start_index??t.page_context?.start_index??1;o={...e,start_index:n+r}}else o=void 0;return o},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({start_index:t.page_context?.start_index??e.start_index,row_count:t.page_context?.row_count??e.row_count,total_count:t.page_context?.total_count,has_more_rows:t.page_context?.has_more_rows??!1}),hasMorePagesAvailable:(e,t)=>t.page_context?.has_more_rows??!1};async function fe(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Ry,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let a=n.result;p(a.data,{page:a.info?.page,per_page:a.info?.per_page,more_records:a.info?.more_records})}}async function ko(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:async a=>{let i=await r(a);return{data:i.requests??[],page_context:i.page_context}},adapter:Cy,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let a=n.result;p(a.data,{start_index:a.page_context?.start_index,row_count:a.page_context?.row_count,total_count:a.page_context?.total_count,has_more_rows:a.page_context?.has_more_rows??!1})}}var Ty={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)))),handler:async e=>{try{let t=oe(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},xy={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await oe(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Ay={command:"search",describe:"Search records in a module",builder:e=>ye(U(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=oe(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Zy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Sy={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Fy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=oe(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Iy={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=oe(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},by={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},ky={command:"attachments",describe:"Get attachments for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=oe(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},_u={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(Ty).command(xy).command(Ay).command(Zy).command(Sy).command(Fy).command(Iy).command(by).command(ky).demandCommand(1,"Please specify a recruit subcommand.").example([["$0 recruit list -m Candidates --per-page 10","List first 10 candidates"],["$0 recruit get -m Candidates --id 12345","Get a candidate by ID"],['$0 recruit search -m Candidates --word "John"',"Search candidates by keyword"],[`$0 recruit insert -m Candidates --data '{"First_Name":"John","Last_Name":"Doe"}'`,"Insert a candidate"]]),handler:A};var Oy={command:"list",describe:"List records from a module",builder:e=>bo(Vt(ye(U(e)),!0)),handler:async e=>{try{let t=re(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await fe({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){d(t),process.exit(1)}}},Ey={command:"get",describe:"Get a record by ID",builder:e=>De(U(e)),handler:async e=>{try{let o=await re(e).getRecordById({module:e.module,id:e.id});p(o)}catch(t){d(t),process.exit(1)}}},Py={command:"search",describe:"Search records in a module",builder:e=>ye(U(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=re(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){d(t),process.exit(1)}}},Dy={command:"insert",describe:"Insert a record into a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},My={command:"upsert",describe:"Upsert a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},wy={command:"update",describe:"Update a record in a module",builder:e=>U(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=re(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});p(r)}catch(t){d(t),process.exit(1)}}},_y={command:"delete",describe:"Delete records from a module",builder:e=>U(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=re(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});p(r)}catch(t){d(t),process.exit(1)}}},vy={command:"emails",describe:"Get emails for a record",builder:e=>ye(De(U(e))),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){d(t),process.exit(1)}}},Ny={command:"attachments",describe:"Get attachments for a record",builder:e=>Vt(ye(De(U(e))),!0),handler:async e=>{try{let t=re(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await fe({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){d(t),process.exit(1)}}},vu={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Oy).command(Ey).command(Py).command(Dy).command(My).command(wy).command(_y).command(vy).command(Ny).demandCommand(1,"Please specify a CRM subcommand.").example([['$0 crm list -m Contacts --fields "First_Name,Last_Name,Email" --per-page 10',"List contacts"],["$0 crm get -m Contacts --id 12345","Get a contact by ID"],['$0 crm search -m Leads --word "Acme"',"Search leads by keyword"],[`$0 crm insert -m Contacts --data '{"First_Name":"Jane","Last_Name":"Doe"}'`,"Insert a contact"]]),handler:A};var Uy={command:"list",describe:"List tickets",builder:e=>D(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status"}).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ly={command:"get <ticketId>",describe:"Get a ticket by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let o=await Z(e).getTicketById({ticketId:e.ticketId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Gy={command:"search",describe:"Search tickets",builder:e=>D(e).option("subject",{type:"string",describe:"Search by subject"}).option("status",{type:"string",describe:"Filter by status"}).option("email",{type:"string",describe:"Filter by email"}).option("department-id",{type:"string",describe:"Filter by department ID"}).option("channel",{type:"string",describe:"Filter by channel"}).option("priority",{type:"string",describe:"Filter by priority"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,subject:e.subject,status:e.status,email:e.email,departmentId:e.departmentId,channel:e.channel,priority:e.priority},r=await k({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Ky={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>D(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=Z(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Vy={command:"metrics <ticketId>",describe:"Get ticket metrics",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await Z(e).getTicketMetrics({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},zy={command:"agent-counts",describe:"Get ticket counts per agent",builder:e=>e.option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}).option("department-id",{type:"string",describe:"Filter by department ID"}),handler:async e=>{try{let t=Z(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});p(r)}catch(t){d(t),process.exit(1)}}},Nu={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Uy).command(Ly).command(Gy).command(Ky).command(Vy).command(zy).demandCommand(1),handler:A};var Jy={command:"list",describe:"List departments",builder:e=>D(e).option("search",{type:"string",describe:"Search by name"}).option("is-enabled",{type:"boolean",describe:"Filter by enabled status"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await k({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Hy={command:"get <departmentId>",describe:"Get a department by ID",builder:e=>e.positional("departmentId",{type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let o=await Z(e).getDepartmentById({departmentId:e.departmentId});p(o)}catch(t){d(t),process.exit(1)}}},Uu={command:"departments",describe:"Desk department operations",builder:e=>e.command(Jy).command(Hy).demandCommand(1),handler:A};var qy={command:"list",describe:"List contacts",builder:e=>D(e).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wy={command:"get <contactId>",describe:"Get a contact by ID",builder:e=>e.positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await Z(e).getContactById({contactId:e.contactId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},Lu={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(qy).command(Wy).demandCommand(1),handler:A};var jy={command:"list",describe:"List agents",builder:e=>D(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status (active, disabled)"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. role,profile,departments)"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},By={command:"get <agentId>",describe:"Get an agent by ID",builder:e=>e.positional("agentId",{type:"string",demandOption:!0,describe:"Agent ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await Z(e).getAgentById({agentId:e.agentId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},$y={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await Z(e).getMyInfo();p(o)}catch(t){d(t),process.exit(1)}}},Gu={command:"agents",describe:"Desk agent operations",builder:e=>e.command(jy).command(By).command($y).demandCommand(1),handler:A};var Yy={command:"list",describe:"List all tags",builder:e=>D(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await k({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Xy={command:"search",describe:"Search tags",builder:e=>D(e).option("department-id",{alias:"d",type:"string",describe:"Department ID"}).option("query",{alias:"q",type:"string",demandOption:!0,describe:"Search string"}),handler:async e=>{try{let t=Z(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await k({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Qy={command:"for-ticket <ticketId>",describe:"Get tags on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await Z(e).getTicketTags({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},ef={command:"associate <ticketId>",describe:"Add tags to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tags",{type:"string",demandOption:!0,describe:"Comma-separated tag names"}),handler:async e=>{try{let t=Z(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});p(r)}catch(t){d(t),process.exit(1)}}},tf={command:"dissociate <ticketId>",describe:"Remove a tag from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tag-id",{type:"string",demandOption:!0,describe:"Tag ID to remove"}),handler:async e=>{try{await Z(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ku={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Yy).command(Xy).command(Qy).command(ef).command(tf).demandCommand(1),handler:A};var of={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await k({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},rf={command:"get <ticketId> <commentId>",describe:"Get a comment by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{let o=await Z(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});p(o)}catch(t){d(t),process.exit(1)}}},nf={command:"create <ticketId>",describe:"Create a comment on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("content",{type:"string",demandOption:!0,describe:"Comment content"}).option("public",{type:"boolean",default:!1,describe:"Make comment public"}).option("content-type",{type:"string",default:"plainText",choices:["plainText","html"],describe:"Content type"}),handler:async e=>{try{let o=await Z(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});p(o)}catch(t){d(t),process.exit(1)}}},af={command:"delete <ticketId> <commentId>",describe:"Delete a comment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{await Z(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},Vu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(of).command(rf).command(nf).command(af).demandCommand(1),handler:A};var sf={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},cf={command:"delete <ticketId> <attachmentId>",describe:"Delete an attachment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("attachmentId",{type:"string",demandOption:!0,describe:"Attachment ID"}),handler:async e=>{try{await Z(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),p({deleted:!0})}catch(t){d(t),process.exit(1)}}},zu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(sf).command(cf).demandCommand(1),handler:A};var uf={command:"list <ticketId>",describe:"List followers of a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await Z(e).getTicketFollowers({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},pf={command:"add <ticketId>",describe:"Add followers to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({added:!0})}catch(t){d(t),process.exit(1)}}},lf={command:"remove <ticketId>",describe:"Remove followers from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=Z(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),p({removed:!0})}catch(t){d(t),process.exit(1)}}},Ju={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(uf).command(pf).command(lf).demandCommand(1),handler:A};var df={command:"timer <ticketId>",describe:"Get current timer state for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await Z(e).getTicketTimer({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},hf={command:"timer-action <ticketId>",describe:"Start, pause, resume, or stop a timer",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("action",{type:"string",demandOption:!0,choices:["start","pause","resume","stop"],describe:"Timer action"}),handler:async e=>{try{let o=await Z(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});p(o)}catch(t){d(t),process.exit(1)}}},mf={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},yf={command:"summation <ticketId>",describe:"Get time entry summation for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await Z(e).getTicketTimeEntrySummation({ticketId:e.ticketId});p(o)}catch(t){d(t),process.exit(1)}}},Hu={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(df).command(hf).command(mf).command(yf).demandCommand(1),handler:A};var ff={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},gf={command:"get <ticketId> <threadId>",describe:"Get a thread by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("threadId",{type:"string",demandOption:!0,describe:"Thread ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await Z(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});p(o)}catch(t){d(t),process.exit(1)}}},qu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(ff).command(gf).demandCommand(1),handler:A};var Rf={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>D(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=Z(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:M,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;p(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){d(t),process.exit(1)}}},Wu={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Rf).demandCommand(1),handler:A};var ju={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(Nu).command(Uu).command(Lu).command(Gu).command(Ku).command(Vu).command(zu).command(Ju).command(Hu).command(qu).command(Wu).demandCommand(1,"Please specify a desk subcommand.").example([["$0 desk tickets list --limit 10","List first 10 tickets"],["$0 desk tickets get 12345","Get a ticket by ID"],["$0 desk agents my-info","Get current agent info"],['$0 desk comments create 12345 --content "Looking into this"',"Add a comment"]]),handler:A};import{readFile as Cf,writeFile as Bu}from"node:fs/promises";import{basename as Tf}from"node:path";function xf(e){let t={};return e.requestName&&(t.request_name=e.requestName),e.folderName&&(t.folder_name=e.folderName),e.ownerFullName&&(t.owner_full_name=e.ownerFullName),e.recipientEmail&&(t.recipient_email=e.recipientEmail),e.recipientName&&(t.recipient_name=e.recipientName),e.formName&&(t.form_name=e.formName),Object.keys(t).length>0?t:void 0}var Af={command:"list",describe:"List sign requests (documents)",builder:e=>Io(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. request_name, created_time, recipient_email)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("request-name",{type:"string",describe:"Filter by request name"}).option("folder-name",{type:"string",describe:"Filter by folder name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}).option("recipient-email",{type:"string",describe:"Filter by recipient email"}).option("recipient-name",{type:"string",describe:"Filter by recipient name"}).option("form-name",{type:"string",describe:"Filter by form name"}),handler:async e=>{try{let t=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:xf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getDocuments(r)})}catch(t){d(t),process.exit(1)}}},Zf={command:"get <requestId>",describe:"Get a sign request by ID",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}),handler:async e=>{try{let o=await N(e).getDocument({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Sf={command:"form-data <requestId>",describe:"Get filled form-field values for a completed request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}),handler:async e=>{try{let o=await N(e).getDocumentFormData({requestId:e.requestId});p(o)}catch(t){d(t),process.exit(1)}}},Ff={command:"create",describe:"Create a draft sign request from a local file",builder:e=>e.option("file",{type:"string",demandOption:!0,describe:"Path to the local document to upload"}).option("data",{type:"string",demandOption:!0,describe:"JSON request data (ZohoSignRequestData: request_name, is_sequential, actions, ...)"}).option("content-type",{type:"string",default:"application/pdf",describe:"MIME type of the uploaded file"}),handler:async e=>{try{let t=N(e),o=JSON.parse(e.data),r=await Cf(e.file),n=new File([r],Tf(e.file),{type:e.contentType}),a=await t.createDocument({requestData:o,file:n});p(a)}catch(t){d(t),process.exit(1)}}},If={command:"create-from-template",describe:"Create a sign request from a template",builder:e=>e.option("template-id",{type:"string",demandOption:!0,describe:"Template ID"}).option("data",{type:"string",demandOption:!0,describe:"JSON template data (ZohoSignCreateDocumentFromTemplateData: request_name, actions, field_data, ...)"}).option("quick-send",{type:"boolean",default:!0,describe:"Send immediately (true) or leave as a draft (false)"}),handler:async e=>{try{let t=N(e),o=JSON.parse(e.data),r=await t.createDocumentFromTemplate({templateId:e.templateId,data:o,isQuickSend:e.quickSend});p(r)}catch(t){d(t),process.exit(1)}}},bf={command:"update <requestId>",describe:"Update a draft sign request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("data",{type:"string",demandOption:!0,describe:"JSON partial request data to apply"}),handler:async e=>{try{let t=N(e),o=JSON.parse(e.data),r=await t.updateDocument({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},kf={command:"send <requestId>",describe:"Submit a draft request to its recipients for signing",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("data",{type:"string",describe:"Optional JSON partial request data to apply before sending"}),handler:async e=>{try{let t=N(e),o=e.data?JSON.parse(e.data):void 0,r=await t.sendDocumentForSignature({requestId:e.requestId,data:o});p(r)}catch(t){d(t),process.exit(1)}}},Of={command:"extend <requestId>",describe:"Extend the expiration date of an in-progress request",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("expire-by",{type:"string",demandOption:!0,describe:'New expiration date string (e.g. "30 November 2024")'}),handler:async e=>{try{let o=await N(e).extendDocument({requestId:e.requestId,expire_by:e.expireBy});p(o)}catch(t){d(t),process.exit(1)}}},Ef={command:"delete <requestId>",describe:"Delete a request (optionally recalling an in-progress one)",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("recall-inprogress",{type:"boolean",describe:"Recall an in-progress request before deleting"}).option("reason",{type:"string",describe:"Reason for recalling/deleting"}),handler:async e=>{try{let o=await N(e).deleteDocument({requestId:e.requestId,recall_inprogress:e.recallInprogress,reason:e.reason});p(o)}catch(t){d(t),process.exit(1)}}},Pf={command:"download <requestId>",describe:"Download the signed PDF (or ZIP) for a request to a local file",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("output",{type:"string",demandOption:!0,describe:"Path to write the downloaded file to"}).option("with-coc",{type:"boolean",describe:"Include the completion certificate"}).option("merge",{type:"boolean",describe:"Merge all signed documents into one file"}).option("password",{type:"string",describe:"Password for protected documents"}),handler:async e=>{try{let o=await N(e).downloadPdf({requestId:e.requestId,with_coc:e.withCoc,merge:e.merge,password:e.password});if(!o.ok)throw new Error(`Download failed with status ${o.status}`);let r=Buffer.from(await o.arrayBuffer());await Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Df={command:"certificate <requestId>",describe:"Download the completion certificate PDF for a request to a local file",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).option("output",{type:"string",demandOption:!0,describe:"Path to write the certificate to"}),handler:async e=>{try{let o=await N(e).downloadCompletionCertificate({requestId:e.requestId});if(!o.ok)throw new Error(`Certificate download failed with status ${o.status}`);let r=Buffer.from(await o.arrayBuffer());await Bu(e.output,r),p({saved:!0,path:e.output,bytes:r.length})}catch(t){d(t),process.exit(1)}}},Mf={command:"embed-url <requestId> <actionId>",describe:"Generate an embedded signing URL for a recipient action",builder:e=>e.positional("requestId",{type:"string",demandOption:!0,describe:"Request (envelope) ID"}).positional("actionId",{type:"string",demandOption:!0,describe:"Recipient action ID"}).option("host",{type:"string",demandOption:!0,describe:"Hosting origin embedded in the token (https required in production)"}),handler:async e=>{try{let o=await N(e).getEmbeddedSigningUrl({requestId:e.requestId,actionId:e.actionId,host:e.host});p(o)}catch(t){d(t),process.exit(1)}}},$u={command:"documents",describe:"Zoho Sign document (request) operations",builder:e=>e.command(Af).command(Zf).command(Sf).command(Ff).command(If).command(bf).command(kf).command(Of).command(Ef).command(Pf).command(Df).command(Mf).demandCommand(1,"Please specify a documents subcommand.").example([["$0 sign documents list --row-count 10","List first 10 sign requests"],["$0 sign documents get 12345","Get a request by ID"],[`$0 sign documents create --file ./nda.pdf --data '{"request_name":"NDA","is_sequential":true,"actions":[{"action_type":"SIGN","recipient_name":"Jane","recipient_email":"jane@example.com"}]}'`,"Create a draft from a file"],["$0 sign documents download 12345 --output ./signed.pdf --with-coc --merge","Download the signed PDF"]]),handler:A};function wf(e){let t={};return e.templateName&&(t.template_name=e.templateName),e.ownerFullName&&(t.owner_full_name=e.ownerFullName),Object.keys(t).length>0?t:void 0}var _f={command:"list",describe:"List templates",builder:e=>Io(e).option("sort-column",{type:"string",describe:"Column to sort by (e.g. template_name, created_time)"}).option("sort-order",{type:"string",choices:["ASC","DESC"],describe:"Sort direction"}).option("template-name",{type:"string",describe:"Filter by template name"}).option("owner-full-name",{type:"string",describe:"Filter by owner full name"}),handler:async e=>{try{let t=N(e),o={start_index:e.startIndex,row_count:e.rowCount,sort_column:e.sortColumn,sort_order:e.sortOrder,search_columns:wf(e)};await ko({argv:e,initialInput:o,fetchPage:r=>t.getTemplates(r)})}catch(t){d(t),process.exit(1)}}},vf={command:"get <templateId>",describe:"Get a template by ID",builder:e=>e.positional("templateId",{type:"string",demandOption:!0,describe:"Template ID"}),handler:async e=>{try{let o=await N(e).getTemplate({templateId:e.templateId});p(o)}catch(t){d(t),process.exit(1)}}},Yu={command:"templates",describe:"Zoho Sign template operations",builder:e=>e.command(_f).command(vf).demandCommand(1,"Please specify a templates subcommand.").example([["$0 sign templates list --row-count 10","List first 10 templates"],["$0 sign templates get 286906000001616000","Get a template by ID"]]),handler:A};var Nf={command:"field-types",describe:"List available document field types",builder:e=>e,handler:async e=>{try{let o=await N(e).retrieveFieldTypes();p(o)}catch(t){d(t),process.exit(1)}}},Xu={command:"sign",describe:"Zoho Sign operations",builder:e=>e.command($u).command(Yu).command(Nf).demandCommand(1,"Please specify a sign subcommand.").example([["$0 sign documents list --row-count 10","List first 10 sign requests"],["$0 sign templates list","List templates"],["$0 sign documents get 12345","Get a request by ID"],["$0 sign field-types","List available field types"]]),handler:A};var Uf={command:"list",describe:"List the organizations available to the authenticated user",handler:async e=>{try{let o=await E(e).getOrgs();p(o.data.orgs,{count:o.data.orgs?.length})}catch(t){d(t),process.exit(1)}}},Qu={command:"orgs",describe:"Analytics organization operations",builder:e=>e.command(Uf).demandCommand(1).example([["$0 analytics orgs list","Find the org id needed by every other Analytics command"]]),handler:A};var Lf={command:"list",describe:"List all accessible workspaces",builder:e=>e.option("owned",{type:"boolean",describe:"Only workspaces owned by the authenticated user"}).option("shared",{type:"boolean",describe:"Only workspaces shared with the authenticated user"}),handler:async e=>{try{let t=E(e);if(e.owned){let o=await t.getOwnedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else if(e.shared){let o=await t.getSharedWorkspaces();p(o.data.workspaces,{count:o.data.workspaces?.length})}else{let o=await t.getAllWorkspaces();p(o.data)}}catch(t){d(t),process.exit(1)}}},Gf={command:"get <workspaceId>",describe:"Get a workspace by ID",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getWorkspaceDetails({workspaceId:e.workspaceId});p(o.data.workspaces)}catch(t){d(t),process.exit(1)}}};function Kf(e,t){if(!t)throw new Error(`Deleting a workspace cannot be undone. Re-run with --confirm ${e} to proceed.`);if(t!==e)throw new Error(`--confirm ${t} does not match the workspace being deleted (${e}).`);return e}var Vf={command:"delete <workspaceId>",describe:"Delete a workspace and everything in it. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("confirm",{type:"string",describe:"Repeat the workspace ID to confirm. Required"}),handler:async e=>{try{let t=Kf(e.workspaceId,e.confirm);await E(e).deleteWorkspace({workspaceId:t}),p({deleted:!0,workspaceId:t})}catch(t){d(t),process.exit(1)}}},ep={command:"workspaces",describe:"Analytics workspace operations",builder:e=>e.command(Lf).command(Gf).command(Vf).demandCommand(1).example([["$0 analytics workspaces list","List owned and shared workspaces"],["$0 analytics workspaces list --owned","List only owned workspaces"],["$0 analytics workspaces delete 1767024000000060001 --confirm 1767024000000060001","Delete a workspace, confirming the id"]]),handler:A};var zf={command:"list <workspaceId>",describe:"List the views of a workspace",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}),handler:async e=>{try{let o=await E(e).getViews({workspaceId:e.workspaceId});p(o.data.views,{count:o.data.views?.length})}catch(t){d(t),process.exit(1)}}},Jf={command:"get <viewId>",describe:"Get a view by ID",builder:e=>e.positional("viewId",{type:"string",demandOption:!0,describe:"View ID (globally unique, no workspace needed)"}),handler:async e=>{try{let o=await E(e).getViewDetails({viewId:e.viewId});p(o.data.views)}catch(t){d(t),process.exit(1)}}},Hf={command:"columns <workspaceId> <viewId>",describe:"List the columns of a table",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}),handler:async e=>{try{let o=await E(e).getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId});p(o.data.columns,{count:o.data.columns?.length})}catch(t){d(t),process.exit(1)}}},qf={command:"delete <workspaceId> <viewId>",describe:"Delete a view. This cannot be undone",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("dependent-views",{type:"boolean",default:!1,describe:"Also delete the reports, dashboards and query tables built on this view"}),handler:async e=>{try{await E(e).deleteView({workspaceId:e.workspaceId,viewId:e.viewId,config:{deleteDependentViews:e.dependentViews}}),p({deleted:!0,workspaceId:e.workspaceId,viewId:e.viewId,deletedDependentViews:e.dependentViews})}catch(t){d(t),process.exit(1)}}},tp={command:"views",describe:"Analytics view operations",builder:e=>e.command(zf).command(Jf).command(Hf).command(qf).demandCommand(1).example([["$0 analytics views list 1767024000000060001","List the views of a workspace"],["$0 analytics views columns 1767024000000060001 1767024000000149001","Inspect a table before importing into it"],["$0 analytics views delete 1767024000000060001 1767024000000149001",'Drop a table created by "import new-table"']]),handler:A};import{readFile as Wf}from"node:fs/promises";import{basename as jf,extname as op}from"node:path";var Bf=["append","truncateadd","updateadd"],$f=["abort","skiprow","setcolumnempty"];async function rp(e){let t=await Wf(e,"utf8"),o=jf(e),r=op(e).toLowerCase()===".json"?"application/json":"text/csv";return Ra({content:t,fileName:o,mimeType:r})}function Oo(e){let t=op(e).toLowerCase();return{".json":"json",".csv":"csv"}[t]}function Yf(e,t){let o=t?.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e==="updateadd"&&!o?.length)throw new Error("The updateadd mode requires --matching-columns.");return o?.length?o:void 0}function np(e){return e.option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file to import"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("on-error",{type:"string",choices:$f,describe:"What to do when a row cannot be imported"}).option("async",{type:"boolean",default:!1,describe:"Queue the import as a job and poll it, rather than waiting on one request"})}var Xf={command:"data <workspaceId> <viewId>",describe:"Import a file into an existing table",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("mode",{alias:"m",type:"string",choices:Bf,default:"append",describe:"append adds rows, truncateadd replaces every row, updateadd upserts on --matching-columns"}).option("matching-columns",{type:"string",describe:"Comma-separated columns to match on. Required for the updateadd mode"}),handler:async e=>{try{let t=E(e),o=e.mode,r=Yf(o,e.matchingColumns),n=await rp(e.file),a={importType:o,fileType:e.fileType??Oo(e.file),onError:e.onError,matchingColumns:r};if(e.async){let i=await t.importDataInTableAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:a}),{jobCode:s,jobStatus:c,jobInfo:u}=i.data;p({jobCode:s,jobStatus:c,...u},{complete:Pe(s)})}else{let i=await t.importDataInTable({workspaceId:e.workspaceId,viewId:e.viewId,file:n,config:a});p(i.data)}}catch(t){d(t),process.exit(1)}}},Qf={command:"new-table <workspaceId> <tableName>",describe:"Create a table in a workspace from an imported file",builder:e=>np(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("tableName",{type:"string",demandOption:!0,describe:"Name of the table to create"}),handler:async e=>{try{let t=E(e),o=await rp(e.file),r={tableName:e.tableName,fileType:e.fileType??Oo(e.file),onError:e.onError};if(e.async){let n=await t.createImportJobInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}else{let n=await t.importDataInNewTable({workspaceId:e.workspaceId,file:o,config:r});p(n.data)}}catch(t){d(t),process.exit(1)}}},eg={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous import job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Import job ID"}),handler:async e=>{try{let o=await E(e).getImportJob({workspaceId:e.workspaceId,jobId:e.jobId});p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ap={command:"import",describe:"Analytics import operations",builder:e=>e.command(Xf).command(Qf).command(eg).demandCommand(1).example([["$0 analytics import data WS VIEW -f rows.csv","Append the rows of a CSV to a table"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace every row in a table"],["$0 analytics import data WS VIEW -f big.csv --async","Queue a large import and poll it"],["$0 analytics import new-table WS Sales -f rows.csv","Create a table from a CSV"]]),handler:A};import{writeFile as tg}from"node:fs/promises";var og=["csv","json","xml","xls","pdf","html","image"];async function en(e,t){let o=await e.text(),r;return t?await tg(t,o,"utf8"):r=o,r}function ip(e){return e.option("format",{type:"string",choices:og,default:"csv",describe:"Format of the exported data"}).option("out",{alias:"o",type:"string",describe:"Write the export to this file instead of printing it"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("columns",{type:"string",describe:"Comma-separated columns to export"})}function rg(e){let t=e?.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t?.length?t:void 0}function sp(e){return{responseFormat:e.format,criteria:e.criteria,selectedColumns:rg(e.columns)}}var ng={command:"data <workspaceId> <viewId>",describe:"Export the data of a view",builder:e=>ip(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"View ID"}).option("async",{type:"boolean",default:!1,describe:"Queue the export as a job and poll it. Required for dashboards, query tables, and tables over a million rows"}),handler:async e=>{try{let t=E(e),o=sp(e);if(e.async){let r=await t.exportDataAndAwaitJob({workspaceId:e.workspaceId,viewId:e.viewId,config:o});if(Pe(r.data.jobCode)){let n=await t.downloadExport({workspaceId:e.workspaceId,jobId:r.data.jobId}),a=await en(n,e.out);p(a??{written:e.out,jobId:r.data.jobId})}else p(r.data,{complete:!1})}else{let r=await t.exportData({workspaceId:e.workspaceId,viewId:e.viewId,config:o}),n=await en(r,e.out);p(n??{written:e.out})}}catch(t){d(t),process.exit(1)}}},ag={command:"query <workspaceId>",describe:"Export the results of a SQL query",builder:e=>ip(e).positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).option("sql",{type:"string",demandOption:!0,describe:"The SQL SELECT statement to run"}),handler:async e=>{try{let t=E(e),o={...sp(e),sqlQuery:e.sql},r=await t.createExportJobForSqlQuery({workspaceId:e.workspaceId,config:o}),n=await t.getExportJob({workspaceId:e.workspaceId,jobId:r.data.jobId});p(n.data,{complete:Pe(n.data.jobCode)})}catch(t){d(t),process.exit(1)}}},ig={command:"job <workspaceId> <jobId>",describe:"Get the status of an asynchronous export job",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("jobId",{type:"string",demandOption:!0,describe:"Export job ID"}).option("download",{type:"boolean",default:!1,describe:"Download the export when the job has completed"}).option("out",{alias:"o",type:"string",describe:"Write the download to this file instead of printing it"}),handler:async e=>{try{let t=E(e),o=await t.getExportJob({workspaceId:e.workspaceId,jobId:e.jobId});if(e.download&&Pe(o.data.jobCode)){let r=await t.downloadExport({workspaceId:e.workspaceId,jobId:e.jobId}),n=await en(r,e.out);p(n??{written:e.out})}else p(o.data,{complete:Pe(o.data.jobCode)})}catch(t){d(t),process.exit(1)}}},cp={command:"export",describe:"Analytics export operations",builder:e=>e.command(ng).command(ag).command(ig).demandCommand(1).example([["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"],["$0 analytics export data WS VIEW --format json","Print a table as JSON"],['$0 analytics export query WS --sql "select * from Sales"',"Queue an ad-hoc SQL export"]]),handler:A};import{readFile as sg}from"node:fs/promises";function cg(e,t){return{clean:t,rowCount:e.rowCount,matched:e.matchedColumns.length,dropped:e.droppedColumns.length,empty:e.emptyColumns.length,emptyRequired:e.emptyColumns.filter(o=>o.required).length,caseMismatched:e.caseMismatchedColumns.length,conflicts:e.conflicts.length,conflictingValues:e.conflicts.reduce((o,r)=>o+r.conflictCount,0)}}var ug={command:"schema <workspaceId> <viewId>",describe:"Compare a file against a table before importing it",builder:e=>e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Target table view ID"}).option("file",{alias:"f",type:"string",demandOption:!0,describe:"Path to the CSV or JSON file that would be imported"}).option("file-type",{type:"string",choices:["csv","json"],describe:"Format of the file. Inferred from its extension when omitted"}).option("delimiter",{type:"string",describe:"Field delimiter of the CSV. Defaults to a comma"}).option("max-samples",{type:"number",describe:"Offending values to report per conflict. Defaults to 3"}).option("strict",{type:"boolean",default:!1,describe:"Also treat a nullable column the file omits as drift"}).option("quiet",{type:"boolean",default:!1,describe:"Report only through the exit code, printing nothing"}),handler:async e=>{try{let t=E(e),o=e.fileType??Oo(e.file);if(o==null)throw new Error(`Cannot tell the format of "${e.file}" from its extension. Pass --file-type csv or --file-type json.`);let r=await sg(e.file,"utf8"),n=Uc({content:r,fileType:o,delimiter:e.delimiter}),{data:a}=await t.getTableMetadata({workspaceId:e.workspaceId,viewId:e.viewId}),i=Lc({...n,columns:a.columns??[],maxSamples:e.maxSamples}),s=Gc(i,{strict:e.strict});e.quiet||p(i,cg(i,s)),s||process.exit(1)}catch(t){d(t),process.exit(1)}}},up={command:"diff",describe:"Analytics comparison operations",builder:e=>e.command(ug).demandCommand(1).example([["$0 analytics diff schema WS VIEW -f rows.csv","Report what an import of the file would drop, leave empty, or mangle"],["$0 analytics diff schema WS VIEW -f rows.csv --strict","Also fail on a nullable column the file omits"],["$0 analytics diff schema WS VIEW -f rows.csv --quiet && zoho-cli analytics import data WS VIEW -f rows.csv","Gate an import on a clean diff"]]),handler:A};function tn(e){return e.positional("workspaceId",{type:"string",demandOption:!0,describe:"Workspace ID"}).positional("viewId",{type:"string",demandOption:!0,describe:"Table view ID"})}var pg={command:"add <workspaceId> <viewId>",describe:"Add a single row to a table",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"Row as a JSON object of column name to value"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.addRow({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o}});p(r.data)}catch(t){d(t),process.exit(1)}}},lg={command:"update <workspaceId> <viewId>",describe:"Update the rows of a table matching a criteria expression",builder:e=>tn(e).option("columns",{type:"string",demandOption:!0,describe:"New values as a JSON object of column name to value"}).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Update every row. Required when no --criteria is given"}).option("add-if-not-exist",{type:"boolean",default:!1,describe:"Insert a row when the criteria matches nothing"}),handler:async e=>{try{let t=E(e),o=JSON.parse(e.columns),r=await t.updateRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{columns:o,criteria:e.criteria,updateAllRows:e.allRows,addIfNotExist:e.addIfNotExist}});p(r.data)}catch(t){d(t),process.exit(1)}}},dg={command:"delete <workspaceId> <viewId>",describe:"Delete the rows of a table matching a criteria expression",builder:e=>tn(e).option("criteria",{type:"string",describe:`Filter expression, e.g. "Sales"."Region"='West'`}).option("all-rows",{type:"boolean",default:!1,describe:"Delete every row. Required when no --criteria is given"}),handler:async e=>{try{let o=await E(e).deleteRows({workspaceId:e.workspaceId,viewId:e.viewId,config:{criteria:e.criteria,deleteAllRows:e.allRows}});p(o.data)}catch(t){d(t),process.exit(1)}}},pp={command:"rows",describe:"Analytics row operations",builder:e=>e.command(pg).command(lg).command(dg).demandCommand(1).example([[`$0 analytics rows add WS VIEW --columns '{"Region":"East"}'`,"Add one row"],[`$0 analytics rows delete WS VIEW --criteria '"Sales"."Region"='"'"'West'"'"''`,"Delete the rows matching a filter"]]),handler:A};var lp={command:"analytics",describe:"Zoho Analytics operations",builder:e=>e.command(Qu).command(ep).command(tp).command(ap).command(cp).command(pp).command(up).demandCommand(1,"Please specify an analytics subcommand.").example([["$0 analytics orgs list","Find the org id every other command needs"],["$0 analytics workspaces list","List the accessible workspaces"],["$0 analytics import data WS VIEW -f rows.csv -m truncateadd","Replace a table with the rows of a CSV"],["$0 analytics export data WS VIEW -o rows.csv","Export a table to a CSV file"]]),handler:A};var dp={command:"request <product> <method> <path>",describe:"Make a raw API request through the authenticated context",builder:e=>e.positional("product",{type:"string",demandOption:!0,choices:["recruit","crm","desk","sign"],describe:"Zoho product"}).positional("method",{type:"string",demandOption:!0,choices:["GET","POST","PUT","PATCH","DELETE"],describe:"HTTP method"}).positional("path",{type:"string",demandOption:!0,describe:"API path (relative to product base URL)"}).option("body",{type:"string",describe:"JSON request body"}).option("query",{type:"string",describe:"JSON query parameters"}).example([["$0 request recruit GET /v2/Candidates","List candidates via raw API"],[`$0 request desk GET /tickets --query '{"limit":5}'`,"List 5 desk tickets via raw API"],[`$0 request crm POST /v8/Contacts --body '{"data":[{"Last_Name":"Test"}]}'`,"Create a CRM contact via raw API"],["$0 request sign GET /templates","List sign templates via raw API"]]),handler:async e=>{try{let t=e.product,o=e.method,r=e.path,n;switch(t){case"recruit":n=oe(e).recruitContext;break;case"crm":n=re(e).crmContext;break;case"desk":n=Z(e).deskContext;break;case"sign":n=N(e).signContext;break;default:throw new Error(`Unknown product: ${t}`)}let a=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),l=a.includes("?")?"&":"?";a=`${a}${l}${u.toString()}`}let i={method:o};e.body&&(i.body=e.body,i.headers={"Content-Type":"application/json"});let s=await n.fetchJson(a,i);p(s)}catch(t){d(t),process.exit(1)}}};var yg=Ea({cliName:"zoho-cli",loadOutputConfig:async()=>(await B())?.output,mergeOutputConfig:e=>ae({output:e}),clearOutputConfig:Da}),fg=[_u,vu,ju,Xu,lp,dp],hp=[Pu,yg,Du];function gg(e){return e.command.split(" ")[0]}var mp=new Set(hp.map(gg)),Rg=Oa({cliName:"zoho-cli",skipCommands:mp,loadOutputConfig:async()=>(await B())?.output,saveCommandOutputConfig:async(e,t)=>{await ae({output:{commands:{[e]:t}}})}});async function Cg(){try{await hg(mg(process.argv)).scriptName("zoho-cli").usage("$0 <command> [options]").option("verbose",{alias:"v",type:"boolean",default:!1,global:!0,describe:"Verbose output"}).option("dump-dir",{type:"string",global:!0,describe:"Directory to save full API responses as JSON files (overrides config)"}).option("pick",{type:"string",global:!0,describe:"Comma-separated top-level fields to include in output (overrides config)"}).option("set-dump-dir",{type:"string",global:!0,describe:"Save dump directory to config for this command and apply now"}).option("set-pick",{type:"string",global:!0,describe:"Save pick fields to config for this command and apply now"}).option("pick-all",{type:"boolean",global:!0,describe:"Ignore any configured pick filters and return full response data"}).middleware([wu(mp),Rg],!0).command(hp).command(fg).demandCommand(1,"Please specify a command. Use --help for available commands.").strict().fail(!1).help().alias("help","h").version(!1).wrap(Math.min(120,process.stdout.columns||80)).parse()}catch(e){d(e),process.exit(1)}}await Cg();
|
package/cli/package.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/cli",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.43.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"zoho-cli": "index.js"
|
|
7
7
|
},
|
|
8
8
|
"peerDependencies": {
|
|
9
|
-
"@dereekb/dbx-cli": "13.
|
|
10
|
-
"@dereekb/nestjs": "13.
|
|
11
|
-
"@dereekb/rxjs": "13.
|
|
12
|
-
"@dereekb/util": "13.
|
|
13
|
-
"@dereekb/zoho": "13.
|
|
14
|
-
"@dereekb/zoho/nestjs": "13.
|
|
9
|
+
"@dereekb/dbx-cli": "13.43.0",
|
|
10
|
+
"@dereekb/nestjs": "13.43.0",
|
|
11
|
+
"@dereekb/rxjs": "13.43.0",
|
|
12
|
+
"@dereekb/util": "13.43.0",
|
|
13
|
+
"@dereekb/zoho": "13.43.0",
|
|
14
|
+
"@dereekb/zoho/nestjs": "13.43.0",
|
|
15
15
|
"yargs": "^18.0.0"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
package/nestjs/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/nestjs",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.43.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"peerDependencies": {
|
|
6
|
-
"@dereekb/nestjs": "13.
|
|
7
|
-
"@dereekb/rxjs": "13.
|
|
8
|
-
"@dereekb/util": "13.
|
|
9
|
-
"@dereekb/zoho": "13.
|
|
6
|
+
"@dereekb/nestjs": "13.43.0",
|
|
7
|
+
"@dereekb/rxjs": "13.43.0",
|
|
8
|
+
"@dereekb/util": "13.43.0",
|
|
9
|
+
"@dereekb/zoho": "13.43.0",
|
|
10
10
|
"@nestjs/common": "^11.1.19",
|
|
11
11
|
"@nestjs/config": "^4.0.4",
|
|
12
12
|
"express": "^5.2.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.43.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": "13.
|
|
26
|
-
"@dereekb/dbx-cli": "13.
|
|
27
|
-
"@dereekb/firebase": "13.
|
|
28
|
-
"@dereekb/model": "13.
|
|
29
|
-
"@dereekb/nestjs": "13.
|
|
30
|
-
"@dereekb/rxjs": "13.
|
|
31
|
-
"@dereekb/util": "13.
|
|
25
|
+
"@dereekb/date": "13.43.0",
|
|
26
|
+
"@dereekb/dbx-cli": "13.43.0",
|
|
27
|
+
"@dereekb/firebase": "13.43.0",
|
|
28
|
+
"@dereekb/model": "13.43.0",
|
|
29
|
+
"@dereekb/nestjs": "13.43.0",
|
|
30
|
+
"@dereekb/rxjs": "13.43.0",
|
|
31
|
+
"@dereekb/util": "13.43.0",
|
|
32
32
|
"@nestjs/common": "^11.1.19",
|
|
33
33
|
"@nestjs/config": "^4.0.4",
|
|
34
34
|
"express": "^5.2.1",
|