jaz-clio 9.2.4 → 9.2.5
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/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/api/references/full-api-surface.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +1 -1
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
> **The endpoints clio wraps (the REST surface is larger).** This file catalogues roughly 200
|
|
4
4
|
> paths, organized by resource, including undocumented endpoints, magic AI features, admin
|
|
5
5
|
> APIs, and advanced search/filter syntax. The committed OpenAPI spec (`spec/openapi.yaml`)
|
|
6
|
-
> carries
|
|
6
|
+
> carries 510 spec paths and 648 spec operations and is the authoritative list; check it before concluding
|
|
7
7
|
> an endpoint does not exist. For request/response examples of core endpoints, see
|
|
8
8
|
> endpoints.md.
|
|
9
9
|
>
|
package/cli.mjs
CHANGED
|
@@ -658,7 +658,7 @@ actual: `+e._bytesWritten),Bz.prototype._finish.call(e)}});var ffe=I((F5r,rtt)=>
|
|
|
658
658
|
Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Mc.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):Pc[n](t._path,o);function o(s,a){if(t.filter&&!t.filter.call(i,i,a)){t._aborted=!0,t.emit("end"),t.emit("close");return}if(s||!a)return pfe(t);t._old=a;var c=ott(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return ggr(t._path,function(u){if(u)return t.error(u);t._old=null,pfe(t)});pfe(t)}};function pfe(e){ygr(sB.dirname(e._path),Mc.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function att(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!Pc[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();Pc[s](n,o,i)}function ctt(e,t,r,n,i){if(process.platform==="win32"||!process.getuid||process.getuid()!==0||typeof t.uid!="number"&&typeof t.gid!="number"||r.uid===t.uid&&r.gid===t.gid)return i();var o=e.props.follow||e.type!=="SymbolicLink"?"chown":"lchown";if(!Pc[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),Pc[o](n,t.uid,t.gid,i)}function ltt(e,t,r,n,i){if(!Pc.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!Pc[o]&&(o="utimes"),!Pc[o])return i();var s=r.atime,a=r.mtime,c=t.atime,u=t.mtime;if(c===void 0&&(c=s),u===void 0&&(u=a),ntt(c)||(c=new Date(c)),ntt(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();Pc[o](n,c,u,i)}Mc.prototype._finish=function(){var e=this;if(e._finishing)return;e._finishing=!0;var t=0,r=null,n=!1;if(e._old)e._old.atime=new Date(0),e._old.mtime=new Date(0),o(e._old);else{var i=e.props.follow?"stat":"lstat";Pc[i](e._path,function(a,c){if(a)if(a.code==="ENOENT"&&(e.type==="Link"||e.type==="SymbolicLink")&&process.platform==="win32"){e.ready=!0,e.emit("ready"),e.emit("end"),e.emit("close"),e.end=e._finish=function(){};return}else return e.error(a);o(e._old=c)})}return;function o(a){t+=3,att(e,e.props,a,e._path,s("chmod")),ctt(e,e.props,a,e._path,s("chown")),ltt(e,e.props,a,e._path,s("utimes"))}function s(a){return function(c){if(r)return;if(c)return c.fstream_finish_call=a,e.error(r=c);if(--t>0||n)return;if(n=!0,e._madeDir)utt(e,e._path,u);else return u();function u(d){if(d)return d.fstream_finish_call="setupMadeDir",e.error(d);e.emit("end"),e.emit("close")}}}};function utt(e,t,r){var n=e._madeDir,i=sB.dirname(t);wgr(e,i,function(o){if(o)return r(o);if(i===n)return r();utt(e,i,r)})}function wgr(e,t,r){var n={};Object.keys(e.props).forEach(function(a){n[a]=e.props[a],a==="mode"&&e.type!=="Directory"&&(n[a]=n[a]|parseInt("0111",8))});var i=3,o=null;Pc.stat(t,function(a,c){if(a)return r(o=a);att(e,n,c,t,s),ctt(e,n,c,t,s),ltt(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}Mc.prototype.pipe=function(){this.error("Can't pipe from writable stream")};Mc.prototype.add=function(){this.error("Can't add to non-Directory type")};Mc.prototype.write=function(){return!0};function _gr(e){return Object.prototype.toString.call(e)}function ntt(e){return typeof e=="object"&&_gr(e)==="[object Date]"}});var hfe=I(Qr=>{Qr.Abstract=vz();Qr.Reader=Uy();Qr.Writer=l_();Qr.File={Reader:Kde(),Writer:ufe()};Qr.Dir={Reader:Wde(),Writer:cfe()};Qr.Link={Reader:Gde(),Writer:lfe()};Qr.Proxy={Reader:Xde(),Writer:ffe()};Qr.Reader.Dir=Qr.DirReader=Qr.Dir.Reader;Qr.Reader.File=Qr.FileReader=Qr.File.Reader;Qr.Reader.Link=Qr.LinkReader=Qr.Link.Reader;Qr.Reader.Proxy=Qr.ProxyReader=Qr.Proxy.Reader;Qr.Writer.Dir=Qr.DirWriter=Qr.Dir.Writer;Qr.Writer.File=Qr.FileWriter=Qr.File.Writer;Qr.Writer.Link=Qr.LinkWriter=Qr.Link.Writer;Qr.Writer.Proxy=Qr.ProxyWriter=Qr.Proxy.Writer;Qr.collect=xz()});var ptt=I((P5r,ftt)=>{ftt.exports=xgr;var vgr=_z(),Sgr=hfe().Writer,mfe=Y("path"),Dgr=Y("stream"),Rgr=Hde(),Tgr=Dm();function xgr(e){e.path=mfe.resolve(mfe.normalize(e.path));var t=new vgr(e),r=new Dgr.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=mfe.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):Sgr({path:a});i.pipe(c).on("error",s).on("close",s)};var n=Rgr(t,r);return t.once("crx-header",function(i){n.crxHeader=i}),t.pipe(r).on("finish",function(){n.emit("close")}),n.promise=function(){return new Tgr(function(i,o){n.on("close",i),n.on("error",o)})},n}});var htt=I((M5r,Nz)=>{var uo=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,x,L,j){return typeof v>"u"?a[0]:typeof x<"u"?+x==10&&!L?ae(v):Ve(v,x,L,j):ae(v)}function c(v,x){this.value=v,this.sign=x,this.isSmall=!1}c.prototype=Object.create(a.prototype);function u(v){this.value=v,this.sign=v<0,this.isSmall=!0}u.prototype=Object.create(a.prototype);function d(v){this.value=v}d.prototype=Object.create(a.prototype);function f(v){return-n<v&&v<n}function p(v){return v<1e7?[v]:v<1e14?[v%1e7,Math.floor(v/1e7)]:[v%1e7,Math.floor(v/1e7)%1e7,Math.floor(v/1e14)]}function h(v){m(v);var x=v.length;if(x<4&&V(v,i)<0)switch(x){case 0:return 0;case 1:return v[0];case 2:return v[0]+v[1]*t;default:return v[0]+(v[1]+v[2]*t)*t}return v}function m(v){for(var x=v.length;v[--x]===0;);v.length=x+1}function A(v){for(var x=new Array(v),L=-1;++L<v;)x[L]=0;return x}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,x){var L=v.length,j=x.length,ie=new Array(L),te=0,se=t,ce,pe;for(pe=0;pe<j;pe++)ce=v[pe]+x[pe]+te,te=ce>=se?1:0,ie[pe]=ce-te*se;for(;pe<L;)ce=v[pe]+te,te=ce===se?1:0,ie[pe++]=ce-te*se;return te>0&&ie.push(te),ie}function b(v,x){return v.length>=x.length?y(v,x):y(x,v)}function E(v,x){var L=v.length,j=new Array(L),ie=t,te,se;for(se=0;se<L;se++)te=v[se]-ie+x,x=Math.floor(te/ie),j[se]=te-x*ie,x+=1;for(;x>0;)j[se++]=x%ie,x=Math.floor(x/ie);return j}c.prototype.add=function(v){var x=ae(v);if(this.sign!==x.sign)return this.subtract(x.negate());var L=this.value,j=x.value;return x.isSmall?new c(E(L,Math.abs(j)),this.sign):new c(b(L,j),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var x=ae(v),L=this.value;if(L<0!==x.sign)return this.subtract(x.negate());var j=x.value;if(x.isSmall){if(f(L+j))return new u(L+j);j=p(Math.abs(j))}return new c(E(j,Math.abs(L)),L<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(v){return new d(this.value+ae(v).value)},d.prototype.plus=d.prototype.add;function C(v,x){var L=v.length,j=x.length,ie=new Array(L),te=0,se=t,ce,pe;for(ce=0;ce<j;ce++)pe=v[ce]-te-x[ce],pe<0?(pe+=se,te=1):te=0,ie[ce]=pe;for(ce=j;ce<L;ce++){if(pe=v[ce]-te,pe<0)pe+=se;else{ie[ce++]=pe;break}ie[ce]=pe}for(;ce<L;ce++)ie[ce]=v[ce];return m(ie),ie}function w(v,x,L){var j;return V(v,x)>=0?j=C(v,x):(j=C(x,v),L=!L),j=h(j),typeof j=="number"?(L&&(j=-j),new u(j)):new c(j,L)}function T(v,x,L){var j=v.length,ie=new Array(j),te=-x,se=t,ce,pe;for(ce=0;ce<j;ce++)pe=v[ce]+te,te=Math.floor(pe/se),pe%=se,ie[ce]=pe<0?pe+se:pe;return ie=h(ie),typeof ie=="number"?(L&&(ie=-ie),new u(ie)):new c(ie,L)}c.prototype.subtract=function(v){var x=ae(v);if(this.sign!==x.sign)return this.add(x.negate());var L=this.value,j=x.value;return x.isSmall?T(L,Math.abs(j),this.sign):w(L,j,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var x=ae(v),L=this.value;if(L<0!==x.sign)return this.add(x.negate());var j=x.value;return x.isSmall?new u(L-j):T(j,Math.abs(L),L>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(v){return new d(this.value-ae(v).value)},d.prototype.minus=d.prototype.subtract,c.prototype.negate=function(){return new c(this.value,!this.sign)},u.prototype.negate=function(){var v=this.sign,x=new u(-this.value);return x.sign=!v,x},d.prototype.negate=function(){return new d(-this.value)},c.prototype.abs=function(){return new c(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},d.prototype.abs=function(){return new d(this.value>=0?this.value:-this.value)};function R(v,x){var L=v.length,j=x.length,ie=L+j,te=A(ie),se=t,ce,pe,Le,Je,st;for(Le=0;Le<L;++Le){Je=v[Le];for(var Kt=0;Kt<j;++Kt)st=x[Kt],ce=Je*st+te[Le+Kt],pe=Math.floor(ce/se),te[Le+Kt]=ce-pe*se,te[Le+Kt+1]+=pe}return m(te),te}function k(v,x){var L=v.length,j=new Array(L),ie=t,te=0,se,ce;for(ce=0;ce<L;ce++)se=v[ce]*x+te,te=Math.floor(se/ie),j[ce]=se-te*ie;for(;te>0;)j[ce++]=te%ie,te=Math.floor(te/ie);return j}function O(v,x){for(var L=[];x-- >0;)L.push(0);return L.concat(v)}function J(v,x){var L=Math.max(v.length,x.length);if(L<=30)return R(v,x);L=Math.ceil(L/2);var j=v.slice(L),ie=v.slice(0,L),te=x.slice(L),se=x.slice(0,L),ce=J(ie,se),pe=J(j,te),Le=J(b(ie,j),b(se,te)),Je=b(b(ce,O(C(C(Le,ce),pe),L)),O(pe,2*L));return m(Je),Je}function z(v,x){return-.012*v-.012*x+15e-6*v*x>0}c.prototype.multiply=function(v){var x=ae(v),L=this.value,j=x.value,ie=this.sign!==x.sign,te;if(x.isSmall){if(j===0)return a[0];if(j===1)return this;if(j===-1)return this.negate();if(te=Math.abs(j),te<t)return new c(k(L,te),ie);j=p(te)}return z(L.length,j.length)?new c(J(L,j),ie):new c(R(L,j),ie)},c.prototype.times=c.prototype.multiply;function S(v,x,L){return v<t?new c(k(x,v),L):new c(R(x,p(v)),L)}u.prototype._multiplyBySmall=function(v){return f(v.value*this.value)?new u(v.value*this.value):S(Math.abs(v.value),p(Math.abs(this.value)),this.sign!==v.sign)},c.prototype._multiplyBySmall=function(v){return v.value===0?a[0]:v.value===1?this:v.value===-1?this.negate():S(Math.abs(v.value),this.value,this.sign!==v.sign)},u.prototype.multiply=function(v){return ae(v)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(v){return new d(this.value*ae(v).value)},d.prototype.times=d.prototype.multiply;function B(v){var x=v.length,L=A(x+x),j=t,ie,te,se,ce,pe;for(se=0;se<x;se++){ce=v[se],te=0-ce*ce;for(var Le=se;Le<x;Le++)pe=v[Le],ie=2*(ce*pe)+L[se+Le]+te,te=Math.floor(ie/j),L[se+Le]=ie-te*j;L[se+x]=te}return m(L),L}c.prototype.square=function(){return new c(B(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(B(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function P(v,x){var L=v.length,j=x.length,ie=t,te=A(x.length),se=x[j-1],ce=Math.ceil(ie/(2*se)),pe=k(v,ce),Le=k(x,ce),Je,st,Kt,yn,ti,Xi,Vc;for(pe.length<=L&&pe.push(0),Le.push(0),se=Le[j-1],st=L-j;st>=0;st--){for(Je=ie-1,pe[st+j]!==se&&(Je=Math.floor((pe[st+j]*ie+pe[st+j-1])/se)),Kt=0,yn=0,Xi=Le.length,ti=0;ti<Xi;ti++)Kt+=Je*Le[ti],Vc=Math.floor(Kt/ie),yn+=pe[st+ti]-(Kt-Vc*ie),Kt=Vc,yn<0?(pe[st+ti]=yn+ie,yn=-1):(pe[st+ti]=yn,yn=0);for(;yn!==0;){for(Je-=1,Kt=0,ti=0;ti<Xi;ti++)Kt+=pe[st+ti]-ie+Le[ti],Kt<0?(pe[st+ti]=Kt+ie,Kt=0):(pe[st+ti]=Kt,Kt=1);yn+=Kt}te[st]=Je}return pe=N(pe,ce)[0],[h(te),h(pe)]}function K(v,x){for(var L=v.length,j=x.length,ie=[],te=[],se=t,ce,pe,Le,Je,st;L;){if(te.unshift(v[--L]),m(te),V(te,x)<0){ie.push(0);continue}pe=te.length,Le=te[pe-1]*se+te[pe-2],Je=x[j-1]*se+x[j-2],pe>j&&(Le=(Le+1)*se),ce=Math.ceil(Le/Je);do{if(st=k(x,ce),V(st,te)<=0)break;ce--}while(ce);ie.push(ce),te=C(te,st)}return ie.reverse(),[h(ie),h(te)]}function N(v,x){var L=v.length,j=A(L),ie=t,te,se,ce,pe;for(ce=0,te=L-1;te>=0;--te)pe=ce*ie+v[te],se=g(pe/x),ce=pe-se*x,j[te]=se|0;return[j,ce|0]}function H(v,x){var L,j=ae(x);if(s)return[new d(v.value/j.value),new d(v.value%j.value)];var ie=v.value,te=j.value,se;if(te===0)throw new Error("Cannot divide by zero");if(v.isSmall)return j.isSmall?[new u(g(ie/te)),new u(ie%te)]:[a[0],v];if(j.isSmall){if(te===1)return[v,a[0]];if(te==-1)return[v.negate(),a[0]];var ce=Math.abs(te);if(ce<t){L=N(ie,ce),se=h(L[0]);var pe=L[1];return v.sign&&(pe=-pe),typeof se=="number"?(v.sign!==j.sign&&(se=-se),[new u(se),new u(pe)]):[new c(se,v.sign!==j.sign),new u(pe)]}te=p(ce)}var Le=V(ie,te);if(Le===-1)return[a[0],v];if(Le===0)return[a[v.sign===j.sign?1:-1],a[0]];ie.length+te.length<=200?L=P(ie,te):L=K(ie,te),se=L[0];var Je=v.sign!==j.sign,st=L[1],Kt=v.sign;return typeof se=="number"?(Je&&(se=-se),se=new u(se)):se=new c(se,Je),typeof st=="number"?(Kt&&(st=-st),st=new u(st)):st=new c(st,Kt),[se,st]}c.prototype.divmod=function(v){var x=H(this,v);return{quotient:x[0],remainder:x[1]}},d.prototype.divmod=u.prototype.divmod=c.prototype.divmod,c.prototype.divide=function(v){return H(this,v)[0]},d.prototype.over=d.prototype.divide=function(v){return new d(this.value/ae(v).value)},u.prototype.over=u.prototype.divide=c.prototype.over=c.prototype.divide,c.prototype.mod=function(v){return H(this,v)[1]},d.prototype.mod=d.prototype.remainder=function(v){return new d(this.value%ae(v).value)},u.prototype.remainder=u.prototype.mod=c.prototype.remainder=c.prototype.mod,c.prototype.pow=function(v){var x=ae(v),L=this.value,j=x.value,ie,te,se;if(j===0)return a[1];if(L===0)return a[0];if(L===1)return a[1];if(L===-1)return x.isEven()?a[1]:a[-1];if(x.sign)return a[0];if(!x.isSmall)throw new Error("The exponent "+x.toString()+" is too large.");if(this.isSmall&&f(ie=Math.pow(L,j)))return new u(g(ie));for(te=this,se=a[1];j&!0&&(se=se.times(te),--j),j!==0;)j/=2,te=te.square();return se},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var x=ae(v),L=this.value,j=x.value,ie=BigInt(0),te=BigInt(1),se=BigInt(2);if(j===ie)return a[1];if(L===ie)return a[0];if(L===te)return a[1];if(L===BigInt(-1))return x.isEven()?a[1]:a[-1];if(x.isNegative())return new d(ie);for(var ce=this,pe=a[1];(j&te)===te&&(pe=pe.times(ce),--j),j!==ie;)j/=se,ce=ce.square();return pe},c.prototype.modPow=function(v,x){if(v=ae(v),x=ae(x),x.isZero())throw new Error("Cannot take modPow with modulus 0");var L=a[1],j=this.mod(x);for(v.isNegative()&&(v=v.multiply(a[-1]),j=j.modInv(x));v.isPositive();){if(j.isZero())return a[0];v.isOdd()&&(L=L.multiply(j).mod(x)),v=v.divide(2),j=j.square().mod(x)}return L},d.prototype.modPow=u.prototype.modPow=c.prototype.modPow;function V(v,x){if(v.length!==x.length)return v.length>x.length?1:-1;for(var L=v.length-1;L>=0;L--)if(v[L]!==x[L])return v[L]>x[L]?1:-1;return 0}c.prototype.compareAbs=function(v){var x=ae(v),L=this.value,j=x.value;return x.isSmall?1:V(L,j)},u.prototype.compareAbs=function(v){var x=ae(v),L=Math.abs(this.value),j=x.value;return x.isSmall?(j=Math.abs(j),L===j?0:L>j?1:-1):-1},d.prototype.compareAbs=function(v){var x=this.value,L=ae(v).value;return x=x>=0?x:-x,L=L>=0?L:-L,x===L?0:x>L?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),L=this.value,j=x.value;return this.sign!==x.sign?x.sign?1:-1:x.isSmall?this.sign?-1:1:V(L,j)*(this.sign?-1:1)},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),L=this.value,j=x.value;return x.isSmall?L==j?0:L>j?1:-1:L<0!==x.sign?L<0?-1:1:L<0?1:-1},u.prototype.compareTo=u.prototype.compare,d.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=this.value,L=ae(v).value;return x===L?0:x>L?1:-1},d.prototype.compareTo=d.prototype.compare,c.prototype.equals=function(v){return this.compare(v)===0},d.prototype.eq=d.prototype.equals=u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals,c.prototype.notEquals=function(v){return this.compare(v)!==0},d.prototype.neq=d.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals,c.prototype.greater=function(v){return this.compare(v)>0},d.prototype.gt=d.prototype.greater=u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater,c.prototype.lesser=function(v){return this.compare(v)<0},d.prototype.lt=d.prototype.lesser=u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser,c.prototype.greaterOrEquals=function(v){return this.compare(v)>=0},d.prototype.geq=d.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals,c.prototype.lesserOrEquals=function(v){return this.compare(v)<=0},d.prototype.leq=d.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals,c.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},d.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},c.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},d.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},c.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},d.prototype.isPositive=u.prototype.isPositive,c.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},d.prototype.isNegative=u.prototype.isNegative,c.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},d.prototype.isUnit=function(){return this.abs().value===BigInt(1)},c.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},d.prototype.isZero=function(){return this.value===BigInt(0)},c.prototype.isDivisibleBy=function(v){var x=ae(v);return x.isZero()?!1:x.isUnit()?!0:x.compareAbs(2)===0?this.isEven():this.mod(x).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=c.prototype.isDivisibleBy;function Z(v){var x=v.abs();if(x.isUnit())return!1;if(x.equals(2)||x.equals(3)||x.equals(5))return!0;if(x.isEven()||x.isDivisibleBy(3)||x.isDivisibleBy(5))return!1;if(x.lesser(49))return!0}function oe(v,x){for(var L=v.prev(),j=L,ie=0,te,se,ce,pe;j.isEven();)j=j.divide(2),ie++;e:for(ce=0;ce<x.length;ce++)if(!v.lesser(x[ce])&&(pe=uo(x[ce]).modPow(j,v),!(pe.isUnit()||pe.equals(L)))){for(te=ie-1;te!=0;te--){if(pe=pe.square().mod(v),pe.isUnit())return!1;if(pe.equals(L))continue e}return!1}return!0}c.prototype.isPrime=function(v){var x=Z(this);if(x!==e)return x;var L=this.abs(),j=L.bitLength();if(j<=64)return oe(L,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ie=Math.log(2)*j.toJSNumber(),te=Math.ceil(v===!0?2*Math.pow(ie,2):ie),se=[],ce=0;ce<te;ce++)se.push(uo(ce+2));return oe(L,se)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,x){var L=Z(this);if(L!==e)return L;for(var j=this.abs(),ie=v===e?5:v,te=[],se=0;se<ie;se++)te.push(uo.randBetween(2,j.minus(2),x));return oe(j,te)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var x=uo.zero,L=uo.one,j=ae(v),ie=this.abs(),te,se,ce;!ie.isZero();)te=j.divide(ie),se=x,ce=j,x=L,j=ie,L=se.subtract(te.multiply(L)),ie=ce.subtract(te.multiply(ie));if(!j.isUnit())throw new Error(this.toString()+" and "+v.toString()+" are not co-prime");return x.compare(0)===-1&&(x=x.add(v)),this.isNegative()?x.negate():x},d.prototype.modInv=u.prototype.modInv=c.prototype.modInv,c.prototype.next=function(){var v=this.value;return this.sign?T(v,1,this.sign):new c(E(v,1),this.sign)},u.prototype.next=function(){var v=this.value;return v+1<n?new u(v+1):new c(i,!1)},d.prototype.next=function(){return new d(this.value+BigInt(1))},c.prototype.prev=function(){var v=this.value;return this.sign?new c(E(v,1),!0):T(v,1,this.sign)},u.prototype.prev=function(){var v=this.value;return v-1>-n?new u(v-1):new c(i,!0)},d.prototype.prev=function(){return new d(this.value-BigInt(1))};for(var he=[1];2*he[he.length-1]<=t;)he.push(2*he[he.length-1]);var Te=he.length,ve=he[Te-1];function dt(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var x=ae(v).toJSNumber();if(!dt(x))throw new Error(String(x)+" is too large for shifting.");if(x<0)return this.shiftRight(-x);var L=this;if(L.isZero())return L;for(;x>=Te;)L=L.multiply(ve),x-=Te-1;return L.multiply(he[x])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var x,L=ae(v).toJSNumber();if(!dt(L))throw new Error(String(L)+" is too large for shifting.");if(L<0)return this.shiftLeft(-L);for(var j=this;L>=Te;){if(j.isZero()||j.isNegative()&&j.isUnit())return j;x=H(j,ve),j=x[1].isNegative()?x[0].prev():x[0],L-=Te-1}return x=H(j,he[L]),x[1].isNegative()?x[0].prev():x[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Be(v,x,L){x=ae(x);for(var j=v.isNegative(),ie=x.isNegative(),te=j?v.not():v,se=ie?x.not():x,ce=0,pe=0,Le=null,Je=null,st=[];!te.isZero()||!se.isZero();)Le=H(te,ve),ce=Le[1].toJSNumber(),j&&(ce=ve-1-ce),Je=H(se,ve),pe=Je[1].toJSNumber(),ie&&(pe=ve-1-pe),te=Le[0],se=Je[0],st.push(L(ce,pe));for(var Kt=L(j?1:0,ie?1:0)!==0?uo(-1):uo(0),yn=st.length-1;yn>=0;yn-=1)Kt=Kt.multiply(ve).add(uo(st[yn]));return Kt}c.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=c.prototype.not,c.prototype.and=function(v){return Be(this,v,function(x,L){return x&L})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Be(this,v,function(x,L){return x|L})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Be(this,v,function(x,L){return x^L})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Me=1<<30,fe=(t&-t)*(t&-t)|Me;function le(v){var x=v.value,L=typeof x=="number"?x|Me:typeof x=="bigint"?x|BigInt(Me):x[0]+x[1]*t|fe;return L&-L}function _e(v,x){if(x.compareTo(v)<=0){var L=_e(v,x.square(x)),j=L.p,ie=L.e,te=j.multiply(x);return te.compareTo(v)<=0?{p:te,e:ie*2+1}:{p:j,e:ie*2}}return{p:uo(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(uo(0))<0&&(v=v.negate().subtract(uo(1))),v.compareTo(uo(0))===0?uo(0):uo(_e(v,uo(2)).e).add(uo(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Fe(v,x){return v=ae(v),x=ae(x),v.greater(x)?v:x}function ze(v,x){return v=ae(v),x=ae(x),v.lesser(x)?v:x}function $t(v,x){if(v=ae(v).abs(),x=ae(x).abs(),v.equals(x))return v;if(v.isZero())return x;if(x.isZero())return v;for(var L=a[1],j,ie;v.isEven()&&x.isEven();)j=ze(le(v),le(x)),v=v.divide(j),x=x.divide(j),L=L.multiply(j);for(;v.isEven();)v=v.divide(le(v));do{for(;x.isEven();)x=x.divide(le(x));v.greater(x)&&(ie=x,x=v,v=ie),x=x.subtract(v)}while(!x.isZero());return L.isUnit()?v:v.multiply(L)}function Ot(v,x){return v=ae(v).abs(),x=ae(x).abs(),v.divide($t(v,x)).multiply(x)}function fr(v,x,L){v=ae(v),x=ae(x);var j=L||Math.random,ie=ze(v,x),te=Fe(v,x),se=te.subtract(ie).add(1);if(se.isSmall)return ie.add(Math.floor(j()*se));for(var ce=Ue(se,t).value,pe=[],Le=!0,Je=0;Je<ce.length;Je++){var st=Le?ce[Je]+(Je+1<ce.length?ce[Je+1]/t:0):t,Kt=g(j()*st);pe.push(Kt),Kt<ce[Je]&&(Le=!1)}return ie.add(a.fromArray(pe,t,!1))}var Ve=function(v,x,L,j){L=L||o,v=String(v),j||(v=v.toLowerCase(),L=L.toLowerCase());var ie=v.length,te,se=Math.abs(x),ce={};for(te=0;te<L.length;te++)ce[L[te]]=te;for(te=0;te<ie;te++){var pe=v[te];if(pe!=="-"&&pe in ce&&ce[pe]>=se){if(pe==="1"&&se===1)continue;throw new Error(pe+" is not a valid digit in base "+x+".")}}x=ae(x);var Le=[],Je=v[0]==="-";for(te=Je?1:0;te<v.length;te++){var pe=v[te];if(pe in ce)Le.push(ae(ce[pe]));else if(pe==="<"){var st=te;do te++;while(v[te]!==">"&&te<v.length);Le.push(ae(v.slice(st+1,te)))}else throw new Error(pe+" is not a valid character")}return qe(Le,x,Je)};function qe(v,x,L){var j=a[0],ie=a[1],te;for(te=v.length-1;te>=0;te--)j=j.add(v[te].times(ie)),ie=ie.times(x);return L?j.negate():j}function bt(v,x){return x=x||o,v<x.length?x[v]:"<"+v+">"}function Ue(v,x){if(x=uo(x),x.isZero()){if(v.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(x.equals(-1)){if(v.isZero())return{value:[0],isNegative:!1};if(v.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-v.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var L=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return L.unshift([1]),{value:[].concat.apply([],L),isNegative:!1}}var j=!1;if(v.isNegative()&&x.isPositive()&&(j=!0,v=v.abs()),x.isUnit())return v.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(v.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:j};for(var ie=[],te=v,se;te.isNegative()||te.compareAbs(x)>=0;){se=te.divmod(x),te=se.quotient;var ce=se.remainder;ce.isNegative()&&(ce=x.minus(ce).abs(),te=te.next()),ie.push(ce.toJSNumber())}return ie.push(te.toJSNumber()),{value:ie.reverse(),isNegative:j}}function Ke(v,x,L){var j=Ue(v,x);return(j.isNegative?"-":"")+j.value.map(function(ie){return bt(ie,L)}).join("")}c.prototype.toArray=function(v){return Ue(this,v)},u.prototype.toArray=function(v){return Ue(this,v)},d.prototype.toArray=function(v){return Ue(this,v)},c.prototype.toString=function(v,x){if(v===e&&(v=10),v!==10||x)return Ke(this,v,x);for(var L=this.value,j=L.length,ie=String(L[--j]),te="0000000",se;--j>=0;)se=String(L[j]),ie+=te.slice(se.length)+se;var ce=this.sign?"-":"";return ce+ie},u.prototype.toString=function(v,x){return v===e&&(v=10),v!=10||x?Ke(this,v,x):String(this.value)},d.prototype.toString=u.prototype.toString,d.prototype.toJSON=c.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},c.prototype.valueOf=function(){return parseInt(this.toString(),10)},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,d.prototype.valueOf=d.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function et(v){if(f(+v)){var x=+v;if(x===g(x))return s?new d(BigInt(x)):new u(x);throw new Error("Invalid integer: "+v)}var L=v[0]==="-";L&&(v=v.slice(1));var j=v.split(/e/i);if(j.length>2)throw new Error("Invalid integer: "+j.join("e"));if(j.length===2){var ie=j[1];if(ie[0]==="+"&&(ie=ie.slice(1)),ie=+ie,ie!==g(ie)||!f(ie))throw new Error("Invalid integer: "+ie+" is not a valid exponent.");var te=j[0],se=te.indexOf(".");if(se>=0&&(ie-=te.length-se-1,te=te.slice(0,se)+te.slice(se+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");te+=new Array(ie+1).join("0"),v=te}var ce=/^([0-9][0-9]*)$/.test(v);if(!ce)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(L?"-"+v:v));for(var pe=[],Le=v.length,Je=r,st=Le-Je;Le>0;)pe.push(+v.slice(st,Le)),st-=Je,st<0&&(st=0),Le-=Je;return m(pe),new c(pe,L)}function Xe(v){if(s)return new d(BigInt(v));if(f(v)){if(v!==g(v))throw new Error(v+" is not an integer.");return new u(v)}return et(v.toString())}function ae(v){return typeof v=="number"?Xe(v):typeof v=="string"?et(v):typeof v=="bigint"?new d(v):v}for(var X=0;X<1e3;X++)a[X]=ae(X),X>0&&(a[-X]=ae(-X));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Fe,a.min=ze,a.gcd=$t,a.lcm=Ot,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=fr,a.fromArray=function(v,x,L){return qe(v.map(ae),ae(x||10),L)},a})();typeof Nz<"u"&&Nz.hasOwnProperty("exports")&&(Nz.exports=uo);typeof define=="function"&&define.amd&&define(function(){return uo})});var gtt=I((U5r,Att)=>{var Bm=htt(),Oz=Y("stream");(!Oz.Writable||!Oz.Writable.prototype.destroy)&&(Oz=ca());var Fz;function kgr(){var e=3988292384,t,r,n;for(Fz=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;Fz[r]=t>>>0}}function mtt(e,t){return Fz||kgr(),e.charCodeAt&&(e=e.charCodeAt(0)),Bm(t).shiftRight(8).and(16777215).xor(Fz[Bm(t).xor(e).and(255)]).value}function u_(){if(!(this instanceof u_))return new u_;this.key0=305419896,this.key1=591751049,this.key2=878082192}u_.prototype.update=function(e){this.key0=mtt(e,this.key0),this.key1=Bm(this.key0).and(255).and(4294967295).add(this.key1),this.key1=Bm(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=mtt(Bm(this.key1).shiftRight(24).and(255),this.key2)};u_.prototype.decryptByte=function(e){var t=Bm(this.key2).or(2);return e=e^Bm(t).multiply(Bm(t^1)).shiftRight(8).and(255),this.update(e),e};u_.prototype.stream=function(){var e=Oz.Transform(),t=this;return e._transform=function(r,n,i){for(var o=0;o<r.length;o++)r[o]=t.decryptByte(r[o]);this.push(r),i()},e};Att.exports=u_});var Ett=I(($5r,ytt)=>{var Bgr=Dm(),Ngr=gtt(),Ogr=Ez(),aB=Y("stream"),Fgr=Jk(),Qgr=Y("zlib"),Lgr=Cz(),Pgr=i_(),Mgr=wz();(!aB.Writable||!aB.Writable.prototype.destroy)&&(aB=ca());ytt.exports=function(t,r,n,i){var o=Ogr(),s=aB.PassThrough(),a=t.stream(r);return a.pipe(o).on("error",function(c){s.emit("error",c)}),s.vars=o.pull(30).then(function(c){var u=Fgr.parse(c).word32lu("signature").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return u.lastModifiedDateTime=Mgr(u.lastModifiedDate,u.lastModifiedTime),o.pull(u.fileNameLength).then(function(d){return u.fileName=d.toString("utf8"),o.pull(u.extraFieldLength)}).then(function(d){var f;return u.extra=Lgr(d,u),i&&i.compressedSize&&(u=i),u.flags&1&&(f=o.pull(12).then(function(p){if(!n)throw new Error("MISSING_PASSWORD");var h=Ngr();String(n).split("").forEach(function(g){h.update(g)});for(var m=0;m<p.length;m++)p[m]=h.decryptByte(p[m]);u.decrypt=h,u.compressedSize-=12;var A=u.flags&8?u.lastModifiedTime>>8&255:u.crc32>>24&255;if(p[11]!==A)throw new Error("BAD_PASSWORD");return u})),Bgr.resolve(f).then(function(){return s.emit("vars",u),u})})}),s.vars.then(function(c){var u=!(c.flags&8)||c.compressedSize>0,d,f=c.compressionMethod?Qgr.createInflateRaw():aB.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=Pgr.alloc(4),d.writeUInt32LE(134695760,0));var p=o.stream(d);c.decrypt&&(p=p.pipe(c.decrypt.stream())),p.pipe(f).on("error",function(h){s.emit("error",h)}).pipe(s).on("finish",function(){a.destroy?a.destroy():a.abort?a.abort():a.close?a.close():a.push?a.push():console.log("warning - unable to close stream")})}).catch(function(c){s.emit("error",c)}),s}});var Ctt=I((q5r,Itt)=>{var uB=Jk(),lB=Ez(),Ugr=Ett(),cB=Dm(),$gr=Iz(),qgr=Cz(),jgr=i_(),Afe=Y("path"),Ygr=hfe().Writer,Hgr=wz(),btt=jgr.alloc(4);btt.writeUInt32LE(101010256,0);function zgr(e){var t=e.stream(0).pipe(lB());return t.pull(4).then(function(r){var n=r.readUInt32LE(0);if(n===875721283){var i;return t.pull(12).then(function(o){i=uB.parse(o).word32lu("version").word32lu("pubKeyLength").word32lu("signatureLength").vars}).then(function(){return t.pull(i.pubKeyLength+i.signatureLength)}).then(function(o){return i.publicKey=o.slice(0,i.pubKeyLength),i.signature=o.slice(i.pubKeyLength),i.size=16+i.pubKeyLength+i.signatureLength,i})}})}function Jgr(e,t){var r=uB.parse(t).word32lu("signature").word32lu("diskNumber").word64lu("offsetToStartOfCentralDirectory").word32lu("numberOfDisks").vars;if(r.signature!=117853008)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+r.signature.toString(16));var n=lB();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function Ggr(e){var t=uB.parse(e).word32lu("signature").word64lu("sizeOfCentralDirectory").word16lu("version").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskStart").word64lu("numberOfRecordsOnDisk").word64lu("numberOfRecords").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;if(t.signature!=101075792)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+t.signature.toString(16));return t}Itt.exports=function(t,r){var n=lB(),i=lB(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=zgr(t)),t.size().then(function(d){return s=d,t.stream(Math.max(0,d-o)).on("error",function(f){n.emit("error",f)}).pipe(n),n.pull(btt)}).then(function(){return cB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=uB.parse(f).word32lu("signature").word16lu("diskNumber").word16lu("diskStart").word16lu("numberOfRecordsOnDisk").word16lu("numberOfRecords").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars,u.numberOfRecords==65535||u.numberOfRecords==65535||u.offsetToStartOfCentralDirectory==4294967295){let h=s-(o-n.match+20),m=lB();return t.stream(h).pipe(m),m.pull(20).then(function(A){return Jgr(t,A)}).then(function(A){u=Ggr(A)})}else u.offsetToStartOfCentralDirectory+=c}).then(function(){if(u.commentLength)return n.pull(u.commentLength).then(function(d){u.comment=d.toString("utf8")})}).then(function(){return t.stream(u.offsetToStartOfCentralDirectory).pipe(i),u.extract=function(d){if(!d||!d.path)throw new Error("PATH_MISSING");return d.path=Afe.resolve(Afe.normalize(d.path)),u.files.then(function(f){return cB.map(f,function(p){if(p.type!="Directory"){var h=Afe.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):Ygr({path:h});return new cB(function(A,g){p.stream(d.password).on("error",g).pipe(m).on("close",A).on("error",g)})}}},{concurrency:d.concurrency>1?d.concurrency:1})})},u.files=cB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=uB.parse(d).word32lu("signature").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return f.offsetToLocalFileHeader+=c,f.lastModifiedDateTime=Hgr(f.lastModifiedDate,f.lastModifiedTime),i.pull(f.fileNameLength).then(function(p){return f.pathBuffer=p,f.path=p.toString("utf8"),f.isUnicode=(f.flags&2048)!=0,i.pull(f.extraFieldLength)}).then(function(p){return f.extra=qgr(p,f),i.pull(f.fileCommentLength)}).then(function(p){return f.comment=p,f.type=f.uncompressedSize===0&&/[\/\\]$/.test(f.path)?"Directory":"File",f.stream=function(h){return Ugr(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return $gr(f.stream(h))},f})})}),cB.props(u)})}});var vtt=I((j5r,_tt)=>{var wtt=ha(),Qz=Dm(),dB=Ctt(),Lz=Y("stream");(!Lz.Writable||!Lz.Writable.prototype.destroy)&&(Lz=ca());_tt.exports={buffer:function(e,t){var r={stream:function(n,i){var o=Lz.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return Qz.resolve(e.length)}};return dB(r,t)},file:function(e,t){var r={stream:function(n,i){return wtt.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new Qz(function(n,i){wtt.stat(e,function(o,s){o?i(o):n(s.size)})})}};return dB(r,t)},url:function(e,t,r){if(typeof t=="string"&&(t={url:t}),!t.url)throw"URL missing";t.headers=t.headers||{};var n={stream:function(i,o){var s=Object.create(t);return s.headers=Object.create(t.headers),s.headers.range="bytes="+i+"-"+(o||""),e(s)},size:function(){return new Qz(function(i,o){var s=e(t);s.on("response",function(a){s.abort(),a.headers["content-length"]?i(a.headers["content-length"]):o(new Error("Missing content length header"))}).on("error",o)})}};return dB(n,r)},s3:function(e,t,r){var n={size:function(){return new Qz(function(i,o){e.headObject(t,function(s,a){s?o(s):i(a.ContentLength)})})},stream:function(i,o){var s={};for(var a in t)s[a]=t[a];return s.Range="bytes="+i+"-"+(o||""),e.getObject(s).createReadStream()}};return dB(n,r)},custom:function(e,t){return dB(e,t)}}});var Stt=I(fB=>{"use strict";iZe();cZe();ate();fB.Parse=_z();fB.ParseOne=met();fB.Extract=ptt();fB.Open=vtt()});var Ytt=I((H5r,$f)=>{var un=Y("fs"),Mz=Y("os"),fo=Y("path"),Dtt=Y("crypto"),Xu={fs:un.constants,os:Mz.constants},Rtt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Btt=/XXXXXX/,Vgr=3,Ntt=(Xu.O_CREAT||Xu.fs.O_CREAT)|(Xu.O_EXCL||Xu.fs.O_EXCL)|(Xu.O_RDWR||Xu.fs.O_RDWR),Wgr=Mz.platform()==="win32",Kgr=Xu.EBADF||Xu.os.errno.EBADF,Zgr=Xu.ENOENT||Xu.os.errno.ENOENT,Ott=448,Ftt=384,Xgr="exit",d_=[],Qtt=un.rmdirSync.bind(un),Ltt=!1;function eyr(e,t){return un.rm(e,{recursive:!0},t)}function Ptt(e){return un.rmSync(e,{recursive:!0})}function bfe(e,t){let r=f_(e,t),n=r[0],i=r[1];uyr(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=Utt(s);un.stat(u,function(d){if(!d)return a-- >0?c():i(new Error("Could not get a unique tmp filename, max tries reached "+u));i(null,u)})}catch(u){i(u)}})()})}function Ife(e){let t=f_(e),r=t[0],n=dyr(r),i=n.tries;do{let o=Utt(n);try{un.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function tyr(e,t){let r=f_(e,t),n=r[0],i=r[1];bfe(n,function(s,a){if(s)return i(s);un.open(a,Ntt,n.mode||Ftt,function(u,d){if(u)return i(u);if(n.discardDescriptor)return un.close(d,function(p){return i(p,a,void 0,yfe(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,yfe(a,f?-1:d,n,!1))}})})}function ryr(e){let t=f_(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=Ife(r),o=un.openSync(i,Ntt,r.mode||Ftt);return r.discardDescriptor&&(un.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:yfe(i,n?-1:o,r,!0)}}function nyr(e,t){let r=f_(e,t),n=r[0],i=r[1];bfe(n,function(s,a){if(s)return i(s);un.mkdir(a,n.mode||Ott,function(u){if(u)return i(u);i(null,a,Mtt(a,n,!1))})})}function iyr(e){let t=f_(e),r=t[0],n=Ife(r);return un.mkdirSync(n,r.mode||Ott),{name:n,removeCallback:Mtt(n,r,!0)}}function oyr(e,t){let r=function(n){if(n&&!Efe(n))return t(n);t()};0<=e[0]?un.close(e[0],function(){un.unlink(e[1],r)}):un.unlink(e[1],r)}function syr(e){let t=null;try{0<=e[0]&&un.closeSync(e[0])}catch(r){if(!fyr(r)&&!Efe(r))throw r}finally{try{un.unlinkSync(e[1])}catch(r){Efe(r)||(t=r)}}if(t!==null)throw t}function yfe(e,t,r,n){let i=Pz(syr,[t,e],n),o=Pz(oyr,[t,e],n,i);return r.keep||d_.unshift(i),n?i:o}function Mtt(e,t,r){let n=t.unsafeCleanup?eyr:un.rmdir.bind(un),i=t.unsafeCleanup?Ptt:Qtt,o=Pz(i,e,r),s=Pz(n,e,r,o);return t.keep||d_.unshift(o),r?o:s}function Pz(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=d_.indexOf(a);return c>=0&&d_.splice(c,1),i=!0,r||e===Qtt||e===Ptt?e(t):e(t,s||function(){})}}}function ayr(){if(Ltt)for(;d_.length;)try{d_[0]()}catch{}}function Ttt(e){let t=[],r=null;try{r=Dtt.randomBytes(e)}catch{r=Dtt.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(Rtt[r[n]%Rtt.length]);return t.join("")}function ma(e){return typeof e>"u"}function f_(e,t){if(typeof e=="function")return[{},e];if(ma(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function cyr(e,t,r){let n=fo.isAbsolute(e)?e:fo.join(t,e);un.stat(n,function(i){i?un.realpath(fo.dirname(n),function(o,s){if(o)return r(o);r(null,fo.join(s,fo.basename(n)))}):un.realpath(n,r)})}function lyr(e,t){let r=fo.isAbsolute(e)?e:fo.join(t,e);try{return un.statSync(r),un.realpathSync(r)}catch{let i=un.realpathSync(fo.dirname(r));return fo.join(i,fo.basename(r))}}function Utt(e){let t=e.tmpdir;if(!ma(e.name))return fo.join(t,e.dir,e.name);if(!ma(e.template))return fo.join(t,e.dir,e.template).replace(Btt,Ttt(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",Ttt(12),e.postfix?"-"+e.postfix:""].join("");return fo.join(t,e.dir,r)}function gfe(e,t){if(typeof t!="string")throw new Error(`${e} option must be a string, got "${typeof t}".`);if(t.includes(".."))throw new Error("Relative value not allowed");return t}function $tt(e){if(!ma(e.name)){let t=e.name;if(fo.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=fo.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!ma(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(Btt))throw new Error(`Invalid template, found "${e.template}".`)}if(!ma(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=ma(e.name)?e.tries||Vgr:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=ma(e.prefix)?"":gfe("prefix",e.prefix),e.postfix=ma(e.postfix)?"":gfe("postfix",e.postfix),e.template=ma(e.template)?void 0:gfe("template",e.template)}function xtt(e,t,r,n){if(ma(t))return n(null);cyr(t,r,function(i,o){if(i)return n(i);let s=fo.relative(r,o);if(s.startsWith("..")||fo.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function ktt(e,t,r){if(ma(t))return;let n=lyr(t,r),i=fo.relative(r,n);if(i.startsWith("..")||fo.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function uyr(e,t){hyr(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{$tt(e,n)}catch(i){return t(i)}xtt("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=ma(o)?"":o,xtt("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function dyr(e){let t=e.tmpdir=jtt(e);$tt(e,t);let r=ktt("dir",e.dir,t);return e.dir=ma(r)?"":r,e.template=ktt("template",e.template,t),e}function fyr(e){return qtt(e,-Kgr,"EBADF")}function Efe(e){return qtt(e,-Zgr,"ENOENT")}function qtt(e,t,r){return Wgr?e.code===r:e.code===r&&e.errno===t}function pyr(){Ltt=!0}function hyr(e,t){return un.realpath(e&&e.tmpdir||Mz.tmpdir(),t)}function jtt(e){return un.realpathSync(e&&e.tmpdir||Mz.tmpdir())}process.addListener(Xgr,ayr);Object.defineProperty($f.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return jtt()}});$f.exports.dir=nyr;$f.exports.dirSync=iyr;$f.exports.file=tyr;$f.exports.fileSync=ryr;$f.exports.tmpName=bfe;$f.exports.tmpNameSync=Ife;$f.exports.setGracefulCleanup=pyr});var ztt=I((z5r,Htt)=>{Htt.exports=async function*(t){let r=[];t.on("data",a=>r.push(a));let n,i=new Promise(a=>n=a),o=!1;t.on("end",()=>{o=!0,n()});let s=!1;for(t.on("error",a=>{s=a,n()});!o||r.length>0;)if(r.length===0?(t.resume(),await Promise.race([myr(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function myr(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Wtt=I((J5r,Vtt)=>{var{EventEmitter:Ayr}=Y("events"),gyr=wx(),yyr=_i(),Uz=As(),Jtt=si(),Eyr=pf(),byr=y2(),Gtt=E2(),Cfe=class extends Ayr{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i||{},this.name=`Sheet${this.id}`,this._columns=null,this._keys={},this._dimensions=new Eyr}destroy(){throw new Error("Invalid Operation: destroy")}get dimensions(){return this._dimensions}get columns(){return this._columns}getColumn(t){if(typeof t=="string"){let r=this._keys[t];if(r)return r;t=Jtt.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new Gtt(this,r++))}return this._columns[t-1]}getColumnKey(t){return this._keys[t]}setColumnKey(t,r){this._keys[t]=r}deleteColumnKey(t){delete this._keys[t]}eachColumnKey(t){yyr.each(this._keys,t)}async read(){try{for await(let t of this.parse())for(let{eventType:r,value:n}of t)this.emit(r,n);this.emit("finished")}catch(t){this.emit("error",t)}}async*[Symbol.asyncIterator](){for await(let t of this.parse())for(let{eventType:r,value:n}of t)r==="row"&&(yield n)}async*parse(){let{iterator:t,options:r}=this,n=!1,i=!1,o=null;switch(r.worksheets){case"emit":n=!0;break;case"prep":break;default:break}switch(r.hyperlinks){case"emit":i=!0;break;case"cache":this.hyperlinks=o={};break;default:break}if(!n&&!i&&!o)return;let{sharedStrings:s,styles:a,properties:c}=this.workbook,u=!1,d=!1,f=!1,p=null,h=null,m=null,A=null;for await(let g of gyr(t)){let y=[];for(let{eventType:b,value:E}of g)if(b==="opentag"){let C=E;if(n)switch(C.name){case"cols":u=!0,p=[];break;case"sheetData":d=!0;break;case"col":u&&p.push({min:parseInt(C.attributes.min,10),max:parseInt(C.attributes.max,10),width:parseFloat(C.attributes.width),styleId:parseInt(C.attributes.style||"0",10)});break;case"row":if(d){let w=parseInt(C.attributes.r,10);if(h=new byr(this,w),C.attributes.ht&&(h.height=parseFloat(C.attributes.ht)),C.attributes.s){let T=parseInt(C.attributes.s,10),R=a.getStyleModel(T);R&&(h.style=R)}}break;case"c":h&&(m={ref:C.attributes.r,s:parseInt(C.attributes.s,10),t:C.attributes.t});break;case"f":m&&(A=m.f={text:""});break;case"v":m&&(A=m.v={text:""});break;case"is":case"t":m&&(A=m.v={text:""});break;case"mergeCell":break;default:break}if(i||o)switch(C.name){case"hyperlinks":f=!0;break;case"hyperlink":if(f){let w={ref:C.attributes.ref,rId:C.attributes["r:id"]};i?y.push({eventType:"hyperlink",value:w}):o[w.ref]=w}break;default:break}}else if(b==="text")n&&A&&(A.text+=E);else if(b==="closetag"){let C=E;if(n)switch(C.name){case"cols":u=!1,this._columns=Gtt.fromModel(p);break;case"sheetData":d=!1;break;case"row":this._dimensions.expandRow(h),y.push({eventType:"row",value:h}),h=null;break;case"c":if(h&&m){let w=Jtt.decodeAddress(m.ref),T=h.getCell(w.col);if(m.s){let R=a.getStyleModel(m.s);R&&(T.style=R)}if(m.f){let R={formula:m.f.text};m.v&&(m.t==="str"?R.result=Uz.xmlDecode(m.v.text):R.result=parseFloat(m.v.text)),T.value=R}else if(m.v)switch(m.t){case"s":{let R=parseInt(m.v.text,10);s?T.value=s[R]:T.value={sharedString:R};break}case"inlineStr":case"str":T.value=Uz.xmlDecode(m.v.text);break;case"e":T.value={error:m.v.text};break;case"b":T.value=parseInt(m.v.text,10)!==0;break;default:Uz.isDateFmt(T.numFmt)?T.value=Uz.excelToDate(parseFloat(m.v.text),c.model&&c.model.date1904):T.value=parseFloat(m.v.text);break}if(o){let R=o[m.ref];R&&(T.text=T.value,T.value=void 0,T.hyperlink=R)}m=null}break;default:break}(i||o)&&C.name==="hyperlinks"&&(f=!1)}y.length>0&&(yield y)}}};Vtt.exports=Cfe});var Ztt=I((G5r,Ktt)=>{var{EventEmitter:Iyr}=Y("events"),Cyr=wx(),wyr=kl(),_yr=kh(),wfe=class extends Iyr{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i}get count(){return this.hyperlinks&&this.hyperlinks.length||0}each(t){return this.hyperlinks.forEach(t)}async read(){let{iterator:t,options:r}=this,n=!1,i=null;switch(r.hyperlinks){case"emit":n=!0;break;case"cache":this.hyperlinks=i={};break;default:break}if(!n&&!i){this.emit("finished");return}try{for await(let o of Cyr(t))for(let{eventType:s,value:a}of o)if(s==="opentag"){let c=a;if(c.name==="Relationship"){let u=c.attributes.Id;switch(c.attributes.Type){case _yr.Hyperlink:{let d={type:wyr.RelationshipType.Styles,rId:u,target:c.attributes.Target,targetMode:c.attributes.TargetMode};n?this.emit("hyperlink",d):i[d.rId]=d}break;default:break}}}this.emit("finished")}catch(o){this.emit("error",o)}}};Ktt.exports=wfe});var rrt=I((V5r,trt)=>{var _fe=Y("fs"),{EventEmitter:vyr}=Y("events"),{PassThrough:Syr,Readable:Dyr}=yx(),Ryr=Y("stream"),Tyr=Stt(),ert=Ytt(),Yy=ztt(),xyr=wx(),Xtt=Kq(),kyr=nj(),Byr=tj(),Nyr=Wtt(),Oyr=Ztt();ert.setGracefulCleanup();var $z=class extends vyr{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new Xtt,this.styles.init()}_getStream(t){if(t instanceof Ryr.Readable||t instanceof Dyr)return t;if(typeof t=="string")return _fe.createReadStream(t);throw new Error(`Could not recognise input: ${t}`)}async read(t,r){try{for await(let{eventType:n,value:i}of this.parse(t,r))switch(n){case"shared-strings":this.emit(n,i);break;case"worksheet":this.emit(n,i),await i.read();break;case"hyperlinks":this.emit(n,i);break}this.emit("end"),this.emit("finished")}catch(n){this.emit("error",n)}}async*[Symbol.asyncIterator](){for await(let{eventType:t,value:r}of this.parse())t==="worksheet"&&(yield r)}async*parse(t,r){r&&(this.options=r);let n=this.stream=this._getStream(t||this.input),i=Tyr.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of Yy(i)){let a,c;switch(s.path){case"_rels/.rels":break;case"xl/_rels/workbook.xml.rels":await this._parseRels(s);break;case"xl/workbook.xml":await this._parseWorkbook(s);break;case"xl/sharedStrings.xml":yield*this._parseSharedStrings(s);break;case"xl/styles.xml":await this._parseStyles(s);break;default:s.path.match(/xl\/worksheets\/sheet\d+[.]xml/)?(a=s.path.match(/xl\/worksheets\/sheet(\d+)[.]xml/),c=a[1],this.sharedStrings&&this.workbookRels?yield*this._parseWorksheet(Yy(s),c):await new Promise((u,d)=>{ert.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=_fe.createWriteStream(p);return A.on("error",d),s.pipe(A),A.on("finish",()=>u())})})):s.path.match(/xl\/worksheets\/_rels\/sheet\d+[.]xml.rels/)&&(a=s.path.match(/xl\/worksheets\/_rels\/sheet(\d+)[.]xml.rels/),c=a[1],yield*this._parseHyperlinks(Yy(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=_fe.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new Syr)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new Byr;this.workbookRels=await r.parseStream(Yy(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new kyr;await r.parseStream(Yy(t)),this.properties=r.map.workbookPr,this.model=r.model}async*_parseSharedStrings(t){switch(this._emitEntry({type:"shared-strings"}),this.options.sharedStrings){case"cache":this.sharedStrings=[];break;case"emit":break;default:return}let r=null,n=[],i=0,o=null;for await(let s of xyr(Yy(t)))for(let{eventType:a,value:c}of s)if(a==="opentag"){let u=c;switch(u.name){case"b":o=o||{},o.bold=!0;break;case"charset":o=o||{},o.charset=parseInt(u.attributes.charset,10);break;case"color":o=o||{},o.color={},u.attributes.rgb&&(o.color.argb=u.attributes.argb),u.attributes.val&&(o.color.argb=u.attributes.val),u.attributes.theme&&(o.color.theme=u.attributes.theme);break;case"family":o=o||{},o.family=parseInt(u.attributes.val,10);break;case"i":o=o||{},o.italic=!0;break;case"outline":o=o||{},o.outline=!0;break;case"rFont":o=o||{},o.name=u.value;break;case"si":o=null,n=[],r=null;break;case"sz":o=o||{},o.size=parseInt(u.attributes.val,10);break;case"strike":break;case"t":r=null;break;case"u":o=o||{},o.underline=!0;break;case"vertAlign":o=o||{},o.vertAlign=u.attributes.val;break}}else if(a==="text")r=r?r+c:c;else if(a==="closetag")switch(c.name){case"r":n.push({font:o,text:r}),o=null,r=null;break;case"si":this.options.sharedStrings==="cache"?this.sharedStrings.push(n.length?{richText:n}:r):this.options.sharedStrings==="emit"&&(yield{index:i++,text:n.length?{richText:n}:r}),n=[],o=null,r=null;break}}async _parseStyles(t){this._emitEntry({type:"styles"}),this.options.styles==="cache"&&(this.styles=new Xtt,await this.styles.parseStream(Yy(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new Nyr({workbook:this,id:r,iterator:t,options:this.options}),i=(this.workbookRels||[]).find(s=>s.Target===`worksheets/sheet${r}.xml`),o=i&&(this.model.sheets||[]).find(s=>s.rId===i.Id);o&&(n.id=o.id,n.name=o.name,n.state=o.state),this.options.worksheets==="emit"&&(yield{eventType:"worksheet",value:n})}*_parseHyperlinks(t,r){this._emitEntry({type:"hyperlinks",id:r});let n=new Oyr({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};$z.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};trt.exports=$z});var ort=I((W5r,irt)=>{var nrt={Workbook:n8e(),ModelContainer:o8e(),stream:{xlsx:{WorkbookWriter:rZe(),WorkbookReader:rrt()}}};Object.assign(nrt,kl());irt.exports=nrt});var art=I((K5r,srt)=>{if(parseInt(process.versions.node.split(".")[0],10)<10)throw new Error("For node versions older than 10, please use the ES5 Import: https://github.com/exceljs/exceljs#es5-imports");srt.exports=ort()});function urt(e){let t=new Set;for(let r=0;r<e.length;r++){let n=e[r];if(!n.trim())throw new Error(`Header row contains a blank column at position ${r+1}`);let i=n.trim().toLowerCase();if(t.has(i))throw new Error(`Header row contains a duplicate column: "${n}"`);t.add(i)}}function Lyr(e,t){let r=new URL(e).pathname.toLowerCase();if(r.endsWith(".xls")||r.endsWith(".xlsx")||r.endsWith(".xlsm")||r.endsWith(".xlsb")||r.endsWith(".ods"))return"excel";let n=(t??"").toLowerCase();return n.includes("spreadsheet")||n.includes("excel")||n.includes("sheet")?"excel":"csv"}async function Pyr(e){let r=(await Promise.resolve().then(()=>eo(PLe(),1))).default.parse(e,{header:!1,skipEmptyLines:"greedy",dynamicTyping:!1,transform:o=>o.trim()});if(r.errors.length>0&&r.data.length===0){let o=r.errors[0];throw new Error(`CSV parse error at row ${o.row}: ${o.message}`)}if(r.data.length===0)return{columns:[],rows:[]};let n=(r.data[0]??[]).map(o=>String(o??"").trim());urt(n);let i=[];for(let o=1;o<r.data.length;o++){let s=r.data[o]??[],a={};for(let c=0;c<n.length;c++)a[n[c]]=s[c]??null;i.push(a)}return{columns:n,rows:i}}function vfe(e){if(e==null)return null;if(e instanceof Date)return e.toISOString().slice(0,10);if(typeof e=="number")return String(e);if(typeof e=="string"||typeof e=="boolean")return e;let t=e;return"text"in t?String(t.text??""):"result"in t?vfe(t.result):"richText"in t&&Array.isArray(t.richText)?t.richText.map(r=>r.text??"").join(""):"hyperlink"in t?String(t.hyperlink??""):String(e)}async function Myr(e){let t=(await Promise.resolve().then(()=>eo(W7(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>crt)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${crt}-byte safety cap`)}function drt(e){let t=0,r=[];return e.eachRow({includeEmpty:!1},(n,i)=>{if(t>0)return;let o=n.values.slice(1);o.some(s=>s!=null&&s!=="")&&(t=i,r=o.map(s=>String(vfe(s)??"").trim()))}),{headerRowNum:t,columns:r}}function lrt(e){let{headerRowNum:t,columns:r}=drt(e);if(!t)return{columns:[],rows:[]};urt(r);let n=[];return e.eachRow({includeEmpty:!1},(i,o)=>{if(o<=t)return;let s=i.values.slice(1);if(s.every(c=>c==null||c===""))return;let a={};for(let c=0;c<r.length;c++)a[r[c]]=vfe(s[c]);n.push(a)}),{columns:r,rows:n}}async function Uyr(e,t,r){await Myr(e);let n=await Promise.resolve().then(()=>eo(art(),1)),i=n.default??n,o=new i.Workbook;await o.xlsx.load(e);let s=o.worksheets.map(u=>u.name);if(t<0||t>=s.length)throw new Error(`sheetIndex ${t} out of range (have ${s.length} sheets: ${s.join(", ")})`);let a=()=>s.map((u,d)=>`${d}:"${u}"`).join(", "),c=(u,d)=>{throw new Error(`${u.message} on sheet ${d} ("${s[d]}"). availableSheets: [${a()}]. Re-call with a sheetIndex pointing at the data sheet.`)};if(r)try{return{...lrt(o.worksheets[t]),sheetName:o.worksheets[t].name,sheetIndex:t,availableSheets:s}}catch(u){c(u,t)}for(let u=t;u<s.length;u++){let d=o.worksheets[u];if(drt(d).headerRowNum!==0)try{return{...lrt(d),sheetName:d.name,sheetIndex:u,availableSheets:s}}catch(f){c(f,u)}}throw new Error(`No sheet with a header row was found. availableSheets: [${a()}].`)}async function frt(e){let t=Math.max(0,e.offset??0),r=Math.min(Fyr,Math.max(1,e.limit??Qyr)),n=e.sheetIndex??0,i=await zd(e.sourceUrl),o=await dc(i,{timeoutMs:cI,maxBytes:jL});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??Lyr(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await Pyr(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await Uyr(s,n,e.sheetIndex!==void 0);c=A.columns,u=A.rows,d=A.sheetName,f=A.availableSheets,p=A.sheetIndex}let h=u.length,m=u.slice(t,t+r);return{sourceUrl:e.sourceUrl,kind:a,...a==="excel"?{sheetIndex:p,sheetName:d,availableSheets:f}:{},totalRows:h,offset:t,limit:r,returned:m.length,hasMore:t+m.length<h,columns:c,rows:m}}var Fyr,Qyr,crt,prt=G(()=>{"use strict";bu();Fyr=500,Qyr=200,crt=100*1024*1024});function $yr(e){if(e.internalNotes!==void 0)throw rr(new Error("A cash entry's notes cannot be edited via the API today (the update fails upstream). Nothing was changed. To change the notes, void the entry and create a new one."));if((Array.isArray(e.lines)?e.lines:[]).some(r=>!!r?.taxProfileResourceId))throw rr(new Error("A taxed cash entry's lines cannot be edited via the API today: void it and create a new one. Nothing was changed."))}function hrt(e){return{create:(t,r)=>t.post(`/api/v1/${p_[e]}`,{saveAsDraft:!1,...r,currency:zt(r.currency),taxCurrency:zt(r.taxCurrency)},Yi),list:(t,r)=>t.list(`/api/v1/${p_[e]}`,r),get:(t,r)=>t.get(`/api/v1/${p_[e]}/${r}`),update:async(t,r,n)=>{$yr(n);let i={...n,resourceId:r};if(!i.accountResourceId){let o=await t.get(`/api/v1/${p_[e]}/${r}`);if(i.accountResourceId=o.data.organizationAccountResourceId??o.data.account?.resourceId,!i.accountResourceId)throw new Error(`accountResourceId required for ${p_[e]} update and could not be derived from existing entry`)}return i.currency&&(i.currency=zt(i.currency)),t.put(`/api/v1/${p_[e]}/${r}`,i)}}}var p_,qz,jz,Yz,Hz,zz,Jz,Gz,Vz,Wz,Kz,Sfe=G(()=>{"use strict";gr();yt();p_={IN:"cash-in-entries",OUT:"cash-out-entries"};qz=hrt("IN"),jz=hrt("OUT"),Yz=qz.create,Hz=qz.list,zz=qz.get,Jz=qz.update,Gz=jz.create,Vz=jz.list,Wz=jz.get,Kz=jz.update});async function pB(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Yi)}async function Zz(e,t){return e.list("/api/v1/cash-transfers",t)}async function Xz(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var Dfe=G(()=>{"use strict";gr();Cn()});async function eJ(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function tJ(e,t){return e.list("/api/v1/scheduled/bills",t)}async function rJ(e,t){return e.list("/api/v1/scheduled/journals",t)}async function nJ(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function iJ(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function oJ(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function sJ(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function aJ(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function cJ(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function lJ(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function uJ(e,t,r){let{currency:n,...i}=qyr(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:zt(n)})}function qyr(e){let t={...e};ZL(t);let r=Array.isArray(t.schedulerEntries)?t.schedulerEntries:[];if(typeof t.taxVatApplicable!="boolean"&&r.some(n=>!!n?.taxProfileResourceId)&&(t.taxVatApplicable=!0),t.taxVatApplicable===!0&&typeof t.taxInclusion!="boolean")throw rr(new Error("taxInclusion is required when the schedule is taxed (a schedulerEntries line carries a tax profile, or taxVatApplicable is true): the update resets it when omitted, and the stored value cannot be read back. Send taxInclusion true (prices include tax) or false (CLI: --tax-inclusion inclusive|exclusive). Nothing was changed."));return t}async function dJ(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var Rfe=G(()=>{"use strict";yt()});import{statSync as mrt}from"node:fs";function Art(e){for(let t of e)try{if(mrt(t).isFile())return t}catch{}return null}function grt(e){for(let t of e)try{if(mrt(t).isDirectory())return t}catch{}return null}var Tfe=G(()=>{"use strict"});import{readFileSync as kfe}from"node:fs";import{dirname as Irt,join as Nm}from"node:path";import{fileURLToPath as Crt}from"node:url";function wrt(e){let t=new Set(e);for(let r of e){let n=Hyr.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function _rt(e){let t=e.toLowerCase();return t=t.replace(/https?:\/\/\S+/g,""),t=t.replace(/[*#`|_\-~\[\]()>]/g," "),(t.match(/[a-z0-9]+/g)??[]).filter(n=>n.length>1&&!Yyr.has(n))}function hB(e){let t=e??Wyr();if(fJ&&brt===t)return fJ;let r=kfe(t,"utf-8");return fJ=JSON.parse(r),brt=t,fJ}function vrt(){let e=Crt(import.meta.url),t=Irt(e),r=[Nm(t,"..","..","..","help-center-mirror","help-center-index.json"),Nm(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),Nm(t,"help-center-mirror","help-center-index.json")];return Art(r)??void 0}function Wyr(){let e=vrt();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function mB(){return xfe===null&&(xfe=vrt()!==void 0),xfe}function Hy(e,t,r={}){let n=r.limit??5,i=_rt(t);if(i.length===0)return[];let o=wrt(i).slice(0,Gyr),s=new Map(e.sections.map(c=>[c.slug,c])),a=[];for(let c of e.articles){if(r.section&&c.section!==r.section)continue;let u=new Map;for(let h of c.tokens)u.set(h,(u.get(h)??0)+1);let d=0,f=[],p=c.title.toLowerCase();for(let h of o){let m=u.get(h)??0,A=e.idf[h]??0,g=!1;if(m===0&&h.length>=Jyr){let C=0;for(let[w,T]of u)if(w.startsWith(h)&&w!==h&&(m+=T,A=Math.max(A,e.idf[w]??0),g=!0,++C>=Vyr))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(yrt+1),b=m+yrt*(1-Ert+Ert*(c.tokenCount/e.avgDocLen)),E=A*(y/b);g&&(E*=zyr),p.includes(h)&&(E*=jyr),d+=E}if(d>0){let h=s.get(c.section);h&&a.push({article:c,score:d,scoreKind:"bm25",section:h,matchedTerms:f})}}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function Bfe(e,t){let r=t??Kyr();if(!r)return null;try{let n=Nm(r,`${e.section}.md`),i=kfe(n,"utf-8"),o=`### ${e.title}`,s=i.indexOf(o);if(s===-1)return null;let a=s+o.length,c=i.indexOf(`
|
|
659
659
|
---
|
|
660
660
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function Kyr(){let e=Crt(import.meta.url),t=Irt(e),r=[Nm(t,"..","..","..","help-center-mirror"),Nm(t,"..","..","..","assets","skills","api","help-center-mirror"),Nm(t,"help-center-mirror")];for(let n of r)try{return kfe(Nm(n,"index.md"),"utf-8"),n}catch{}return null}var yrt,Ert,jyr,Yyr,Hyr,zyr,Jyr,Gyr,Vyr,fJ,brt,xfe,AB=G(()=>{"use strict";Tfe();ng();yrt=1.2,Ert=.75,jyr=1.5,Yyr=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),Hyr=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);zyr=.7,Jyr=3,Gyr=32,Vyr=5;fJ=null,brt=null;xfe=null});import{existsSync as Zyr,readFileSync as Xyr}from"node:fs";import{dirname as eEr,join as Nfe}from"node:path";import{fileURLToPath as tEr}from"node:url";function gB(e){let t=e??sEr();if(!t)return null;if(pJ&&Drt===t)return pJ;try{let r=Xyr(t,"utf-8");return pJ=JSON.parse(r),Drt=t,pJ}catch{return null}}function sEr(){let e=tEr(import.meta.url),t=eEr(e),r=[Nfe(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),Nfe(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Nfe(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(Zyr(n))return n;return null}function xrt(e,t){let r=Math.min(e.length,t.length),n=0;for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function krt(){return hJ!==null?hJ:(hJ=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",hJ||null)}async function Ofe(e){let t=krt();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),nEr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:rEr,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Rrt&&(Rrt=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
661
|
-
`)),null)}catch{return null}}async function yB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??iEr,c=n.minBm25??oEr;if(i==="bm25"||!t)return Hy(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Ofe(r);return m?Trt(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):Hy(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Ofe(r),Promise.resolve(Hy(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Trt(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Brt(p,h,o)}function Trt(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=xrt(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Brt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Srt+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(Srt+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function Ffe(e){return e!==null&&!!krt()}var rEr,nEr,Srt,iEr,oEr,pJ,Drt,hJ,Rrt,mJ=G(()=>{"use strict";AB();rEr="text-embedding-3-small",nEr=2e3,Srt=60,iEr=.3,oEr=1.5,pJ=null,Drt=null,hJ=null,Rrt=!1});async function Nrt(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=hB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:gB(),u=await yB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Bfe(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Ort(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:aEr}async function AJ(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Ort())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(cEr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return lEr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function lEr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Qfe(e,t={}){return process.env.CLIO_DAEMON==="1"||mB()?Nrt(e,t):AJ(e,t)}var aEr,cEr,Frt=G(()=>{"use strict";AB();mJ();aEr="https://mcp.jaz.ai/help-center/search",cEr=4e3});var Lfe=G(()=>{"use strict";AB();mJ();Frt();AB()});async function Om(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function Fm(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var EB=G(()=>{"use strict";Cn()});async function gJ(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:zt(t.currency),taxCurrency:zt(t.taxCurrency)},BRe)}var Pfe=G(()=>{"use strict";yt();gr()});async function yJ(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EJ(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function bB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bJ(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Mfe=G(()=>{"use strict"});function uEr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function h_(e,t){return e.post("/api/v1/jots",{entries:t.map(uEr)})}async function IJ(e,t){return e.post("/api/v1/jots/search",t,Qt)}async function Qrt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CJ=G(()=>{"use strict";gr()});async function Lrt(e,t){return e.post("/api/v1/agents/memories",t)}async function Ufe(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Prt=G(()=>{"use strict";gr()});function wJ(){return process.env.ENABLE_MEMORY==="true"}function $fe(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Mrt(e){return!wJ()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var qfe=G(()=>{"use strict"});import{createHash as dEr}from"node:crypto";function CEr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:qrt.some(r=>t.includes(r))?[null,"directive_invalid"]:$rt.test(t)?[null,"directive_invalid"]:gEr.test(t)?[null,"directive_contains_url"]:yEr.test(t)?[null,"directive_contains_email"]:[t,null]}function wEr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>EEr?[null,"match_condition_too_long"]:qrt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:$rt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function _Er(e){return e==null?[null,null]:Number.isInteger(e)?e<bEr||e>IEr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function vEr(e,t,r,n,i,o,s,a){if(e)return dEr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function SEr(e){Promise.resolve().then(()=>(UL(),ML)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function zrt(e,t,r){let n=t.action,i=t.category,o=mEr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(SEr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Mrt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>fEr||!AEr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=CEr(t.directive);if(E)return u(E);p=b;let[C,w]=_Er(t.importance);if(w)return u(w);h=C}let[m,A]=wEr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=pEr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,hEr));let E=vEr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await jfe(()=>Lrt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await jfe(()=>Ufe(e.client,b))}else{let b={forgetAll:!0};y=await jfe(()=>Ufe(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function jfe(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof Ur?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var $rt,qrt,fEr,pEr,hEr,jrt,Yrt,Hrt,mEr,AEr,gEr,yEr,EEr,bEr,IEr,Jrt=G(()=>{"use strict";Prt();bo();qfe();qfe();$rt=/[\x00-\x1f\x7f]/,qrt=["{{","}}","```","<",">"],fEr=120,pEr=3,hEr=140,jrt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Yrt=["set","forget","forget_all"],Hrt=["this_org","all_orgs"],mEr={this_org:"ORG_USER",all_orgs:"USER"},AEr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,gEr=/https?:\/\//i,yEr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,EEr=255,bEr=0,IEr=100});async function _J(e,t){return e.list("/api/v1/organization-users",t)}async function vJ(e,t){return e.search("/api/v1/organization-users/search",t)}async function m_(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SJ(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DJ(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Yfe=G(()=>{"use strict"});async function RJ(e,t){return e.get(`/api/v1/payments/${t}`)}async function TJ(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:zt(r.currency)})}async function xJ(e,t){await e.delete(`/api/v1/payments/${t}`)}function kJ(e){return(t,r)=>t.post(`/api/v1/${DEr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:zt(n.currency)}))},RRe)}var DEr,eKr,Grt,tKr,rKr,Hfe=G(()=>{"use strict";yt();gr();DEr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};eKr=kJ("saleBulk"),Grt=kJ("saleBatch"),tKr=kJ("purchaseBulk"),rKr=kJ("purchaseBatch")});async function qf(e,t,r,n,i,o=kRe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof Ur?c.status<500&&c.status!==401?rr(c):new $d(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof Tp?rr(c):c}let a=s?.data;if(!i(a))throw new $d(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function NJ(e,t,r){try{Co(e,t,r)}catch(n){throw rr(n)}}function zy(e){return NJ(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OJ(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FJ(e,t){return qf(e,"POST",REr,t,Qm)}async function QJ(e,t,r){return qf(e,"PUT",`/api/v1/unapplied-payments/${zy(t)}`,r,Qm)}async function LJ(e,t,r){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/activate`,{hash:r},Qm)}async function PJ(e,t,r,n){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/attributions`,{hash:r,attributions:n},Qm)}async function MJ(e,t,r,n){return NJ(n,"paymentResourceId","Pass the payment record resourceId."),qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/payments`,{hash:r,paymentResourceId:n},Qm)}async function UJ(e,t,r,n){return NJ(r,"childResourceId","Pass the payment record resourceId from the children list."),qf(e,"DELETE",`/api/v1/unapplied-payments/${zy(t)}/children/${encodeURIComponent(r)}`,{hash:n},Qm)}async function $J(e,t,r){return qf(e,"DELETE",`/api/v1/unapplied-payments/${zy(t)}`,{hash:r},Qm)}async function qJ(e,t,r){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/unbatch`,{hash:r},Qm)}async function jJ(e,t){return NJ(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),qf(e,"POST",TEr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ia)}var REr,TEr,BJ,Vrt,Wrt,Qm,zfe=G(()=>{"use strict";bo();gr();xQ();yt();REr="/api/v1/unapplied-payments",TEr="/api/v1/reconciliations/unapplied-payment",BJ=["SALE","PURCHASE"],Vrt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Wrt=["AMOUNT","PERCENTAGE"];Qm=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YJ(e,t,r={},n=Jfe){let i=xEr.has(t)?`/api/v1/${Iu(Krt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=yg.get(t);if(o!==void 0){if(!a)throw new me(`${t} does not take a report template. Templates apply to: ${[...yg.keys()].join(", ")}.`);let A=await df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Qt,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new me(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...IB].join(", ")}.`}:d}var Krt,xEr,Jfe,IB,Zrt,Gfe=G(()=>{"use strict";gr();yt();pT();Tu();Krt=["statement-of-account-export"],xEr=new Set(Krt),Jfe=9e4,IB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),Zrt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as kEr}from"node:crypto";import{writeFile as BEr,mkdir as NEr}from"node:fs/promises";import{dirname as OEr,isAbsolute as FEr,join as QEr}from"node:path";async function HJ(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Qt)}async function CB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function A_(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Vfe(e){return kEr("sha256").update(e).digest("hex").slice(0,16)}async function zJ(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Vfe(t),o=await CB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await A_(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await A_(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!FEr(r.outPath))throw new me(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??QEr(f,"Downloads",`pseudo-sql-${s}.csv`);return await NEr(OEr(p),{recursive:!0}),await BEr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function JJ(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new me(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function g_(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Wfe=G(()=>{"use strict";yt();gr()});async function ui(e,t,r){let n=await e.get(`/api/v1/${Kfe[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GJ(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Kfe[r]}/${n}/attachments`,o)}async function VJ(e,t,r,n){return e.delete(`/api/v1/${Kfe[t]}/${r}/attachments/${n}`)}var Kfe,wB,Lm=G(()=>{"use strict";Kfe={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},wB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ro(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var y_=G(()=>{"use strict"});async function WJ(e,t){return e.post("/api/v1/claims/conversion/preview",t,Qt)}async function KJ(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new me('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:FQ)}var _B,Zfe=G(()=>{"use strict";yt();gr();_B=["POST","POST_AND_RECORD"]});async function ZJ(e,t){if(!(t.amount>0))throw new me("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,TRe)}async function XJ(e,t){return e.search("/api/v1/employees/payouts/search",t)}var Xrt,Xfe=G(()=>{"use strict";yt();gr();Xrt=["REIMBURSEMENT","ADVANCE"]});async function eG(e,t){return e.search("/api/v1/filing-submissions/search",t)}var epe=G(()=>{"use strict"});function tpe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function rpe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${ent(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>wu.has(u)),s=i.filter(u=>!wu.has(u)&&pc.has(u)),a=[`Nothing here can be extracted: found ${ent(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=kxe[u];d&&a.push(d)}return o.length>0&&a.push(`${CP(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${CP(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!wu.has(u)&&!pc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${CP([...wu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function ent(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var tnt=G(()=>{"use strict";_u()});function tG(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function vB(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&tG()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function Jy(e,t){return{error:e,hint:t,...npe}}function rnt(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${vB(e)}.`,...npe}}function Gy(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function Pm(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${vB({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...npe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var npe,nnt=G(()=>{"use strict";npe={kind:"validation",retriable:!1}});import{randomUUID as LEr}from"node:crypto";import{rmSync as PEr}from"node:fs";function ope(e){for(let t of e.tempDirs??[])try{PEr(t,{recursive:!0,force:!0})}catch{}}function ont(e){for(let[t,r]of Vy)e-r.createdAt>int&&(ope(r.plan),Vy.delete(t))}function UEr(){ipe||(ipe=setInterval(()=>ont(Date.now()),MEr),ipe.unref?.())}function spe(e,t){let r=Date.now();ont(r),UEr();let n=`dc_${LEr()}`;return Vy.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function snt(e,t){let r=Vy.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>int?(ope(r.plan),Vy.delete(e),null):r.plan}function ant(e,t){let r=Vy.get(e);!r||r.ownerKey!==t||(ope(r.plan),Vy.delete(e))}var int,MEr,Vy,ipe,cnt=G(()=>{"use strict";int=1800*1e3,MEr=300*1e3,Vy=new Map});function $Er(e){if(!e||typeof e!="object")return;let t=e;return t.validFiles?.[0]?.workflowResourceId??t.workflowResourceId}function qEr(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>dI(i.documentType)&&r.has(i.documentType))}))}}async function lnt(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?qEr(t,i):t;if(!n&&jEr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");RS(o);let a=await LP({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,workflowId:d.status==="uploaded"?$Er(d.response):void 0,error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function jEr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var unt=G(()=>{"use strict";iK();_u();Xd()});async function ed(e,t,r){if(!t)return e;let n=YEr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}function YEr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function jf(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var dnt=G(()=>{"use strict"});async function rG(e,t){return e.list("/api/v1/bank-rules",t)}async function SB(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function nG(e,t){return e.search("/api/v1/bank-rules/search",t)}async function iG(e,t){return e.post("/api/v1/bank-rules",t)}async function oG(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function sG(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var ape=G(()=>{"use strict"});async function aG(e,t){return e.list("/api/v1/fixed-assets",t)}async function DB(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function cG(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function lG(e,t){return e.post("/api/v1/fixed-assets",t,G0)}async function uG(e,t,r){let i=(await DB(e,t)).data,o={};for(let s of HEr){let a=i[s];if(a==null)continue;let c=zEr.has(s)?Hd(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/fixed-assets/${t}`,o)}async function dG(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function fG(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},G0)}async function RB(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,G0)}async function pG(e,t){return e.post("/api/v1/transfer-fixed-assets",t,G0)}async function hG(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function mG(e,t){return Io(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var Wy,HEr,zEr,AG=G(()=>{"use strict";Cn();rS();gr();Wy=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];HEr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],zEr=new Set(["purchaseDate","depreciationStartDate"])});async function gG(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function TB(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function yG(e,t){return e.post("/api/v1/scheduled/subscriptions",t,xp)}async function EG(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await TB(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw JEr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function JEr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function bG(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function IG(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function CG(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var cpe=G(()=>{"use strict";gr()});async function wG(e,t){return e.list("/api/v1/contact-groups",t)}async function _G(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function vG(e,t){return e.search("/api/v1/contact-groups/search",t)}async function SG(e,t){return e.post("/api/v1/contact-groups",t)}async function DG(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,Yb(r,A7))}async function RG(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var lpe=G(()=>{"use strict";Cn()});async function TG(e,t){return e.list("/api/v1/inventory-items",t)}async function xG(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function kG(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function NG(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof Ur&&n.status===404&&GEr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var BG,GEr,upe=G(()=>{"use strict";bo();BG=["ALL","AVAILABLE","FULLY_DRAWN"],GEr=/Inventory balance Not Found/i});async function OG(e,t){return e.list("/api/v1/custom-fields",t)}async function xB(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function FG(e,t){return e.search("/api/v1/custom-fields/search",t)}async function QG(e,t){return e.post("/api/v1/custom-fields",t)}function WEr(e){return e!==void 0&&VEr.every(t=>e[t]!==void 0)}function KEr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function ZEr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function LG(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!WEr(n.appliesTo)){let i=await xB(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??ZEr(i.data),n.appliesTo={...KEr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function PG(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var VEr,dpe=G(()=>{"use strict";VEr=["invoices","bills","customerCredits","supplierCredits","payments"]});var Uc,Ky,XEr,ebr,fpe,MG,UG,tbr,Aa,jl,Zy,E_,Xy,ppe=G(()=>{"use strict";Uc={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217)."}}},Ky={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition."}}},XEr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},ebr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},fpe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},MG={type:"object",properties:{billingAddress:{...fpe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},UG={type:"object",properties:{billingAddress:{...fpe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...fpe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},tbr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Aa={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:tbr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},jl={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},Zy={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},E_={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:Ky},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...XEr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...ebr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...MG,description:"Issuer identity and billing address (credit from)."},creditTo:{...UG,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:Ky},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:Ky},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:Ky},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},Xy={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}}}});function hpe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function fnt(e){let t=e.updated??[],r=hpe(e.failed);return{...t.length===0&&r.length>0?{error:ibr}:{},updated:t,failed:r}}function pnt(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function $G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hnt(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=pnt(s);if(a)for(let c of Array.isArray(o)?o:[o])$G(c)&&n.push(...hnt(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function obr(e){return Object.entries(e).map(([t,r])=>{let n=pnt(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function mpe(e,t,r){if(!$G(t))return;let n=hnt(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw rr(new At(`${e} has no field ${i.join("; ")}. Fields: ${obr(r)}. Nothing was changed.`))}function sbr(e){let t=E_[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function abr(e){let t=Xy[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function cbr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!$G(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw rr(new At(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!$G(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw rr(new At(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));mpe(`${e} line items`,a.attributes,t.fields)}}}async function kB(e,t,r){if(!b_.includes(t)){let i=jG.includes(t);throw rr(new At(i?`${t} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${t} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${t} has no quick fix route. Transaction-level entities: ${b_.join(", ")}.`))}mpe(`${t} quick fix`,r.attributes,sbr(t));let n=await e.post(`/api/v1/quick-fix/${Iu(b_,t)}`,r);return fnt(n)}async function BB(e,t,r){let n=Iu(I_,t),i=abr(t);i.entryKeys?cbr(t,i,r.schedulerUpdates):mpe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return fnt(o)}var rbr,nbr,qG,jG,b_,I_,ibr,YG=G(()=>{"use strict";yt();Oo();ppe();rbr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],nbr=["journals","cash-entries"],qG=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],jG=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],b_=[...rbr,...nbr,...qG],I_=[...b_,...jG],ibr="Nothing changed: every record failed. See failed for each reason."});function HG(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=HG(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<ubr&&i.length<=dbr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,HG(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Ant(e,t,r){let n=fbr(t);if(!n)return[];let i=pbr(r);if(!i){if(mnt[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Ant(o,s,i[o]):[])}function hbr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function Ape(e,t){let r=Object.keys(e),n=[...new Set(r.flatMap(a=>Object.keys(e[a])))].sort(),i={},o=new Map;for(let a of n){let c=r.filter(g=>e[g][a]),u=new Map;for(let g of c){let y=mbr(e[g][a]);u.set(y,[...u.get(y)??[],g])}let[[,d],...f]=[...u].sort((g,y)=>y[1].length-g[1].length),{description:p,...h}=HG(e[d[0]][a]),m=f.length&&h.properties?{...h,required:void 0,properties:Object.assign({},...[d,...f.map(([,g])=>g)].map(g=>HG(e[g[0]][a]).properties))}:h;m.required||delete m.required;let A=[mnt[a],hbr(c,r),...f.map(([,g])=>{let y=e[g[0]][a];return`${g.join(", ")}: {${Object.keys(y.properties??y.items?.properties??{}).join(", ")}}.`})].filter(Boolean);i[a]=A.length?{...m,description:A.join(" ")}:m;for(let g of c)for(let[y,b]of Ant(a,e[g][a],m))o.set(b,(o.get(b)??new Set).add(y))}let s=[...o].map(([a,c])=>`${[...c].join(", ")}: ${a}.`);return{type:"object",description:[t,...s].join(" "),properties:i}}function bnt(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>lbr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var lbr,mnt,ubr,dbr,fbr,pbr,mbr,Abr,C_,gnt,ynt,Ent,Int,Cnt,wnt,gpe=G(()=>{"use strict";ppe();lbr={valueDate:"date",dueDate:"due date",startDate:"start date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},mnt={currencySettings:"Changes the record currency; line amounts and tax profiles stay. Always send sourceCurrencyCode: alone for the platform rate (not on schedules), or with rateFunctionalToSource.",tags:"Replaces every tag on the record. At most 50 tags of 50 characters each.",customFields:"Rows: {customFieldName, actualValue}, as on create."},ubr=2,dbr=8;fbr=e=>e.properties??e.items?.properties,pbr=e=>e.properties??e.items?.properties;mbr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]);Abr=Object.entries(Xy).filter(([,e])=>!e.entryKeys),C_=Object.entries(Xy).filter(([,e])=>e.entryKeys),gnt=Ape({...E_},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields."),ynt=Ape(Object.fromEntries(Abr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Ent=(()=>{let e=n=>C_.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=C_[0],r=[...new Set(C_.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>C_.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${C_.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:Ape(Object.fromEntries(C_.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Int=[...new Set([...Object.keys(E_),...Object.keys(Xy)])].map(e=>e.replace(/-/g," ")).join(", "),Cnt=bnt(Object.values(E_)),wnt=bnt(Object.values(Xy).map(e=>e.fields))});function zG(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var ype=G(()=>{"use strict"});function GG(){return Mm.map(e=>`${e} sets ${__[e].change.join(", ")}`).join("; ")}function knt(e){let t={};for(let r of e)t[r]=Object.hasOwn(vnt,r)?vnt[r]:Ebr.find(([n])=>n.test(r))?.[1]??bbr;return Object.keys(t).length>0?t:void 0}function Bnt(e){if(!(e instanceof Ur)||!e.endpoint.startsWith(ybr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Snt,n))return;let{hint:i,repairTool:o,command:s}=Snt[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Tnt.LINE_ITEMS?"line items":"records",...e.endpoint===JG?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function wbr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function _br(e){return typeof e=="string"&&Mm.includes(e)}function vbr(e,t){if(!_br(e))throw new At(`level must be one of ${Mm.join(", ")}.`);let r=Mm.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))__[e][i].includes(s)||n.push(__[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=__[e];throw new At(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Dnt(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new At(`${e} must be a JSON object, not ${n}.`)}async function WG(e,t,r){let n={filter:Dnt("filter",r.filter),change:Dnt("change",r.change)};vbr(t,n);let i;try{i=await e.post(Tnt[t],{filter:n.filter,change:n.change},Qt)}catch(u){throw Bnt(u),u}let{data:o,...s}=i,a=knt([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=wbr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function bpe(e,t){return{error:`${t} ${Ont}`,outcome:"UNKNOWN",previewId:e,next:Nnt}}function Rbr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return bpe(e,"The apply answered without a per-record result.");let i=hpe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=knt(Object.keys(o)),a=o[Ibr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Dbr}:a==="UNKNOWN"?{error:Ont}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Nnt:Sbr},failed:i.slice(0,Epe),...i.length>Epe?{failedNotShown:i.length-Epe}:{},data:r}}async function KG(e,t,r=Cbr){let n;try{n=await e.post(JG,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof Ur){let s=Bnt(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw rr(i);return bpe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof Tp)throw rr(i);let o=i instanceof Error?i.message:String(i);return bpe(t,`No answer arrived from the apply (${o}).`)}return Rbr(t,n)}var Rnt,Mm,Tnt,JG,ybr,xnt,_nt,__,vnt,Ebr,bbr,Ibr,Cbr,VG,Epe,v_,hZr,w_,Snt,Nnt,Sbr,Dbr,Ont,Ipe=G(()=>{"use strict";bo();YG();xQ();yt();Oo();gr();ype();Rnt=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],Mm=["TRANSACTIONS","LINE_ITEMS"],Tnt={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},JG="/api/v1/ledger/find-fix/apply",ybr=JG.slice(0,JG.lastIndexOf("/")+1),xnt={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},_nt=["types","resourceIds","reference","valueDate","contactResourceId"],__={TRANSACTIONS:{filter:_nt,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[..._nt,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};vnt={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},Ebr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],bbr="Not described by this client version; read the records that carry it.";Ibr="OUTCOME_UNKNOWN",Cbr=25e3,VG=3e5,Epe=50,v_=12,hZr=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${v_}}(?![A-Za-z0-9_-])`,"i"),w_=e=>e.resourceId?` (${e.resourceId})`:"",Snt={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${w_(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${w_(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${w_(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${w_(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${w_(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${w_(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Nnt="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",Sbr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Dbr="Nothing changed: every record in the preview failed.",Ont="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function ZG(e,t){return e.list("/api/v1/nano-classifiers",t)}async function eE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function XG(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function NB(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function OB(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function eV(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Tbr(e,t):{};let{data:n}=await eE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Qnt(n)}async function Tbr(e,t){let{data:r}=await eE(e,t);return Qnt(r)}function Qnt(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function tV(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Fnt,Cpe=G(()=>{"use strict";Fnt=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function rV(e,t){return e.post("/api/v1/export-records",t,Qt)}async function nV(e,t){return e.post("/api/v1/export-records/preview",t,Qt)}async function iV(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var wpe=G(()=>{"use strict";gr()});async function FB(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var _pe=G(()=>{"use strict"});function oV(e,t){if(!t.has(e))throw new me(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Unt(e,t,r,n=!1){if(!Array.isArray(e))throw new me(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new me(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new me(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new me(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function sV(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function aV(e,t,r){return oV(t,Pnt),Co(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Iu(Yf,t)}/${encodeURIComponent(r)}/approve`,void 0,SRe)}async function cV(e,t,r){return oV(t,Pnt),Unt(r,xbr,"bulk approve",!0),r.forEach(n=>Co(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Iu(Yf,t)}/bulk-approve`,{resourceIds:r},DRe)}async function lV(e,t,r,n){oV(t,Mnt),Co(r,"resourceId","Pass the document resourceId."),$nt(n);let i=await e.post(`/api/v1/${Iu(tE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Nbr(i)}}}async function uV(e,t,r,n){return oV(t,Mnt),$nt(n),Unt(r,kbr,"bulk request changes"),r.forEach(i=>Co(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Bbr(t),{resourceIds:r,message:n})}function Bbr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Iu(Lnt,e)}/bulk-request-changes`}function $nt(e){if(!e||e.trim().length===0)throw new me("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Nbr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var Yf,Lnt,tE,Pnt,Mnt,xbr,kbr,vpe=G(()=>{"use strict";yt();gr();Yf=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Lnt=[...Yf,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],tE=[...Lnt,"claims"],Pnt=new Set(Yf),Mnt=new Set(tE);xbr=100,kbr=500});function Obr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${qnt(t)}:${qnt(r)}:${n}`}function qnt(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function Spe(e){if(!jnt.has(e))throw new me(`unknown entity "${e}" \u2014 expected one of ${[...jnt].join(", ")}`)}async function Ynt(e,t,r){return Spe(t),Co(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function Hnt(e,t,r,n){return Spe(t),Co(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function znt(e,t,r,n,i){if(Spe(t),Co(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new me('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Obr(t,r,n)}})}async function Jnt(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var jnt,Gnt=G(()=>{"use strict";yt();jnt=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function S_(e){Ut(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new me(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!pBe(n.btResourceId))throw new me(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!Fbr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new me(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function dV(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Qt);return{data:Lbr(r.data)}}function Qbr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function Lbr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(Qbr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function fV(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function pV(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var Fbr,Dpe=G(()=>{"use strict";yt();oK();Cn();gr();Fbr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Pbr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function Ubr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $br(e,t){if(e!==Mbr)return;let r=Ubr(t);if(r)return Vnt.get(r)??Vnt.get(r.replace(/_ERROR$/,""))}function hV(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function qbr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=hV(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function Rpe(e){return $br(e.status,e.body)??e.refusal?.hint??qbr(e)}function QB(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function mV(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function LB(e,t={}){let r=t.readOnly===!1&&$S()?yBe:"";if(e instanceof Ur){let o=[Rpe(e)??Pbr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...hV(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=AV(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof At;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mbr,Vnt,D_=G(()=>{"use strict";bo();Oo();gV();UP();Mbr=422,Vnt=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});function Xnt(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new me("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Tpe(e,t){if(!e||typeof e!="object")throw new me(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new me(`${t}.lineItems array is empty.`);if(n.length>500)throw new me(`max 500 ${t}.lineItems per call.`);hl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&hl([i],["valueDate"])}async function EV(e,t,r=xpe){return e.post("/api/v1/search-magic-reconciliation",t,{...Qt,timeoutMs:r})}function yV(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function zbr(e){let t=yV(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=yV(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Jbr(e){return e?e.value>=(e.from==="confidenceScore"?jbr:Ybr)?"high":e.value>=Hbr?"medium":"low":"low"}function Vbr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(Wnt,t))return;let r=Wnt[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function Um(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function Knt(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Wbr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>Knt({account:Um(n?.account),taxProfile:Um(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!Um(e.contact)&&!Um(e.account)&&!Um(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return Knt({contact:Um(e.contact),account:Um(e.account),taxProfile:Um(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function eit(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>Zbr(c,h??{},u.length-1,t)).sort(Kbr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function Kbr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function Zbr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=yV(t.matchScore),s=yV(t.confidenceScore),a=zbr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=PB.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=PB.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let k=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,O=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,J=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;k&&O&&J&&(m=PB.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:k,predictedPayload:O,predictedPayloadSchemaVersion:J});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let k=t.actionShortcut??{},O=typeof k.resourceId=="string"?k.resourceId:void 0;O&&(m=PB.applyBankRule,A={actionShortcutResourceId:O,businessTransactionResourceIds:[e]});break}default:break}let g=m?Jbr(a):"low",y=typeof h=="number"&&!Number.isNaN(h),b=n.autoCommitMaxAmount!==void 0,E=!b||y&&Math.abs(h)<=n.autoCommitMaxAmount,C=m!==PB.withPayments||y,w=Vbr(t),T=!m||!A?"NO_PLAN":w?Gbr[w]:g!=="high"?"BELOW_THRESHOLD":!C||b&&!y?"AMOUNT_UNKNOWN":E?void 0:"ABOVE_AMOUNT_CAP",R=Wbr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:A,confidenceTier:g,autoCommitEligible:T===void 0,...T?{checkpointReason:T}:{},...R?{proposedPosting:R}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:w===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(t)}`}}function Xbr(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function eIr(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await Ns(e,i):await Ls(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${QB(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function tit(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,Znt);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await EI(e,t,{filter:{resourceId:{in:u}},limit:Znt}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${QB(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return Xbr(u,f,await eIr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function bV(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ia)}async function IV(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ia)}async function CV(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ia)}async function wV(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ia)}async function _V(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ia)}async function vV(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ia)}async function SV(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ia)}async function DV(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ia)}async function RV(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ia)}async function TV(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ia)}async function xV(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ia)}async function kV(e,t){return e.post("/api/v1/reconciliations/reset",t)}var PB,xpe,jbr,Ybr,Hbr,Gbr,Wnt,Znt,BV=G(()=>{"use strict";rg();D_();yt();Np();Cn();KI();gr();PB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},xpe=6e4;jbr=.9,Ybr=.95,Hbr=.7;Gbr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},Wnt={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};Znt=25});function Hs(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function To(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:kpe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=kpe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=kpe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function kpe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function Yo(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Hs(e,t,n),a=To(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ga,$c,po,Yl,rit=G(()=>{"use strict";ga=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],$c=[...ga],po=ga.filter(e=>e.field!=="dueDate"),Yl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function td(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=uc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function NV(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=Gb(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var nit=G(()=>{"use strict";Bp()});var Bpe=G(()=>{"use strict";rit();Bp();nit()});var MB,OV,Hl,Npe=G(()=>{"use strict";MB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",OV=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],Hl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function iit(e){return tIr.get(e)}function oit(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!FV.has(o));return n.length===0?[]:Bi.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Bi,FV,tIr,rd=G(()=>{"use strict";Npe();gpe();Bi=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Int}. On a record: ${Cnt}. On lines: ${wnt}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${OV.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],FV=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),tIr=new Map(Bi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function nd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function rIr(e){let t=sit.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(nd(r),n);for(let r of e.enum??[])t.set(nd(r),r);sit.set(e,t)}return t}function ait(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=nd(e);if(!r)return null;let n=rIr(t).get(r);return n!==void 0&&n!==e?n:null}function nIr(e){let t=cit.get(e);return t||(t=new Map(Object.keys(e).map(r=>[nd(r),r])),cit.set(e,t)),t}function iIr(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function oIr(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Ope(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=nIr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=nd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?iIr(d):oIr(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=ait(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=ait(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=pK(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=Ope(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=Ope(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function lit(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:Ope(t,e.params,"",r),coercions:r}}function uit(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var sit,cit,Fpe=G(()=>{"use strict";GP();sit=new WeakMap;cit=new WeakMap});function R_(e){let t=new Set,r=[];for(let n of e)for(let i of zl(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function UB(){return Bi.map(e=>{let t=R_(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function sIr(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function aIr(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function $m(e,t=!1){let r=qm(void 0).length,n=Bi.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:aIr(r)}:e&&i!==void 0?{packaging:sIr(e,i,r)}:{},map:UB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var QV=G(()=>{"use strict";rd();Jl()});function LV(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=LV(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=LV(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function Gl(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=LV(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function $B(e){return{name:e.name,description:e.description,input_schema:Gl(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var T_=G(()=>{"use strict"});function qB(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function Qpe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function PV(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&qB(e),idempotentHint:e.readOnly,openWorldHint:Qpe(e)}}function lIr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function uIr(e){let t=lIr(e);return!t||cIr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!FV.has(n)).length===0}function Lpe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function Ppe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?Ppe(o,`${i}.`):[]]})}function fIr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
661
|
+
`)),null)}catch{return null}}async function yB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??iEr,c=n.minBm25??oEr;if(i==="bm25"||!t)return Hy(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Ofe(r);return m?Trt(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):Hy(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Ofe(r),Promise.resolve(Hy(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Trt(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Brt(p,h,o)}function Trt(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=xrt(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Brt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Srt+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(Srt+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function Ffe(e){return e!==null&&!!krt()}var rEr,nEr,Srt,iEr,oEr,pJ,Drt,hJ,Rrt,mJ=G(()=>{"use strict";AB();rEr="text-embedding-3-small",nEr=2e3,Srt=60,iEr=.3,oEr=1.5,pJ=null,Drt=null,hJ=null,Rrt=!1});async function Nrt(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=hB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:gB(),u=await yB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Bfe(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Ort(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:aEr}async function AJ(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Ort())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(cEr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return lEr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function lEr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Qfe(e,t={}){return process.env.CLIO_DAEMON==="1"||mB()?Nrt(e,t):AJ(e,t)}var aEr,cEr,Frt=G(()=>{"use strict";AB();mJ();aEr="https://mcp.jaz.ai/help-center/search",cEr=4e3});var Lfe=G(()=>{"use strict";AB();mJ();Frt();AB()});async function Om(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function Fm(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var EB=G(()=>{"use strict";Cn()});async function gJ(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:zt(t.currency),taxCurrency:zt(t.taxCurrency)},BRe)}var Pfe=G(()=>{"use strict";yt();gr()});async function yJ(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EJ(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function bB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bJ(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Mfe=G(()=>{"use strict"});function uEr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function h_(e,t){return e.post("/api/v1/jots",{entries:t.map(uEr)})}async function IJ(e,t){return e.post("/api/v1/jots/search",t,Qt)}async function Qrt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CJ=G(()=>{"use strict";gr()});async function Lrt(e,t){return e.post("/api/v1/agents/memories",t)}async function Ufe(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Prt=G(()=>{"use strict";gr()});function wJ(){return process.env.ENABLE_MEMORY==="true"}function $fe(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Mrt(e){return!wJ()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var qfe=G(()=>{"use strict"});import{createHash as dEr}from"node:crypto";function CEr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:qrt.some(r=>t.includes(r))?[null,"directive_invalid"]:$rt.test(t)?[null,"directive_invalid"]:gEr.test(t)?[null,"directive_contains_url"]:yEr.test(t)?[null,"directive_contains_email"]:[t,null]}function wEr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>EEr?[null,"match_condition_too_long"]:qrt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:$rt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function _Er(e){return e==null?[null,null]:Number.isInteger(e)?e<bEr||e>IEr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function vEr(e,t,r,n,i,o,s,a){if(e)return dEr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function SEr(e){Promise.resolve().then(()=>(UL(),ML)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function zrt(e,t,r){let n=t.action,i=t.category,o=mEr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(SEr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Mrt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>fEr||!AEr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=CEr(t.directive);if(E)return u(E);p=b;let[C,w]=_Er(t.importance);if(w)return u(w);h=C}let[m,A]=wEr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=pEr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,hEr));let E=vEr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await jfe(()=>Lrt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await jfe(()=>Ufe(e.client,b))}else{let b={forgetAll:!0};y=await jfe(()=>Ufe(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function jfe(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof Ur?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var $rt,qrt,fEr,pEr,hEr,jrt,Yrt,Hrt,mEr,AEr,gEr,yEr,EEr,bEr,IEr,Jrt=G(()=>{"use strict";Prt();bo();qfe();qfe();$rt=/[\x00-\x1f\x7f]/,qrt=["{{","}}","```","<",">"],fEr=120,pEr=3,hEr=140,jrt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Yrt=["set","forget","forget_all"],Hrt=["this_org","all_orgs"],mEr={this_org:"ORG_USER",all_orgs:"USER"},AEr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,gEr=/https?:\/\//i,yEr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,EEr=255,bEr=0,IEr=100});async function _J(e,t){return e.list("/api/v1/organization-users",t)}async function vJ(e,t){return e.search("/api/v1/organization-users/search",t)}async function m_(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SJ(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DJ(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Yfe=G(()=>{"use strict"});async function RJ(e,t){return e.get(`/api/v1/payments/${t}`)}async function TJ(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:zt(r.currency)})}async function xJ(e,t){await e.delete(`/api/v1/payments/${t}`)}function kJ(e){return(t,r)=>t.post(`/api/v1/${DEr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:zt(n.currency)}))},RRe)}var DEr,eKr,Grt,tKr,rKr,Hfe=G(()=>{"use strict";yt();gr();DEr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};eKr=kJ("saleBulk"),Grt=kJ("saleBatch"),tKr=kJ("purchaseBulk"),rKr=kJ("purchaseBatch")});async function qf(e,t,r,n,i,o=kRe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof Ur?c.status<500&&c.status!==401?rr(c):new $d(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof Tp?rr(c):c}let a=s?.data;if(!i(a))throw new $d(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function NJ(e,t,r){try{Co(e,t,r)}catch(n){throw rr(n)}}function zy(e){return NJ(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OJ(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FJ(e,t){return qf(e,"POST",REr,t,Qm)}async function QJ(e,t,r){return qf(e,"PUT",`/api/v1/unapplied-payments/${zy(t)}`,r,Qm)}async function LJ(e,t,r){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/activate`,{hash:r},Qm)}async function PJ(e,t,r,n){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/attributions`,{hash:r,attributions:n},Qm)}async function MJ(e,t,r,n){return NJ(n,"paymentResourceId","Pass the payment record resourceId."),qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/payments`,{hash:r,paymentResourceId:n},Qm)}async function UJ(e,t,r,n){return NJ(r,"childResourceId","Pass the payment record resourceId from the children list."),qf(e,"DELETE",`/api/v1/unapplied-payments/${zy(t)}/children/${encodeURIComponent(r)}`,{hash:n},Qm)}async function $J(e,t,r){return qf(e,"DELETE",`/api/v1/unapplied-payments/${zy(t)}`,{hash:r},Qm)}async function qJ(e,t,r){return qf(e,"POST",`/api/v1/unapplied-payments/${zy(t)}/unbatch`,{hash:r},Qm)}async function jJ(e,t){return NJ(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),qf(e,"POST",TEr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ia)}var REr,TEr,BJ,Vrt,Wrt,Qm,zfe=G(()=>{"use strict";bo();gr();xQ();yt();REr="/api/v1/unapplied-payments",TEr="/api/v1/reconciliations/unapplied-payment",BJ=["SALE","PURCHASE"],Vrt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Wrt=["AMOUNT","PERCENTAGE"];Qm=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YJ(e,t,r={},n=Jfe){let i=xEr.has(t)?`/api/v1/${Iu(Krt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=yg.get(t);if(o!==void 0){if(!a)throw new me(`${t} does not take a report template. Templates apply to: ${[...yg.keys()].join(", ")}.`);let A=await df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Qt,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new me(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...IB].join(", ")}.`}:d}var Krt,xEr,Jfe,IB,Zrt,Gfe=G(()=>{"use strict";gr();yt();pT();Tu();Krt=["statement-of-account-export"],xEr=new Set(Krt),Jfe=9e4,IB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),Zrt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as kEr}from"node:crypto";import{writeFile as BEr,mkdir as NEr}from"node:fs/promises";import{dirname as OEr,isAbsolute as FEr,join as QEr}from"node:path";async function HJ(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Qt)}async function CB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function A_(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Vfe(e){return kEr("sha256").update(e).digest("hex").slice(0,16)}async function zJ(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Vfe(t),o=await CB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await A_(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await A_(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!FEr(r.outPath))throw new me(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??QEr(f,"Downloads",`pseudo-sql-${s}.csv`);return await NEr(OEr(p),{recursive:!0}),await BEr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function JJ(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new me(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function g_(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Wfe=G(()=>{"use strict";yt();gr()});async function ui(e,t,r){let n=await e.get(`/api/v1/${Kfe[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GJ(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Kfe[r]}/${n}/attachments`,o)}async function VJ(e,t,r,n){return e.delete(`/api/v1/${Kfe[t]}/${r}/attachments/${n}`)}var Kfe,wB,Lm=G(()=>{"use strict";Kfe={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},wB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ro(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var y_=G(()=>{"use strict"});async function WJ(e,t){return e.post("/api/v1/claims/conversion/preview",t,Qt)}async function KJ(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new me('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:FQ)}var _B,Zfe=G(()=>{"use strict";yt();gr();_B=["POST","POST_AND_RECORD"]});async function ZJ(e,t){if(!(t.amount>0))throw new me("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,TRe)}async function XJ(e,t){return e.search("/api/v1/employees/payouts/search",t)}var Xrt,Xfe=G(()=>{"use strict";yt();gr();Xrt=["REIMBURSEMENT","ADVANCE"]});async function eG(e,t){return e.search("/api/v1/filing-submissions/search",t)}var epe=G(()=>{"use strict"});function tpe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function rpe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${ent(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>wu.has(u)),s=i.filter(u=>!wu.has(u)&&pc.has(u)),a=[`Nothing here can be extracted: found ${ent(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=kxe[u];d&&a.push(d)}return o.length>0&&a.push(`${CP(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${CP(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!wu.has(u)&&!pc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${CP([...wu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function ent(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var tnt=G(()=>{"use strict";_u()});function tG(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function vB(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&tG()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function Jy(e,t){return{error:e,hint:t,...npe}}function rnt(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${vB(e)}.`,...npe}}function Gy(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function Pm(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${vB({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...npe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var npe,nnt=G(()=>{"use strict";npe={kind:"validation",retriable:!1}});import{randomUUID as LEr}from"node:crypto";import{rmSync as PEr}from"node:fs";function ope(e){for(let t of e.tempDirs??[])try{PEr(t,{recursive:!0,force:!0})}catch{}}function ont(e){for(let[t,r]of Vy)e-r.createdAt>int&&(ope(r.plan),Vy.delete(t))}function UEr(){ipe||(ipe=setInterval(()=>ont(Date.now()),MEr),ipe.unref?.())}function spe(e,t){let r=Date.now();ont(r),UEr();let n=`dc_${LEr()}`;return Vy.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function snt(e,t){let r=Vy.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>int?(ope(r.plan),Vy.delete(e),null):r.plan}function ant(e,t){let r=Vy.get(e);!r||r.ownerKey!==t||(ope(r.plan),Vy.delete(e))}var int,MEr,Vy,ipe,cnt=G(()=>{"use strict";int=1800*1e3,MEr=300*1e3,Vy=new Map});function $Er(e){if(!e||typeof e!="object")return;let t=e;return t.validFiles?.[0]?.workflowResourceId??t.workflowResourceId}function qEr(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>dI(i.documentType)&&r.has(i.documentType))}))}}async function lnt(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?qEr(t,i):t;if(!n&&jEr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");RS(o);let a=await LP({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,workflowId:d.status==="uploaded"?$Er(d.response):void 0,error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function jEr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var unt=G(()=>{"use strict";iK();_u();Xd()});async function ed(e,t,r){if(!t)return e;let n=YEr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}function YEr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function jf(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var dnt=G(()=>{"use strict"});async function rG(e,t){return e.list("/api/v1/bank-rules",t)}async function SB(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function nG(e,t){return e.search("/api/v1/bank-rules/search",t)}async function iG(e,t){return e.post("/api/v1/bank-rules",t)}async function oG(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function sG(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var ape=G(()=>{"use strict"});async function aG(e,t){return e.list("/api/v1/fixed-assets",t)}async function DB(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function cG(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function lG(e,t){return e.post("/api/v1/fixed-assets",t,G0)}async function uG(e,t,r){let i=(await DB(e,t)).data,o={};for(let s of HEr){let a=i[s];if(a==null)continue;let c=zEr.has(s)?Hd(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/fixed-assets/${t}`,o)}async function dG(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function fG(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},G0)}async function RB(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,G0)}async function pG(e,t){return e.post("/api/v1/transfer-fixed-assets",t,G0)}async function hG(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function mG(e,t){return Io(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var Wy,HEr,zEr,AG=G(()=>{"use strict";Cn();rS();gr();Wy=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];HEr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],zEr=new Set(["purchaseDate","depreciationStartDate"])});async function gG(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function TB(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function yG(e,t){return e.post("/api/v1/scheduled/subscriptions",t,xp)}async function EG(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await TB(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw JEr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function JEr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function bG(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function IG(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function CG(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var cpe=G(()=>{"use strict";gr()});async function wG(e,t){return e.list("/api/v1/contact-groups",t)}async function _G(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function vG(e,t){return e.search("/api/v1/contact-groups/search",t)}async function SG(e,t){return e.post("/api/v1/contact-groups",t)}async function DG(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,Yb(r,A7))}async function RG(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var lpe=G(()=>{"use strict";Cn()});async function TG(e,t){return e.list("/api/v1/inventory-items",t)}async function xG(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function kG(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function NG(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof Ur&&n.status===404&&GEr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var BG,GEr,upe=G(()=>{"use strict";bo();BG=["ALL","AVAILABLE","FULLY_DRAWN"],GEr=/Inventory balance Not Found/i});async function OG(e,t){return e.list("/api/v1/custom-fields",t)}async function xB(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function FG(e,t){return e.search("/api/v1/custom-fields/search",t)}async function QG(e,t){return e.post("/api/v1/custom-fields",t)}function WEr(e){return e!==void 0&&VEr.every(t=>e[t]!==void 0)}function KEr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function ZEr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function LG(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!WEr(n.appliesTo)){let i=await xB(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??ZEr(i.data),n.appliesTo={...KEr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function PG(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var VEr,dpe=G(()=>{"use strict";VEr=["invoices","bills","customerCredits","supplierCredits","payments"]});var Uc,Ky,XEr,ebr,fpe,MG,UG,tbr,Aa,jl,Zy,E_,Xy,ppe=G(()=>{"use strict";Uc={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},Ky={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},XEr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},ebr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},fpe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},MG={type:"object",properties:{billingAddress:{...fpe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},UG={type:"object",properties:{billingAddress:{...fpe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...fpe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},tbr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Aa={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:tbr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},jl={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},Zy={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},E_={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:Ky},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...XEr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...ebr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...MG,description:"Issuer identity and billing address (credit from)."},creditTo:{...UG,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:Ky},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:Ky},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...MG,description:"Seller identity and billing address."},billTo:{...UG,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:Ky},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...Uc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:Ky},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Uc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},Xy={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},description:{type:"string",description:"Line item description or memo."},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Aa},discount:{...jl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...Zy,description:"Withholding tax details for this line item."}}}}});function hpe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function fnt(e){let t=e.updated??[],r=hpe(e.failed);return{...t.length===0&&r.length>0?{error:ibr}:{},updated:t,failed:r}}function pnt(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function $G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hnt(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=pnt(s);if(a)for(let c of Array.isArray(o)?o:[o])$G(c)&&n.push(...hnt(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function obr(e){return Object.entries(e).map(([t,r])=>{let n=pnt(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function mpe(e,t,r){if(!$G(t))return;let n=hnt(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw rr(new At(`${e} has no field ${i.join("; ")}. Fields: ${obr(r)}. Nothing was changed.`))}function sbr(e){let t=E_[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function abr(e){let t=Xy[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function cbr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!$G(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw rr(new At(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!$G(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw rr(new At(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));mpe(`${e} line items`,a.attributes,t.fields)}}}async function kB(e,t,r){if(!b_.includes(t)){let i=jG.includes(t);throw rr(new At(i?`${t} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${t} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${t} has no quick fix route. Transaction-level entities: ${b_.join(", ")}.`))}mpe(`${t} quick fix`,r.attributes,sbr(t));let n=await e.post(`/api/v1/quick-fix/${Iu(b_,t)}`,r);return fnt(n)}async function BB(e,t,r){let n=Iu(I_,t),i=abr(t);i.entryKeys?cbr(t,i,r.schedulerUpdates):mpe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return fnt(o)}var rbr,nbr,qG,jG,b_,I_,ibr,YG=G(()=>{"use strict";yt();Oo();ppe();rbr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],nbr=["journals","cash-entries"],qG=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],jG=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],b_=[...rbr,...nbr,...qG],I_=[...b_,...jG],ibr="Nothing changed: every record failed. See failed for each reason."});function HG(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=HG(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<ubr&&i.length<=dbr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,HG(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Ant(e,t,r){let n=fbr(t);if(!n)return[];let i=pbr(r);if(!i){if(mnt[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Ant(o,s,i[o]):[])}function hbr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function Ape(e,t){let r=Object.keys(e),n=[...new Set(r.flatMap(a=>Object.keys(e[a])))].sort(),i={},o=new Map;for(let a of n){let c=r.filter(g=>e[g][a]),u=new Map;for(let g of c){let y=mbr(e[g][a]);u.set(y,[...u.get(y)??[],g])}let[[,d],...f]=[...u].sort((g,y)=>y[1].length-g[1].length),{description:p,...h}=HG(e[d[0]][a]),m=f.length&&h.properties?{...h,required:void 0,properties:Object.assign({},...[d,...f.map(([,g])=>g)].map(g=>HG(e[g[0]][a]).properties))}:h;m.required||delete m.required;let A=[mnt[a],hbr(c,r),...f.map(([,g])=>{let y=e[g[0]][a];return`${g.join(", ")}: {${Object.keys(y.properties??y.items?.properties??{}).join(", ")}}.`})].filter(Boolean);i[a]=A.length?{...m,description:A.join(" ")}:m;for(let g of c)for(let[y,b]of Ant(a,e[g][a],m))o.set(b,(o.get(b)??new Set).add(y))}let s=[...o].map(([a,c])=>`${[...c].join(", ")}: ${a}.`);return{type:"object",description:[t,...s].join(" "),properties:i}}function bnt(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>lbr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var lbr,mnt,ubr,dbr,fbr,pbr,mbr,Abr,C_,gnt,ynt,Ent,Int,Cnt,wnt,gpe=G(()=>{"use strict";ppe();lbr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},mnt={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:"Replaces every tag on the record. At most 50 tags of 50 characters each.",customFields:"Rows: {customFieldName or resourceId, actualValue}."},ubr=2,dbr=8;fbr=e=>e.properties??e.items?.properties,pbr=e=>e.properties??e.items?.properties;mbr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]);Abr=Object.entries(Xy).filter(([,e])=>!e.entryKeys),C_=Object.entries(Xy).filter(([,e])=>e.entryKeys),gnt=Ape({...E_},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields."),ynt=Ape(Object.fromEntries(Abr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Ent=(()=>{let e=n=>C_.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=C_[0],r=[...new Set(C_.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>C_.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${C_.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:Ape(Object.fromEntries(C_.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Int=[...new Set([...Object.keys(E_),...Object.keys(Xy)])].map(e=>e.replace(/-/g," ")).join(", "),Cnt=bnt(Object.values(E_)),wnt=bnt(Object.values(Xy).map(e=>e.fields))});function zG(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var ype=G(()=>{"use strict"});function GG(){return Mm.map(e=>`${e} sets ${__[e].change.join(", ")}`).join("; ")}function knt(e){let t={};for(let r of e)t[r]=Object.hasOwn(vnt,r)?vnt[r]:Ebr.find(([n])=>n.test(r))?.[1]??bbr;return Object.keys(t).length>0?t:void 0}function Bnt(e){if(!(e instanceof Ur)||!e.endpoint.startsWith(ybr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Snt,n))return;let{hint:i,repairTool:o,command:s}=Snt[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Tnt.LINE_ITEMS?"line items":"records",...e.endpoint===JG?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function wbr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function _br(e){return typeof e=="string"&&Mm.includes(e)}function vbr(e,t){if(!_br(e))throw new At(`level must be one of ${Mm.join(", ")}.`);let r=Mm.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))__[e][i].includes(s)||n.push(__[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=__[e];throw new At(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Dnt(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new At(`${e} must be a JSON object, not ${n}.`)}async function WG(e,t,r){let n={filter:Dnt("filter",r.filter),change:Dnt("change",r.change)};vbr(t,n);let i;try{i=await e.post(Tnt[t],{filter:n.filter,change:n.change},Qt)}catch(u){throw Bnt(u),u}let{data:o,...s}=i,a=knt([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=wbr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function bpe(e,t){return{error:`${t} ${Ont}`,outcome:"UNKNOWN",previewId:e,next:Nnt}}function Rbr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return bpe(e,"The apply answered without a per-record result.");let i=hpe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=knt(Object.keys(o)),a=o[Ibr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Dbr}:a==="UNKNOWN"?{error:Ont}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Nnt:Sbr},failed:i.slice(0,Epe),...i.length>Epe?{failedNotShown:i.length-Epe}:{},data:r}}async function KG(e,t,r=Cbr){let n;try{n=await e.post(JG,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof Ur){let s=Bnt(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw rr(i);return bpe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof Tp)throw rr(i);let o=i instanceof Error?i.message:String(i);return bpe(t,`No answer arrived from the apply (${o}).`)}return Rbr(t,n)}var Rnt,Mm,Tnt,JG,ybr,xnt,_nt,__,vnt,Ebr,bbr,Ibr,Cbr,VG,Epe,v_,hZr,w_,Snt,Nnt,Sbr,Dbr,Ont,Ipe=G(()=>{"use strict";bo();YG();xQ();yt();Oo();gr();ype();Rnt=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],Mm=["TRANSACTIONS","LINE_ITEMS"],Tnt={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},JG="/api/v1/ledger/find-fix/apply",ybr=JG.slice(0,JG.lastIndexOf("/")+1),xnt={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},_nt=["types","resourceIds","reference","valueDate","contactResourceId"],__={TRANSACTIONS:{filter:_nt,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[..._nt,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};vnt={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},Ebr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],bbr="Not described by this client version; read the records that carry it.";Ibr="OUTCOME_UNKNOWN",Cbr=25e3,VG=3e5,Epe=50,v_=12,hZr=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${v_}}(?![A-Za-z0-9_-])`,"i"),w_=e=>e.resourceId?` (${e.resourceId})`:"",Snt={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${w_(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${w_(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${w_(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${w_(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${w_(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${w_(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Nnt="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",Sbr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Dbr="Nothing changed: every record in the preview failed.",Ont="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function ZG(e,t){return e.list("/api/v1/nano-classifiers",t)}async function eE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function XG(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function NB(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function OB(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function eV(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Tbr(e,t):{};let{data:n}=await eE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Qnt(n)}async function Tbr(e,t){let{data:r}=await eE(e,t);return Qnt(r)}function Qnt(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function tV(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Fnt,Cpe=G(()=>{"use strict";Fnt=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function rV(e,t){return e.post("/api/v1/export-records",t,Qt)}async function nV(e,t){return e.post("/api/v1/export-records/preview",t,Qt)}async function iV(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var wpe=G(()=>{"use strict";gr()});async function FB(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var _pe=G(()=>{"use strict"});function oV(e,t){if(!t.has(e))throw new me(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Unt(e,t,r,n=!1){if(!Array.isArray(e))throw new me(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new me(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new me(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new me(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function sV(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function aV(e,t,r){return oV(t,Pnt),Co(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Iu(Yf,t)}/${encodeURIComponent(r)}/approve`,void 0,SRe)}async function cV(e,t,r){return oV(t,Pnt),Unt(r,xbr,"bulk approve",!0),r.forEach(n=>Co(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Iu(Yf,t)}/bulk-approve`,{resourceIds:r},DRe)}async function lV(e,t,r,n){oV(t,Mnt),Co(r,"resourceId","Pass the document resourceId."),$nt(n);let i=await e.post(`/api/v1/${Iu(tE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Nbr(i)}}}async function uV(e,t,r,n){return oV(t,Mnt),$nt(n),Unt(r,kbr,"bulk request changes"),r.forEach(i=>Co(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Bbr(t),{resourceIds:r,message:n})}function Bbr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Iu(Lnt,e)}/bulk-request-changes`}function $nt(e){if(!e||e.trim().length===0)throw new me("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Nbr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var Yf,Lnt,tE,Pnt,Mnt,xbr,kbr,vpe=G(()=>{"use strict";yt();gr();Yf=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Lnt=[...Yf,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],tE=[...Lnt,"claims"],Pnt=new Set(Yf),Mnt=new Set(tE);xbr=100,kbr=500});function Obr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${qnt(t)}:${qnt(r)}:${n}`}function qnt(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function Spe(e){if(!jnt.has(e))throw new me(`unknown entity "${e}" \u2014 expected one of ${[...jnt].join(", ")}`)}async function Ynt(e,t,r){return Spe(t),Co(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function Hnt(e,t,r,n){return Spe(t),Co(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function znt(e,t,r,n,i){if(Spe(t),Co(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new me('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Obr(t,r,n)}})}async function Jnt(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var jnt,Gnt=G(()=>{"use strict";yt();jnt=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function S_(e){Ut(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new me(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!pBe(n.btResourceId))throw new me(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!Fbr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new me(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function dV(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Qt);return{data:Lbr(r.data)}}function Qbr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function Lbr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(Qbr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function fV(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function pV(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var Fbr,Dpe=G(()=>{"use strict";yt();oK();Cn();gr();Fbr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Pbr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function Ubr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $br(e,t){if(e!==Mbr)return;let r=Ubr(t);if(r)return Vnt.get(r)??Vnt.get(r.replace(/_ERROR$/,""))}function hV(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function qbr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=hV(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function Rpe(e){return $br(e.status,e.body)??e.refusal?.hint??qbr(e)}function QB(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function mV(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function LB(e,t={}){let r=t.readOnly===!1&&$S()?yBe:"";if(e instanceof Ur){let o=[Rpe(e)??Pbr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...hV(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=AV(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof At;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mbr,Vnt,D_=G(()=>{"use strict";bo();Oo();gV();UP();Mbr=422,Vnt=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});function Xnt(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new me("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Tpe(e,t){if(!e||typeof e!="object")throw new me(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new me(`${t}.lineItems array is empty.`);if(n.length>500)throw new me(`max 500 ${t}.lineItems per call.`);hl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&hl([i],["valueDate"])}async function EV(e,t,r=xpe){return e.post("/api/v1/search-magic-reconciliation",t,{...Qt,timeoutMs:r})}function yV(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function zbr(e){let t=yV(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=yV(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Jbr(e){return e?e.value>=(e.from==="confidenceScore"?jbr:Ybr)?"high":e.value>=Hbr?"medium":"low":"low"}function Vbr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(Wnt,t))return;let r=Wnt[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function Um(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function Knt(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Wbr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>Knt({account:Um(n?.account),taxProfile:Um(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!Um(e.contact)&&!Um(e.account)&&!Um(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return Knt({contact:Um(e.contact),account:Um(e.account),taxProfile:Um(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function eit(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>Zbr(c,h??{},u.length-1,t)).sort(Kbr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function Kbr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function Zbr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=yV(t.matchScore),s=yV(t.confidenceScore),a=zbr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=PB.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=PB.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let k=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,O=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,J=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;k&&O&&J&&(m=PB.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:k,predictedPayload:O,predictedPayloadSchemaVersion:J});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let k=t.actionShortcut??{},O=typeof k.resourceId=="string"?k.resourceId:void 0;O&&(m=PB.applyBankRule,A={actionShortcutResourceId:O,businessTransactionResourceIds:[e]});break}default:break}let g=m?Jbr(a):"low",y=typeof h=="number"&&!Number.isNaN(h),b=n.autoCommitMaxAmount!==void 0,E=!b||y&&Math.abs(h)<=n.autoCommitMaxAmount,C=m!==PB.withPayments||y,w=Vbr(t),T=!m||!A?"NO_PLAN":w?Gbr[w]:g!=="high"?"BELOW_THRESHOLD":!C||b&&!y?"AMOUNT_UNKNOWN":E?void 0:"ABOVE_AMOUNT_CAP",R=Wbr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:A,confidenceTier:g,autoCommitEligible:T===void 0,...T?{checkpointReason:T}:{},...R?{proposedPosting:R}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:w===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(t)}`}}function Xbr(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function eIr(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await Ns(e,i):await Ls(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${QB(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function tit(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,Znt);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await EI(e,t,{filter:{resourceId:{in:u}},limit:Znt}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${QB(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return Xbr(u,f,await eIr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function bV(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ia)}async function IV(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ia)}async function CV(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ia)}async function wV(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ia)}async function _V(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ia)}async function vV(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ia)}async function SV(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ia)}async function DV(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ia)}async function RV(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ia)}async function TV(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ia)}async function xV(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ia)}async function kV(e,t){return e.post("/api/v1/reconciliations/reset",t)}var PB,xpe,jbr,Ybr,Hbr,Gbr,Wnt,Znt,BV=G(()=>{"use strict";rg();D_();yt();Np();Cn();KI();gr();PB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},xpe=6e4;jbr=.9,Ybr=.95,Hbr=.7;Gbr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},Wnt={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};Znt=25});function Hs(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function To(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:kpe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=kpe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=kpe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function kpe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function Yo(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Hs(e,t,n),a=To(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ga,$c,po,Yl,rit=G(()=>{"use strict";ga=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],$c=[...ga],po=ga.filter(e=>e.field!=="dueDate"),Yl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function td(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=uc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function NV(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=Gb(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var nit=G(()=>{"use strict";Bp()});var Bpe=G(()=>{"use strict";rit();Bp();nit()});var MB,OV,Hl,Npe=G(()=>{"use strict";MB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",OV=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],Hl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function iit(e){return tIr.get(e)}function oit(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!FV.has(o));return n.length===0?[]:Bi.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Bi,FV,tIr,rd=G(()=>{"use strict";Npe();gpe();Bi=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Int}. On a record: ${Cnt}. On lines: ${wnt}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${OV.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],FV=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),tIr=new Map(Bi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function nd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function rIr(e){let t=sit.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(nd(r),n);for(let r of e.enum??[])t.set(nd(r),r);sit.set(e,t)}return t}function ait(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=nd(e);if(!r)return null;let n=rIr(t).get(r);return n!==void 0&&n!==e?n:null}function nIr(e){let t=cit.get(e);return t||(t=new Map(Object.keys(e).map(r=>[nd(r),r])),cit.set(e,t)),t}function iIr(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function oIr(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Ope(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=nIr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=nd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?iIr(d):oIr(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=ait(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=ait(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=pK(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=Ope(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=Ope(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function lit(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:Ope(t,e.params,"",r),coercions:r}}function uit(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var sit,cit,Fpe=G(()=>{"use strict";GP();sit=new WeakMap;cit=new WeakMap});function R_(e){let t=new Set,r=[];for(let n of e)for(let i of zl(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function UB(){return Bi.map(e=>{let t=R_(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function sIr(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function aIr(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function $m(e,t=!1){let r=qm(void 0).length,n=Bi.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:aIr(r)}:e&&i!==void 0?{packaging:sIr(e,i,r)}:{},map:UB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var QV=G(()=>{"use strict";rd();Jl()});function LV(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=LV(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=LV(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function Gl(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=LV(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function $B(e){return{name:e.name,description:e.description,input_schema:Gl(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var T_=G(()=>{"use strict"});function qB(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function Qpe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function PV(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&qB(e),idempotentHint:e.readOnly,openWorldHint:Qpe(e)}}function lIr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function uIr(e){let t=lIr(e);return!t||cIr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!FV.has(n)).length===0}function Lpe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function Ppe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?Ppe(o,`${i}.`):[]]})}function fIr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
662
662
|
`)[0]}`.toLowerCase(),n=[...e.description.split(`
|
|
663
663
|
`).slice(1),...Ppe(e.params)].map(i=>i.trim()).filter(Boolean);for(let i of t){if(r.includes(i))continue;let o=n.find(s=>s.replace(/\b(Only|Not): [^.]*\./g,"").toLowerCase().includes(i));if(o)return o.length>dit?`${o.slice(0,dit-1)}\u2026`:o}}function MV(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(uIr(e)){if(t!=="meta")return $m(t);let{next:a,...c}=$m();return{...c,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let n=pl(e.trim());if(n)return{matches:[],hint:n};let i=oit(e,5);if(i.length===0){let{operations:a,namespaces:c}=$m();return{matches:[],hint:`No operation matches "${e}". Jaz has ${a} operations across ${c} namespaces \u2014 call ${r} for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let s=e.toLowerCase().split(/\s+/).filter(Boolean);return{matches:i.map(a=>{let c=a.groups.flatMap(m=>zl(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${Ppe(m.params).join(" ")}`.toLowerCase()),d=new Map(s.map(m=>{let A=u.filter(g=>g.includes(m)).length;return[m,Math.log((c.length+1)/(A+1))]})),f=s.slice(1).map((m,A)=>`${s[A]} ${m}`),p=c.map((m,A)=>{let g=u[A],y=s.reduce((b,E)=>g.includes(E)?b+(d.get(E)??0):b,0)+f.filter(b=>g.includes(b)).length;return{tool:m,score:y}}).sort((m,A)=>A.score-m.score),h=[...d].filter(([m,A])=>A>0&&m.length>=3&&!FV.has(m)&&!dIr.has(m)).sort((m,A)=>A[1]-m[1]).map(([m])=>m);return{namespace:a.name,description:a.description,tools:p.map(m=>{let A=m.score>0?fIr(m.tool,h):void 0;return{name:m.tool.name,description:m.tool.description.split(`
|
|
664
664
|
`)[0],...m.tool.searchHint?{searchHint:m.tool.searchHint}:{},...A?{matched:A}:{}}})}}),hint:t==="meta"?"Call describe_tools with the tool names you need, then execute_tool to run them.":`These are summaries. Before concluding something is unsupported, open the namespace with describe_capabilities({ namespace }) for every operation and its parameters. ${Lpe(t)}`}}function fit(e){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(e.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let t=[],r=[];for(let n of e){let i=jB(n);if(!i){r.push(n);continue}t.push({...$B(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&qB(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(pl).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var cIr,dit,dIr,pIr,hIr,mIr,x_,jm,rE=G(()=>{"use strict";rd();QV();Jl();T_();jA();cIr=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);dit=160,dIr=new Set(["change","changes","changing","update","updates","updating","edit","modify","set","make","existing","new","add","create","remove","delete","all","every","each","these","those","record","records","want","need","keep","keeping","remaining","unchanged","while","only"]);pIr={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:Gl({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};hIr={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:Gl({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},mIr={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:Gl({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},x_={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs to pass as org_id on other tool calls.",inputSchema:Gl({},[])},jm=[pIr,hIr,mIr]});function EIr(e){if(!(ya in e))return{cleanedInput:e};let{[ya]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function YB(e){return!e.readOnly&&!e.params[ya]&&e.group!=="jots"}function mit(e,t){if(e.params[ya])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=EIr(t);return YB(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function bIr(e){let t=gIr.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function CIr(e){let t=e.toLowerCase();for(let[r,n]of IIr)if(n.test(t))return r}function wIr(e,t){let r=CIr(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=pit||a>yIr||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=pit)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(t,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function UV(e,t,r,n){let{kind:i,call:o}=bIr(r),s=wIr(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};h_(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(UL(),ML)).then(({log:d})=>d.error({tool:t,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${t}): ${u}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jaz-clio",
|
|
3
|
-
"version": "9.2.
|
|
3
|
+
"version": "9.2.5",
|
|
4
4
|
"description": "Fastest ledger for agents. Jaz accounting CLI and MCP server: invoicing, bills, payments, quotes & orders, bank reconciliation, fixed assets, inventory, expense claims, tax, reports, and period close.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|