From b474aa1d86c7841586041a44be6deefb11452cab Mon Sep 17 00:00:00 2001 From: Luligu <132135057+Luligu@users.noreply.github.com> Date: Wed, 8 May 2024 11:36:21 +0200 Subject: [PATCH] Removed Shutdown button when Matterbridge runs as a service or with docker --- CHANGELOG.md | 1 + frontend/build/asset-manifest.json | 6 +++--- frontend/build/index.html | 2 +- .../static/js/{main.ab5e3bac.js => main.ed3f81ca.js} | 6 +++--- ...bac.js.LICENSE.txt => main.ed3f81ca.js.LICENSE.txt} | 0 .../js/{main.ab5e3bac.js.map => main.ed3f81ca.js.map} | 2 +- frontend/src/components/Header.js | 10 ++++++---- frontend/src/components/Home.js | 8 +++++--- 8 files changed, 20 insertions(+), 15 deletions(-) rename frontend/build/static/js/{main.ab5e3bac.js => main.ed3f81ca.js} (97%) rename frontend/build/static/js/{main.ab5e3bac.js.LICENSE.txt => main.ed3f81ca.js.LICENSE.txt} (100%) rename frontend/build/static/js/{main.ab5e3bac.js.map => main.ed3f81ca.js.map} (50%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79052087..9684023d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file. - [frontend]: Frontend updated to 0.9.0. - [frontend]: Added Plugin config editor - [frontend]: Added tool column to registered plugins with QRCode, Config, Remove and Enable/Disable +- [frontend]: Removed Shutdown button when Matterbridge runs as a service or with docker Buy me a coffee diff --git a/frontend/build/asset-manifest.json b/frontend/build/asset-manifest.json index db7959e0..ede6dde5 100644 --- a/frontend/build/asset-manifest.json +++ b/frontend/build/asset-manifest.json @@ -1,15 +1,15 @@ { "files": { "main.css": "/static/css/main.979e07d2.css", - "main.js": "/static/js/main.ab5e3bac.js", + "main.js": "/static/js/main.ed3f81ca.js", "static/js/453.d855a71b.chunk.js": "/static/js/453.d855a71b.chunk.js", "index.html": "/index.html", "main.979e07d2.css.map": "/static/css/main.979e07d2.css.map", - "main.ab5e3bac.js.map": "/static/js/main.ab5e3bac.js.map", + "main.ed3f81ca.js.map": "/static/js/main.ed3f81ca.js.map", "453.d855a71b.chunk.js.map": "/static/js/453.d855a71b.chunk.js.map" }, "entrypoints": [ "static/css/main.979e07d2.css", - "static/js/main.ab5e3bac.js" + "static/js/main.ed3f81ca.js" ] } \ No newline at end of file diff --git a/frontend/build/index.html b/frontend/build/index.html index 2ef87019..0c4958ba 100644 --- a/frontend/build/index.html +++ b/frontend/build/index.html @@ -1 +1 @@ -Matterbridge
\ No newline at end of file +Matterbridge
\ No newline at end of file diff --git a/frontend/build/static/js/main.ab5e3bac.js b/frontend/build/static/js/main.ed3f81ca.js similarity index 97% rename from frontend/build/static/js/main.ab5e3bac.js rename to frontend/build/static/js/main.ed3f81ca.js index 21a99d4a..3bffcca1 100644 --- a/frontend/build/static/js/main.ab5e3bac.js +++ b/frontend/build/static/js/main.ed3f81ca.js @@ -1,3 +1,3 @@ -/*! For license information please see main.ab5e3bac.js.LICENSE.txt */ -(()=>{var e={5513:(e,t,r)=>{"use strict";r.d(t,{A:()=>oe});var n=function(){function e(e){var t=this;this._insertTag=function(e){var r;r=0===t.tags.length?t.insertionPoint?t.insertionPoint.nextSibling:t.prepend?t.container.firstChild:t.before:t.tags[t.tags.length-1].nextSibling,t.container.insertBefore(e,r),t.tags.push(e)},this.isSpeedy=void 0===e.speedy||e.speedy,this.tags=[],this.ctr=0,this.nonce=e.nonce,this.key=e.key,this.container=e.container,this.prepend=e.prepend,this.insertionPoint=e.insertionPoint,this.before=null}var t=e.prototype;return t.hydrate=function(e){e.forEach(this._insertTag)},t.insert=function(e){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(function(e){var t=document.createElement("style");return t.setAttribute("data-emotion",e.key),void 0!==e.nonce&&t.setAttribute("nonce",e.nonce),t.appendChild(document.createTextNode("")),t.setAttribute("data-s",""),t}(this));var t=this.tags[this.tags.length-1];if(this.isSpeedy){var r=function(e){if(e.sheet)return e.sheet;for(var t=0;t0?u(w,--y):0,g--,10===b&&(g=1,m--),b}function k(){return b=y2||P(b)>3?"":" "}function T(e,t){for(;--t&&k()&&!(b<48||b>102||b>57&&b<65||b>70&&b<97););return _(e,E()+(t<6&&32==C()&&32==k()))}function I(e){for(;k();)switch(b){case e:return y;case 34:case 39:34!==e&&39!==e&&I(b);break;case 40:41===e&&I(e);break;case 92:k()}return y}function M(e,t){for(;k()&&e+b!==57&&(e+b!==84||47!==C()););return"/*"+_(t,y-1)+"*"+a(47===e?e:k())}function F(e){for(;!P(C());)k();return _(e,y)}var D="-ms-",z="-moz-",L="-webkit-",B="comm",$="rule",W="decl",V="@keyframes";function U(e,t){for(var r="",n=p(e),o=0;o0&&f(z)-v&&h(b>32?Q(z+";",n,r,v-1):Q(l(z," ","")+";",n,r,v-2),p);break;case 59:z+=";";default:if(h(D=K(z,t,r,m,g,o,d,j,R=[],I=[],v),i),123===P)if(0===g)G(z,t,D,D,R,i,v,d,I);else switch(99===y&&110===u(z,3)?100:y){case 100:case 108:case 109:case 115:G(e,D,D,n&&h(K(e,D,D,0,0,o,d,j,o,R=[],v),I),o,I,v,d,n?R:I);break;default:G(z,D,D,D,[""],I,0,d,I)}}m=g=b=0,x=_=1,j=z="",v=s;break;case 58:v=1+f(z),b=w;default:if(x<1)if(123==P)--x;else if(125==P&&0==x++&&125==A())continue;switch(z+=a(P),P*x){case 38:_=g>0?1:(z+="\f",-1);break;case 44:d[m++]=(f(z)-1)*_,_=1;break;case 64:45===C()&&(z+=O(k())),y=C(),g=v=f(j=z+=F(E())),P++;break;case 45:45===w&&2==f(z)&&(x=0)}}return i}function K(e,t,r,n,a,i,c,u,f,h,m){for(var g=a-1,v=0===a?i:[""],y=p(v),b=0,w=0,S=0;b0?v[A]+" "+k:l(k,/&\f/g,v[A])))&&(f[S++]=C);return x(e,t,r,0===a?$:u,f,h,m)}function X(e,t,r){return x(e,t,r,B,a(b),d(e,2,-2),0)}function Q(e,t,r,n){return x(e,t,r,W,d(e,0,n),d(e,n+1,-1),n)}var Y=function(e,t,r){for(var n=0,o=0;n=o,o=C(),38===n&&12===o&&(t[r]=1),!P(o);)k();return _(e,y)},J=function(e,t){return R(function(e,t){var r=-1,n=44;do{switch(P(n)){case 0:38===n&&12===C()&&(t[r]=1),e[r]+=Y(y-1,t,r);break;case 2:e[r]+=O(n);break;case 4:if(44===n){e[++r]=58===C()?"&\f":"",t[r]=e[r].length;break}default:e[r]+=a(n)}}while(n=k());return e}(j(e),t))},Z=new WeakMap,ee=function(e){if("rule"===e.type&&e.parent&&!(e.length<1)){for(var t=e.value,r=e.parent,n=e.column===r.column&&e.line===r.line;"rule"!==r.type;)if(!(r=r.parent))return;if((1!==e.props.length||58===t.charCodeAt(0)||Z.get(r))&&!n){Z.set(e,!0);for(var o=[],a=J(t,o),i=r.props,s=0,l=0;s6)switch(u(e,t+1)){case 109:if(45!==u(e,t+4))break;case 102:return l(e,/(.+:)(.+)-([^]+)/,"$1"+L+"$2-$3$1"+z+(108==u(e,t+3)?"$3":"$2-$3"))+e;case 115:return~c(e,"stretch")?re(l(e,"stretch","fill-available"),t)+e:e}break;case 4949:if(115!==u(e,t+1))break;case 6444:switch(u(e,f(e)-3-(~c(e,"!important")&&10))){case 107:return l(e,":",":"+L)+e;case 101:return l(e,/(.+:)([^;!]+)(;|!.+)?/,"$1"+L+(45===u(e,14)?"inline-":"")+"box$3$1"+L+"$2$3$1"+D+"$2box$3")+e}break;case 5936:switch(u(e,t+11)){case 114:return L+e+D+l(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return L+e+D+l(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return L+e+D+l(e,/[svh]\w+-[tblr]{2}/,"lr")+e}return L+e+D+e+e}return e}var ne=[function(e,t,r,n){if(e.length>-1&&!e.return)switch(e.type){case W:e.return=re(e.value,e.length);break;case V:return U([S(e,{value:l(e.value,"@","@"+L)})],n);case $:if(e.length)return function(e,t){return e.map(t).join("")}(e.props,(function(t){switch(function(e,t){return(e=t.exec(e))?e[0]:e}(t,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return U([S(e,{props:[l(t,/:(read-\w+)/,":-moz-$1")]})],n);case"::placeholder":return U([S(e,{props:[l(t,/:(plac\w+)/,":"+L+"input-$1")]}),S(e,{props:[l(t,/:(plac\w+)/,":-moz-$1")]}),S(e,{props:[l(t,/:(plac\w+)/,D+"input-$1")]})],n)}return""}))}}],oe=function(e){var t=e.key;if("css"===t){var r=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(r,(function(e){-1!==e.getAttribute("data-emotion").indexOf(" ")&&(document.head.appendChild(e),e.setAttribute("data-s",""))}))}var o=e.stylisPlugins||ne;var a,i,s={},l=[];a=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+t+' "]'),(function(e){for(var t=e.getAttribute("data-emotion").split(" "),r=1;r{"use strict";function n(e){var t=Object.create(null);return function(r){return void 0===t[r]&&(t[r]=e(r)),t[r]}}r.d(t,{A:()=>n})},5756:(e,t,r)=>{"use strict";r.d(t,{C:()=>s,T:()=>c,i:()=>a,w:()=>l});var n=r(5043),o=r(5513),a=(r(2830),r(9436),!0),i=n.createContext("undefined"!==typeof HTMLElement?(0,o.A)({key:"css"}):null);var s=i.Provider,l=function(e){return(0,n.forwardRef)((function(t,r){var o=(0,n.useContext)(i);return e(t,o,r)}))};a||(l=function(e){return function(t){var r=(0,n.useContext)(i);return null===r?(r=(0,o.A)({key:"css"}),n.createElement(i.Provider,{value:r},e(t,r))):e(t,r)}});var c=n.createContext({})},3290:(e,t,r)=>{"use strict";r.d(t,{AH:()=>c,i7:()=>u,mL:()=>l});var n=r(5756),o=r(5043),a=r(1722),i=r(9436),s=r(2830),l=(r(5513),r(219),(0,n.w)((function(e,t){var r=e.styles,l=(0,s.J)([r],void 0,o.useContext(n.T));if(!n.i){for(var c,u=l.name,d=l.styles,f=l.next;void 0!==f;)u+=" "+f.name,d+=f.styles,f=f.next;var p=!0===t.compat,h=t.insert("",{name:u,styles:d},t.sheet,p);return p?null:o.createElement("style",((c={})["data-emotion"]=t.key+"-global "+u,c.dangerouslySetInnerHTML={__html:h},c.nonce=t.sheet.nonce,c))}var m=o.useRef();return(0,i.i)((function(){var e=t.key+"-global",r=new t.sheet.constructor({key:e,nonce:t.sheet.nonce,container:t.sheet.container,speedy:t.sheet.isSpeedy}),n=!1,o=document.querySelector('style[data-emotion="'+e+" "+l.name+'"]');return t.sheet.tags.length&&(r.before=t.sheet.tags[0]),null!==o&&(n=!0,o.setAttribute("data-emotion",e),r.hydrate([o])),m.current=[r,n],function(){r.flush()}}),[t]),(0,i.i)((function(){var e=m.current,r=e[0];if(e[1])e[1]=!1;else{if(void 0!==l.next&&(0,a.sk)(t,l.next,!0),r.tags.length){var n=r.tags[r.tags.length-1].nextElementSibling;r.before=n,r.flush()}t.insert("",l,r,!1)}}),[t,l.name]),null})));function c(){for(var e=arguments.length,t=new Array(e),r=0;r{"use strict";r.d(t,{J:()=>h});var n={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},o=r(918),a=/[A-Z]|^ms/g,i=/_EMO_([^_]+?)_([^]*?)_EMO_/g,s=function(e){return 45===e.charCodeAt(1)},l=function(e){return null!=e&&"boolean"!==typeof e},c=(0,o.A)((function(e){return s(e)?e:e.replace(a,"-$&").toLowerCase()})),u=function(e,t){switch(e){case"animation":case"animationName":if("string"===typeof t)return t.replace(i,(function(e,t,r){return f={name:t,styles:r,next:f},t}))}return 1===n[e]||s(e)||"number"!==typeof t||0===t?t:t+"px"};function d(e,t,r){if(null==r)return"";if(void 0!==r.__emotion_styles)return r;switch(typeof r){case"boolean":return"";case"object":if(1===r.anim)return f={name:r.name,styles:r.styles,next:f},r.name;if(void 0!==r.styles){var n=r.next;if(void 0!==n)for(;void 0!==n;)f={name:n.name,styles:n.styles,next:f},n=n.next;return r.styles+";"}return function(e,t,r){var n="";if(Array.isArray(r))for(var o=0;o=4;++n,o-=4)t=1540483477*(65535&(t=255&e.charCodeAt(n)|(255&e.charCodeAt(++n))<<8|(255&e.charCodeAt(++n))<<16|(255&e.charCodeAt(++n))<<24))+(59797*(t>>>16)<<16),r=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&r)+(59797*(r>>>16)<<16);switch(o){case 3:r^=(255&e.charCodeAt(n+2))<<16;case 2:r^=(255&e.charCodeAt(n+1))<<8;case 1:r=1540483477*(65535&(r^=255&e.charCodeAt(n)))+(59797*(r>>>16)<<16)}return(((r=1540483477*(65535&(r^=r>>>13))+(59797*(r>>>16)<<16))^r>>>15)>>>0).toString(36)}(o)+l;return{name:c,styles:o,next:f}}},9436:(e,t,r)=>{"use strict";var n;r.d(t,{i:()=>s,s:()=>i});var o=r(5043),a=!!(n||(n=r.t(o,2))).useInsertionEffect&&(n||(n=r.t(o,2))).useInsertionEffect,i=a||function(e){return e()},s=a||o.useLayoutEffect},1722:(e,t,r)=>{"use strict";r.d(t,{Rk:()=>n,SF:()=>o,sk:()=>a});function n(e,t,r){var n="";return r.split(" ").forEach((function(r){void 0!==e[r]?t.push(e[r]+";"):n+=r+" "})),n}var o=function(e,t,r){var n=e.key+"-"+t.name;!1===r&&void 0===e.registered[n]&&(e.registered[n]=t.styles)},a=function(e,t,r){o(e,t,r);var n=e.key+"-"+t.name;if(void 0===e.inserted[t.name]){var a=t;do{e.insert(t===a?"."+n:"",a,e.sheet,!0),a=a.next}while(void 0!==a)}}},2505:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"}),"Add")},977:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"m20 12-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8z"}),"ArrowDownward")},3608:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"m4 12 1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8z"}),"ArrowUpward")},4914:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2m0 16H8V7h11z"}),"ContentCopy")},1528:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-2h2zm0-4h-2V7h2z"}),"Error")},9790:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M13 3h-2v10h2zm4.83 2.17-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83"}),"PowerSettingsNew")},7850:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M15 21h-2v-2h2zm-2-7h-2v5h2zm8-2h-2v4h2zm-2-2h-2v2h2zM7 12H5v2h2zm-2-2H3v2h2zm7-5h2V3h-2zm-7.5-.5v3h3v-3zM9 9H3V3h6zm-4.5 7.5v3h3v-3zM9 21H3v-6h6zm7.5-16.5v3h3v-3zM21 9h-6V3h6zm-2 10v-3h-4v2h2v3h4v-2zm-2-7h-4v2h4zm-4-2H7v2h2v2h2v-2h2zm1-1V7h-2V5h-2v4zM6.75 5.25h-1.5v1.5h1.5zm0 12h-1.5v1.5h1.5zm12-12h-1.5v1.5h1.5z"}),"QrCode2")},6164:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M19 13H5v-2h14z"}),"Remove")},6170:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"M12 5V2L8 6l4 4V7c3.31 0 6 2.69 6 6 0 2.97-2.17 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93 0-4.42-3.58-8-8-8m-6 8c0-1.65.67-3.15 1.76-4.24L6.34 7.34C4.9 8.79 4 10.79 4 13c0 4.08 3.05 7.44 7 7.93v-2.02c-2.83-.48-5-2.94-5-5.91"}),"RestartAlt")},7193:(e,t,r)=>{"use strict";var n=r(4994);t.A=void 0;var o=n(r(39)),a=r(579);t.A=(0,o.default)((0,a.jsx)("path",{d:"m12 16.5 4-4h-3v-9h-2v9H8zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2"}),"SystemUpdateAlt")},39:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.createSvgIcon}});var n=r(1512)},5881:(e,t)=>{"use strict";var r,n=Symbol.for("react.element"),o=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.server_context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen");function v(e){if("object"===typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case a:case s:case i:case f:case p:return e;default:switch(e=e&&e.$$typeof){case u:case c:case d:case m:case h:case l:return e;default:return t}}case o:return t}}}r=Symbol.for("react.module.reference")},805:(e,t,r)=>{"use strict";r(5881)},8279:(e,t,r)=>{"use strict";r.d(t,{A:()=>L});var n=r(8168),o=r(8587),a=r(6632),i=r(3216),s=r(7758),l=r(8812),c=r(8280);var u=r(7266);const d={black:"#000",white:"#fff"},f={50:"#fafafa",100:"#f5f5f5",200:"#eeeeee",300:"#e0e0e0",400:"#bdbdbd",500:"#9e9e9e",600:"#757575",700:"#616161",800:"#424242",900:"#212121",A100:"#f5f5f5",A200:"#eeeeee",A400:"#bdbdbd",A700:"#616161"},p={50:"#f3e5f5",100:"#e1bee7",200:"#ce93d8",300:"#ba68c8",400:"#ab47bc",500:"#9c27b0",600:"#8e24aa",700:"#7b1fa2",800:"#6a1b9a",900:"#4a148c",A100:"#ea80fc",A200:"#e040fb",A400:"#d500f9",A700:"#aa00ff"},h={50:"#ffebee",100:"#ffcdd2",200:"#ef9a9a",300:"#e57373",400:"#ef5350",500:"#f44336",600:"#e53935",700:"#d32f2f",800:"#c62828",900:"#b71c1c",A100:"#ff8a80",A200:"#ff5252",A400:"#ff1744",A700:"#d50000"},m={50:"#fff3e0",100:"#ffe0b2",200:"#ffcc80",300:"#ffb74d",400:"#ffa726",500:"#ff9800",600:"#fb8c00",700:"#f57c00",800:"#ef6c00",900:"#e65100",A100:"#ffd180",A200:"#ffab40",A400:"#ff9100",A700:"#ff6d00"},g={50:"#e3f2fd",100:"#bbdefb",200:"#90caf9",300:"#64b5f6",400:"#42a5f5",500:"#2196f3",600:"#1e88e5",700:"#1976d2",800:"#1565c0",900:"#0d47a1",A100:"#82b1ff",A200:"#448aff",A400:"#2979ff",A700:"#2962ff"},v={50:"#e1f5fe",100:"#b3e5fc",200:"#81d4fa",300:"#4fc3f7",400:"#29b6f6",500:"#03a9f4",600:"#039be5",700:"#0288d1",800:"#0277bd",900:"#01579b",A100:"#80d8ff",A200:"#40c4ff",A400:"#00b0ff",A700:"#0091ea"},y={50:"#e8f5e9",100:"#c8e6c9",200:"#a5d6a7",300:"#81c784",400:"#66bb6a",500:"#4caf50",600:"#43a047",700:"#388e3c",800:"#2e7d32",900:"#1b5e20",A100:"#b9f6ca",A200:"#69f0ae",A400:"#00e676",A700:"#00c853"},b=["mode","contrastThreshold","tonalOffset"],w={text:{primary:"rgba(0, 0, 0, 0.87)",secondary:"rgba(0, 0, 0, 0.6)",disabled:"rgba(0, 0, 0, 0.38)"},divider:"rgba(0, 0, 0, 0.12)",background:{paper:d.white,default:d.white},action:{active:"rgba(0, 0, 0, 0.54)",hover:"rgba(0, 0, 0, 0.04)",hoverOpacity:.04,selected:"rgba(0, 0, 0, 0.08)",selectedOpacity:.08,disabled:"rgba(0, 0, 0, 0.26)",disabledBackground:"rgba(0, 0, 0, 0.12)",disabledOpacity:.38,focus:"rgba(0, 0, 0, 0.12)",focusOpacity:.12,activatedOpacity:.12}},x={text:{primary:d.white,secondary:"rgba(255, 255, 255, 0.7)",disabled:"rgba(255, 255, 255, 0.5)",icon:"rgba(255, 255, 255, 0.5)"},divider:"rgba(255, 255, 255, 0.12)",background:{paper:"#121212",default:"#121212"},action:{active:d.white,hover:"rgba(255, 255, 255, 0.08)",hoverOpacity:.08,selected:"rgba(255, 255, 255, 0.16)",selectedOpacity:.16,disabled:"rgba(255, 255, 255, 0.3)",disabledBackground:"rgba(255, 255, 255, 0.12)",disabledOpacity:.38,focus:"rgba(255, 255, 255, 0.12)",focusOpacity:.12,activatedOpacity:.24}};function S(e,t,r,n){const o=n.light||n,a=n.dark||1.5*n;e[t]||(e.hasOwnProperty(r)?e[t]=e[r]:"light"===t?e.light=(0,u.a)(e.main,o):"dark"===t&&(e.dark=(0,u.e$)(e.main,a)))}function A(e){const{mode:t="light",contrastThreshold:r=3,tonalOffset:s=.2}=e,l=(0,o.A)(e,b),c=e.primary||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:g[200],light:g[50],dark:g[400]}:{main:g[700],light:g[400],dark:g[800]}}(t),A=e.secondary||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:p[200],light:p[50],dark:p[400]}:{main:p[500],light:p[300],dark:p[700]}}(t),k=e.error||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:h[500],light:h[300],dark:h[700]}:{main:h[700],light:h[400],dark:h[800]}}(t),C=e.info||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:v[400],light:v[300],dark:v[700]}:{main:v[700],light:v[500],dark:v[900]}}(t),E=e.success||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:y[400],light:y[300],dark:y[700]}:{main:y[800],light:y[500],dark:y[900]}}(t),_=e.warning||function(){return"dark"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"light")?{main:m[400],light:m[300],dark:m[700]}:{main:"#ed6c02",light:m[500],dark:m[900]}}(t);function P(e){return(0,u.eM)(e,x.text.primary)>=r?x.text.primary:w.text.primary}const j=e=>{let{color:t,name:r,mainShade:o=500,lightShade:i=300,darkShade:l=700}=e;if(t=(0,n.A)({},t),!t.main&&t[o]&&(t.main=t[o]),!t.hasOwnProperty("main"))throw new Error((0,a.A)(11,r?" (".concat(r,")"):"",o));if("string"!==typeof t.main)throw new Error((0,a.A)(12,r?" (".concat(r,")"):"",JSON.stringify(t.main)));return S(t,"light",i,s),S(t,"dark",l,s),t.contrastText||(t.contrastText=P(t.main)),t},R={dark:x,light:w};return(0,i.A)((0,n.A)({common:(0,n.A)({},d),mode:t,primary:j({color:c,name:"primary"}),secondary:j({color:A,name:"secondary",mainShade:"A400",lightShade:"A200",darkShade:"A700"}),error:j({color:k,name:"error"}),warning:j({color:_,name:"warning"}),info:j({color:C,name:"info"}),success:j({color:E,name:"success"}),grey:f,contrastThreshold:r,getContrastText:P,augmentColor:j,tonalOffset:s},R[t]),l)}const k=["fontFamily","fontSize","fontWeightLight","fontWeightRegular","fontWeightMedium","fontWeightBold","htmlFontSize","allVariants","pxToRem"];const C={textTransform:"uppercase"},E='"Roboto", "Helvetica", "Arial", sans-serif';function _(e,t){const r="function"===typeof t?t(e):t,{fontFamily:a=E,fontSize:s=14,fontWeightLight:l=300,fontWeightRegular:c=400,fontWeightMedium:u=500,fontWeightBold:d=700,htmlFontSize:f=16,allVariants:p,pxToRem:h}=r,m=(0,o.A)(r,k);const g=s/14,v=h||(e=>"".concat(e/f*g,"rem")),y=(e,t,r,o,i)=>{return(0,n.A)({fontFamily:a,fontWeight:e,fontSize:v(t),lineHeight:r},a===E?{letterSpacing:"".concat((s=o/t,Math.round(1e5*s)/1e5),"em")}:{},i,p);var s},b={h1:y(l,96,1.167,-1.5),h2:y(l,60,1.2,-.5),h3:y(c,48,1.167,0),h4:y(c,34,1.235,.25),h5:y(c,24,1.334,0),h6:y(u,20,1.6,.15),subtitle1:y(c,16,1.75,.15),subtitle2:y(u,14,1.57,.1),body1:y(c,16,1.5,.15),body2:y(c,14,1.43,.15),button:y(u,14,1.75,.4,C),caption:y(c,12,1.66,.4),overline:y(c,12,2.66,1,C),inherit:{fontFamily:"inherit",fontWeight:"inherit",fontSize:"inherit",lineHeight:"inherit",letterSpacing:"inherit"}};return(0,i.A)((0,n.A)({htmlFontSize:f,pxToRem:v,fontFamily:a,fontSize:s,fontWeightLight:l,fontWeightRegular:c,fontWeightMedium:u,fontWeightBold:d},b),m,{clone:!1})}function P(){return["".concat(arguments.length<=0?void 0:arguments[0],"px ").concat(arguments.length<=1?void 0:arguments[1],"px ").concat(arguments.length<=2?void 0:arguments[2],"px ").concat(arguments.length<=3?void 0:arguments[3],"px rgba(0,0,0,").concat(.2,")"),"".concat(arguments.length<=4?void 0:arguments[4],"px ").concat(arguments.length<=5?void 0:arguments[5],"px ").concat(arguments.length<=6?void 0:arguments[6],"px ").concat(arguments.length<=7?void 0:arguments[7],"px rgba(0,0,0,").concat(.14,")"),"".concat(arguments.length<=8?void 0:arguments[8],"px ").concat(arguments.length<=9?void 0:arguments[9],"px ").concat(arguments.length<=10?void 0:arguments[10],"px ").concat(arguments.length<=11?void 0:arguments[11],"px rgba(0,0,0,").concat(.12,")")].join(",")}const j=["none",P(0,2,1,-1,0,1,1,0,0,1,3,0),P(0,3,1,-2,0,2,2,0,0,1,5,0),P(0,3,3,-2,0,3,4,0,0,1,8,0),P(0,2,4,-1,0,4,5,0,0,1,10,0),P(0,3,5,-1,0,5,8,0,0,1,14,0),P(0,3,5,-1,0,6,10,0,0,1,18,0),P(0,4,5,-2,0,7,10,1,0,2,16,1),P(0,5,5,-3,0,8,10,1,0,3,14,2),P(0,5,6,-3,0,9,12,1,0,3,16,2),P(0,6,6,-3,0,10,14,1,0,4,18,3),P(0,6,7,-4,0,11,15,1,0,4,20,3),P(0,7,8,-4,0,12,17,2,0,5,22,4),P(0,7,8,-4,0,13,19,2,0,5,24,4),P(0,7,9,-4,0,14,21,2,0,5,26,4),P(0,8,9,-5,0,15,22,2,0,6,28,5),P(0,8,10,-5,0,16,24,2,0,6,30,5),P(0,8,11,-5,0,17,26,2,0,6,32,5),P(0,9,11,-5,0,18,28,2,0,7,34,6),P(0,9,12,-6,0,19,29,2,0,7,36,6),P(0,10,13,-6,0,20,31,3,0,8,38,7),P(0,10,13,-6,0,21,33,3,0,8,40,7),P(0,10,14,-6,0,22,35,3,0,8,42,7),P(0,11,14,-7,0,23,36,3,0,9,44,8),P(0,11,15,-7,0,24,38,3,0,9,46,8)],R=["duration","easing","delay"],O={easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",easeOut:"cubic-bezier(0.0, 0, 0.2, 1)",easeIn:"cubic-bezier(0.4, 0, 1, 1)",sharp:"cubic-bezier(0.4, 0, 0.6, 1)"},N={shortest:150,shorter:200,short:250,standard:300,complex:375,enteringScreen:225,leavingScreen:195};function T(e){return"".concat(Math.round(e),"ms")}function I(e){if(!e)return 0;const t=e/36;return Math.round(10*(4+15*t**.25+t/5))}function M(e){const t=(0,n.A)({},O,e.easing),r=(0,n.A)({},N,e.duration);return(0,n.A)({getAutoHeightDuration:I,create:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["all"],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{duration:a=r.standard,easing:i=t.easeInOut,delay:s=0}=n;(0,o.A)(n,R);return(Array.isArray(e)?e:[e]).map((e=>"".concat(e," ").concat("string"===typeof a?a:T(a)," ").concat(i," ").concat("string"===typeof s?s:T(s)))).join(",")}},e,{easing:t,duration:r})}const F={mobileStepper:1e3,fab:1050,speedDial:1050,appBar:1100,drawer:1200,modal:1300,snackbar:1400,tooltip:1500},D=["breakpoints","mixins","spacing","palette","transitions","typography","shape"];function z(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{mixins:t={},palette:r={},transitions:u={},typography:d={}}=e,f=(0,o.A)(e,D);if(e.vars)throw new Error((0,a.A)(18));const p=A(r),h=(0,c.A)(e);let m=(0,i.A)(h,{mixins:(g=h.breakpoints,v=t,(0,n.A)({toolbar:{minHeight:56,[g.up("xs")]:{"@media (orientation: landscape)":{minHeight:48}},[g.up("sm")]:{minHeight:64}}},v)),palette:p,shadows:j.slice(),typography:_(p,d),transitions:M(u),zIndex:(0,n.A)({},F)});var g,v;m=(0,i.A)(m,f);for(var y=arguments.length,b=new Array(y>1?y-1:0),w=1;w(0,i.A)(e,t)),m),m.unstable_sxConfig=(0,n.A)({},s.A,null==f?void 0:f.unstable_sxConfig),m.unstable_sx=function(e){return(0,l.A)({sx:e,theme:this})},m}const L=z},5170:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=(0,r(8279).A)()},3375:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n="$$material"},4535:(e,t,r)=>{"use strict";r.d(t,{Ay:()=>l,_n:()=>s,ep:()=>i});var n=r(8052),o=r(5170),a=r(3375);const i=e=>(0,n.MC)(e)&&"classes"!==e,s=n.MC,l=(0,n.Ay)({themeId:a.A,defaultTheme:o.A,rootShouldForwardProp:i})},2876:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});var n=r(2919),o=r(5170),a=r(3375);function i(e){let{props:t,name:r}=e;return(0,n.A)({props:t,name:r,defaultTheme:o.A,themeId:a.A})}},6803:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(410).A},6593:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(4708).A},9662:(e,t,r)=>{"use strict";r.d(t,{A:()=>b});var n=r(8168),o=r(5043),a=r(8587),i=r(8387),s=r(8606),l=r(6803),c=r(2876),u=r(4535),d=r(7056),f=r(2400);function p(e){return(0,f.Ay)("MuiSvgIcon",e)}(0,d.A)("MuiSvgIcon",["root","colorPrimary","colorSecondary","colorAction","colorError","colorDisabled","fontSizeInherit","fontSizeSmall","fontSizeMedium","fontSizeLarge"]);var h=r(579);const m=["children","className","color","component","fontSize","htmlColor","inheritViewBox","titleAccess","viewBox"],g=(0,u.Ay)("svg",{name:"MuiSvgIcon",slot:"Root",overridesResolver:(e,t)=>{const{ownerState:r}=e;return[t.root,"inherit"!==r.color&&t["color".concat((0,l.A)(r.color))],t["fontSize".concat((0,l.A)(r.fontSize))]]}})((e=>{let{theme:t,ownerState:r}=e;var n,o,a,i,s,l,c,u,d,f,p,h,m;return{userSelect:"none",width:"1em",height:"1em",display:"inline-block",fill:r.hasSvgAsChild?void 0:"currentColor",flexShrink:0,transition:null==(n=t.transitions)||null==(o=n.create)?void 0:o.call(n,"fill",{duration:null==(a=t.transitions)||null==(a=a.duration)?void 0:a.shorter}),fontSize:{inherit:"inherit",small:(null==(i=t.typography)||null==(s=i.pxToRem)?void 0:s.call(i,20))||"1.25rem",medium:(null==(l=t.typography)||null==(c=l.pxToRem)?void 0:c.call(l,24))||"1.5rem",large:(null==(u=t.typography)||null==(d=u.pxToRem)?void 0:d.call(u,35))||"2.1875rem"}[r.fontSize],color:null!=(f=null==(p=(t.vars||t).palette)||null==(p=p[r.color])?void 0:p.main)?f:{action:null==(h=(t.vars||t).palette)||null==(h=h.action)?void 0:h.active,disabled:null==(m=(t.vars||t).palette)||null==(m=m.action)?void 0:m.disabled,inherit:void 0}[r.color]}})),v=o.forwardRef((function(e,t){const r=(0,c.A)({props:e,name:"MuiSvgIcon"}),{children:u,className:d,color:f="inherit",component:v="svg",fontSize:y="medium",htmlColor:b,inheritViewBox:w=!1,titleAccess:x,viewBox:S="0 0 24 24"}=r,A=(0,a.A)(r,m),k=o.isValidElement(u)&&"svg"===u.type,C=(0,n.A)({},r,{color:f,component:v,fontSize:y,instanceFontSize:e.fontSize,inheritViewBox:w,viewBox:S,hasSvgAsChild:k}),E={};w||(E.viewBox=S);const _=(e=>{const{color:t,fontSize:r,classes:n}=e,o={root:["root","inherit"!==t&&"color".concat((0,l.A)(t)),"fontSize".concat((0,l.A)(r))]};return(0,s.A)(o,p,n)})(C);return(0,h.jsxs)(g,(0,n.A)({as:v,className:(0,i.A)(_.root,d),focusable:"false",color:b,"aria-hidden":!x||void 0,role:x?"img":void 0,ref:t},E,A,k&&u.props,{ownerState:C,children:[k?u.props.children:u,x?(0,h.jsx)("title",{children:x}):null]}))}));v.muiName="SvgIcon";const y=v;function b(e,t){function r(r,o){return(0,h.jsx)(y,(0,n.A)({"data-testid":"".concat(t,"Icon"),ref:o},r,{children:e}))}return r.muiName=y.muiName,o.memo(o.forwardRef(r))}},950:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(6440).A},1512:(e,t,r)=>{"use strict";r.r(t),r.d(t,{capitalize:()=>o.A,createChainedFunction:()=>a.A,createSvgIcon:()=>i.A,debounce:()=>s.A,deprecatedPropType:()=>l,isMuiElement:()=>c.A,ownerDocument:()=>u.A,ownerWindow:()=>d.A,requirePropFactory:()=>f,setRef:()=>p,unstable_ClassNameGenerator:()=>x,unstable_useEnhancedEffect:()=>h.A,unstable_useId:()=>m.A,unsupportedProp:()=>g,useControlled:()=>v.A,useEventCallback:()=>y.A,useForkRef:()=>b.A,useIsFocusVisible:()=>w.A});var n=r(5430),o=r(6803),a=r(6593),i=r(9662),s=r(950);const l=function(e,t){return()=>null};var c=r(154),u=r(2427),d=r(6078);r(8168);const f=function(e,t){return()=>null};const p=r(9184).A;var h=r(5013),m=r(5879);const g=function(e,t,r,n,o){return null};var v=r(4516),y=r(3319),b=r(5849),w=r(7844);const x={configure:e=>{n.A.configure(e)}}},154:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(5043);const o=function(e,t){var r,o;return n.isValidElement(e)&&-1!==t.indexOf(null!=(r=e.type.muiName)?r:null==(o=e.type)||null==(o=o._payload)||null==(o=o.value)?void 0:o.muiName)}},2427:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(2144).A},6078:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(6288).A},4516:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(1944).A},5013:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(3844).A},3319:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(4626).A},5849:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(7042).A},5879:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(992).A},7844:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=r(932).A},869:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});r(5043);var n=r(3290),o=r(579);function a(e){const{styles:t,defaultTheme:r={}}=e,a="function"===typeof t?e=>{return t(void 0===(n=e)||null===n||0===Object.keys(n).length?r:e);var n}:t;return(0,o.jsx)(n.mL,{styles:a})}},3174:(e,t,r)=>{"use strict";r.r(t),r.d(t,{GlobalStyles:()=>A.A,StyledEngineProvider:()=>S,ThemeContext:()=>l.T,css:()=>y.AH,default:()=>k,internal_processStyles:()=>C,keyframes:()=>y.i7});var n=r(8168),o=r(5043),a=r(918),i=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,s=(0,a.A)((function(e){return i.test(e)||111===e.charCodeAt(0)&&110===e.charCodeAt(1)&&e.charCodeAt(2)<91})),l=r(5756),c=r(1722),u=r(2830),d=r(9436),f=s,p=function(e){return"theme"!==e},h=function(e){return"string"===typeof e&&e.charCodeAt(0)>96?f:p},m=function(e,t,r){var n;if(t){var o=t.shouldForwardProp;n=e.__emotion_forwardProp&&o?function(t){return e.__emotion_forwardProp(t)&&o(t)}:o}return"function"!==typeof n&&r&&(n=e.__emotion_forwardProp),n},g=function(e){var t=e.cache,r=e.serialized,n=e.isStringTag;return(0,c.SF)(t,r,n),(0,d.s)((function(){return(0,c.sk)(t,r,n)})),null},v=function e(t,r){var a,i,s=t.__emotion_real===t,d=s&&t.__emotion_base||t;void 0!==r&&(a=r.label,i=r.target);var f=m(t,r,s),p=f||h(d),v=!p("as");return function(){var y=arguments,b=s&&void 0!==t.__emotion_styles?t.__emotion_styles.slice(0):[];if(void 0!==a&&b.push("label:"+a+";"),null==y[0]||void 0===y[0].raw)b.push.apply(b,y);else{0,b.push(y[0][0]);for(var w=y.length,x=1;x{Array.isArray(e.__emotion_styles)&&(e.__emotion_styles=t(e.__emotion_styles))}},7266:(e,t,r)=>{"use strict";var n=r(4994);t.X4=p,t.e$=h,t.tL=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.15;return f(e)>.5?h(e,t):m(e,t)},t.eM=function(e,t){const r=f(e),n=f(t);return(Math.max(r,n)+.05)/(Math.min(r,n)+.05)},t.a=m;var o=n(r(7245)),a=n(r(5383));function i(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return(0,a.default)(e,t,r)}function s(e){e=e.slice(1);const t=new RegExp(".{1,".concat(e.length>=6?2:1,"}"),"g");let r=e.match(t);return r&&1===r[0].length&&(r=r.map((e=>e+e))),r?"rgb".concat(4===r.length?"a":"","(").concat(r.map(((e,t)=>t<3?parseInt(e,16):Math.round(parseInt(e,16)/255*1e3)/1e3)).join(", "),")"):""}function l(e){if(e.type)return e;if("#"===e.charAt(0))return l(s(e));const t=e.indexOf("("),r=e.substring(0,t);if(-1===["rgb","rgba","hsl","hsla","color"].indexOf(r))throw new Error((0,o.default)(9,e));let n,a=e.substring(t+1,e.length-1);if("color"===r){if(a=a.split(" "),n=a.shift(),4===a.length&&"/"===a[3].charAt(0)&&(a[3]=a[3].slice(1)),-1===["srgb","display-p3","a98-rgb","prophoto-rgb","rec-2020"].indexOf(n))throw new Error((0,o.default)(10,n))}else a=a.split(",");return a=a.map((e=>parseFloat(e))),{type:r,values:a,colorSpace:n}}const c=e=>{const t=l(e);return t.values.slice(0,3).map(((e,r)=>-1!==t.type.indexOf("hsl")&&0!==r?"".concat(e,"%"):e)).join(" ")};function u(e){const{type:t,colorSpace:r}=e;let{values:n}=e;return-1!==t.indexOf("rgb")?n=n.map(((e,t)=>t<3?parseInt(e,10):e)):-1!==t.indexOf("hsl")&&(n[1]="".concat(n[1],"%"),n[2]="".concat(n[2],"%")),n=-1!==t.indexOf("color")?"".concat(r," ").concat(n.join(" ")):"".concat(n.join(", ")),"".concat(t,"(").concat(n,")")}function d(e){e=l(e);const{values:t}=e,r=t[0],n=t[1]/100,o=t[2]/100,a=n*Math.min(o,1-o),i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e+r/30)%12;return o-a*Math.max(Math.min(t-3,9-t,1),-1)};let s="rgb";const c=[Math.round(255*i(0)),Math.round(255*i(8)),Math.round(255*i(4))];return"hsla"===e.type&&(s+="a",c.push(t[3])),u({type:s,values:c})}function f(e){let t="hsl"===(e=l(e)).type||"hsla"===e.type?l(d(e)).values:e.values;return t=t.map((t=>("color"!==e.type&&(t/=255),t<=.03928?t/12.92:((t+.055)/1.055)**2.4))),Number((.2126*t[0]+.7152*t[1]+.0722*t[2]).toFixed(3))}function p(e,t){return e=l(e),t=i(t),"rgb"!==e.type&&"hsl"!==e.type||(e.type+="a"),"color"===e.type?e.values[3]="/".concat(t):e.values[3]=t,u(e)}function h(e,t){if(e=l(e),t=i(t),-1!==e.type.indexOf("hsl"))e.values[2]*=1-t;else if(-1!==e.type.indexOf("rgb")||-1!==e.type.indexOf("color"))for(let r=0;r<3;r+=1)e.values[r]*=1-t;return u(e)}function m(e,t){if(e=l(e),t=i(t),-1!==e.type.indexOf("hsl"))e.values[2]+=(100-e.values[2])*t;else if(-1!==e.type.indexOf("rgb"))for(let r=0;r<3;r+=1)e.values[r]+=(255-e.values[r])*t;else if(-1!==e.type.indexOf("color"))for(let r=0;r<3;r+=1)e.values[r]+=(1-e.values[r])*t;return u(e)}},8052:(e,t,r)=>{"use strict";var n=r(4994);t.Ay=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{themeId:t,defaultTheme:r=m,rootShouldForwardProp:n=h,slotShouldForwardProp:l=h}=e,u=e=>(0,c.default)((0,o.default)({},e,{theme:v((0,o.default)({},e,{defaultTheme:r,themeId:t}))}));return u.__mui_systemSx=!0,function(e){let c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,i.internal_processStyles)(e,(e=>e.filter((e=>!(null!=e&&e.__mui_systemSx)))));const{name:d,slot:p,skipVariantsResolver:m,skipSx:w,overridesResolver:x=y(g(p))}=c,S=(0,a.default)(c,f),A=void 0!==m?m:p&&"Root"!==p&&"root"!==p||!1,k=w||!1;let C=h;"Root"===p||"root"===p?C=n:p?C=l:function(e){return"string"===typeof e&&e.charCodeAt(0)>96}(e)&&(C=void 0);const E=(0,i.default)(e,(0,o.default)({shouldForwardProp:C,label:undefined},S)),_=e=>"function"===typeof e&&e.__emotion_real!==e||(0,s.isPlainObject)(e)?n=>b(e,(0,o.default)({},n,{theme:v({theme:n.theme,defaultTheme:r,themeId:t})})):e,P=function(n){let a=_(n);for(var i=arguments.length,s=new Array(i>1?i-1:0),l=1;l{const n=v((0,o.default)({},e,{defaultTheme:r,themeId:t}));if(!n.components||!n.components[d]||!n.components[d].styleOverrides)return null;const a=n.components[d].styleOverrides,i={};return Object.entries(a).forEach((t=>{let[r,a]=t;i[r]=b(a,(0,o.default)({},e,{theme:n}))})),x(e,i)})),d&&!A&&c.push((e=>{var n;const a=v((0,o.default)({},e,{defaultTheme:r,themeId:t}));return b({variants:null==a||null==(n=a.components)||null==(n=n[d])?void 0:n.variants},(0,o.default)({},e,{theme:a}))})),k||c.push(u);const f=c.length-s.length;if(Array.isArray(n)&&f>0){const e=new Array(f).fill("");a=[...n,...e],a.raw=[...n.raw,...e]}const p=E(a,...c);return e.muiName&&(p.muiName=e.muiName),p};return E.withConfig&&(P.withConfig=E.withConfig),P}},t.MC=h;var o=n(r(4634)),a=n(r(4893)),i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=p(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var i=o?Object.getOwnPropertyDescriptor(e,a):null;i&&(i.get||i.set)?Object.defineProperty(n,a,i):n[a]=e[a]}return n.default=e,r&&r.set(e,n),n}(r(3174)),s=r(4534),l=(n(r(578)),n(r(2046)),n(r(4989))),c=n(r(3234));const u=["ownerState"],d=["variants"],f=["name","slot","skipVariantsResolver","skipSx","overridesResolver"];function p(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(p=function(e){return e?r:t})(e)}function h(e){return"ownerState"!==e&&"theme"!==e&&"sx"!==e&&"as"!==e}const m=(0,l.default)(),g=e=>e?e.charAt(0).toLowerCase()+e.slice(1):e;function v(e){let{defaultTheme:t,theme:r,themeId:n}=e;return o=r,0===Object.keys(o).length?t:r[n]||r;var o}function y(e){return e?(t,r)=>r[e]:null}function b(e,t){let{ownerState:r}=t,n=(0,a.default)(t,u);const i="function"===typeof e?e((0,o.default)({ownerState:r},n)):e;if(Array.isArray(i))return i.flatMap((e=>b(e,(0,o.default)({ownerState:r},n))));if(i&&"object"===typeof i&&Array.isArray(i.variants)){const{variants:e=[]}=i;let t=(0,a.default)(i,d);return e.forEach((e=>{let a=!0;"function"===typeof e.props?a=e.props((0,o.default)({ownerState:r},n,r)):Object.keys(e.props).forEach((t=>{(null==r?void 0:r[t])!==e.props[t]&&n[t]!==e.props[t]&&(a=!1)})),a&&(Array.isArray(t)||(t=[t]),t.push("function"===typeof e.style?e.style((0,o.default)({ownerState:r},n,r)):e.style))})),t}return i}},9751:(e,t,r)=>{"use strict";r.d(t,{EU:()=>s,NI:()=>i,iZ:()=>c,kW:()=>u,vf:()=>l,zu:()=>o});var n=r(3216);const o={xs:0,sm:600,md:900,lg:1200,xl:1536},a={keys:["xs","sm","md","lg","xl"],up:e=>"@media (min-width:".concat(o[e],"px)")};function i(e,t,r){const n=e.theme||{};if(Array.isArray(t)){const e=n.breakpoints||a;return t.reduce(((n,o,a)=>(n[e.up(e.keys[a])]=r(t[a]),n)),{})}if("object"===typeof t){const e=n.breakpoints||a;return Object.keys(t).reduce(((n,a)=>{if(-1!==Object.keys(e.values||o).indexOf(a)){n[e.up(a)]=r(t[a],a)}else{const e=a;n[e]=t[e]}return n}),{})}return r(t)}function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t;return(null==(t=e.keys)?void 0:t.reduce(((t,r)=>(t[e.up(r)]={},t)),{}))||{}}function l(e,t){return e.reduce(((e,t)=>{const r=e[t];return(!r||0===Object.keys(r).length)&&delete e[t],e}),t)}function c(e){const t=s(e);for(var r=arguments.length,o=new Array(r>1?r-1:0),a=1;a(0,n.A)(e,t)),{});return l(Object.keys(t),i)}function u(e){let{values:t,breakpoints:r,base:n}=e;const o=n||function(e,t){if("object"!==typeof e)return{};const r={},n=Object.keys(t);return Array.isArray(e)?n.forEach(((t,n)=>{n{null!=e[t]&&(r[t]=!0)})),r}(t,r),a=Object.keys(o);if(0===a.length)return t;let i;return a.reduce(((e,r,n)=>(Array.isArray(t)?(e[r]=null!=t[n]?t[n]:t[i],i=n):"object"===typeof t?(e[r]=null!=t[r]?t[r]:t[i],i=r):e[r]=t,e)),{})}},9703:(e,t,r)=>{"use strict";function n(e,t){const r=this;if(r.vars&&"function"===typeof r.getColorSchemeSelector){return{[r.getColorSchemeSelector(e).replace(/(\[[^\]]+\])/,"*:where($1)")]:t}}return r.palette.mode===e?t:{}}r.d(t,{A:()=>n})},4853:(e,t,r)=>{"use strict";r.d(t,{A:()=>s});var n=r(8587),o=r(8168);const a=["values","unit","step"],i=e=>{const t=Object.keys(e).map((t=>({key:t,val:e[t]})))||[];return t.sort(((e,t)=>e.val-t.val)),t.reduce(((e,t)=>(0,o.A)({},e,{[t.key]:t.val})),{})};function s(e){const{values:t={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:r="px",step:s=5}=e,l=(0,n.A)(e,a),c=i(t),u=Object.keys(c);function d(e){const n="number"===typeof t[e]?t[e]:e;return"@media (min-width:".concat(n).concat(r,")")}function f(e){const n="number"===typeof t[e]?t[e]:e;return"@media (max-width:".concat(n-s/100).concat(r,")")}function p(e,n){const o=u.indexOf(n);return"@media (min-width:".concat("number"===typeof t[e]?t[e]:e).concat(r,") and ")+"(max-width:".concat((-1!==o&&"number"===typeof t[u[o]]?t[u[o]]:n)-s/100).concat(r,")")}return(0,o.A)({keys:u,values:c,up:d,down:f,between:p,only:function(e){return u.indexOf(e)+1{"use strict";r.d(t,{A:()=>p});var n=r(8168),o=r(8587),a=r(3216),i=r(4853);const s={borderRadius:4};var l=r(8604);var c=r(8812),u=r(7758),d=r(9703);const f=["breakpoints","palette","spacing","shape"];const p=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{breakpoints:t={},palette:r={},spacing:p,shape:h={}}=e,m=(0,o.A)(e,f),g=(0,i.A)(t),v=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8;if(e.mui)return e;const t=(0,l.LX)({spacing:e}),r=function(){for(var e=arguments.length,r=new Array(e),n=0;n{const r=t(e);return"number"===typeof r?"".concat(r,"px"):r})).join(" ")};return r.mui=!0,r}(p);let y=(0,a.A)({breakpoints:g,direction:"ltr",components:{},palette:(0,n.A)({mode:"light"},r),spacing:v,shape:(0,n.A)({},s,h)},m);y.applyStyles=d.A;for(var b=arguments.length,w=new Array(b>1?b-1:0),x=1;x(0,a.A)(e,t)),y),y.unstable_sxConfig=(0,n.A)({},u.A,null==m?void 0:m.unstable_sxConfig),y.unstable_sx=function(e){return(0,c.A)({sx:e,theme:this})},y}},4989:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A,private_createBreakpoints:()=>o.A,unstable_applyStyles:()=>a.A});var n=r(8280),o=r(4853),a=r(9703)},3815:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(3216);const o=function(e,t){return t?(0,n.A)(e,t,{clone:!1}):e}},8604:(e,t,r)=>{"use strict";r.d(t,{LX:()=>h,MA:()=>p,_W:()=>m,Lc:()=>y,Ms:()=>b});var n=r(9751),o=r(7162),a=r(3815);const i={m:"margin",p:"padding"},s={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},l={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},c=function(e){const t={};return r=>(void 0===t[r]&&(t[r]=e(r)),t[r])}((e=>{if(e.length>2){if(!l[e])return[e];e=l[e]}const[t,r]=e.split(""),n=i[t],o=s[r]||"";return Array.isArray(o)?o.map((e=>n+e)):[n+o]})),u=["m","mt","mr","mb","ml","mx","my","margin","marginTop","marginRight","marginBottom","marginLeft","marginX","marginY","marginInline","marginInlineStart","marginInlineEnd","marginBlock","marginBlockStart","marginBlockEnd"],d=["p","pt","pr","pb","pl","px","py","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","paddingX","paddingY","paddingInline","paddingInlineStart","paddingInlineEnd","paddingBlock","paddingBlockStart","paddingBlockEnd"],f=[...u,...d];function p(e,t,r,n){var a;const i=null!=(a=(0,o.Yn)(e,t,!1))?a:r;return"number"===typeof i?e=>"string"===typeof e?e:i*e:Array.isArray(i)?e=>"string"===typeof e?e:i[e]:"function"===typeof i?i:()=>{}}function h(e){return p(e,"spacing",8)}function m(e,t){if("string"===typeof t||null==t)return t;const r=e(Math.abs(t));return t>=0?r:"number"===typeof r?-r:"-".concat(r)}function g(e,t,r,o){if(-1===t.indexOf(r))return null;const a=function(e,t){return r=>e.reduce(((e,n)=>(e[n]=m(t,r),e)),{})}(c(r),o),i=e[r];return(0,n.NI)(e,i,a)}function v(e,t){const r=h(e.theme);return Object.keys(e).map((n=>g(e,t,n,r))).reduce(a.A,{})}function y(e){return v(e,u)}function b(e){return v(e,d)}function w(e){return v(e,f)}y.propTypes={},y.filterProps=u,b.propTypes={},b.filterProps=d,w.propTypes={},w.filterProps=f},7162:(e,t,r)=>{"use strict";r.d(t,{Ay:()=>s,BO:()=>i,Yn:()=>a});var n=r(410),o=r(9751);function a(e,t){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!t||"string"!==typeof t)return null;if(e&&e.vars&&r){const r="vars.".concat(t).split(".").reduce(((e,t)=>e&&e[t]?e[t]:null),e);if(null!=r)return r}return t.split(".").reduce(((e,t)=>e&&null!=e[t]?e[t]:null),e)}function i(e,t,r){let n,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:r;return n="function"===typeof e?e(r):Array.isArray(e)?e[r]||o:a(e,r)||o,t&&(n=t(n,o,e)),n}const s=function(e){const{prop:t,cssProperty:r=e.prop,themeKey:s,transform:l}=e,c=e=>{if(null==e[t])return null;const c=e[t],u=a(e.theme,s)||{};return(0,o.NI)(e,c,(e=>{let o=i(u,l,e);return e===o&&"string"===typeof e&&(o=i(u,l,"".concat(t).concat("default"===e?"":(0,n.A)(e)),e)),!1===r?o:{[r]:o}}))};return c.propTypes={},c.filterProps=[t],c}},7758:(e,t,r)=>{"use strict";r.d(t,{A:()=>I});var n=r(8604),o=r(7162),a=r(3815);const i=function(){for(var e=arguments.length,t=new Array(e),r=0;r(t.filterProps.forEach((r=>{e[r]=t})),e)),{}),o=e=>Object.keys(e).reduce(((t,r)=>n[r]?(0,a.A)(t,n[r](e)):t),{});return o.propTypes={},o.filterProps=t.reduce(((e,t)=>e.concat(t.filterProps)),[]),o};var s=r(9751);function l(e){return"number"!==typeof e?e:"".concat(e,"px solid")}function c(e,t){return(0,o.Ay)({prop:e,themeKey:"borders",transform:t})}const u=c("border",l),d=c("borderTop",l),f=c("borderRight",l),p=c("borderBottom",l),h=c("borderLeft",l),m=c("borderColor"),g=c("borderTopColor"),v=c("borderRightColor"),y=c("borderBottomColor"),b=c("borderLeftColor"),w=c("outline",l),x=c("outlineColor"),S=e=>{if(void 0!==e.borderRadius&&null!==e.borderRadius){const t=(0,n.MA)(e.theme,"shape.borderRadius",4,"borderRadius"),r=e=>({borderRadius:(0,n._W)(t,e)});return(0,s.NI)(e,e.borderRadius,r)}return null};S.propTypes={},S.filterProps=["borderRadius"];i(u,d,f,p,h,m,g,v,y,b,S,w,x);const A=e=>{if(void 0!==e.gap&&null!==e.gap){const t=(0,n.MA)(e.theme,"spacing",8,"gap"),r=e=>({gap:(0,n._W)(t,e)});return(0,s.NI)(e,e.gap,r)}return null};A.propTypes={},A.filterProps=["gap"];const k=e=>{if(void 0!==e.columnGap&&null!==e.columnGap){const t=(0,n.MA)(e.theme,"spacing",8,"columnGap"),r=e=>({columnGap:(0,n._W)(t,e)});return(0,s.NI)(e,e.columnGap,r)}return null};k.propTypes={},k.filterProps=["columnGap"];const C=e=>{if(void 0!==e.rowGap&&null!==e.rowGap){const t=(0,n.MA)(e.theme,"spacing",8,"rowGap"),r=e=>({rowGap:(0,n._W)(t,e)});return(0,s.NI)(e,e.rowGap,r)}return null};C.propTypes={},C.filterProps=["rowGap"];i(A,k,C,(0,o.Ay)({prop:"gridColumn"}),(0,o.Ay)({prop:"gridRow"}),(0,o.Ay)({prop:"gridAutoFlow"}),(0,o.Ay)({prop:"gridAutoColumns"}),(0,o.Ay)({prop:"gridAutoRows"}),(0,o.Ay)({prop:"gridTemplateColumns"}),(0,o.Ay)({prop:"gridTemplateRows"}),(0,o.Ay)({prop:"gridTemplateAreas"}),(0,o.Ay)({prop:"gridArea"}));function E(e,t){return"grey"===t?t:e}i((0,o.Ay)({prop:"color",themeKey:"palette",transform:E}),(0,o.Ay)({prop:"bgcolor",cssProperty:"backgroundColor",themeKey:"palette",transform:E}),(0,o.Ay)({prop:"backgroundColor",themeKey:"palette",transform:E}));function _(e){return e<=1&&0!==e?"".concat(100*e,"%"):e}const P=(0,o.Ay)({prop:"width",transform:_}),j=e=>{if(void 0!==e.maxWidth&&null!==e.maxWidth){const t=t=>{var r,n;const o=(null==(r=e.theme)||null==(r=r.breakpoints)||null==(r=r.values)?void 0:r[t])||s.zu[t];return o?"px"!==(null==(n=e.theme)||null==(n=n.breakpoints)?void 0:n.unit)?{maxWidth:"".concat(o).concat(e.theme.breakpoints.unit)}:{maxWidth:o}:{maxWidth:_(t)}};return(0,s.NI)(e,e.maxWidth,t)}return null};j.filterProps=["maxWidth"];const R=(0,o.Ay)({prop:"minWidth",transform:_}),O=(0,o.Ay)({prop:"height",transform:_}),N=(0,o.Ay)({prop:"maxHeight",transform:_}),T=(0,o.Ay)({prop:"minHeight",transform:_}),I=((0,o.Ay)({prop:"size",cssProperty:"width",transform:_}),(0,o.Ay)({prop:"size",cssProperty:"height",transform:_}),i(P,j,R,O,N,T,(0,o.Ay)({prop:"boxSizing"})),{border:{themeKey:"borders",transform:l},borderTop:{themeKey:"borders",transform:l},borderRight:{themeKey:"borders",transform:l},borderBottom:{themeKey:"borders",transform:l},borderLeft:{themeKey:"borders",transform:l},borderColor:{themeKey:"palette"},borderTopColor:{themeKey:"palette"},borderRightColor:{themeKey:"palette"},borderBottomColor:{themeKey:"palette"},borderLeftColor:{themeKey:"palette"},outline:{themeKey:"borders",transform:l},outlineColor:{themeKey:"palette"},borderRadius:{themeKey:"shape.borderRadius",style:S},color:{themeKey:"palette",transform:E},bgcolor:{themeKey:"palette",cssProperty:"backgroundColor",transform:E},backgroundColor:{themeKey:"palette",transform:E},p:{style:n.Ms},pt:{style:n.Ms},pr:{style:n.Ms},pb:{style:n.Ms},pl:{style:n.Ms},px:{style:n.Ms},py:{style:n.Ms},padding:{style:n.Ms},paddingTop:{style:n.Ms},paddingRight:{style:n.Ms},paddingBottom:{style:n.Ms},paddingLeft:{style:n.Ms},paddingX:{style:n.Ms},paddingY:{style:n.Ms},paddingInline:{style:n.Ms},paddingInlineStart:{style:n.Ms},paddingInlineEnd:{style:n.Ms},paddingBlock:{style:n.Ms},paddingBlockStart:{style:n.Ms},paddingBlockEnd:{style:n.Ms},m:{style:n.Lc},mt:{style:n.Lc},mr:{style:n.Lc},mb:{style:n.Lc},ml:{style:n.Lc},mx:{style:n.Lc},my:{style:n.Lc},margin:{style:n.Lc},marginTop:{style:n.Lc},marginRight:{style:n.Lc},marginBottom:{style:n.Lc},marginLeft:{style:n.Lc},marginX:{style:n.Lc},marginY:{style:n.Lc},marginInline:{style:n.Lc},marginInlineStart:{style:n.Lc},marginInlineEnd:{style:n.Lc},marginBlock:{style:n.Lc},marginBlockStart:{style:n.Lc},marginBlockEnd:{style:n.Lc},displayPrint:{cssProperty:!1,transform:e=>({"@media print":{display:e}})},display:{},overflow:{},textOverflow:{},visibility:{},whiteSpace:{},flexBasis:{},flexDirection:{},flexWrap:{},justifyContent:{},alignItems:{},alignContent:{},order:{},flex:{},flexGrow:{},flexShrink:{},alignSelf:{},justifyItems:{},justifySelf:{},gap:{style:A},rowGap:{style:C},columnGap:{style:k},gridColumn:{},gridRow:{},gridAutoFlow:{},gridAutoColumns:{},gridAutoRows:{},gridTemplateColumns:{},gridTemplateRows:{},gridTemplateAreas:{},gridArea:{},position:{},zIndex:{themeKey:"zIndex"},top:{},right:{},bottom:{},left:{},boxShadow:{themeKey:"shadows"},width:{transform:_},maxWidth:{style:j},minWidth:{transform:_},height:{transform:_},maxHeight:{transform:_},minHeight:{transform:_},boxSizing:{},fontFamily:{themeKey:"typography"},fontSize:{themeKey:"typography"},fontStyle:{themeKey:"typography"},fontWeight:{themeKey:"typography"},letterSpacing:{},textTransform:{},lineHeight:{},textAlign:{},typography:{cssProperty:!1,themeKey:"typography"}})},8698:(e,t,r)=>{"use strict";r.d(t,{A:()=>c});var n=r(8168),o=r(8587),a=r(3216),i=r(7758);const s=["sx"],l=e=>{var t,r;const n={systemProps:{},otherProps:{}},o=null!=(t=null==e||null==(r=e.theme)?void 0:r.unstable_sxConfig)?t:i.A;return Object.keys(e).forEach((t=>{o[t]?n.systemProps[t]=e[t]:n.otherProps[t]=e[t]})),n};function c(e){const{sx:t}=e,r=(0,o.A)(e,s),{systemProps:i,otherProps:c}=l(r);let u;return u=Array.isArray(t)?[i,...t]:"function"===typeof t?function(){const e=t(...arguments);return(0,a.Q)(e)?(0,n.A)({},i,e):i}:(0,n.A)({},i,t),(0,n.A)({},c,{sx:u})}},3234:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A,extendSxProp:()=>o.A,unstable_createStyleFunctionSx:()=>n.k,unstable_defaultSxConfig:()=>a.A});var n=r(8812),o=r(8698),a=r(7758)},8812:(e,t,r)=>{"use strict";r.d(t,{A:()=>u,k:()=>l});var n=r(410),o=r(3815),a=r(7162),i=r(9751),s=r(7758);function l(){function e(e,t,r,o){const s={[e]:t,theme:r},l=o[e];if(!l)return{[e]:t};const{cssProperty:c=e,themeKey:u,transform:d,style:f}=l;if(null==t)return null;if("typography"===u&&"inherit"===t)return{[e]:t};const p=(0,a.Yn)(r,u)||{};if(f)return f(s);return(0,i.NI)(s,t,(t=>{let r=(0,a.BO)(p,d,t);return t===r&&"string"===typeof t&&(r=(0,a.BO)(p,d,"".concat(e).concat("default"===t?"":(0,n.A)(t)),t)),!1===c?r:{[c]:r}}))}return function t(r){var n;const{sx:a,theme:l={}}=r||{};if(!a)return null;const c=null!=(n=l.unstable_sxConfig)?n:s.A;function u(r){let n=r;if("function"===typeof r)n=r(l);else if("object"!==typeof r)return r;if(!n)return null;const a=(0,i.EU)(l.breakpoints),s=Object.keys(a);let u=a;return Object.keys(n).forEach((r=>{const a=(s=n[r],d=l,"function"===typeof s?s(d):s);var s,d;if(null!==a&&void 0!==a)if("object"===typeof a)if(c[r])u=(0,o.A)(u,e(r,a,l,c));else{const e=(0,i.NI)({theme:l},a,(e=>({[r]:e})));!function(){for(var e=arguments.length,t=new Array(e),r=0;re.concat(Object.keys(t))),[]),o=new Set(n);return t.every((e=>o.size===Object.keys(e).length))}(e,a)?u=(0,o.A)(u,e):u[r]=t({sx:a,theme:l})}else u=(0,o.A)(u,e(r,a,l,c))})),(0,i.vf)(s,u)}return Array.isArray(a)?a.map(u):u(a)}}const c=l();c.filterProps=["sx"];const u=c},5527:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});var n=r(8280),o=r(7082);const a=(0,n.A)();const i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a;return(0,o.A)(e)}},2919:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});var n=r(2018);var o=r(5527);function a(e){let{props:t,name:r,defaultTheme:a,themeId:i}=e,s=(0,o.A)(a);i&&(s=s[i]||s);const l=function(e){const{theme:t,name:r,props:o}=e;return t&&t.components&&t.components[r]&&t.components[r].defaultProps?(0,n.A)(t.components[r].defaultProps,o):o}({theme:s,name:r,props:t});return l}},7082:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});var n=r(5043),o=r(5756);const a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;const t=n.useContext(o.T);return t&&(r=t,0!==Object.keys(r).length)?t:e;var r}},2374:(e,t,r)=>{"use strict";t.A=void 0;var n=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&Object.prototype.hasOwnProperty.call(e,i)){var s=o?Object.getOwnPropertyDescriptor(e,i):null;s&&(s.get||s.set)?Object.defineProperty(n,i,s):n[i]=e[i]}return n.default=e,r&&r.set(e,n),n}(r(5043)),o=r(3174);function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}t.A=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;const t=n.useContext(o.ThemeContext);return t&&(r=t,0!==Object.keys(r).length)?t:e;var r}},5430:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});const n=e=>e,o=(()=>{let e=n;return{configure(t){e=t},generate:t=>e(t),reset(){e=n}}})()},410:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(6632);function o(e){if("string"!==typeof e)throw new Error((0,n.A)(7));return e.charAt(0).toUpperCase()+e.slice(1)}},578:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A});var n=r(410)},7040:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Number.MIN_SAFE_INTEGER,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Number.MAX_SAFE_INTEGER;return Math.max(t,Math.min(e,r))}},5383:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A});var n=r(7040)},8606:(e,t,r)=>{"use strict";function n(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;const n={};return Object.keys(e).forEach((o=>{n[o]=e[o].reduce(((e,n)=>{if(n){const o=t(n);""!==o&&e.push(o),r&&r[n]&&e.push(r[n])}return e}),[]).join(" ")})),n}r.d(t,{A:()=>n})},4708:(e,t,r)=>{"use strict";function n(){for(var e=arguments.length,t=new Array(e),r=0;rnull==t?e:function(){for(var r=arguments.length,n=new Array(r),o=0;o{}))}r.d(t,{A:()=>n})},6440:(e,t,r)=>{"use strict";function n(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:166;function n(){for(var n=arguments.length,o=new Array(n),a=0;a{e.apply(this,o)}),r)}return n.clear=()=>{clearTimeout(t)},n}r.d(t,{A:()=>n})},3216:(e,t,r)=>{"use strict";r.d(t,{A:()=>i,Q:()=>o});var n=r(8168);function o(e){if("object"!==typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function a(e){if(!o(e))return e;const t={};return Object.keys(e).forEach((r=>{t[r]=a(e[r])})),t}function i(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{clone:!0};const s=r.clone?(0,n.A)({},e):e;return o(e)&&o(t)&&Object.keys(t).forEach((n=>{"__proto__"!==n&&(o(t[n])&&n in e&&o(e[n])?s[n]=i(e[n],t[n],r):r.clone?s[n]=o(t[n])?a(t[n]):t[n]:s[n]=t[n])})),s}},4534:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A,isPlainObject:()=>n.Q});var n=r(3216)},6632:(e,t,r)=>{"use strict";function n(e){let t="https://mui.com/production-error/?code="+e;for(let r=1;rn})},7245:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>n.A});var n=r(6632)},2400:(e,t,r)=>{"use strict";r.d(t,{Ay:()=>a,li:()=>o});var n=r(5430);const o={active:"active",checked:"checked",completed:"completed",disabled:"disabled",error:"error",expanded:"expanded",focused:"focused",focusVisible:"focusVisible",open:"open",readOnly:"readOnly",required:"required",selected:"selected"};function a(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"Mui";const a=o[t];return a?"".concat(r,"-").concat(a):"".concat(n.A.generate(e),"-").concat(t)}},7056:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(2400);function o(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"Mui";const o={};return t.forEach((t=>{o[t]=(0,n.Ay)(e,t,r)})),o}},2046:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>l,getFunctionName:()=>a});var n=r(9565);const o=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;function a(e){const t="".concat(e).match(o);return t&&t[1]||""}function i(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e.displayName||e.name||a(e)||t}function s(e,t,r){const n=i(t);return e.displayName||(""!==n?"".concat(r,"(").concat(n,")"):r)}function l(e){if(null!=e){if("string"===typeof e)return e;if("function"===typeof e)return i(e,"Component");if("object"===typeof e)switch(e.$$typeof){case n.ForwardRef:return s(e,e.render,"ForwardRef");case n.Memo:return s(e,e.type,"memo");default:return}}}},8609:(e,t)=>{"use strict";var r,n=Symbol.for("react.element"),o=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.server_context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen");function v(e){if("object"===typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case a:case s:case i:case f:case p:return e;default:switch(e=e&&e.$$typeof){case u:case c:case d:case m:case h:case l:return e;default:return t}}case o:return t}}}r=Symbol.for("react.module.reference"),t.ForwardRef=d,t.Memo=h},9565:(e,t,r)=>{"use strict";e.exports=r(8609)},2144:(e,t,r)=>{"use strict";function n(e){return e&&e.ownerDocument||document}r.d(t,{A:()=>n})},6288:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(2144);function o(e){return(0,n.A)(e).defaultView||window}},2018:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(8168);function o(e,t){const r=(0,n.A)({},t);return Object.keys(e).forEach((a=>{if(a.toString().match(/^(components|slots)$/))r[a]=(0,n.A)({},e[a],r[a]);else if(a.toString().match(/^(componentsProps|slotProps)$/)){const i=e[a]||{},s=t[a];r[a]={},s&&Object.keys(s)?i&&Object.keys(i)?(r[a]=(0,n.A)({},s),Object.keys(i).forEach((e=>{r[a][e]=o(i[e],s[e])}))):r[a]=s:r[a]=i}else void 0===r[a]&&(r[a]=e[a])})),r}},9184:(e,t,r)=>{"use strict";function n(e,t){"function"===typeof e?e(t):e&&(e.current=t)}r.d(t,{A:()=>n})},1944:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(5043);function o(e){let{controlled:t,default:r,name:o,state:a="value"}=e;const{current:i}=n.useRef(void 0!==t),[s,l]=n.useState(r);return[i?t:s,n.useCallback((e=>{i||l(e)}),[])]}},3844:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(5043);const o="undefined"!==typeof window?n.useLayoutEffect:n.useEffect},4626:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});var n=r(5043),o=r(3844);const a=function(e){const t=n.useRef(e);return(0,o.A)((()=>{t.current=e})),n.useRef((function(){return(0,t.current)(...arguments)})).current}},7042:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});var n=r(5043),o=r(9184);function a(){for(var e=arguments.length,t=new Array(e),r=0;rt.every((e=>null==e))?null:e=>{t.forEach((t=>{(0,o.A)(t,e)}))}),t)}},992:(e,t,r)=>{"use strict";var n;r.d(t,{A:()=>s});var o=r(5043);let a=0;const i=(n||(n=r.t(o,2)))["useId".toString()];function s(e){if(void 0!==i){const t=i();return null!=e?e:t}return function(e){const[t,r]=o.useState(e),n=e||t;return o.useEffect((()=>{null==t&&(a+=1,r("mui-".concat(a)))}),[t]),n}(e)}},932:(e,t,r)=>{"use strict";r.d(t,{A:()=>p});var n=r(5043),o=r(1140);let a=!0,i=!1;const s=new o.E,l={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function c(e){e.metaKey||e.altKey||e.ctrlKey||(a=!0)}function u(){a=!1}function d(){"hidden"===this.visibilityState&&i&&(a=!0)}function f(e){const{target:t}=e;try{return t.matches(":focus-visible")}catch(r){}return a||function(e){const{type:t,tagName:r}=e;return!("INPUT"!==r||!l[t]||e.readOnly)||"TEXTAREA"===r&&!e.readOnly||!!e.isContentEditable}(t)}function p(){const e=n.useCallback((e=>{var t;null!=e&&((t=e.ownerDocument).addEventListener("keydown",c,!0),t.addEventListener("mousedown",u,!0),t.addEventListener("pointerdown",u,!0),t.addEventListener("touchstart",u,!0),t.addEventListener("visibilitychange",d,!0))}),[]),t=n.useRef(!1);return{isFocusVisibleRef:t,onFocus:function(e){return!!f(e)&&(t.current=!0,!0)},onBlur:function(){return!!t.current&&(i=!0,s.start(100,(()=>{i=!1})),t.current=!1,!0)},ref:e}}},1140:(e,t,r)=>{"use strict";r.d(t,{E:()=>i,A:()=>s});var n=r(5043);const o={};const a=[];class i{constructor(){this.currentId=null,this.clear=()=>{null!==this.currentId&&(clearTimeout(this.currentId),this.currentId=null)},this.disposeEffect=()=>this.clear}static create(){return new i}start(e,t){this.clear(),this.currentId=setTimeout((()=>{this.currentId=null,t()}),e)}}function s(){const e=function(e,t){const r=n.useRef(o);return r.current===o&&(r.current=e(t)),r}(i.create).current;var t;return t=e.disposeEffect,n.useEffect(t,a),e}},3853:(e,t)=>{"use strict";var r,n=Symbol.for("react.element"),o=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.server_context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen");function v(e){if("object"===typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case a:case s:case i:case f:case p:return e;default:switch(e=e&&e.$$typeof){case u:case c:case d:case m:case h:case l:return e;default:return t}}case o:return t}}}r=Symbol.for("react.module.reference"),t.ContextConsumer=c,t.ContextProvider=l,t.Element=n,t.ForwardRef=d,t.Fragment=a,t.Lazy=m,t.Memo=h,t.Portal=o,t.Profiler=s,t.StrictMode=i,t.Suspense=f,t.SuspenseList=p,t.isAsyncMode=function(){return!1},t.isConcurrentMode=function(){return!1},t.isContextConsumer=function(e){return v(e)===c},t.isContextProvider=function(e){return v(e)===l},t.isElement=function(e){return"object"===typeof e&&null!==e&&e.$$typeof===n},t.isForwardRef=function(e){return v(e)===d},t.isFragment=function(e){return v(e)===a},t.isLazy=function(e){return v(e)===m},t.isMemo=function(e){return v(e)===h},t.isPortal=function(e){return v(e)===o},t.isProfiler=function(e){return v(e)===s},t.isStrictMode=function(e){return v(e)===i},t.isSuspense=function(e){return v(e)===f},t.isSuspenseList=function(e){return v(e)===p},t.isValidElementType=function(e){return"string"===typeof e||"function"===typeof e||e===a||e===s||e===i||e===f||e===p||e===g||"object"===typeof e&&null!==e&&(e.$$typeof===m||e.$$typeof===h||e.$$typeof===l||e.$$typeof===c||e.$$typeof===d||e.$$typeof===r||void 0!==e.getModuleId)},t.typeOf=v},1697:(e,t,r)=>{"use strict";e.exports=r(3853)},3081:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;const n=r(1631),o=r(6423),a=r(8e3),i=r(7805),s=["/properties"],l="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),o.default.forEach((e=>this.addVocabulary(e))),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(i,s):i;this.addMetaSchema(e,l,!1),this.refs["http://json-schema.org/schema"]=l}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}}e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=r(8647);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=r(8789);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var f=r(4639);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=r(1180);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})},2037:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class i{}t._CodeOrName=i,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class s extends i{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=s;class l extends i{constructor(e){super(),this._items="string"===typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce(((e,t)=>"".concat(e).concat(t)),"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce(((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e)),{})}}function c(e){const t=[e[0]];let r=0;for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a1?n-1:0),a=1;a{"use strict";var n,o,a,i,s,l,c=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const u=r(2037),d=r(6602);var f=r(2037);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return f.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return f.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return f.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return f.Name}});var p=r(6602);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return p.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return p.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return p.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return p.varKinds}}),t.operators={GT:new u._Code(">"),GTE:new u._Code(">="),LT:new u._Code("<"),LTE:new u._Code("<="),EQ:new u._Code("==="),NEQ:new u._Code("!=="),NOT:new u._Code("!"),OR:new u._Code("||"),AND:new u._Code("&&"),ADD:new u._Code("+")};class h{optimizeNodes(){return this}optimizeNames(e,t){return this}}class m extends h{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render(e){let{es5:t,_n:r}=e;const n=t?d.varKinds.var:this.varKind,o=void 0===this.rhs?"":" = ".concat(this.rhs);return"".concat(n," ").concat(this.name).concat(o,";")+r}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=z(this.rhs,e,t)),this}get names(){return this.rhs instanceof u._CodeOrName?this.rhs.names:{}}}class g extends h{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render(e){let{_n:t}=e;return"".concat(this.lhs," = ").concat(this.rhs,";")+t}optimizeNames(e,t){if(!(this.lhs instanceof u.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=z(this.rhs,e,t),this}get names(){return D(this.lhs instanceof u.Name?{}:{...this.lhs.names},this.rhs)}}class v extends g{constructor(e,t,r,n){super(e,r,n),this.op=t}render(e){let{_n:t}=e;return"".concat(this.lhs," ").concat(this.op,"= ").concat(this.rhs,";")+t}}class y extends h{constructor(e){super(),this.label=e,this.names={}}render(e){let{_n:t}=e;return"".concat(this.label,":")+t}}class b extends h{constructor(e){super(),this.label=e,this.names={}}render(e){let{_n:t}=e;const r=this.label?" ".concat(this.label):"";return"break".concat(r,";")+t}}class w extends h{constructor(e){super(),this.error=e}render(e){let{_n:t}=e;return"throw ".concat(this.error,";")+t}get names(){return this.error.names}}class x extends h{constructor(e){super(),this.code=e}render(e){let{_n:t}=e;return"".concat(this.code,";")+t}optimizeNodes(){return"".concat(this.code)?this:void 0}optimizeNames(e,t){return this.code=z(this.code,e,t),this}get names(){return this.code instanceof u._CodeOrName?this.code.names:{}}}class S extends h{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];super(),this.nodes=e}render(e){return this.nodes.reduce(((t,r)=>t+r.render(e)),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const o=r[n];o.optimizeNames(e,t)||(L(e,o.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce(((e,t)=>F(e,t.names)),{})}}class A extends S{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class k extends S{}class C extends A{}C.kind="else";class E extends A{constructor(e,t){super(t),this.condition=e}render(e){let t="if(".concat(this.condition,")")+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new C(e):e}return t?!1===e?t instanceof E?t:t.nodes:this.nodes.length?this:new E(B(e),t instanceof E?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=z(this.condition,e,t),this}get names(){const e=super.names;return D(e,this.condition),this.else&&F(e,this.else.names),e}}E.kind="if";class _ extends A{}_.kind="for";class P extends _{constructor(e){super(),this.iteration=e}render(e){return"for(".concat(this.iteration,")")+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=z(this.iteration,e,t),this}get names(){return F(super.names,this.iteration.names)}}class j extends _{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?d.varKinds.var:this.varKind,{name:r,from:n,to:o}=this;return"for(".concat(t," ").concat(r,"=").concat(n,"; ").concat(r,"<").concat(o,"; ").concat(r,"++)")+super.render(e)}get names(){const e=D(super.names,this.from);return D(e,this.to)}}class R extends _{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return"for(".concat(this.varKind," ").concat(this.name," ").concat(this.loop," ").concat(this.iterable,")")+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=z(this.iterable,e,t),this}get names(){return F(super.names,this.iterable.names)}}class O extends A{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){const t=this.async?"async ":"";return"".concat(t,"function ").concat(this.name,"(").concat(this.args,")")+super.render(e)}}O.kind="func";class N extends S{render(e){return"return "+super.render(e)}}N.kind="return";class T extends A{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&F(e,this.catch.names),this.finally&&F(e,this.finally.names),e}}class I extends A{constructor(e){super(),this.error=e}render(e){return"catch(".concat(this.error,")")+super.render(e)}}I.kind="catch";class M extends A{render(e){return"finally"+super.render(e)}}M.kind="finally";function F(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function D(e,t){return t instanceof u._CodeOrName?F(e,t.names):e}function z(e,t,r){return e instanceof u.Name?o(e):(n=e)instanceof u._Code&&n._items.some((e=>e instanceof u.Name&&1===t[e.str]&&void 0!==r[e.str]))?new u._Code(e._items.reduce(((e,t)=>(t instanceof u.Name&&(t=o(t)),t instanceof u._Code?e.push(...t._items):e.push(t),e)),[])):e;var n;function o(e){const n=r[e.str];return void 0===n||1!==t[e.str]?e:(delete t[e.str],n)}}function L(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function B(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:(0,u._)(i||(i=c(["!",""])),U(e))}t.CodeGen=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new d.Scope({parent:e}),this._nodes=[new k]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const o=this._scope.toName(t);return void 0!==r&&n&&(this._constants[o.str]=r),this._leafNode(new m(e,o,r)),o}const(e,t,r){return this._def(d.varKinds.const,e,t,r)}let(e,t,r){return this._def(d.varKinds.let,e,t,r)}var(e,t,r){return this._def(d.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new g(e,t,r))}add(e,r){return this._leafNode(new v(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==u.nil&&this._leafNode(new x(e)),this}object(){const e=["{"];for(var t=arguments.length,r=new Array(t),n=0;n1&&e.push(","),e.push(o),(o!==a||this.opts.es5)&&(e.push(":"),(0,u.addCodeArg)(e,a));return e.push("}"),new u._Code(e)}if(e,t,r){if(this._blockNode(new E(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new E(e))}else(){return this._elseNode(new C)}endIf(){return this._endBlockNode(E,C)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new P(e),t)}forRange(e,t,r,n){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.opts.es5?d.varKinds.var:d.varKinds.let;const a=this._scope.toName(e);return this._for(new j(o,a,t,r),(()=>n(a)))}forOf(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:d.varKinds.const;const i=this._scope.toName(e);if(this.opts.es5){const e=t instanceof u.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,u._)(n||(n=c(["",".length"])),e),(t=>{this.var(i,(0,u._)(o||(o=c(["","[","]"])),e,t)),r(i)}))}return this._for(new R("of",a,i,t),(()=>r(i)))}forIn(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.es5?d.varKinds.var:d.varKinds.const;if(this.opts.ownProperties)return this.forOf(e,(0,u._)(a||(a=c(["Object.keys(",")"])),t),r);const o=this._scope.toName(e);return this._for(new R("in",n,o,t),(()=>r(o)))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new y(e))}break(e){return this._leafNode(new b(e))}return(e){const t=new N;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(N)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new T;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new I(e),t(e)}return r&&(this._currNode=n.finally=new M,this.code(r)),this._endBlockNode(I,M)}throw(e){return this._leafNode(new w(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error("CodeGen: wrong number of nodes: ".concat(r," vs ").concat(e," expected"));return this._nodes.length=t,this}func(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.nil,r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0;return this._blockNode(new O(e,t,r)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(O)}optimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error('CodeGen: not in block "'.concat(t?"".concat(e.kind,"/").concat(t.kind):e.kind,'"'))}_elseNode(e){const t=this._currNode;if(!(t instanceof E))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=B;const $=V(t.operators.AND);t.and=function(){for(var e=arguments.length,t=new Array(e),r=0;rt===u.nil?r:r===u.nil?t:(0,u._)(s||(s=c([""," "," ",""])),U(t),e,U(r))}function U(e){return e instanceof u.Name?e:(0,u._)(l||(l=c(["(",")"])),e)}t.or=function(){for(var e=arguments.length,t=new Array(e),r=0;r{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const c=r(2037);class u extends Error{constructor(e){super('CodeGen: "code" for '.concat(e," not defined")),this.value=e.value}}var d;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(d=t.UsedValueState||(t.UsedValueState={})),t.varKinds={const:new c.Name("const"),let:new c.Name("let"),var:new c.Name("var")};class f{constructor(){let{prefixes:e,parent:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof c.Name?e:this.name(e)}name(e){return new c.Name(this._newName(e))}_newName(e){const t=this._names[e]||this._nameGroup(e);return"".concat(e).concat(t.index++)}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error('CodeGen: prefix "'.concat(e,'" is not allowed in this scope'));return this._names[e]={prefix:e,index:0}}}t.Scope=f;class p extends c.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,t){let{property:r,itemIndex:o}=t;this.value=e,this.scopePath=(0,c._)(n||(n=l([".","[","]"])),new c.Name(r),o)}}t.ValueScopeName=p;const h=(0,c._)(o||(o=l(["\n"],["\\n"])));t.ValueScope=class extends f{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?h:c.nil}}get(){return this._scope}name(e){return new p(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:o}=n,a=null!==(r=t.key)&&void 0!==r?r:t.ref;let i=this._values[o];if(i){const e=i.get(a);if(e)return e}else i=this._values[o]=new Map;i.set(a,n);const s=this._scope[o]||(this._scope[o]=[]),l=s.length;return s[l]=t.ref,n.setValue(t,{property:o,itemIndex:l}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._values;return this._reduceValues(t,(t=>{if(void 0===t.scopePath)throw new Error('CodeGen: name "'.concat(t,'" has no value'));return(0,c._)(a||(a=l(["","",""])),e,t.scopePath)}))}scopeCode(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._values,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0;return this._reduceValues(e,(e=>{if(void 0===e.value)throw new Error('CodeGen: name "'.concat(e,'" has no value'));return e.value.code}),t,r)}_reduceValues(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0,a=c.nil;for(const f in e){const p=e[f];if(!p)continue;const h=n[f]=n[f]||new Map;p.forEach((e=>{if(h.has(e))return;h.set(e,d.Started);let n=r(e);if(n){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;a=(0,c._)(i||(i=l(["",""," "," = ",";",""])),a,r,e,n,this.opts._n)}else{if(!(n=null===o||void 0===o?void 0:o(e)))throw new u(e);a=(0,c._)(s||(s=l(["","","",""])),a,n,this.opts._n)}h.set(e,d.Completed)}))}return a}}},5705:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const j=r(8789),R=r(1410),O=r(9188);function N(e,t){const r=e.const("err",t);e.if((0,j._)(g||(g=P([""," === null"])),O.default.vErrors),(()=>e.assign(O.default.vErrors,(0,j._)(v||(v=P(["[","]"])),r))),(0,j._)(y||(y=P(["",".push(",")"])),O.default.vErrors,r)),e.code((0,j._)(b||(b=P(["","++"])),O.default.errors))}function T(e,t){const{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,j._)(w||(w=P(["new ","(",")"])),e.ValidationError,t)):(r.assign((0,j._)(x||(x=P(["",".errors"])),n),t),r.return(!1))}t.keywordError={message:e=>{let{keyword:t}=e;return(0,j.str)(n||(n=P(['must pass "','" keyword validation'])),t)}},t.keyword$DataError={message:e=>{let{keyword:t,schemaType:r}=e;return r?(0,j.str)(o||(o=P(['"','" keyword must be '," ($data)"])),t,r):(0,j.str)(a||(a=P(['"','" keyword is invalid ($data)'])),t)}},t.reportError=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.keywordError,n=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0;const{it:a}=e,{gen:s,compositeRule:l,allErrors:c}=a,u=M(e,r,n);(null!==o&&void 0!==o?o:l||c)?N(s,u):T(a,(0,j._)(i||(i=P(["[","]"])),u))},t.reportExtraError=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.keywordError,n=arguments.length>2?arguments[2]:void 0;const{it:o}=e,{gen:a,compositeRule:i,allErrors:s}=o;N(a,M(e,r,n)),i||s||T(o,O.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(O.default.errors,t),e.if((0,j._)(s||(s=P([""," !== null"])),O.default.vErrors),(()=>e.if(t,(()=>e.assign((0,j._)(l||(l=P(["",".length"])),O.default.vErrors),t)),(()=>e.assign(O.default.vErrors,null)))))},t.extendErrors=function(e){let{gen:t,keyword:r,schemaValue:n,data:o,errsCount:a,it:i}=e;if(void 0===a)throw new Error("ajv implementation error");const s=t.name("err");t.forRange("i",a,O.default.errors,(e=>{t.const(s,(0,j._)(c||(c=P(["","[","]"])),O.default.vErrors,e)),t.if((0,j._)(u||(u=P(["",".instancePath === undefined"])),s),(()=>t.assign((0,j._)(d||(d=P(["",".instancePath"])),s),(0,j.strConcat)(O.default.instancePath,i.errorPath)))),t.assign((0,j._)(f||(f=P(["",".schemaPath"])),s),(0,j.str)(p||(p=P(["","/",""])),i.errSchemaPath,r)),i.opts.verbose&&(t.assign((0,j._)(h||(h=P(["",".schema"])),s),n),t.assign((0,j._)(m||(m=P(["",".data"])),s),o))}))};const I={keyword:new j.Name("keyword"),schemaPath:new j.Name("schemaPath"),params:new j.Name("params"),propertyName:new j.Name("propertyName"),message:new j.Name("message"),schema:new j.Name("schema"),parentSchema:new j.Name("parentSchema")};function M(e,t,r){const{createErrors:n}=e.it;return!1===n?(0,j._)(S||(S=P(["{}"]))):function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{gen:n,it:o}=e,a=[F(o,r),D(e,r)];return function(e,t,r){let{params:n,message:o}=t;const{keyword:a,data:i,schemaValue:s,it:l}=e,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:f}=l;r.push([I.keyword,a],[I.params,"function"==typeof n?n(e):n||(0,j._)(E||(E=P(["{}"])))]),c.messages&&r.push([I.message,"function"==typeof o?o(e):o]);c.verbose&&r.push([I.schema,s],[I.parentSchema,(0,j._)(_||(_=P(["","",""])),d,f)],[O.default.data,i]);u&&r.push([I.propertyName,u])}(e,t,a),n.object(...a)}(e,t,r)}function F(e,t){let{errorPath:r}=e,{instancePath:n}=t;const o=n?(0,j.str)(A||(A=P(["","",""])),r,(0,R.getErrorPath)(n,R.Type.Str)):r;return[O.default.instancePath,(0,j.strConcat)(O.default.instancePath,o)]}function D(e,t){let{keyword:r,it:{errSchemaPath:n}}=e,{schemaPath:o,parentSchema:a}=t,i=a?n:(0,j.str)(k||(k=P(["","/",""])),n,r);return o&&(i=(0,j.str)(C||(C=P(["","",""])),i,(0,R.getErrorPath)(o,R.Type.Str))),[I.schemaPath,i]}},5787:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const i=r(8789),s=r(4639),l=r(9188),c=r(9936),u=r(1410),d=r(8647);class f{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,c.normalizeId)(null===r||void 0===r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null===r||void 0===r?void 0:r.$async,this.refs={}}}function p(e){const t=m.call(this,e);if(t)return t;const r=(0,c.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:u,lines:f}=this.opts.code,{ownProperties:p}=this.opts,h=new i.CodeGen(this.scope,{es5:u,lines:f,ownProperties:p});let g;e.$async&&(g=h.scopeValue("Error",{ref:s.default,code:(0,i._)(n||(n=a(['require("ajv/dist/runtime/validation_error").default'])))}));const v=h.scopeName("validate");e.validateName=v;const y={gen:h,allErrors:this.opts.allErrors,data:l.default.data,parentData:l.default.parentData,parentDataProperty:l.default.parentDataProperty,dataNames:[l.default.data],dataPathArr:[i.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,i.stringify)(e.schema)}:{ref:e.schema}),validateName:v,ValidationError:g,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:i.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,i._)(o||(o=a(['""']))),opts:this.opts,self:this};let b;try{this._compilations.add(e),(0,d.validateFunctionCode)(y),h.optimize(this.opts.code.optimize);const t=h.toString();b="".concat(h.scopeRefs(l.default.scope),"return ").concat(t),this.opts.code.process&&(b=this.opts.code.process(b,e));const r=new Function("".concat(l.default.self),"".concat(l.default.scope),b)(this,this.scope.get());if(this.scope.value(v,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:v,validateCode:t,scopeValues:h._values}),this.opts.unevaluated){const{props:e,items:t}=y;r.evaluated={props:e instanceof i.Name?void 0:e,items:t instanceof i.Name?void 0:t,dynamicProps:e instanceof i.Name,dynamicItems:t instanceof i.Name},r.source&&(r.source.evaluated=(0,i.stringify)(r.evaluated))}return e.validate=r,e}catch(w){throw delete e.validate,delete e.validateName,b&&this.logger.error("Error compiling schema, function code:",b),w}finally{this._compilations.delete(e)}}function h(e){return(0,c.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:p.call(this,e)}function m(e){for(const n of this._compilations)if(r=e,(t=n).schema===r.schema&&t.root===r.root&&t.baseId===r.baseId)return n;var t,r}function g(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||v.call(this,e,t)}function v(e,t){const r=this.opts.uriResolver.parse(t),n=(0,c._getFullPath)(this.opts.uriResolver,r);let o=(0,c.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return b.call(this,r,e);const a=(0,c.normalizeId)(n),i=this.refs[a]||this.schemas[a];if("string"==typeof i){const t=v.call(this,e,i);if("object"!==typeof(null===t||void 0===t?void 0:t.schema))return;return b.call(this,r,t)}if("object"===typeof(null===i||void 0===i?void 0:i.schema)){if(i.validate||p.call(this,i),a===(0,c.normalizeId)(t)){const{schema:t}=i,{schemaId:r}=this.opts,n=t[r];return n&&(o=(0,c.resolveUrl)(this.opts.uriResolver,o,n)),new f({schema:t,schemaId:r,root:e,baseId:o})}return b.call(this,r,i)}}t.SchemaEnv=f,t.compileSchema=p,t.resolveRef=function(e,t,r){var n;r=(0,c.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let a=g.call(this,e,r);if(void 0===a){const o=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:i}=this.opts;o&&(a=new f({schema:o,schemaId:i,root:e,baseId:t}))}return void 0!==a?e.refs[r]=h.call(this,a):void 0},t.getCompilingSchema=m,t.resolveSchema=v;const y=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(e,t){let{baseId:r,schema:n,root:o}=t;var a;if("/"!==(null===(a=e.fragment)||void 0===a?void 0:a[0]))return;for(const l of e.fragment.slice(1).split("/")){if("boolean"===typeof n)return;const e=n[(0,u.unescapeFragment)(l)];if(void 0===e)return;n=e;const t="object"===typeof n&&n[this.opts.schemaId];!y.has(l)&&t&&(r=(0,c.resolveUrl)(this.opts.uriResolver,r,t))}let i;if("boolean"!=typeof n&&n.$ref&&!(0,u.schemaHasRulesButRef)(n,this.RULES)){const e=(0,c.resolveUrl)(this.opts.uriResolver,r,n.$ref);i=v.call(this,o,e)}const{schemaId:s}=this.opts;return i=i||new f({schema:n,schemaId:s,root:o,baseId:r}),i.schema!==i.root.schema?i:void 0}},9188:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(8789),o={data:new n.Name("data"),valCxt:new n.Name("valCxt"),instancePath:new n.Name("instancePath"),parentData:new n.Name("parentData"),parentDataProperty:new n.Name("parentDataProperty"),rootData:new n.Name("rootData"),dynamicAnchors:new n.Name("dynamicAnchors"),vErrors:new n.Name("vErrors"),errors:new n.Name("errors"),this:new n.Name("this"),self:new n.Name("self"),scope:new n.Name("scope"),json:new n.Name("json"),jsonPos:new n.Name("jsonPos"),jsonLen:new n.Name("jsonLen"),jsonPart:new n.Name("jsonPart")};t.default=o},1180:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9936);class o extends Error{constructor(e,t,r,o){super(o||"can't resolve reference ".concat(r," from id ").concat(t)),this.missingRef=(0,n.resolveUrl)(e,t,r),this.missingSchema=(0,n.normalizeId)((0,n.getFullPath)(e,this.missingRef))}}t.default=o},9936:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const n=r(1410),o=r(122),a=r(1125),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return"boolean"==typeof e||(!0===t?!l(e):!!t&&c(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function l(e){for(const t in e){if(s.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(l))return!0;if("object"==typeof r&&l(r))return!0}return!1}function c(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!i.has(r)&&("object"==typeof e[r]&&(0,n.eachItem)(e[r],(e=>t+=c(e))),t===1/0))return 1/0}return t}function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";!1!==(arguments.length>2?arguments[2]:void 0)&&(t=p(t));const r=e.parse(t);return d(e,r)}function d(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=u,t._getFullPath=d;const f=/#\/?$/;function p(e){return e?e.replace(f,""):""}t.normalizeId=p,t.resolveUrl=function(e,t,r){return r=p(r),e.resolve(t,r)};const h=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,i=p(e[r]||t),s={"":i},l=u(n,i,!1),c={},d=new Set;return a(e,{allKeys:!0},((e,t,n,o)=>{if(void 0===o)return;const a=l+t;let i=s[o];function u(t){const r=this.opts.uriResolver.resolve;if(t=p(i?r(i,t):t),d.has(t))throw m(t);d.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?f(e,n.schema,t):t!==p(a)&&("#"===t[0]?(f(e,c[t],t),c[t]=e):this.refs[t]=a),t}function g(e){if("string"==typeof e){if(!h.test(e))throw new Error('invalid anchor "'.concat(e,'"'));u.call(this,"#".concat(e))}}"string"==typeof e[r]&&(i=u.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=i})),c;function f(e,t,r){if(void 0!==t&&!o(e,t))throw m(r)}function m(e){return new Error('reference "'.concat(e,'" resolves to more than one schema'))}}},9447:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}},1410:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const S=r(8789),A=r(2037);function k(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"===typeof t)return;const o=n.RULES.keywords;for(const a in t)o[a]||T(e,'unknown keyword: "'.concat(a,'"'))}function C(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function E(e){return"number"==typeof e?"".concat(e):e.replace(/~/g,"~0").replace(/\//g,"~1")}function _(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function P(e){let{mergeNames:t,mergeToName:r,mergeValues:n,resultToName:o}=e;return(e,a,i,s)=>{const l=void 0===i?a:i instanceof S.Name?(a instanceof S.Name?t(e,a,i):r(e,a,i),i):a instanceof S.Name?(r(e,i,a),a):n(a,i);return s!==S.Name||l instanceof S.Name?l:o(e,l)}}function j(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",(0,S._)(m||(m=x(["{}"]))));return void 0!==t&&R(e,r,t),r}function R(e,t,r){Object.keys(r).forEach((r=>e.assign((0,S._)(g||(g=x(["","",""])),t,(0,S.getProperty)(r)),!0)))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(k(e,t),!C(t,e.self.RULES.all))},t.checkUnknownRules=k,t.schemaHasRules=C,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function(e,t,r,a){let{topSchemaRef:i,schemaPath:s}=e;if(!a){if("number"==typeof t||"boolean"==typeof t)return t;if("string"==typeof t)return(0,S._)(n||(n=x(["",""])),t)}return(0,S._)(o||(o=x(["","","",""])),i,s,(0,S.getProperty)(r))},t.unescapeFragment=function(e){return _(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(E(e))},t.escapeJsonPointer=E,t.unescapeJsonPointer=_,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:P({mergeNames:(e,t,r)=>e.if((0,S._)(a||(a=x([""," !== true && "," !== undefined"])),r,t),(()=>{e.if((0,S._)(i||(i=x([""," === true"])),t),(()=>e.assign(r,!0)),(()=>e.assign(r,(0,S._)(s||(s=x([""," || {}"])),r)).code((0,S._)(l||(l=x(["Object.assign(",", ",")"])),r,t))))})),mergeToName:(e,t,r)=>e.if((0,S._)(c||(c=x([""," !== true"])),r),(()=>{!0===t?e.assign(r,!0):(e.assign(r,(0,S._)(u||(u=x([""," || {}"])),r)),R(e,r,t))})),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:j}),items:P({mergeNames:(e,t,r)=>e.if((0,S._)(d||(d=x([""," !== true && "," !== undefined"])),r,t),(()=>e.assign(r,(0,S._)(f||(f=x([""," === true ? true : "," > "," ? "," : ",""])),t,r,t,r,t)))),mergeToName:(e,t,r)=>e.if((0,S._)(p||(p=x([""," !== true"])),r),(()=>e.assign(r,!0===t||(0,S._)(h||(h=x([""," > "," ? "," : ",""])),r,t,r,t)))),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=j,t.setEvaluated=R;const O={};var N;function T(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.opts.strictSchema;if(r){if(t="strict mode: ".concat(t),!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:O[t.code]||(O[t.code]=new A._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(N=t.Type||(t.Type={})),t.getErrorPath=function(e,t,r){if(e instanceof S.Name){const n=t===N.Num;return r?n?(0,S._)(v||(v=x(['"[" + ',' + "]"'])),e):(0,S._)(y||(y=x(['"[\'" + ',' + "\']"'])),e):n?(0,S._)(b||(b=x(['"/" + ',""])),e):(0,S._)(w||(w=x(['"/" + ','.replace(/~/g, "~0").replace(/\\//g, "~1")'],['"/" + ','.replace(/~/g, "~0").replace(/\\\\//g, "~1")'])),e)}return r?(0,S.getProperty)(e).toString():"/"+E(e)},t.checkStrictMode=T},5566:(e,t)=>{"use strict";function r(e,t){return t.rules.some((t=>n(e,t)))}function n(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some((t=>void 0!==e[t])))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function(e,t){let{schema:n,self:o}=e;const a=o.RULES.types[t];return a&&!0!==a&&r(n,a)},t.shouldUseGroup=r,t.shouldUseRule=n},6404:(e,t,r)=>{"use strict";var n,o=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const a=r(5705),i=r(8789),s=r(9188),l={message:"boolean schema is false"};function c(e,t){const{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,a.reportError)(o,l,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:a}=e;!1===r?c(e,!1):"object"==typeof r&&!0===r.$async?t.return(s.default.data):(t.assign((0,i._)(n||(n=o(["",".errors"])),a),null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),c(e)):r.var(t,!0)}},9507:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P,j,R,O,N,T,I,M,F=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const D=r(9447),z=r(5566),L=r(5705),B=r(8789),$=r(1410);var W;function V(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(D.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(W=t.DataType||(t.DataType={})),t.getSchemaTypes=function(e){const t=V(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=V,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:C,opts:E}=e,_=function(e,t){return t?e.filter((e=>U.has(e)||"array"===t&&"array"===e)):[]}(t,E.coerceTypes),P=t.length>0&&!(0===_.length&&1===t.length&&(0,z.schemaHasRulesForType)(e,t[0]));if(P){const P=q(t,C,E.strictNumbers,W.Wrong);r.if(P,(()=>{_.length?function(e,t,r){const{gen:C,data:E,opts:_}=e,P=C.let("dataType",(0,B._)(n||(n=F(["typeof ",""])),E)),j=C.let("coerced",(0,B._)(o||(o=F(["undefined"]))));"array"===_.coerceTypes&&C.if((0,B._)(a||(a=F([""," == 'object' && Array.isArray(",") && ",".length == 1"])),P,E,E),(()=>C.assign(E,(0,B._)(i||(i=F(["","[0]"])),E)).assign(P,(0,B._)(s||(s=F(["typeof ",""])),E)).if(q(t,E,_.strictNumbers),(()=>C.assign(j,E)))));C.if((0,B._)(l||(l=F([""," !== undefined"])),j));for(const n of r)(U.has(n)||"array"===n&&"array"===_.coerceTypes)&&R(n);function R(e){switch(e){case"string":return void C.elseIf((0,B._)(u||(u=F(["",' == "number" || ',' == "boolean"'])),P,P)).assign(j,(0,B._)(d||(d=F(['"" + ',""])),E)).elseIf((0,B._)(f||(f=F([""," === null"])),E)).assign(j,(0,B._)(p||(p=F(['""']))));case"number":return void C.elseIf((0,B._)(h||(h=F(["",' == "boolean" || '," === null\n || (",' == "string" && '," && "," == +",")"])),P,E,P,E,E,E)).assign(j,(0,B._)(m||(m=F(["+",""])),E));case"integer":return void C.elseIf((0,B._)(g||(g=F(["",' === "boolean" || '," === null\n || (",' === "string" && '," && "," == +"," && !("," % 1))"])),P,E,P,E,E,E,E)).assign(j,(0,B._)(v||(v=F(["+",""])),E));case"boolean":return void C.elseIf((0,B._)(y||(y=F(["",' === "false" || '," === 0 || "," === null"])),E,E,E)).assign(j,!1).elseIf((0,B._)(b||(b=F(["",' === "true" || '," === 1"])),E,E)).assign(j,!0);case"null":return C.elseIf((0,B._)(w||(w=F(["",' === "" || '," === 0 || "," === false"])),E,E,E)),void C.assign(j,null);case"array":C.elseIf((0,B._)(x||(x=F(["",' === "string" || ',' === "number"\n || ',' === "boolean" || '," === null"])),P,P,P,E)).assign(j,(0,B._)(S||(S=F(["[","]"])),E))}}C.else(),K(e),C.endIf(),C.if((0,B._)(c||(c=F([""," !== undefined"])),j),(()=>{C.assign(E,j),function(e,t){let{gen:r,parentData:n,parentDataProperty:o}=e;r.if((0,B._)(A||(A=F([""," !== undefined"])),n),(()=>r.assign((0,B._)(k||(k=F(["","[","]"])),n,o),t)))}(e,j)}))}(e,t,_):K(e)}))}return P};const U=new Set(["string","number","integer","boolean","null"]);function H(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:W.Correct;const o=n===W.Correct?B.operators.EQ:B.operators.NEQ;let a;switch(e){case"null":return(0,B._)(C||(C=F([""," "," null"])),t,o);case"array":a=(0,B._)(E||(E=F(["Array.isArray(",")"])),t);break;case"object":a=(0,B._)(_||(_=F([""," && typeof ",' == "object" && !Array.isArray(',")"])),t,t,t);break;case"integer":a=i((0,B._)(P||(P=F(["!("," % 1) && !isNaN(",")"])),t,t));break;case"number":a=i();break;default:return(0,B._)(j||(j=F(["typeof "," "," ",""])),t,o,e)}return n===W.Correct?a:(0,B.not)(a);function i(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:B.nil;return(0,B.and)((0,B._)(R||(R=F(["typeof ",' == "number"'])),t),e,r?(0,B._)(O||(O=F(["isFinite(",")"])),t):B.nil)}}function q(e,t,r,n){if(1===e.length)return H(e[0],t,r,n);let o;const a=(0,$.toHash)(e);if(a.array&&a.object){const e=(0,B._)(N||(N=F(["typeof ",' != "object"'])),t);o=a.null?e:(0,B._)(T||(T=F(["!"," || ",""])),t,e),delete a.null,delete a.array,delete a.object}else o=B.nil;a.number&&delete a.integer;for(const i in a)o=(0,B.and)(o,H(i,t,r,n));return o}t.checkDataType=H,t.checkDataTypes=q;const G={message:e=>{let{schema:t}=e;return"must be ".concat(t)},params:e=>{let{schema:t,schemaValue:r}=e;return"string"==typeof t?(0,B._)(I||(I=F(["{type: ","}"])),t):(0,B._)(M||(M=F(["{type: ","}"])),r)}};function K(e){const t=function(e){const{gen:t,data:r,schema:n}=e,o=(0,$.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}(e);(0,L.reportError)(t,G)}t.reportTypeError=K},8929:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const l=r(8789),c=r(1410);function u(e,t,r){const{gen:u,compositeRule:d,data:f,opts:p}=e;if(void 0===r)return;const h=(0,l._)(n||(n=s(["","",""])),f,(0,l.getProperty)(t));if(d)return void(0,c.checkStrictMode)(e,"default is ignored for: ".concat(h));let m=(0,l._)(o||(o=s([""," === undefined"])),h);"empty"===p.useDefaults&&(m=(0,l._)(a||(a=s([""," || "," === null || ",' === ""'])),m,h,h)),u.if(m,(0,l._)(i||(i=s([""," = ",""])),h,(0,l.stringify)(r)))}t.assignDefaults=function(e,t){const{properties:r,items:n}=e.schema;if("object"===t&&r)for(const o in r)u(e,o,r[o].default);else"array"===t&&Array.isArray(n)&&n.forEach(((t,r)=>u(e,r,t.default)))}},8647:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P,j,R,O,N,T,I,M,F,D,z,L,B,$,W=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const V=r(6404),U=r(9507),H=r(5566),q=r(9507),G=r(8929),K=r(6223),X=r(4642),Q=r(8789),Y=r(9188),J=r(9936),Z=r(1410),ee=r(5705);function te(e,t){let{gen:r,validateName:v,schema:y,schemaEnv:b,opts:w}=e;w.code.es5?r.func(v,(0,Q._)(n||(n=W(["",", ",""])),Y.default.data,Y.default.valCxt),b.$async,(()=>{r.code((0,Q._)(o||(o=W(['"use strict"; ',""])),re(y,w))),function(e,t){e.if(Y.default.valCxt,(()=>{e.var(Y.default.instancePath,(0,Q._)(l||(l=W(["",".",""])),Y.default.valCxt,Y.default.instancePath)),e.var(Y.default.parentData,(0,Q._)(c||(c=W(["",".",""])),Y.default.valCxt,Y.default.parentData)),e.var(Y.default.parentDataProperty,(0,Q._)(u||(u=W(["",".",""])),Y.default.valCxt,Y.default.parentDataProperty)),e.var(Y.default.rootData,(0,Q._)(d||(d=W(["",".",""])),Y.default.valCxt,Y.default.rootData)),t.dynamicRef&&e.var(Y.default.dynamicAnchors,(0,Q._)(f||(f=W(["",".",""])),Y.default.valCxt,Y.default.dynamicAnchors))}),(()=>{e.var(Y.default.instancePath,(0,Q._)(p||(p=W(['""'])))),e.var(Y.default.parentData,(0,Q._)(h||(h=W(["undefined"])))),e.var(Y.default.parentDataProperty,(0,Q._)(m||(m=W(["undefined"])))),e.var(Y.default.rootData,Y.default.data),t.dynamicRef&&e.var(Y.default.dynamicAnchors,(0,Q._)(g||(g=W(["{}"]))))}))}(r,w),r.code(t)})):r.func(v,(0,Q._)(a||(a=W(["",", ",""])),Y.default.data,function(e){return(0,Q._)(i||(i=W(["{",'="", ',", ",", ","=","","}={}"])),Y.default.instancePath,Y.default.parentData,Y.default.parentDataProperty,Y.default.rootData,Y.default.data,e.dynamicRef?(0,Q._)(s||(s=W([", ","={}"])),Y.default.dynamicAnchors):Q.nil)}(w)),b.$async,(()=>r.code(re(y,w)).code(t)))}function re(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,Q._)(k||(k=W(["/*# sourceURL="," */"])),r):Q.nil}function ne(e,t){ae(e)&&(ie(e),oe(e))?function(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&le(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,J.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const a=n.const("_errs",Y.default.errors);se(e,a),n.var(t,(0,Q._)(C||(C=W([""," === ",""])),a,Y.default.errors))}(e,t):(0,V.boolOrEmptySchema)(e,t)}function oe(e){let{schema:t,self:r}=e;if("boolean"==typeof t)return!t;for(const n in t)if(r.RULES.all[n])return!0;return!1}function ae(e){return"boolean"!=typeof e.schema}function ie(e){(0,Z.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Z.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn('$ref: keywords ignored in schema at path "'.concat(r,'"'))}(e)}function se(e,t){if(e.opts.jtd)return ce(e,[],!1,t);const r=(0,U.getSchemaTypes)(e.schema);ce(e,r,!(0,U.coerceAndCheckDataType)(e,r),t)}function le(e){let{gen:t,schemaEnv:r,schema:n,errSchemaPath:o,opts:a}=e;const i=n.$comment;if(!0===a.$comment)t.code((0,Q._)(E||(E=W(["",".logger.log(",")"])),Y.default.self,i));else if("function"==typeof a.$comment){const e=(0,Q.str)(_||(_=W(["","/$comment"])),o),n=t.scopeValue("root",{ref:r.root});t.code((0,Q._)(P||(P=W(["",".opts.$comment(",", ",", ",".schema)"])),Y.default.self,i,e,n))}}function ce(e,t,r,n){const{gen:o,schema:a,data:i,allErrors:s,opts:l,self:c}=e,{RULES:u}=c;function d(c){(0,H.shouldUseGroup)(a,c)&&(c.type?(o.if((0,q.checkDataType)(c.type,i,l.strictNumbers)),ue(e,c),1===t.length&&t[0]===c.type&&r&&(o.else(),(0,q.reportTypeError)(e)),o.endIf()):ue(e,c),s||o.if((0,Q._)(M||(M=W([""," === ",""])),Y.default.errors,n||0)))}!a.$ref||!l.ignoreKeywordsWithRef&&(0,Z.schemaHasRulesButRef)(a,u)?(l.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach((t=>{fe(e.dataTypes,t)||pe(e,'type "'.concat(t,'" not allowed by context "').concat(e.dataTypes.join(","),'"'))})),function(e,t){const r=[];for(const n of e.dataTypes)fe(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&pe(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const r=e.self.RULES.all;for(const n in r){const o=r[n];if("object"==typeof o&&(0,H.shouldUseRule)(e.schema,o)){const{type:r}=o.definition;r.length&&!r.some((e=>de(t,e)))&&pe(e,'missing type "'.concat(r.join(","),'" for keyword "').concat(n,'"'))}}}(e,e.dataTypes)}(e,t),o.block((()=>{for(const e of u.rules)d(e);d(u.post)}))):o.block((()=>me(e,"$ref",u.all.$ref.definition)))}function ue(e,t){const{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,G.assignDefaults)(e,t.type),r.block((()=>{for(const r of t.rules)(0,H.shouldUseRule)(n,r)&&me(e,r.keyword,r.definition,t.type)}))}function de(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function fe(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function pe(e,t){const r=e.schemaEnv.baseId+e.errSchemaPath;t+=' at "'.concat(r,'" (strictTypes)'),(0,Z.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){ae(e)&&(ie(e),oe(e))?function(e){const{schema:t,opts:r,gen:n}=e;te(e,(()=>{r.$comment&&t.$comment&&le(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,Z.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,Q._)(v||(v=W(["",".evaluated"])),r)),t.if((0,Q._)(y||(y=W(["",".dynamicProps"])),e.evaluated),(()=>t.assign((0,Q._)(b||(b=W(["",".props"])),e.evaluated),(0,Q._)(w||(w=W(["undefined"])))))),t.if((0,Q._)(x||(x=W(["",".dynamicItems"])),e.evaluated),(()=>t.assign((0,Q._)(S||(S=W(["",".items"])),e.evaluated),(0,Q._)(A||(A=W(["undefined"]))))))}(e),se(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:a}=e;r.$async?t.if((0,Q._)(j||(j=W([""," === 0"])),Y.default.errors),(()=>t.return(Y.default.data)),(()=>t.throw((0,Q._)(R||(R=W(["new ","(",")"])),o,Y.default.vErrors)))):(t.assign((0,Q._)(O||(O=W(["",".errors"])),n),Y.default.vErrors),a.unevaluated&&function(e){let{gen:t,evaluated:r,props:n,items:o}=e;n instanceof Q.Name&&t.assign((0,Q._)(T||(T=W(["",".props"])),r),n);o instanceof Q.Name&&t.assign((0,Q._)(I||(I=W(["",".items"])),r),o)}(e),t.return((0,Q._)(N||(N=W([""," === 0"])),Y.default.errors)))}(e)}))}(e):te(e,(()=>(0,V.topBoolOrEmptySchema)(e)))};class he{constructor(e,t,r){if((0,K.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Z.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",ye(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,K.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error("".concat(r," value must be ").concat(JSON.stringify(t.schemaType)));("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,t,r){this.failResult((0,Q.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,Q.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail((0,Q._)(F||(F=W([""," !== undefined && (",")"])),t,(0,Q.or)(this.invalid$data(),e)))}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?ee.reportExtraError:ee.reportError)(this,this.def.error,t)}$dataError(){(0,ee.reportError)(this,this.def.$dataError||ee.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,ee.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Q.nil;this.gen.block((()=>{this.check$data(e,r),t()}))}check$data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Q.nil,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Q.nil;if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:o,def:a}=this;r.if((0,Q.or)((0,Q._)(D||(D=W([""," === undefined"])),n),t)),e!==Q.nil&&r.assign(e,!0),(o.length||a.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==Q.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:o}=this;return(0,Q.or)(function(){if(r.length){if(!(t instanceof Q.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return(0,Q._)(z||(z=W(["",""])),(0,q.checkDataTypes)(e,t,o.opts.strictNumbers,q.DataType.Wrong))}return Q.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,Q._)(L||(L=W(["!","(",")"])),r,t)}return Q.nil}())}subschema(e,t){const r=(0,X.getSubschema)(this.it,e);(0,X.extendSubschemaData)(r,this.it,e),(0,X.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return ne(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=Z.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=Z.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,(()=>this.mergeEvaluated(e,Q.Name))),!0}}function me(e,t,r,n){const o=new he(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,K.funcKeywordCode)(o,r):"macro"in r?(0,K.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,K.funcKeywordCode)(o,r)}t.KeywordCxt=he;const ge=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ye(e,t){let r,n,{dataLevel:o,dataNames:a,dataPathArr:i}=t;if(""===e)return Y.default.rootData;if("/"===e[0]){if(!ge.test(e))throw new Error("Invalid JSON-pointer: ".concat(e));r=e,n=Y.default.rootData}else{const t=ve.exec(e);if(!t)throw new Error("Invalid JSON-pointer: ".concat(e));const s=+t[1];if(r=t[2],"#"===r){if(s>=o)throw new Error(c("property/index",s));return i[o-s]}if(s>o)throw new Error(c("data",s));if(n=a[o-s],!r)return n}let s=n;const l=r.split("/");for(const u of l)u&&(n=(0,Q._)(B||(B=W(["","",""])),n,(0,Q.getProperty)((0,Z.unescapeJsonPointer)(u))),s=(0,Q._)($||($=W([""," && ",""])),s,n));return s;function c(e,t){return"Cannot access ".concat(e," ").concat(t," levels up, current level is ").concat(o)}}t.getData=ye},6223:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const h=r(8789),m=r(9188),g=r(378),v=r(5705);function y(e){const{gen:t,data:r,it:n}=e;t.if(n.parentData,(()=>t.assign(r,(0,h._)(c||(c=p(["","[","]"])),n.parentData,n.parentDataProperty))))}function b(e,t,r){if(void 0===r)throw new Error('keyword "'.concat(t,'" failed to compile'));return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,h.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:n,schema:o,parentSchema:a,it:i}=e,s=t.macro.call(i.self,o,a,i),l=b(r,n,s);!1!==i.opts.validateSchema&&i.self.validateSchema(s,!0);const c=r.name("valid");e.subschema({schema:s,schemaPath:h.nil,errSchemaPath:"".concat(i.errSchemaPath,"/").concat(n),topSchemaRef:l,compositeRule:!0},c),e.pass(c,(()=>e.error(!0)))},t.funcKeywordCode=function(e,t){var r;const{gen:c,keyword:w,schema:x,parentSchema:S,$data:A,it:k}=e;!function(e,t){let{schemaEnv:r}=e;if(t.async&&!r.$async)throw new Error("async keyword in sync schema")}(k,t);const C=!A&&t.compile?t.compile.call(k.self,x,S,k):t.validate,E=b(c,w,C),_=c.let("valid");function P(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.async?(0,h._)(s||(s=p(["await "]))):h.nil;const n=k.opts.passContext?m.default.this:m.default.self,o=!("compile"in t&&!A||!1===t.schema);c.assign(_,(0,h._)(l||(l=p(["","",""])),r,(0,g.callValidateCode)(e,E,n,o)),t.modifying)}function j(e){var r;c.if((0,h.not)(null!==(r=t.valid)&&void 0!==r?r:_),e)}e.block$data(_,(function(){if(!1===t.errors)P(),t.modifying&&y(e),j((()=>e.error()));else{const r=t.async?function(){const e=c.let("ruleErrs",null);return c.try((()=>P((0,h._)(n||(n=p(["await "]))))),(t=>c.assign(_,!1).if((0,h._)(o||(o=p([""," instanceof ",""])),t,k.ValidationError),(()=>c.assign(e,(0,h._)(a||(a=p(["",".errors"])),t))),(()=>c.throw(t))))),e}():function(){const e=(0,h._)(i||(i=p(["",".errors"])),E);return c.assign(e,null),P(h.nil),e}();t.modifying&&y(e),j((()=>function(e,t){const{gen:r}=e;r.if((0,h._)(u||(u=p(["Array.isArray(",")"])),t),(()=>{r.assign(m.default.vErrors,(0,h._)(d||(d=p([""," === null ? "," : ",".concat(",")"])),m.default.vErrors,t,m.default.vErrors,t)).assign(m.default.errors,(0,h._)(f||(f=p(["",".length"])),m.default.vErrors)),(0,v.extendErrors)(e)}),(()=>e.error()))}(e,r)))}})),e.ok(null!==(r=t.valid)&&void 0!==r?r:_)},t.validSchemaType=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return!t.length||t.some((t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&"undefined"==typeof e))},t.validateKeywordUsage=function(e,t,r){let{schema:n,opts:o,self:a,errSchemaPath:i}=e;if(Array.isArray(t.keyword)?!t.keyword.includes(r):t.keyword!==r)throw new Error("ajv implementation error");const s=t.dependencies;if(null===s||void 0===s?void 0:s.some((e=>!Object.prototype.hasOwnProperty.call(n,e))))throw new Error("parent schema must have dependencies of ".concat(r,": ").concat(s.join(",")));if(t.validateSchema){if(!t.validateSchema(n[r])){const e='keyword "'.concat(r,'" value is invalid at path "').concat(i,'": ')+a.errorsText(t.validateSchema.errors);if("log"!==o.validateSchema)throw new Error(e);a.logger.error(e)}}}},4642:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const c=r(8789),u=r(1410);t.getSubschema=function(e,t){let{keyword:r,schemaProp:a,schema:i,schemaPath:s,errSchemaPath:d,topSchemaRef:f}=t;if(void 0!==r&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){const t=e.schema[r];return void 0===a?{schema:t,schemaPath:(0,c._)(n||(n=l(["","",""])),e.schemaPath,(0,c.getProperty)(r)),errSchemaPath:"".concat(e.errSchemaPath,"/").concat(r)}:{schema:t[a],schemaPath:(0,c._)(o||(o=l(["","","",""])),e.schemaPath,(0,c.getProperty)(r),(0,c.getProperty)(a)),errSchemaPath:"".concat(e.errSchemaPath,"/").concat(r,"/").concat((0,u.escapeFragment)(a))}}if(void 0!==i){if(void 0===s||void 0===d||void 0===f)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:s,topSchemaRef:f,errSchemaPath:d}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,r){let{dataProp:n,dataPropType:o,data:d,dataTypes:f,propertyName:p}=r;if(void 0!==d&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=t;if(void 0!==n){const{errorPath:r,dataPathArr:d,opts:f}=t;m(h.let("data",(0,c._)(a||(a=l(["","",""])),t.data,(0,c.getProperty)(n)),!0)),e.errorPath=(0,c.str)(i||(i=l(["","",""])),r,(0,u.getErrorPath)(n,o,f.jsPropertySyntax)),e.parentDataProperty=(0,c._)(s||(s=l(["",""])),n),e.dataPathArr=[...d,e.parentDataProperty]}if(void 0!==d){m(d instanceof c.Name?d:h.let("data",d,!0)),void 0!==p&&(e.propertyName=p)}function m(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}f&&(e.dataTypes=f)},t.extendSubschemaMode=function(e,t){let{jtdDiscriminator:r,jtdMetadata:n,compositeRule:o,createErrors:a,allErrors:i}=t;void 0!==o&&(e.compositeRule=o),void 0!==a&&(e.createErrors=a),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=r,e.jtdMetadata=n}},1631:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var n=r(8647);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return n.KeywordCxt}});var o=r(8789);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return o.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return o.CodeGen}});const a=r(4639),i=r(1180),s=r(9447),l=r(5787),c=r(8789),u=r(9936),d=r(9507),f=r(1410),p=r(3983),h=r(3524),m=(e,t)=>new RegExp(e,t);m.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function w(e){var t,r,n,o,a,i,s,l,c,u,d,f,p,g,v,y,b,w,x,S,A,k,C,E,_;const P=e.strict,j=null===(t=e.code)||void 0===t?void 0:t.optimize,R=!0===j||void 0===j?1:j||0,O=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:m,N=null!==(o=e.uriResolver)&&void 0!==o?o:h.default;return{strictSchema:null===(i=null!==(a=e.strictSchema)&&void 0!==a?a:P)||void 0===i||i,strictNumbers:null===(l=null!==(s=e.strictNumbers)&&void 0!==s?s:P)||void 0===l||l,strictTypes:null!==(u=null!==(c=e.strictTypes)&&void 0!==c?c:P)&&void 0!==u?u:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:P)&&void 0!==f?f:"log",strictRequired:null!==(g=null!==(p=e.strictRequired)&&void 0!==p?p:P)&&void 0!==g&&g,code:e.code?{...e.code,optimize:R,regExp:O}:{optimize:R,regExp:O},loopRequired:null!==(v=e.loopRequired)&&void 0!==v?v:200,loopEnum:null!==(y=e.loopEnum)&&void 0!==y?y:200,meta:null===(b=e.meta)||void 0===b||b,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(x=e.inlineRefs)||void 0===x||x,schemaId:null!==(S=e.schemaId)&&void 0!==S?S:"$id",addUsedSchema:null===(A=e.addUsedSchema)||void 0===A||A,validateSchema:null===(k=e.validateSchema)||void 0===k||k,validateFormats:null===(C=e.validateFormats)||void 0===C||C,unicodeRegExp:null===(E=e.unicodeRegExp)||void 0===E||E,int32range:null===(_=e.int32range)||void 0===_||_,uriResolver:N}}class x{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...w(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:v,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,y,e,"NOT SUPPORTED"),S.call(this,b,e,"DEPRECATED","warn"),this._metaOpts=_.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=p;"id"===r&&(n={...p},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error('no schema with key or ref "'.concat(e,'"'))}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await o.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function o(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await l.call(this,t.missingSchema),a.call(this,e)}}function s(e){let{missingSchema:t,missingRef:r}=e;if(this.refs[t])throw new Error("AnySchema ".concat(t," is loaded but ").concat(r," cannot be resolved"))}async function l(e){const r=await c.call(this,e);this.refs[e]||await o.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function c(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r){let n,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema;if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);return this}if("object"===typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error("schema ".concat(t," must be string"))}return t=(0,u.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!0),this}addMetaSchema(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.opts.validateSchema;return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=A.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new l.SchemaEnv({schema:{},schemaId:r});if(t=l.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=A.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,u.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(R.call(this,r,t),!t)return(0,f.eachItem)(r,(e=>O.call(this,e))),this;T.call(this,t);const n={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,f.eachItem)(r,0===n.type.length?e=>O.call(this,e,n):e=>n.type.forEach((t=>O.call(this,e,n,t)))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex((t=>t.keyword===e));t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.errors,{separator:t=", ",dataVar:r="data"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e&&0!==e.length?e.map((e=>"".concat(r).concat(e.instancePath," ").concat(e.message))).reduce(((e,r)=>e+t+r)):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,a=o[e];n&&a&&(o[e]=M(a))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r){let n,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.opts.addUsedSchema;const{schemaId:i}=this.opts;if("object"==typeof e)n=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let s=this._cache.get(e);if(void 0!==s)return s;r=(0,u.normalizeId)(n||r);const c=u.getSchemaRefs.call(this,e,r);return s=new l.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:c}),this._cache.set(s.schema,s),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=s),o&&this.validateSchema(e,!0),s}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error('schema with key or id "'.concat(e,'" already exists'))}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):l.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{l.compileSchema.call(this,e)}finally{this.opts=t}}}function S(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"error";for(const o in e){const a=o;a in t&&this.logger[n]("".concat(r,": option ").concat(o,". ").concat(e[a]))}}function A(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function C(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function _(){const e={...this.opts};for(const t of g)delete e[t];return e}t.default=x,x.ValidationError=a.default,x.MissingRefError=i.default;const P={log(){},warn(){},error(){}};const j=/^[a-z_$][a-z0-9_$:-]*$/i;function R(e,t){const{RULES:r}=this;if((0,f.eachItem)(e,(e=>{if(r.keywords[e])throw new Error("Keyword ".concat(e," is already defined"));if(!j.test(e))throw new Error("Keyword ".concat(e," has invalid name"))})),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function O(e,t,r){var n;const o=null===t||void 0===t?void 0:t.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:a}=this;let i=o?a.post:a.rules.find((e=>{let{type:t}=e;return t===r}));if(i||(i={type:r,rules:[]},a.rules.push(i)),a.keywords[e]=!0,!t)return;const s={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?N.call(this,i,s,t.before):i.rules.push(s),a.all[e]=s,null===(n=t.implements)||void 0===n||n.forEach((e=>this.addKeyword(e)))}function N(e,t,r){const n=e.rules.findIndex((e=>e.keyword===r));n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn("rule ".concat(r," is not defined")))}function T(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=M(t)),e.validateSchema=this.compile(t,!0))}const I={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function M(e){return{anyOf:[e,I]}}},4877:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(122);n.code='require("ajv/dist/runtime/equal").default',t.default=n},8348:(e,t)=>{"use strict";function r(e){const t=e.length;let r,n=0,o=0;for(;o=55296&&r<=56319&&o{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9392);n.code='require("ajv/dist/runtime/uri").default',t.default=n},4639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},170:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const c=r(8789),u=r(1410),d={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:e=>{let{params:{len:t}}=e;return(0,c.str)(n||(n=l(["must NOT have more than "," items"])),t)},params:e=>{let{params:{len:t}}=e;return(0,c._)(o||(o=l(["{limit: ","}"])),t)}},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?f(e,n):(0,u.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function f(e,t){const{gen:r,schema:n,data:o,keyword:d,it:f}=e;f.items=!0;const p=r.const("len",(0,c._)(a||(a=l(["",".length"])),o));if(!1===n)e.setParams({len:t.length}),e.pass((0,c._)(i||(i=l([""," <= ",""])),p,t.length));else if("object"==typeof n&&!(0,u.alwaysValidSchema)(f,n)){const n=r.var("valid",(0,c._)(s||(s=l([""," <= ",""])),p,t.length));r.if((0,c.not)(n),(()=>function(n){r.forRange("i",t.length,p,(t=>{e.subschema({keyword:d,dataProp:t,dataPropType:u.Type.Num},n),f.allErrors||r.if((0,c.not)(n),(()=>r.break()))}))}(n))),e.ok(n)}}t.validateAdditionalItems=f,t.default=d},6289:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(378),u=r(8789),d=r(9188),f=r(1410),p={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:e=>{let{params:t}=e;return(0,u._)(n||(n=l(["{additionalProperty: ","}"])),t.additionalProperty)}},code(e){const{gen:t,schema:r,parentSchema:n,data:p,errsCount:h,it:m}=e;if(!h)throw new Error("ajv implementation error");const{allErrors:g,opts:v}=m;if(m.props=!0,"all"!==v.removeAdditional&&(0,f.alwaysValidSchema)(m,r))return;const y=(0,c.allSchemaProperties)(n.properties),b=(0,c.allSchemaProperties)(n.patternProperties);function w(e){t.code((0,u._)(s||(s=l(["delete ","[","]"])),p,e))}function x(n){if("all"===v.removeAdditional||v.removeAdditional&&!1===r)w(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(g||t.break());if("object"==typeof r&&!(0,f.alwaysValidSchema)(m,r)){const r=t.name("valid");"failing"===v.removeAdditional?(S(n,r,!1),t.if((0,u.not)(r),(()=>{e.reset(),w(n)}))):(S(n,r),g||t.if((0,u.not)(r),(()=>t.break())))}}}function S(t,r,n){const o={keyword:"additionalProperties",dataProp:t,dataPropType:f.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(o,r)}t.forIn("key",p,(r=>{y.length||b.length?t.if(function(r){let o;if(y.length>8){const e=(0,f.schemaRefOrVal)(m,n.properties,"properties");o=(0,c.isOwnProperty)(t,e,r)}else o=y.length?(0,u.or)(...y.map((e=>(0,u._)(a||(a=l([""," === ",""])),r,e)))):u.nil;return b.length&&(o=(0,u.or)(o,...b.map((t=>(0,u._)(i||(i=l(["",".test(",")"])),(0,c.usePattern)(e,t),r))))),(0,u.not)(o)}(r),(()=>x(r))):x(r)})),e.ok((0,u._)(o||(o=l([""," === ",""])),h,d.default.errors))}};t.default=p},5219:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1410),o={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const a=t.name("valid");r.forEach(((t,r)=>{if((0,n.alwaysValidSchema)(o,t))return;const i=e.subschema({keyword:"allOf",schemaProp:r},a);e.ok(a),e.mergeEvaluated(i)}))}};t.default=o},1150:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(378).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=n},5540:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const g=r(8789),v=r(1410),y={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:e=>{let{params:{min:t,max:r}}=e;return void 0===r?(0,g.str)(n||(n=m(["must contain at least "," valid item(s)"])),t):(0,g.str)(o||(o=m(["must contain at least "," and no more than "," valid item(s)"])),t,r)},params:e=>{let{params:{min:t,max:r}}=e;return void 0===r?(0,g._)(a||(a=m(["{minContains: ","}"])),t):(0,g._)(i||(i=m(["{minContains: ",", maxContains: ","}"])),t,r)}},code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:a}=e;let i,y;const{minContains:b,maxContains:w}=n;a.opts.next?(i=void 0===b?1:b,y=w):i=1;const x=t.const("len",(0,g._)(s||(s=m(["",".length"])),o));if(e.setParams({min:i,max:y}),void 0===y&&0===i)return void(0,v.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==y&&i>y)return(0,v.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,v.alwaysValidSchema)(a,r)){let t=(0,g._)(l||(l=m([""," >= ",""])),x,i);return void 0!==y&&(t=(0,g._)(c||(c=m([""," && "," <= ",""])),t,x,y)),void e.pass(t)}a.items=!0;const S=t.name("valid");function A(){const e=t.name("_valid"),r=t.let("count",0);k(e,(()=>t.if(e,(()=>function(e){t.code((0,g._)(d||(d=m(["","++"])),e)),void 0===y?t.if((0,g._)(f||(f=m([""," >= ",""])),e,i),(()=>t.assign(S,!0).break())):(t.if((0,g._)(p||(p=m([""," > ",""])),e,y),(()=>t.assign(S,!1).break())),1===i?t.assign(S,!0):t.if((0,g._)(h||(h=m([""," >= ",""])),e,i),(()=>t.assign(S,!0))))}(r)))))}function k(r,n){t.forRange("i",0,x,(t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:v.Type.Num,compositeRule:!0},r),n()}))}void 0===y&&1===i?k(S,(()=>t.if(S,(()=>t.break())))):0===i?(t.let(S,!0),void 0!==y&&t.if((0,g._)(u||(u=m(["",".length > 0"])),o),A)):(t.let(S,!1),A()),e.result(S,(()=>e.reset()))}};t.default=y},8164:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const s=r(8789),l=r(1410),c=r(378);t.error={message:e=>{let{params:{property:t,depsCount:r,deps:o}}=e;const a=1===r?"property":"properties";return(0,s.str)(n||(n=i(["must have "," "," when property "," is present"])),a,o,t)},params:e=>{let{params:{property:t,depsCount:r,deps:n,missingProperty:a}}=e;return(0,s._)(o||(o=i(["{property: ",",\n missingProperty: ",",\n depsCount: ",",\n deps: ","}"])),t,a,r,n)}};const u={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,r]=function(e){let{schema:t}=e;const r={},n={};for(const o in t){if("__proto__"===o)continue;(Array.isArray(t[o])?r:n)[o]=t[o]}return[r,n]}(e);d(e,t),f(e,r)}};function d(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:r,data:n,it:o}=e;if(0===Object.keys(t).length)return;const l=r.let("missing");for(const u in t){const d=t[u];if(0===d.length)continue;const f=(0,c.propertyInData)(r,n,u,o.opts.ownProperties);e.setParams({property:u,depsCount:d.length,deps:d.join(", ")}),o.allErrors?r.if(f,(()=>{for(const t of d)(0,c.checkReportMissingProp)(e,t)})):(r.if((0,s._)(a||(a=i([""," && (",")"])),f,(0,c.checkMissingProp)(e,d,l))),(0,c.reportMissingProp)(e,l),r.else())}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:r,data:n,keyword:o,it:a}=e,i=r.name("valid");for(const s in t)(0,l.alwaysValidSchema)(a,t[s])||(r.if((0,c.propertyInData)(r,n,s,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:o,schemaProp:s},i);e.mergeValidEvaluated(t,i)}),(()=>r.var(i,!0))),e.ok(i))}t.validatePropertyDeps=d,t.validateSchemaDeps=f,t.default=u},6854:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l=r(1410),c={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:e=>{let{params:t}=e;return(0,s.str)(n||(n=i(['must match "','" schema'])),t.ifClause)},params:e=>{let{params:t}=e;return(0,s._)(o||(o=i(["{failingKeyword: ","}"])),t.ifClause)}},code(e){const{gen:t,parentSchema:r,it:n}=e;void 0===r.then&&void 0===r.else&&(0,l.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const o=u(n,"then"),c=u(n,"else");if(!o&&!c)return;const d=t.let("valid",!0),f=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);e.mergeEvaluated(t)}(),e.reset(),o&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(f,p("then",r),p("else",r))}else o?t.if(f,p("then")):t.if((0,s.not)(f),p("else"));function p(r,n){return()=>{const o=e.subschema({keyword:r},f);t.assign(d,f),e.mergeValidEvaluated(o,d),n?t.assign(n,(0,s._)(a||(a=i(["",""])),r)):e.setParams({ifClause:r})}}e.pass(d,(()=>e.error(!0)))}};function u(e,t){const r=e.schema[t];return void 0!==r&&!(0,l.alwaysValidSchema)(e,r)}t.default=c},1913:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(170),o=r(4733),a=r(3441),i=r(3617),s=r(5540),l=r(8164),c=r(4966),u=r(6289),d=r(6676),f=r(4414),p=r(2724),h=r(1150),m=r(9176),g=r(5219),v=r(6854),y=r(6812);t.default=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const t=[p.default,h.default,m.default,g.default,v.default,y.default,c.default,u.default,l.default,d.default,f.default];return e?t.push(o.default,i.default):t.push(n.default,a.default),t.push(s.default),t}},3441:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const i=r(8789),s=r(1410),l=r(378),c={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return u(e,"additionalItems",t);r.items=!0,(0,s.alwaysValidSchema)(r,t)||e.ok((0,l.validateArray)(e))}};function u(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.schema;const{gen:l,parentSchema:c,data:u,keyword:d,it:f}=e;!function(e){const{opts:n,errSchemaPath:o}=f,a=r.length,i=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(n.strictTuples&&!i){const e='"'.concat(d,'" is ').concat(a,"-tuple, but minItems or maxItems/").concat(t,' are not specified or different at path "').concat(o,'"');(0,s.checkStrictMode)(f,e,n.strictTuples)}}(c),f.opts.unevaluated&&r.length&&!0!==f.items&&(f.items=s.mergeEvaluated.items(l,r.length,f.items));const p=l.name("valid"),h=l.const("len",(0,i._)(n||(n=a(["",".length"])),u));r.forEach(((t,r)=>{(0,s.alwaysValidSchema)(f,t)||(l.if((0,i._)(o||(o=a([""," > ",""])),h,r),(()=>e.subschema({keyword:d,schemaProp:r,dataProp:r},p))),e.ok(p))}))}t.validateTuple=u,t.default=c},3617:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(8789),s=r(1410),l=r(378),c=r(170),u={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:e=>{let{params:{len:t}}=e;return(0,i.str)(n||(n=a(["must NOT have more than "," items"])),t)},params:e=>{let{params:{len:t}}=e;return(0,i._)(o||(o=a(["{limit: ","}"])),t)}},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,(0,s.alwaysValidSchema)(n,t)||(o?(0,c.validateAdditionalItems)(e,o):e.ok((0,l.validateArray)(e)))}};t.default=u},2724:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1410),o={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,n.alwaysValidSchema)(o,r))return void e.fail();const a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=o},9176:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l=r(1410),c={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:e=>{let{params:t}=e;return(0,s._)(n||(n=i(["{passingSchemas: ","}"])),t.passing)}},code(e){const{gen:t,schema:r,parentSchema:n,it:c}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(c.opts.discriminator&&n.discriminator)return;const u=r,d=t.let("valid",!1),f=t.let("passing",null),p=t.name("_valid");e.setParams({passing:f}),t.block((function(){u.forEach(((r,n)=>{let u;(0,l.alwaysValidSchema)(c,r)?t.var(p,!0):u=e.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},p),n>0&&t.if((0,s._)(o||(o=i([""," && ",""])),p,d)).assign(d,!1).assign(f,(0,s._)(a||(a=i(["[",", ","]"])),f,n)).else(),t.if(p,(()=>{t.assign(d,!0),t.assign(f,n),u&&e.mergeEvaluated(u,s.Name)}))}))})),e.result(d,(()=>e.reset()),(()=>e.error(!0)))}};t.default=c},4414:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(378),s=r(8789),l=r(1410),c=r(1410),u={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:u,parentSchema:d,it:f}=e,{opts:p}=f,h=(0,i.allSchemaProperties)(r),m=h.filter((e=>(0,l.alwaysValidSchema)(f,r[e])));if(0===h.length||m.length===h.length&&(!f.opts.unevaluated||!0===f.props))return;const g=p.strictSchema&&!p.allowMatchingProperties&&d.properties,v=t.name("valid");!0===f.props||f.props instanceof s.Name||(f.props=(0,c.evaluatedPropsToName)(t,f.props));const{props:y}=f;function b(e){for(const t in g)new RegExp(e).test(t)&&(0,l.checkStrictMode)(f,"property ".concat(t," matches pattern ").concat(e," (use allowMatchingProperties)"))}function w(r){t.forIn("key",u,(l=>{t.if((0,s._)(n||(n=a(["",".test(",")"])),(0,i.usePattern)(e,r),l),(()=>{const n=m.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:l,dataPropType:c.Type.Str},v),f.opts.unevaluated&&!0!==y?t.assign((0,s._)(o||(o=a(["","[","]"])),y,l),!0):n||f.allErrors||t.if((0,s.not)(v),(()=>t.break()))}))}))}!function(){for(const e of h)g&&b(e),f.allErrors?w(e):(t.var(v,!0),w(e),t.if(v))}()}};t.default=u},4733:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(3441),o={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,n.validateTuple)(e,"items")};t.default=o},6676:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(8647),o=r(378),a=r(1410),i=r(6289),s={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:s,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===s.additionalProperties&&i.default.code(new n.KeywordCxt(c,i.default,"additionalProperties"));const u=(0,o.allSchemaProperties)(r);for(const n of u)c.definedProperties.add(n);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=a.mergeEvaluated.props(t,(0,a.toHash)(u),c.props));const d=u.filter((e=>!(0,a.alwaysValidSchema)(c,r[e])));if(0===d.length)return;const f=t.name("valid");for(const n of d)p(n)?h(n):(t.if((0,o.propertyInData)(t,l,n,c.opts.ownProperties)),h(n),c.allErrors||t.else().var(f,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(f);function p(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==r[e].default}function h(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},f)}}};t.default=s},4966:(e,t,r)=>{"use strict";var n,o=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const a=r(8789),i=r(1410),s={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:e=>{let{params:t}=e;return(0,a._)(n||(n=o(["{propertyName: ","}"])),t.propertyName)}},code(e){const{gen:t,schema:r,data:n,it:o}=e;if((0,i.alwaysValidSchema)(o,r))return;const s=t.name("valid");t.forIn("key",n,(r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,a.not)(s),(()=>{e.error(!0),o.allErrors||t.break()}))})),e.ok(s)}};t.default=s},6812:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1410),o={keyword:["then","else"],schemaType:["object","boolean"],code(e){let{keyword:t,parentSchema:r,it:o}=e;void 0===r.if&&(0,n.checkStrictMode)(o,'"'.concat(t,'" without "if" is ignored'))}};t.default=o},378:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const b=r(8789),w=r(1410),x=r(9188),S=r(1410);function A(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,b._)(a||(a=y(["Object.prototype.hasOwnProperty"])))})}function k(e,t,r){return(0,b._)(i||(i=y(["",".call(",", ",")"])),A(e),t,r)}function C(e,t,r,n){const o=(0,b._)(c||(c=y(["",""," === undefined"])),t,(0,b.getProperty)(r));return n?(0,b.or)(o,(0,b.not)(k(e,t,r))):o}function E(e){return e?Object.keys(e).filter((e=>"__proto__"!==e)):[]}t.checkReportMissingProp=function(e,t){const{gen:r,data:o,it:a}=e;r.if(C(r,o,t,a.opts.ownProperties),(()=>{e.setParams({missingProperty:(0,b._)(n||(n=y(["",""])),t)},!0),e.error()}))},t.checkMissingProp=function(e,t,r){let{gen:n,data:a,it:{opts:i}}=e;return(0,b.or)(...t.map((e=>(0,b.and)(C(n,a,e,i.ownProperties),(0,b._)(o||(o=y([""," = ",""])),r,e)))))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=A,t.isOwnProperty=k,t.propertyInData=function(e,t,r,n){const o=(0,b._)(s||(s=y(["",""," !== undefined"])),t,(0,b.getProperty)(r));return n?(0,b._)(l||(l=y([""," && ",""])),o,k(e,t,r)):o},t.noPropertyInData=C,t.allSchemaProperties=E,t.schemaProperties=function(e,t){return E(t).filter((r=>!(0,w.alwaysValidSchema)(e,t[r])))},t.callValidateCode=function(e,t,r,n){let{schemaCode:o,data:a,it:{gen:i,topSchemaRef:s,schemaPath:l,errorPath:c},it:h}=e;const m=n?(0,b._)(u||(u=y(["",", ",", ","",""])),o,a,s,l):a,g=[[x.default.instancePath,(0,b.strConcat)(x.default.instancePath,c)],[x.default.parentData,h.parentData],[x.default.parentDataProperty,h.parentDataProperty],[x.default.rootData,x.default.rootData]];h.opts.dynamicRef&&g.push([x.default.dynamicAnchors,x.default.dynamicAnchors]);const v=(0,b._)(d||(d=y(["",", ",""])),m,i.object(...g));return r!==b.nil?(0,b._)(f||(f=y(["",".call(",", ",")"])),t,r,v):(0,b._)(p||(p=y(["","(",")"])),t,v)};const _=(0,b._)(h||(h=y(["new RegExp"])));t.usePattern=function(e,t){let{gen:r,it:{opts:n}}=e;const o=n.unicodeRegExp?"u":"",{regExp:a}=n.code,i=a(t,o);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,b._)(m||(m=y(["","(",", ",")"])),"new RegExp"===a.code?_:(0,S.useFunc)(r,a),t,o)})},t.validateArray=function(e){const{gen:t,data:r,keyword:n,it:o}=e,a=t.name("valid");if(o.allErrors){const e=t.let("valid",!0);return i((()=>t.assign(e,!1))),e}return t.var(a,!0),i((()=>t.break())),a;function i(o){const i=t.const("len",(0,b._)(g||(g=y(["",".length"])),r));t.forRange("i",0,i,(r=>{e.subschema({keyword:n,dataProp:r,dataPropType:w.Type.Num},a),t.if((0,b.not)(a),o)}))}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some((e=>(0,w.alwaysValidSchema)(o,e)))&&!o.opts.unevaluated)return;const a=t.let("valid",!1),i=t.name("_valid");t.block((()=>r.forEach(((r,o)=>{const s=e.subschema({keyword:n,schemaProp:o,compositeRule:!0},i);t.assign(a,(0,b._)(v||(v=y([""," || ",""])),a,i));e.mergeValidEvaluated(s,i)||t.if((0,b.not)(a))})))),e.result(a,(()=>e.reset()),(()=>e.error(!0)))}},7714:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},8535:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(7714),o=r(7554),a=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",n.default,o.default];t.default=a},7554:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const p=r(1180),h=r(378),m=r(8789),g=r(9188),v=r(5787),y=r(1410),b={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:a,schemaEnv:i,validateName:s,opts:l,self:c}=o,{root:u}=i;if(("#"===r||"#/"===r)&&a===u.baseId)return function(){if(i===u)return x(e,s,i,i.$async);const r=t.scopeValue("root",{ref:u});return x(e,(0,m._)(n||(n=f(["",".validate"])),r),u,u.$async)}();const d=v.resolveRef.call(c,u,a,r);if(void 0===d)throw new p.default(o.opts.uriResolver,a,r);return d instanceof v.SchemaEnv?function(t){const r=w(e,t);x(e,r,t,t.$async)}(d):function(n){const o=t.scopeValue("schema",!0===l.code.source?{ref:n,code:(0,m.stringify)(n)}:{ref:n}),a=t.name("valid"),i=e.subschema({schema:n,dataTypes:[],schemaPath:m.nil,topSchemaRef:o,errSchemaPath:r},a);e.mergeEvaluated(i),e.ok(a)}(d)}};function w(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,m._)(o||(o=f(["",".validate"])),r.scopeValue("wrapper",{ref:t}))}function x(e,t,r,n){const{gen:o,it:p}=e,{allErrors:v,schemaEnv:b,opts:w}=p,x=w.passContext?g.default.this:m.nil;function S(e){const t=(0,m._)(s||(s=f(["",".errors"])),e);o.assign(g.default.vErrors,(0,m._)(l||(l=f([""," === null ? "," : ",".concat(",")"])),g.default.vErrors,t,g.default.vErrors,t)),o.assign(g.default.errors,(0,m._)(c||(c=f(["",".length"])),g.default.vErrors))}function A(e){var t;if(!p.opts.unevaluated)return;const n=null===(t=null===r||void 0===r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==p.props)if(n&&!n.dynamicProps)void 0!==n.props&&(p.props=y.mergeEvaluated.props(o,n.props,p.props));else{const t=o.var("props",(0,m._)(u||(u=f(["",".evaluated.props"])),e));p.props=y.mergeEvaluated.props(o,t,p.props,m.Name)}if(!0!==p.items)if(n&&!n.dynamicItems)void 0!==n.items&&(p.items=y.mergeEvaluated.items(o,n.items,p.items));else{const t=o.var("items",(0,m._)(d||(d=f(["",".evaluated.items"])),e));p.items=y.mergeEvaluated.items(o,t,p.items,m.Name)}}n?function(){if(!b.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try((()=>{o.code((0,m._)(a||(a=f(["await ",""])),(0,h.callValidateCode)(e,t,x))),A(t),v||o.assign(r,!0)}),(e=>{o.if((0,m._)(i||(i=f(["!("," instanceof ",")"])),e,p.ValidationError),(()=>o.throw(e))),S(e),v||o.assign(r,!1)})),e.ok(r)}():e.result((0,h.callValidateCode)(e,t,x),(()=>A(t)),(()=>S(t)))}t.getValidate=w,t.callRef=x,t.default=b},8e3:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(8789),c=r(6869),u=r(5787),d=r(1410),f={keyword:"discriminator",type:"object",schemaType:"object",error:{message:e=>{let{params:{discrError:t,tagName:r}}=e;return t===c.DiscrError.Tag?'tag "'.concat(r,'" must be string'):'value of tag "'.concat(r,'" must be in oneOf')},params:e=>{let{params:{discrError:t,tag:r,tagName:o}}=e;return(0,l._)(n||(n=s(["{error: ",", tag: ",", tagValue: ","}"])),t,o,r)}},code(e){const{gen:t,data:r,schema:n,parentSchema:f,it:p}=e,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const m=n.propertyName;if("string"!=typeof m)throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const g=t.let("valid",!1),v=t.const("tag",(0,l._)(o||(o=s(["","",""])),r,(0,l.getProperty)(m)));function y(r){const n=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(o,l.Name),n}t.if((0,l._)(a||(a=s(["typeof ",' == "string"'])),v),(()=>function(){const r=function(){var e;const t={},r=o(f);let n=!0;for(let s=0;se.error(!1,{discrError:c.DiscrError.Tag,tag:v,tagName:m}))),e.ok(g)}};t.default=f},6869:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(t.DiscrError||(t.DiscrError={}))},6423:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(8535),o=r(5587),a=r(1913),i=r(5187),s=r(9594),l=[n.default,o.default,(0,a.default)(),i.default,s.metadataVocabulary,s.contentVocabulary];t.default=l},5688:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const x=r(8789),S={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,x.str)(n||(n=w(['must match format "','"'])),t)},params:e=>{let{schemaCode:t}=e;return(0,x._)(o||(o=w(["{format: ","}"])),t)}},code(e,t){const{gen:r,data:n,$data:o,schema:S,schemaCode:A,it:k}=e,{opts:C,errSchemaPath:E,schemaEnv:_,self:P}=k;C.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:P.formats,code:C.code.formats}),m=r.const("fDef",(0,x._)(a||(a=w(["","[","]"])),o,A)),g=r.let("fType"),v=r.let("format");r.if((0,x._)(i||(i=w(["typeof ",' == "object" && !('," instanceof RegExp)"])),m,m),(()=>r.assign(g,(0,x._)(s||(s=w(["",'.type || "string"'])),m)).assign(v,(0,x._)(l||(l=w(["",".validate"])),m))),(()=>r.assign(g,(0,x._)(c||(c=w(['"string"'])))).assign(v,m))),e.fail$data((0,x.or)(!1===C.strictSchema?x.nil:(0,x._)(u||(u=w([""," && !",""])),A,v),function(){const e=_.$async?(0,x._)(d||(d=w(["(",".async ? await ","(",") : ","(","))"])),m,v,n,v,n):(0,x._)(f||(f=w(["","(",")"])),v,n),r=(0,x._)(p||(p=w(["(typeof ",' == "function" ? '," : ",".test(","))"])),v,e,v,n);return(0,x._)(h||(h=w([""," && "," !== true && "," === "," && !",""])),v,v,g,t,r)}()))}():function(){const o=P.formats[S];if(!o)return void function(){if(!1===C.strictSchema)return void P.logger.warn(e());throw new Error(e());function e(){return'unknown format "'.concat(S,'" ignored in schema at path "').concat(E,'"')}}();if(!0===o)return;const[a,i,s]=function(e){const t=e instanceof RegExp?(0,x.regexpCode)(e):C.code.formats?(0,x._)(m||(m=w(["","",""])),C.code.formats,(0,x.getProperty)(S)):void 0,n=r.scopeValue("formats",{key:S,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,(0,x._)(g||(g=w(["",".validate"])),n)];return["string",e,n]}(o);a===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!_.$async)throw new Error("async format in sync schema");return(0,x._)(v||(v=w(["await ","(",")"])),s,n)}return"function"==typeof i?(0,x._)(y||(y=w(["","(",")"])),s,n):(0,x._)(b||(b=w(["",".test(",")"])),s,n)}())}())}};t.default=S},5187:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=[r(5688).default];t.default=n},9594:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},3704:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l=r(1410),c=r(4877),u={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:e=>{let{schemaCode:t}=e;return(0,s._)(n||(n=i(["{allowedValue: ","}"])),t)}},code(e){const{gen:t,data:r,$data:n,schemaCode:u,schema:d}=e;n||d&&"object"==typeof d?e.fail$data((0,s._)(o||(o=i(["!","(",", ",")"])),(0,l.useFunc)(t,c.default),r,u)):e.fail((0,s._)(a||(a=i([""," !== ",""])),d,r))}};t.default=u},5374:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(8789),c=r(1410),u=r(4877),d={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:e=>{let{schemaCode:t}=e;return(0,l._)(n||(n=s(["{allowedValues: ","}"])),t)}},code(e){const{gen:t,data:r,$data:n,schema:d,schemaCode:f,it:p}=e;if(!n&&0===d.length)throw new Error("enum must have non-empty array");const h=d.length>=p.opts.loopEnum;let m;const g=()=>null!==m&&void 0!==m?m:m=(0,c.useFunc)(t,u.default);let v;if(h||n)v=t.let("valid"),e.block$data(v,(function(){t.assign(v,!1),t.forOf("v",f,(e=>t.if((0,l._)(o||(o=s(["","(",", ",")"])),g(),r,e),(()=>t.assign(v,!0).break()))))}));else{if(!Array.isArray(d))throw new Error("ajv implementation error");const e=t.const("vSchema",f);v=(0,l.or)(...d.map(((t,n)=>function(e,t){const n=d[t];return"object"===typeof n&&null!==n?(0,l._)(a||(a=s(["","(",", ","[","])"])),g(),r,e,t):(0,l._)(i||(i=s([""," === ",""])),r,n)}(e,n))))}e.pass(v)}};t.default=d},5587:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(3189),o=r(406),a=r(1736),i=r(4101),s=r(2989),l=r(3218),c=r(4233),u=r(8450),d=r(3704),f=r(5374),p=[n.default,o.default,a.default,i.default,s.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},d.default,f.default];t.default=p},4233:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxItems"===t?"more":"fewer";return(0,s.str)(n||(n=i(["must NOT have "," than "," items"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,s._)(o||(o=i(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data((0,s._)(a||(a=i(["",".length "," ",""])),r,o,n))}};t.default=l},1736:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(8789),u=r(1410),d=r(8348),f={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxLength"===t?"more":"fewer";return(0,c.str)(n||(n=l(["must NOT have "," than "," characters"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=l(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n,it:o}=e,f="maxLength"===t?c.operators.GT:c.operators.LT,p=!1===o.opts.unicode?(0,c._)(a||(a=l(["",".length"])),r):(0,c._)(i||(i=l(["","(",")"])),(0,u.useFunc)(e.gen,d.default),r);e.fail$data((0,c._)(s||(s=l([""," "," ",""])),p,f,n))}};t.default=f},3189:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l=s.operators,c={maximum:{okStr:"<=",ok:l.LTE,fail:l.GT},minimum:{okStr:">=",ok:l.GTE,fail:l.LT},exclusiveMaximum:{okStr:"<",ok:l.LT,fail:l.GTE},exclusiveMinimum:{okStr:">",ok:l.GT,fail:l.LTE}},u={message:e=>{let{keyword:t,schemaCode:r}=e;return(0,s.str)(n||(n=i(["must be "," ",""])),c[t].okStr,r)},params:e=>{let{keyword:t,schemaCode:r}=e;return(0,s._)(o||(o=i(["{comparison: ",", limit: ","}"])),c[t].okStr,r)}},d={keyword:Object.keys(c),type:"number",schemaType:"number",$data:!0,error:u,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,s._)(a||(a=i([""," "," "," || isNaN(",")"])),r,c[t].fail,n,r))}};t.default=d},2989:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8789),l={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxProperties"===t?"more":"fewer";return(0,s.str)(n||(n=i(["must NOT have "," than "," properties"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,s._)(o||(o=i(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data((0,s._)(a||(a=i(["Object.keys(",").length "," ",""])),r,o,n))}};t.default=l},406:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(8789),u={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,c.str)(n||(n=l(["must be multiple of ",""])),t)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=l(["{multipleOf: ","}"])),t)}},code(e){const{gen:t,data:r,schemaCode:n,it:o}=e,u=o.opts.multipleOfPrecision,d=t.let("res"),f=u?(0,c._)(a||(a=l(["Math.abs(Math.round(",") - ",") > 1e-",""])),d,d,u):(0,c._)(i||(i=l([""," !== parseInt(",")"])),d,d);e.fail$data((0,c._)(s||(s=l(["("," === 0 || ("," = ","/",", ","))"])),n,d,r,n,f))}};t.default=u},4101:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(378),c=r(8789),u={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,c.str)(n||(n=s(['must match pattern "','"'])),t)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=s(["{pattern: ","}"])),t)}},code(e){const{data:t,$data:r,schema:n,schemaCode:o,it:u}=e,d=u.opts.unicodeRegExp?"u":"",f=r?(0,c._)(a||(a=s(["(new RegExp(",", ","))"])),o,d):(0,l.usePattern)(e,n);e.fail$data((0,c._)(i||(i=s(["!",".test(",")"])),f,t))}};t.default=u},3218:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(378),s=r(8789),l=r(1410),c={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:e=>{let{params:{missingProperty:t}}=e;return(0,s.str)(n||(n=a(["must have required property '","'"])),t)},params:e=>{let{params:{missingProperty:t}}=e;return(0,s._)(o||(o=a(["{missingProperty: ","}"])),t)}},code(e){const{gen:t,schema:r,schemaCode:n,data:o,$data:a,it:c}=e,{opts:u}=c;if(!a&&0===r.length)return;const d=r.length>=u.loopRequired;if(c.allErrors?function(){if(d||a)e.block$data(s.nil,f);else for(const t of r)(0,i.checkReportMissingProp)(e,t)}():function(){const l=t.let("missing");if(d||a){const r=t.let("valid",!0);e.block$data(r,(()=>function(r,a){e.setParams({missingProperty:r}),t.forOf(r,n,(()=>{t.assign(a,(0,i.propertyInData)(t,o,r,u.ownProperties)),t.if((0,s.not)(a),(()=>{e.error(),t.break()}))}),s.nil)}(l,r))),e.ok(r)}else t.if((0,i.checkMissingProp)(e,r,l)),(0,i.reportMissingProp)(e,l),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null===t||void 0===t?void 0:t[e])&&!n.has(e)){const t=c.schemaEnv.baseId+c.errSchemaPath,r='required property "'.concat(e,'" is not defined at "').concat(t,'" (strictRequired)');(0,l.checkStrictMode)(c,r,c.opts.strictRequired)}}function f(){t.forOf("prop",n,(r=>{e.setParams({missingProperty:r}),t.if((0,i.noPropertyInData)(t,o,r,u.ownProperties),(()=>e.error()))}))}}};t.default=c},8450:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const x=r(9507),S=r(8789),A=r(1410),k=r(4877),C={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:e=>{let{params:{i:t,j:r}}=e;return(0,S.str)(n||(n=w(["must NOT have duplicate items (items ## "," and "," are identical)"])),r,t)},params:e=>{let{params:{i:t,j:r}}=e;return(0,S._)(o||(o=w(["{i: ",", j: ","}"])),t,r)}},code(e){const{gen:t,data:r,$data:n,schema:o,parentSchema:C,schemaCode:E,it:_}=e;if(!n&&!o)return;const P=t.let("valid"),j=C.items?(0,x.getSchemaTypes)(C.items):[];function R(n,o){const a=t.name("item"),i=(0,x.checkDataTypes)(j,a,_.opts.strictNumbers,x.DataType.Wrong),s=t.const("indices",(0,S._)(l||(l=w(["{}"]))));t.for((0,S._)(c||(c=w([";","--;"])),n),(()=>{t.let(a,(0,S._)(u||(u=w(["","[","]"])),r,n)),t.if(i,(0,S._)(d||(d=w(["continue"])))),j.length>1&&t.if((0,S._)(f||(f=w(["typeof ",' == "string"'])),a),(0,S._)(p||(p=w(["",' += "_"'])),a)),t.if((0,S._)(h||(h=w(["typeof ","[",'] == "number"'])),s,a),(()=>{t.assign(o,(0,S._)(m||(m=w(["","[","]"])),s,a)),e.error(),t.assign(P,!1).break()})).code((0,S._)(g||(g=w(["","[","] = ",""])),s,a,n))}))}function O(n,o){const a=(0,A.useFunc)(t,k.default),i=t.name("outer");t.label(i).for((0,S._)(v||(v=w([";","--;"])),n),(()=>t.for((0,S._)(y||(y=w([""," = ","; ","--;"])),o,n,o),(()=>t.if((0,S._)(b||(b=w(["","(","[","], ","[","])"])),a,r,n,r,o),(()=>{e.error(),t.assign(P,!1).break(i)}))))))}e.block$data(P,(function(){const n=t.let("i",(0,S._)(i||(i=w(["",".length"])),r)),o=t.let("j");e.setParams({i:n,j:o}),t.assign(P,!0),t.if((0,S._)(s||(s=w([""," > 1"])),n),(()=>(j.length>0&&!j.some((e=>"object"===e||"array"===e))?R:O)(n,o)))}),(0,S._)(a||(a=w([""," === false"])),E)),e.ok(P)}};t.default=C},1125:e=>{"use strict";var t=e.exports=function(e,t,n){"function"==typeof t&&(n=t,t={}),r(t,"function"==typeof(n=t.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function r(e,n,o,a,i,s,l,c,u,d){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var f in n(a,i,s,l,c,u,d),a){var p=a[f];if(Array.isArray(p)){if(f in t.arrayKeywords)for(var h=0;h{"use strict";function r(e,t){return{validate:e,compare:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(a,i),time:r(l,c),"date-time":r((function(e){const t=e.split(u);return 2===t.length&&a(t[0])&&l(t[1],!0)}),d),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return f.test(e)&&p.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(y.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return h.lastIndex=0,h.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=g&&e>=m}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:v},double:{type:"number",validate:v},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,c),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){const t=n.exec(e);if(!t)return!1;const r=+t[1],a=+t[2],i=+t[3];return a>=1&&a<=12&&i>=1&&i<=(2===a&&function(e){return e%4===0&&(e%100!==0||e%400===0)}(r)?29:o[a])}function i(e,t){if(e&&t)return e>t?1:e(t=n[1]+n[2]+n[3]+(n[4]||""))?1:e{"use strict";var n,o=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const a=r(2215),i=r(7864),s=r(8494),l=new s.Name("fullFormats"),c=new s.Name("fastFormats"),u=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{keywords:!0};if(Array.isArray(t))return d(e,t,a.fullFormats,l),e;const[r,n]="fast"===t.mode?[a.fastFormats,c]:[a.fullFormats,l];return d(e,t.formats||a.formatNames,r,n),t.keywords&&i.default(e),e};function d(e,t,r,a){var i,l;null!==(i=(l=e.opts.code).formats)&&void 0!==i||(l.formats=s._(n||(n=o(['require("ajv-formats/dist/formats").',""])),a));for(const n of t)e.addFormat(n,r[n])}u.get=function(e){const t=("fast"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"full")?a.fastFormats:a.fullFormats)[e];if(!t)throw new Error('Unknown format "'.concat(e,'"'));return t},e.exports=t=u,Object.defineProperty(t,"__esModule",{value:!0}),t.default=u},7864:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const f=r(9122),p=r(8494),h=p.operators,m={formatMaximum:{okStr:"<=",ok:h.LTE,fail:h.GT},formatMinimum:{okStr:">=",ok:h.GTE,fail:h.LT},formatExclusiveMaximum:{okStr:"<",ok:h.LT,fail:h.GTE},formatExclusiveMinimum:{okStr:">",ok:h.GT,fail:h.LTE}},g={message:e=>{let{keyword:t,schemaCode:r}=e;return p.str(n||(n=d(["should be "," ",""])),m[t].okStr,r)},params:e=>{let{keyword:t,schemaCode:r}=e;return p._(o||(o=d(["{comparison: ",", limit: ","}"])),m[t].okStr,r)}};t.formatLimitDefinition={keyword:Object.keys(m),type:"string",schemaType:"string",$data:!0,error:g,code(e){const{gen:t,data:r,schemaCode:n,keyword:o,it:h}=e,{opts:g,self:v}=h;if(!g.validateFormats)return;const y=new f.KeywordCxt(h,v.RULES.all.format.definition,"format");function b(e){return p._(u||(u=d(["",".compare(",", ",") "," 0"])),e,r,n,m[o].fail)}y.$data?function(){const r=t.scopeValue("formats",{ref:v.formats,code:g.code.formats}),n=t.const("fmt",p._(a||(a=d(["","[","]"])),r,y.schemaCode));e.fail$data(p.or(p._(i||(i=d(["typeof ",' != "object"'])),n),p._(s||(s=d([""," instanceof RegExp"])),n),p._(l||(l=d(["typeof ",'.compare != "function"'])),n),b(n)))}():function(){const r=y.schema,n=v.formats[r];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error('"'.concat(o,'": format "').concat(r,'" does not define "compare" function'));const a=t.scopeValue("formats",{key:r,ref:n,code:g.code.formats?p._(c||(c=d(["","",""])),g.code.formats,p.getProperty(r)):void 0});e.fail$data(b(a))}()},dependencies:["format"]};t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},9122:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;const n=r(9899),o=r(5915),a=r(5012),i=r(2455),s=["/properties"],l="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),o.default.forEach((e=>this.addVocabulary(e))),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(i,s):i;this.addMetaSchema(e,l,!1),this.refs["http://json-schema.org/schema"]=l}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}}e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=r(7683);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=r(8494);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var f=r(2323);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=r(8723);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})},5545:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class i{}t._CodeOrName=i,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class s extends i{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=s;class l extends i{constructor(e){super(),this._items="string"===typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce(((e,t)=>"".concat(e).concat(t)),"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce(((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e)),{})}}function c(e){const t=[e[0]];let r=0;for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a1?n-1:0),a=1;a{"use strict";var n,o,a,i,s,l,c=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const u=r(5545),d=r(8094);var f=r(5545);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return f.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return f.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return f.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return f.Name}});var p=r(8094);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return p.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return p.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return p.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return p.varKinds}}),t.operators={GT:new u._Code(">"),GTE:new u._Code(">="),LT:new u._Code("<"),LTE:new u._Code("<="),EQ:new u._Code("==="),NEQ:new u._Code("!=="),NOT:new u._Code("!"),OR:new u._Code("||"),AND:new u._Code("&&"),ADD:new u._Code("+")};class h{optimizeNodes(){return this}optimizeNames(e,t){return this}}class m extends h{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render(e){let{es5:t,_n:r}=e;const n=t?d.varKinds.var:this.varKind,o=void 0===this.rhs?"":" = ".concat(this.rhs);return"".concat(n," ").concat(this.name).concat(o,";")+r}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=z(this.rhs,e,t)),this}get names(){return this.rhs instanceof u._CodeOrName?this.rhs.names:{}}}class g extends h{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render(e){let{_n:t}=e;return"".concat(this.lhs," = ").concat(this.rhs,";")+t}optimizeNames(e,t){if(!(this.lhs instanceof u.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=z(this.rhs,e,t),this}get names(){return D(this.lhs instanceof u.Name?{}:{...this.lhs.names},this.rhs)}}class v extends g{constructor(e,t,r,n){super(e,r,n),this.op=t}render(e){let{_n:t}=e;return"".concat(this.lhs," ").concat(this.op,"= ").concat(this.rhs,";")+t}}class y extends h{constructor(e){super(),this.label=e,this.names={}}render(e){let{_n:t}=e;return"".concat(this.label,":")+t}}class b extends h{constructor(e){super(),this.label=e,this.names={}}render(e){let{_n:t}=e;const r=this.label?" ".concat(this.label):"";return"break".concat(r,";")+t}}class w extends h{constructor(e){super(),this.error=e}render(e){let{_n:t}=e;return"throw ".concat(this.error,";")+t}get names(){return this.error.names}}class x extends h{constructor(e){super(),this.code=e}render(e){let{_n:t}=e;return"".concat(this.code,";")+t}optimizeNodes(){return"".concat(this.code)?this:void 0}optimizeNames(e,t){return this.code=z(this.code,e,t),this}get names(){return this.code instanceof u._CodeOrName?this.code.names:{}}}class S extends h{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];super(),this.nodes=e}render(e){return this.nodes.reduce(((t,r)=>t+r.render(e)),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const o=r[n];o.optimizeNames(e,t)||(L(e,o.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce(((e,t)=>F(e,t.names)),{})}}class A extends S{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class k extends S{}class C extends A{}C.kind="else";class E extends A{constructor(e,t){super(t),this.condition=e}render(e){let t="if(".concat(this.condition,")")+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new C(e):e}return t?!1===e?t instanceof E?t:t.nodes:this.nodes.length?this:new E(B(e),t instanceof E?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=z(this.condition,e,t),this}get names(){const e=super.names;return D(e,this.condition),this.else&&F(e,this.else.names),e}}E.kind="if";class _ extends A{}_.kind="for";class P extends _{constructor(e){super(),this.iteration=e}render(e){return"for(".concat(this.iteration,")")+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=z(this.iteration,e,t),this}get names(){return F(super.names,this.iteration.names)}}class j extends _{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?d.varKinds.var:this.varKind,{name:r,from:n,to:o}=this;return"for(".concat(t," ").concat(r,"=").concat(n,"; ").concat(r,"<").concat(o,"; ").concat(r,"++)")+super.render(e)}get names(){const e=D(super.names,this.from);return D(e,this.to)}}class R extends _{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return"for(".concat(this.varKind," ").concat(this.name," ").concat(this.loop," ").concat(this.iterable,")")+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=z(this.iterable,e,t),this}get names(){return F(super.names,this.iterable.names)}}class O extends A{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){const t=this.async?"async ":"";return"".concat(t,"function ").concat(this.name,"(").concat(this.args,")")+super.render(e)}}O.kind="func";class N extends S{render(e){return"return "+super.render(e)}}N.kind="return";class T extends A{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&F(e,this.catch.names),this.finally&&F(e,this.finally.names),e}}class I extends A{constructor(e){super(),this.error=e}render(e){return"catch(".concat(this.error,")")+super.render(e)}}I.kind="catch";class M extends A{render(e){return"finally"+super.render(e)}}M.kind="finally";function F(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function D(e,t){return t instanceof u._CodeOrName?F(e,t.names):e}function z(e,t,r){return e instanceof u.Name?o(e):(n=e)instanceof u._Code&&n._items.some((e=>e instanceof u.Name&&1===t[e.str]&&void 0!==r[e.str]))?new u._Code(e._items.reduce(((e,t)=>(t instanceof u.Name&&(t=o(t)),t instanceof u._Code?e.push(...t._items):e.push(t),e)),[])):e;var n;function o(e){const n=r[e.str];return void 0===n||1!==t[e.str]?e:(delete t[e.str],n)}}function L(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function B(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:(0,u._)(i||(i=c(["!",""])),U(e))}t.CodeGen=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new d.Scope({parent:e}),this._nodes=[new k]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const o=this._scope.toName(t);return void 0!==r&&n&&(this._constants[o.str]=r),this._leafNode(new m(e,o,r)),o}const(e,t,r){return this._def(d.varKinds.const,e,t,r)}let(e,t,r){return this._def(d.varKinds.let,e,t,r)}var(e,t,r){return this._def(d.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new g(e,t,r))}add(e,r){return this._leafNode(new v(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==u.nil&&this._leafNode(new x(e)),this}object(){const e=["{"];for(var t=arguments.length,r=new Array(t),n=0;n1&&e.push(","),e.push(o),(o!==a||this.opts.es5)&&(e.push(":"),(0,u.addCodeArg)(e,a));return e.push("}"),new u._Code(e)}if(e,t,r){if(this._blockNode(new E(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new E(e))}else(){return this._elseNode(new C)}endIf(){return this._endBlockNode(E,C)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new P(e),t)}forRange(e,t,r,n){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.opts.es5?d.varKinds.var:d.varKinds.let;const a=this._scope.toName(e);return this._for(new j(o,a,t,r),(()=>n(a)))}forOf(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:d.varKinds.const;const i=this._scope.toName(e);if(this.opts.es5){const e=t instanceof u.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,u._)(n||(n=c(["",".length"])),e),(t=>{this.var(i,(0,u._)(o||(o=c(["","[","]"])),e,t)),r(i)}))}return this._for(new R("of",a,i,t),(()=>r(i)))}forIn(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.es5?d.varKinds.var:d.varKinds.const;if(this.opts.ownProperties)return this.forOf(e,(0,u._)(a||(a=c(["Object.keys(",")"])),t),r);const o=this._scope.toName(e);return this._for(new R("in",n,o,t),(()=>r(o)))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new y(e))}break(e){return this._leafNode(new b(e))}return(e){const t=new N;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(N)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new T;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new I(e),t(e)}return r&&(this._currNode=n.finally=new M,this.code(r)),this._endBlockNode(I,M)}throw(e){return this._leafNode(new w(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error("CodeGen: wrong number of nodes: ".concat(r," vs ").concat(e," expected"));return this._nodes.length=t,this}func(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.nil,r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0;return this._blockNode(new O(e,t,r)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(O)}optimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error('CodeGen: not in block "'.concat(t?"".concat(e.kind,"/").concat(t.kind):e.kind,'"'))}_elseNode(e){const t=this._currNode;if(!(t instanceof E))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=B;const $=V(t.operators.AND);t.and=function(){for(var e=arguments.length,t=new Array(e),r=0;rt===u.nil?r:r===u.nil?t:(0,u._)(s||(s=c([""," "," ",""])),U(t),e,U(r))}function U(e){return e instanceof u.Name?e:(0,u._)(l||(l=c(["(",")"])),e)}t.or=function(){for(var e=arguments.length,t=new Array(e),r=0;r{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const c=r(5545);class u extends Error{constructor(e){super('CodeGen: "code" for '.concat(e," not defined")),this.value=e.value}}var d;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(d=t.UsedValueState||(t.UsedValueState={})),t.varKinds={const:new c.Name("const"),let:new c.Name("let"),var:new c.Name("var")};class f{constructor(){let{prefixes:e,parent:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof c.Name?e:this.name(e)}name(e){return new c.Name(this._newName(e))}_newName(e){const t=this._names[e]||this._nameGroup(e);return"".concat(e).concat(t.index++)}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error('CodeGen: prefix "'.concat(e,'" is not allowed in this scope'));return this._names[e]={prefix:e,index:0}}}t.Scope=f;class p extends c.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,t){let{property:r,itemIndex:o}=t;this.value=e,this.scopePath=(0,c._)(n||(n=l([".","[","]"])),new c.Name(r),o)}}t.ValueScopeName=p;const h=(0,c._)(o||(o=l(["\n"],["\\n"])));t.ValueScope=class extends f{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?h:c.nil}}get(){return this._scope}name(e){return new p(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:o}=n,a=null!==(r=t.key)&&void 0!==r?r:t.ref;let i=this._values[o];if(i){const e=i.get(a);if(e)return e}else i=this._values[o]=new Map;i.set(a,n);const s=this._scope[o]||(this._scope[o]=[]),l=s.length;return s[l]=t.ref,n.setValue(t,{property:o,itemIndex:l}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._values;return this._reduceValues(t,(t=>{if(void 0===t.scopePath)throw new Error('CodeGen: name "'.concat(t,'" has no value'));return(0,c._)(a||(a=l(["","",""])),e,t.scopePath)}))}scopeCode(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._values,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0;return this._reduceValues(e,(e=>{if(void 0===e.value)throw new Error('CodeGen: name "'.concat(e,'" has no value'));return e.value.code}),t,r)}_reduceValues(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0,a=c.nil;for(const f in e){const p=e[f];if(!p)continue;const h=n[f]=n[f]||new Map;p.forEach((e=>{if(h.has(e))return;h.set(e,d.Started);let n=r(e);if(n){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;a=(0,c._)(i||(i=l(["",""," "," = ",";",""])),a,r,e,n,this.opts._n)}else{if(!(n=null===o||void 0===o?void 0:o(e)))throw new u(e);a=(0,c._)(s||(s=l(["","","",""])),a,n,this.opts._n)}h.set(e,d.Completed)}))}return a}}},9773:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const j=r(8494),R=r(1646),O=r(1e3);function N(e,t){const r=e.const("err",t);e.if((0,j._)(g||(g=P([""," === null"])),O.default.vErrors),(()=>e.assign(O.default.vErrors,(0,j._)(v||(v=P(["[","]"])),r))),(0,j._)(y||(y=P(["",".push(",")"])),O.default.vErrors,r)),e.code((0,j._)(b||(b=P(["","++"])),O.default.errors))}function T(e,t){const{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,j._)(w||(w=P(["new ","(",")"])),e.ValidationError,t)):(r.assign((0,j._)(x||(x=P(["",".errors"])),n),t),r.return(!1))}t.keywordError={message:e=>{let{keyword:t}=e;return(0,j.str)(n||(n=P(['must pass "','" keyword validation'])),t)}},t.keyword$DataError={message:e=>{let{keyword:t,schemaType:r}=e;return r?(0,j.str)(o||(o=P(['"','" keyword must be '," ($data)"])),t,r):(0,j.str)(a||(a=P(['"','" keyword is invalid ($data)'])),t)}},t.reportError=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.keywordError,n=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0;const{it:a}=e,{gen:s,compositeRule:l,allErrors:c}=a,u=M(e,r,n);(null!==o&&void 0!==o?o:l||c)?N(s,u):T(a,(0,j._)(i||(i=P(["[","]"])),u))},t.reportExtraError=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.keywordError,n=arguments.length>2?arguments[2]:void 0;const{it:o}=e,{gen:a,compositeRule:i,allErrors:s}=o;N(a,M(e,r,n)),i||s||T(o,O.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(O.default.errors,t),e.if((0,j._)(s||(s=P([""," !== null"])),O.default.vErrors),(()=>e.if(t,(()=>e.assign((0,j._)(l||(l=P(["",".length"])),O.default.vErrors),t)),(()=>e.assign(O.default.vErrors,null)))))},t.extendErrors=function(e){let{gen:t,keyword:r,schemaValue:n,data:o,errsCount:a,it:i}=e;if(void 0===a)throw new Error("ajv implementation error");const s=t.name("err");t.forRange("i",a,O.default.errors,(e=>{t.const(s,(0,j._)(c||(c=P(["","[","]"])),O.default.vErrors,e)),t.if((0,j._)(u||(u=P(["",".instancePath === undefined"])),s),(()=>t.assign((0,j._)(d||(d=P(["",".instancePath"])),s),(0,j.strConcat)(O.default.instancePath,i.errorPath)))),t.assign((0,j._)(f||(f=P(["",".schemaPath"])),s),(0,j.str)(p||(p=P(["","/",""])),i.errSchemaPath,r)),i.opts.verbose&&(t.assign((0,j._)(h||(h=P(["",".schema"])),s),n),t.assign((0,j._)(m||(m=P(["",".data"])),s),o))}))};const I={keyword:new j.Name("keyword"),schemaPath:new j.Name("schemaPath"),params:new j.Name("params"),propertyName:new j.Name("propertyName"),message:new j.Name("message"),schema:new j.Name("schema"),parentSchema:new j.Name("parentSchema")};function M(e,t,r){const{createErrors:n}=e.it;return!1===n?(0,j._)(S||(S=P(["{}"]))):function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{gen:n,it:o}=e,a=[F(o,r),D(e,r)];return function(e,t,r){let{params:n,message:o}=t;const{keyword:a,data:i,schemaValue:s,it:l}=e,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:f}=l;r.push([I.keyword,a],[I.params,"function"==typeof n?n(e):n||(0,j._)(E||(E=P(["{}"])))]),c.messages&&r.push([I.message,"function"==typeof o?o(e):o]);c.verbose&&r.push([I.schema,s],[I.parentSchema,(0,j._)(_||(_=P(["","",""])),d,f)],[O.default.data,i]);u&&r.push([I.propertyName,u])}(e,t,a),n.object(...a)}(e,t,r)}function F(e,t){let{errorPath:r}=e,{instancePath:n}=t;const o=n?(0,j.str)(A||(A=P(["","",""])),r,(0,R.getErrorPath)(n,R.Type.Str)):r;return[O.default.instancePath,(0,j.strConcat)(O.default.instancePath,o)]}function D(e,t){let{keyword:r,it:{errSchemaPath:n}}=e,{schemaPath:o,parentSchema:a}=t,i=a?n:(0,j.str)(k||(k=P(["","/",""])),n,r);return o&&(i=(0,j.str)(C||(C=P(["","",""])),i,(0,R.getErrorPath)(o,R.Type.Str))),[I.schemaPath,i]}},7804:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const i=r(8494),s=r(2323),l=r(1e3),c=r(2228),u=r(1646),d=r(7683);class f{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,c.normalizeId)(null===r||void 0===r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null===r||void 0===r?void 0:r.$async,this.refs={}}}function p(e){const t=m.call(this,e);if(t)return t;const r=(0,c.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:u,lines:f}=this.opts.code,{ownProperties:p}=this.opts,h=new i.CodeGen(this.scope,{es5:u,lines:f,ownProperties:p});let g;e.$async&&(g=h.scopeValue("Error",{ref:s.default,code:(0,i._)(n||(n=a(['require("ajv/dist/runtime/validation_error").default'])))}));const v=h.scopeName("validate");e.validateName=v;const y={gen:h,allErrors:this.opts.allErrors,data:l.default.data,parentData:l.default.parentData,parentDataProperty:l.default.parentDataProperty,dataNames:[l.default.data],dataPathArr:[i.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,i.stringify)(e.schema)}:{ref:e.schema}),validateName:v,ValidationError:g,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:i.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,i._)(o||(o=a(['""']))),opts:this.opts,self:this};let b;try{this._compilations.add(e),(0,d.validateFunctionCode)(y),h.optimize(this.opts.code.optimize);const t=h.toString();b="".concat(h.scopeRefs(l.default.scope),"return ").concat(t),this.opts.code.process&&(b=this.opts.code.process(b,e));const r=new Function("".concat(l.default.self),"".concat(l.default.scope),b)(this,this.scope.get());if(this.scope.value(v,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:v,validateCode:t,scopeValues:h._values}),this.opts.unevaluated){const{props:e,items:t}=y;r.evaluated={props:e instanceof i.Name?void 0:e,items:t instanceof i.Name?void 0:t,dynamicProps:e instanceof i.Name,dynamicItems:t instanceof i.Name},r.source&&(r.source.evaluated=(0,i.stringify)(r.evaluated))}return e.validate=r,e}catch(w){throw delete e.validate,delete e.validateName,b&&this.logger.error("Error compiling schema, function code:",b),w}finally{this._compilations.delete(e)}}function h(e){return(0,c.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:p.call(this,e)}function m(e){for(const n of this._compilations)if(r=e,(t=n).schema===r.schema&&t.root===r.root&&t.baseId===r.baseId)return n;var t,r}function g(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||v.call(this,e,t)}function v(e,t){const r=this.opts.uriResolver.parse(t),n=(0,c._getFullPath)(this.opts.uriResolver,r);let o=(0,c.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return b.call(this,r,e);const a=(0,c.normalizeId)(n),i=this.refs[a]||this.schemas[a];if("string"==typeof i){const t=v.call(this,e,i);if("object"!==typeof(null===t||void 0===t?void 0:t.schema))return;return b.call(this,r,t)}if("object"===typeof(null===i||void 0===i?void 0:i.schema)){if(i.validate||p.call(this,i),a===(0,c.normalizeId)(t)){const{schema:t}=i,{schemaId:r}=this.opts,n=t[r];return n&&(o=(0,c.resolveUrl)(this.opts.uriResolver,o,n)),new f({schema:t,schemaId:r,root:e,baseId:o})}return b.call(this,r,i)}}t.SchemaEnv=f,t.compileSchema=p,t.resolveRef=function(e,t,r){var n;r=(0,c.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let a=g.call(this,e,r);if(void 0===a){const o=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:i}=this.opts;o&&(a=new f({schema:o,schemaId:i,root:e,baseId:t}))}return void 0!==a?e.refs[r]=h.call(this,a):void 0},t.getCompilingSchema=m,t.resolveSchema=v;const y=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(e,t){let{baseId:r,schema:n,root:o}=t;var a;if("/"!==(null===(a=e.fragment)||void 0===a?void 0:a[0]))return;for(const l of e.fragment.slice(1).split("/")){if("boolean"===typeof n)return;const e=n[(0,u.unescapeFragment)(l)];if(void 0===e)return;n=e;const t="object"===typeof n&&n[this.opts.schemaId];!y.has(l)&&t&&(r=(0,c.resolveUrl)(this.opts.uriResolver,r,t))}let i;if("boolean"!=typeof n&&n.$ref&&!(0,u.schemaHasRulesButRef)(n,this.RULES)){const e=(0,c.resolveUrl)(this.opts.uriResolver,r,n.$ref);i=v.call(this,o,e)}const{schemaId:s}=this.opts;return i=i||new f({schema:n,schemaId:s,root:o,baseId:r}),i.schema!==i.root.schema?i:void 0}},1e3:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(8494),o={data:new n.Name("data"),valCxt:new n.Name("valCxt"),instancePath:new n.Name("instancePath"),parentData:new n.Name("parentData"),parentDataProperty:new n.Name("parentDataProperty"),rootData:new n.Name("rootData"),dynamicAnchors:new n.Name("dynamicAnchors"),vErrors:new n.Name("vErrors"),errors:new n.Name("errors"),this:new n.Name("this"),self:new n.Name("self"),scope:new n.Name("scope"),json:new n.Name("json"),jsonPos:new n.Name("jsonPos"),jsonLen:new n.Name("jsonLen"),jsonPart:new n.Name("jsonPart")};t.default=o},8723:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(2228);class o extends Error{constructor(e,t,r,o){super(o||"can't resolve reference ".concat(r," from id ").concat(t)),this.missingRef=(0,n.resolveUrl)(e,t,r),this.missingSchema=(0,n.normalizeId)((0,n.getFullPath)(e,this.missingRef))}}t.default=o},2228:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const n=r(1646),o=r(122),a=r(9569),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return"boolean"==typeof e||(!0===t?!l(e):!!t&&c(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function l(e){for(const t in e){if(s.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(l))return!0;if("object"==typeof r&&l(r))return!0}return!1}function c(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!i.has(r)&&("object"==typeof e[r]&&(0,n.eachItem)(e[r],(e=>t+=c(e))),t===1/0))return 1/0}return t}function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";!1!==(arguments.length>2?arguments[2]:void 0)&&(t=p(t));const r=e.parse(t);return d(e,r)}function d(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=u,t._getFullPath=d;const f=/#\/?$/;function p(e){return e?e.replace(f,""):""}t.normalizeId=p,t.resolveUrl=function(e,t,r){return r=p(r),e.resolve(t,r)};const h=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,i=p(e[r]||t),s={"":i},l=u(n,i,!1),c={},d=new Set;return a(e,{allKeys:!0},((e,t,n,o)=>{if(void 0===o)return;const a=l+t;let i=s[o];function u(t){const r=this.opts.uriResolver.resolve;if(t=p(i?r(i,t):t),d.has(t))throw m(t);d.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?f(e,n.schema,t):t!==p(a)&&("#"===t[0]?(f(e,c[t],t),c[t]=e):this.refs[t]=a),t}function g(e){if("string"==typeof e){if(!h.test(e))throw new Error('invalid anchor "'.concat(e,'"'));u.call(this,"#".concat(e))}}"string"==typeof e[r]&&(i=u.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=i})),c;function f(e,t,r){if(void 0!==t&&!o(e,t))throw m(r)}function m(e){return new Error('reference "'.concat(e,'" resolves to more than one schema'))}}},9675:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}},1646:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const S=r(8494),A=r(5545);function k(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"===typeof t)return;const o=n.RULES.keywords;for(const a in t)o[a]||T(e,'unknown keyword: "'.concat(a,'"'))}function C(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function E(e){return"number"==typeof e?"".concat(e):e.replace(/~/g,"~0").replace(/\//g,"~1")}function _(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function P(e){let{mergeNames:t,mergeToName:r,mergeValues:n,resultToName:o}=e;return(e,a,i,s)=>{const l=void 0===i?a:i instanceof S.Name?(a instanceof S.Name?t(e,a,i):r(e,a,i),i):a instanceof S.Name?(r(e,i,a),a):n(a,i);return s!==S.Name||l instanceof S.Name?l:o(e,l)}}function j(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",(0,S._)(m||(m=x(["{}"]))));return void 0!==t&&R(e,r,t),r}function R(e,t,r){Object.keys(r).forEach((r=>e.assign((0,S._)(g||(g=x(["","",""])),t,(0,S.getProperty)(r)),!0)))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(k(e,t),!C(t,e.self.RULES.all))},t.checkUnknownRules=k,t.schemaHasRules=C,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function(e,t,r,a){let{topSchemaRef:i,schemaPath:s}=e;if(!a){if("number"==typeof t||"boolean"==typeof t)return t;if("string"==typeof t)return(0,S._)(n||(n=x(["",""])),t)}return(0,S._)(o||(o=x(["","","",""])),i,s,(0,S.getProperty)(r))},t.unescapeFragment=function(e){return _(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(E(e))},t.escapeJsonPointer=E,t.unescapeJsonPointer=_,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:P({mergeNames:(e,t,r)=>e.if((0,S._)(a||(a=x([""," !== true && "," !== undefined"])),r,t),(()=>{e.if((0,S._)(i||(i=x([""," === true"])),t),(()=>e.assign(r,!0)),(()=>e.assign(r,(0,S._)(s||(s=x([""," || {}"])),r)).code((0,S._)(l||(l=x(["Object.assign(",", ",")"])),r,t))))})),mergeToName:(e,t,r)=>e.if((0,S._)(c||(c=x([""," !== true"])),r),(()=>{!0===t?e.assign(r,!0):(e.assign(r,(0,S._)(u||(u=x([""," || {}"])),r)),R(e,r,t))})),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:j}),items:P({mergeNames:(e,t,r)=>e.if((0,S._)(d||(d=x([""," !== true && "," !== undefined"])),r,t),(()=>e.assign(r,(0,S._)(f||(f=x([""," === true ? true : "," > "," ? "," : ",""])),t,r,t,r,t)))),mergeToName:(e,t,r)=>e.if((0,S._)(p||(p=x([""," !== true"])),r),(()=>e.assign(r,!0===t||(0,S._)(h||(h=x([""," > "," ? "," : ",""])),r,t,r,t)))),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=j,t.setEvaluated=R;const O={};var N;function T(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.opts.strictSchema;if(r){if(t="strict mode: ".concat(t),!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:O[t.code]||(O[t.code]=new A._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(N=t.Type||(t.Type={})),t.getErrorPath=function(e,t,r){if(e instanceof S.Name){const n=t===N.Num;return r?n?(0,S._)(v||(v=x(['"[" + ',' + "]"'])),e):(0,S._)(y||(y=x(['"[\'" + ',' + "\']"'])),e):n?(0,S._)(b||(b=x(['"/" + ',""])),e):(0,S._)(w||(w=x(['"/" + ','.replace(/~/g, "~0").replace(/\\//g, "~1")'],['"/" + ','.replace(/~/g, "~0").replace(/\\\\//g, "~1")'])),e)}return r?(0,S.getProperty)(e).toString():"/"+E(e)},t.checkStrictMode=T},5706:(e,t)=>{"use strict";function r(e,t){return t.rules.some((t=>n(e,t)))}function n(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some((t=>void 0!==e[t])))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function(e,t){let{schema:n,self:o}=e;const a=o.RULES.types[t];return a&&!0!==a&&r(n,a)},t.shouldUseGroup=r,t.shouldUseRule=n},9544:(e,t,r)=>{"use strict";var n,o=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const a=r(9773),i=r(8494),s=r(1e3),l={message:"boolean schema is false"};function c(e,t){const{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,a.reportError)(o,l,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:a}=e;!1===r?c(e,!1):"object"==typeof r&&!0===r.$async?t.return(s.default.data):(t.assign((0,i._)(n||(n=o(["",".errors"])),a),null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),c(e)):r.var(t,!0)}},7839:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P,j,R,O,N,T,I,M,F=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const D=r(9675),z=r(5706),L=r(9773),B=r(8494),$=r(1646);var W;function V(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(D.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(W=t.DataType||(t.DataType={})),t.getSchemaTypes=function(e){const t=V(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=V,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:C,opts:E}=e,_=function(e,t){return t?e.filter((e=>U.has(e)||"array"===t&&"array"===e)):[]}(t,E.coerceTypes),P=t.length>0&&!(0===_.length&&1===t.length&&(0,z.schemaHasRulesForType)(e,t[0]));if(P){const P=q(t,C,E.strictNumbers,W.Wrong);r.if(P,(()=>{_.length?function(e,t,r){const{gen:C,data:E,opts:_}=e,P=C.let("dataType",(0,B._)(n||(n=F(["typeof ",""])),E)),j=C.let("coerced",(0,B._)(o||(o=F(["undefined"]))));"array"===_.coerceTypes&&C.if((0,B._)(a||(a=F([""," == 'object' && Array.isArray(",") && ",".length == 1"])),P,E,E),(()=>C.assign(E,(0,B._)(i||(i=F(["","[0]"])),E)).assign(P,(0,B._)(s||(s=F(["typeof ",""])),E)).if(q(t,E,_.strictNumbers),(()=>C.assign(j,E)))));C.if((0,B._)(l||(l=F([""," !== undefined"])),j));for(const n of r)(U.has(n)||"array"===n&&"array"===_.coerceTypes)&&R(n);function R(e){switch(e){case"string":return void C.elseIf((0,B._)(u||(u=F(["",' == "number" || ',' == "boolean"'])),P,P)).assign(j,(0,B._)(d||(d=F(['"" + ',""])),E)).elseIf((0,B._)(f||(f=F([""," === null"])),E)).assign(j,(0,B._)(p||(p=F(['""']))));case"number":return void C.elseIf((0,B._)(h||(h=F(["",' == "boolean" || '," === null\n || (",' == "string" && '," && "," == +",")"])),P,E,P,E,E,E)).assign(j,(0,B._)(m||(m=F(["+",""])),E));case"integer":return void C.elseIf((0,B._)(g||(g=F(["",' === "boolean" || '," === null\n || (",' === "string" && '," && "," == +"," && !("," % 1))"])),P,E,P,E,E,E,E)).assign(j,(0,B._)(v||(v=F(["+",""])),E));case"boolean":return void C.elseIf((0,B._)(y||(y=F(["",' === "false" || '," === 0 || "," === null"])),E,E,E)).assign(j,!1).elseIf((0,B._)(b||(b=F(["",' === "true" || '," === 1"])),E,E)).assign(j,!0);case"null":return C.elseIf((0,B._)(w||(w=F(["",' === "" || '," === 0 || "," === false"])),E,E,E)),void C.assign(j,null);case"array":C.elseIf((0,B._)(x||(x=F(["",' === "string" || ',' === "number"\n || ',' === "boolean" || '," === null"])),P,P,P,E)).assign(j,(0,B._)(S||(S=F(["[","]"])),E))}}C.else(),K(e),C.endIf(),C.if((0,B._)(c||(c=F([""," !== undefined"])),j),(()=>{C.assign(E,j),function(e,t){let{gen:r,parentData:n,parentDataProperty:o}=e;r.if((0,B._)(A||(A=F([""," !== undefined"])),n),(()=>r.assign((0,B._)(k||(k=F(["","[","]"])),n,o),t)))}(e,j)}))}(e,t,_):K(e)}))}return P};const U=new Set(["string","number","integer","boolean","null"]);function H(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:W.Correct;const o=n===W.Correct?B.operators.EQ:B.operators.NEQ;let a;switch(e){case"null":return(0,B._)(C||(C=F([""," "," null"])),t,o);case"array":a=(0,B._)(E||(E=F(["Array.isArray(",")"])),t);break;case"object":a=(0,B._)(_||(_=F([""," && typeof ",' == "object" && !Array.isArray(',")"])),t,t,t);break;case"integer":a=i((0,B._)(P||(P=F(["!("," % 1) && !isNaN(",")"])),t,t));break;case"number":a=i();break;default:return(0,B._)(j||(j=F(["typeof "," "," ",""])),t,o,e)}return n===W.Correct?a:(0,B.not)(a);function i(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:B.nil;return(0,B.and)((0,B._)(R||(R=F(["typeof ",' == "number"'])),t),e,r?(0,B._)(O||(O=F(["isFinite(",")"])),t):B.nil)}}function q(e,t,r,n){if(1===e.length)return H(e[0],t,r,n);let o;const a=(0,$.toHash)(e);if(a.array&&a.object){const e=(0,B._)(N||(N=F(["typeof ",' != "object"'])),t);o=a.null?e:(0,B._)(T||(T=F(["!"," || ",""])),t,e),delete a.null,delete a.array,delete a.object}else o=B.nil;a.number&&delete a.integer;for(const i in a)o=(0,B.and)(o,H(i,t,r,n));return o}t.checkDataType=H,t.checkDataTypes=q;const G={message:e=>{let{schema:t}=e;return"must be ".concat(t)},params:e=>{let{schema:t,schemaValue:r}=e;return"string"==typeof t?(0,B._)(I||(I=F(["{type: ","}"])),t):(0,B._)(M||(M=F(["{type: ","}"])),r)}};function K(e){const t=function(e){const{gen:t,data:r,schema:n}=e,o=(0,$.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}(e);(0,L.reportError)(t,G)}t.reportTypeError=K},1677:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const l=r(8494),c=r(1646);function u(e,t,r){const{gen:u,compositeRule:d,data:f,opts:p}=e;if(void 0===r)return;const h=(0,l._)(n||(n=s(["","",""])),f,(0,l.getProperty)(t));if(d)return void(0,c.checkStrictMode)(e,"default is ignored for: ".concat(h));let m=(0,l._)(o||(o=s([""," === undefined"])),h);"empty"===p.useDefaults&&(m=(0,l._)(a||(a=s([""," || "," === null || ",' === ""'])),m,h,h)),u.if(m,(0,l._)(i||(i=s([""," = ",""])),h,(0,l.stringify)(r)))}t.assignDefaults=function(e,t){const{properties:r,items:n}=e.schema;if("object"===t&&r)for(const o in r)u(e,o,r[o].default);else"array"===t&&Array.isArray(n)&&n.forEach(((t,r)=>u(e,r,t.default)))}},7683:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w,x,S,A,k,C,E,_,P,j,R,O,N,T,I,M,F,D,z,L,B,$,W=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const V=r(9544),U=r(7839),H=r(5706),q=r(7839),G=r(1677),K=r(5264),X=r(8414),Q=r(8494),Y=r(1e3),J=r(2228),Z=r(1646),ee=r(9773);function te(e,t){let{gen:r,validateName:v,schema:y,schemaEnv:b,opts:w}=e;w.code.es5?r.func(v,(0,Q._)(n||(n=W(["",", ",""])),Y.default.data,Y.default.valCxt),b.$async,(()=>{r.code((0,Q._)(o||(o=W(['"use strict"; ',""])),re(y,w))),function(e,t){e.if(Y.default.valCxt,(()=>{e.var(Y.default.instancePath,(0,Q._)(l||(l=W(["",".",""])),Y.default.valCxt,Y.default.instancePath)),e.var(Y.default.parentData,(0,Q._)(c||(c=W(["",".",""])),Y.default.valCxt,Y.default.parentData)),e.var(Y.default.parentDataProperty,(0,Q._)(u||(u=W(["",".",""])),Y.default.valCxt,Y.default.parentDataProperty)),e.var(Y.default.rootData,(0,Q._)(d||(d=W(["",".",""])),Y.default.valCxt,Y.default.rootData)),t.dynamicRef&&e.var(Y.default.dynamicAnchors,(0,Q._)(f||(f=W(["",".",""])),Y.default.valCxt,Y.default.dynamicAnchors))}),(()=>{e.var(Y.default.instancePath,(0,Q._)(p||(p=W(['""'])))),e.var(Y.default.parentData,(0,Q._)(h||(h=W(["undefined"])))),e.var(Y.default.parentDataProperty,(0,Q._)(m||(m=W(["undefined"])))),e.var(Y.default.rootData,Y.default.data),t.dynamicRef&&e.var(Y.default.dynamicAnchors,(0,Q._)(g||(g=W(["{}"]))))}))}(r,w),r.code(t)})):r.func(v,(0,Q._)(a||(a=W(["",", ",""])),Y.default.data,function(e){return(0,Q._)(i||(i=W(["{",'="", ',", ",", ","=","","}={}"])),Y.default.instancePath,Y.default.parentData,Y.default.parentDataProperty,Y.default.rootData,Y.default.data,e.dynamicRef?(0,Q._)(s||(s=W([", ","={}"])),Y.default.dynamicAnchors):Q.nil)}(w)),b.$async,(()=>r.code(re(y,w)).code(t)))}function re(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,Q._)(k||(k=W(["/*# sourceURL="," */"])),r):Q.nil}function ne(e,t){ae(e)&&(ie(e),oe(e))?function(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&le(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,J.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const a=n.const("_errs",Y.default.errors);se(e,a),n.var(t,(0,Q._)(C||(C=W([""," === ",""])),a,Y.default.errors))}(e,t):(0,V.boolOrEmptySchema)(e,t)}function oe(e){let{schema:t,self:r}=e;if("boolean"==typeof t)return!t;for(const n in t)if(r.RULES.all[n])return!0;return!1}function ae(e){return"boolean"!=typeof e.schema}function ie(e){(0,Z.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Z.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn('$ref: keywords ignored in schema at path "'.concat(r,'"'))}(e)}function se(e,t){if(e.opts.jtd)return ce(e,[],!1,t);const r=(0,U.getSchemaTypes)(e.schema);ce(e,r,!(0,U.coerceAndCheckDataType)(e,r),t)}function le(e){let{gen:t,schemaEnv:r,schema:n,errSchemaPath:o,opts:a}=e;const i=n.$comment;if(!0===a.$comment)t.code((0,Q._)(E||(E=W(["",".logger.log(",")"])),Y.default.self,i));else if("function"==typeof a.$comment){const e=(0,Q.str)(_||(_=W(["","/$comment"])),o),n=t.scopeValue("root",{ref:r.root});t.code((0,Q._)(P||(P=W(["",".opts.$comment(",", ",", ",".schema)"])),Y.default.self,i,e,n))}}function ce(e,t,r,n){const{gen:o,schema:a,data:i,allErrors:s,opts:l,self:c}=e,{RULES:u}=c;function d(c){(0,H.shouldUseGroup)(a,c)&&(c.type?(o.if((0,q.checkDataType)(c.type,i,l.strictNumbers)),ue(e,c),1===t.length&&t[0]===c.type&&r&&(o.else(),(0,q.reportTypeError)(e)),o.endIf()):ue(e,c),s||o.if((0,Q._)(M||(M=W([""," === ",""])),Y.default.errors,n||0)))}!a.$ref||!l.ignoreKeywordsWithRef&&(0,Z.schemaHasRulesButRef)(a,u)?(l.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach((t=>{fe(e.dataTypes,t)||pe(e,'type "'.concat(t,'" not allowed by context "').concat(e.dataTypes.join(","),'"'))})),function(e,t){const r=[];for(const n of e.dataTypes)fe(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&pe(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const r=e.self.RULES.all;for(const n in r){const o=r[n];if("object"==typeof o&&(0,H.shouldUseRule)(e.schema,o)){const{type:r}=o.definition;r.length&&!r.some((e=>de(t,e)))&&pe(e,'missing type "'.concat(r.join(","),'" for keyword "').concat(n,'"'))}}}(e,e.dataTypes)}(e,t),o.block((()=>{for(const e of u.rules)d(e);d(u.post)}))):o.block((()=>me(e,"$ref",u.all.$ref.definition)))}function ue(e,t){const{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,G.assignDefaults)(e,t.type),r.block((()=>{for(const r of t.rules)(0,H.shouldUseRule)(n,r)&&me(e,r.keyword,r.definition,t.type)}))}function de(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function fe(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function pe(e,t){const r=e.schemaEnv.baseId+e.errSchemaPath;t+=' at "'.concat(r,'" (strictTypes)'),(0,Z.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){ae(e)&&(ie(e),oe(e))?function(e){const{schema:t,opts:r,gen:n}=e;te(e,(()=>{r.$comment&&t.$comment&&le(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,Z.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,Q._)(v||(v=W(["",".evaluated"])),r)),t.if((0,Q._)(y||(y=W(["",".dynamicProps"])),e.evaluated),(()=>t.assign((0,Q._)(b||(b=W(["",".props"])),e.evaluated),(0,Q._)(w||(w=W(["undefined"])))))),t.if((0,Q._)(x||(x=W(["",".dynamicItems"])),e.evaluated),(()=>t.assign((0,Q._)(S||(S=W(["",".items"])),e.evaluated),(0,Q._)(A||(A=W(["undefined"]))))))}(e),se(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:a}=e;r.$async?t.if((0,Q._)(j||(j=W([""," === 0"])),Y.default.errors),(()=>t.return(Y.default.data)),(()=>t.throw((0,Q._)(R||(R=W(["new ","(",")"])),o,Y.default.vErrors)))):(t.assign((0,Q._)(O||(O=W(["",".errors"])),n),Y.default.vErrors),a.unevaluated&&function(e){let{gen:t,evaluated:r,props:n,items:o}=e;n instanceof Q.Name&&t.assign((0,Q._)(T||(T=W(["",".props"])),r),n);o instanceof Q.Name&&t.assign((0,Q._)(I||(I=W(["",".items"])),r),o)}(e),t.return((0,Q._)(N||(N=W([""," === 0"])),Y.default.errors)))}(e)}))}(e):te(e,(()=>(0,V.topBoolOrEmptySchema)(e)))};class he{constructor(e,t,r){if((0,K.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Z.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",ye(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,K.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error("".concat(r," value must be ").concat(JSON.stringify(t.schemaType)));("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,t,r){this.failResult((0,Q.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,Q.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail((0,Q._)(F||(F=W([""," !== undefined && (",")"])),t,(0,Q.or)(this.invalid$data(),e)))}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?ee.reportExtraError:ee.reportError)(this,this.def.error,t)}$dataError(){(0,ee.reportError)(this,this.def.$dataError||ee.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,ee.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Q.nil;this.gen.block((()=>{this.check$data(e,r),t()}))}check$data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Q.nil,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Q.nil;if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:o,def:a}=this;r.if((0,Q.or)((0,Q._)(D||(D=W([""," === undefined"])),n),t)),e!==Q.nil&&r.assign(e,!0),(o.length||a.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==Q.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:o}=this;return(0,Q.or)(function(){if(r.length){if(!(t instanceof Q.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return(0,Q._)(z||(z=W(["",""])),(0,q.checkDataTypes)(e,t,o.opts.strictNumbers,q.DataType.Wrong))}return Q.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,Q._)(L||(L=W(["!","(",")"])),r,t)}return Q.nil}())}subschema(e,t){const r=(0,X.getSubschema)(this.it,e);(0,X.extendSubschemaData)(r,this.it,e),(0,X.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return ne(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=Z.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=Z.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,(()=>this.mergeEvaluated(e,Q.Name))),!0}}function me(e,t,r,n){const o=new he(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,K.funcKeywordCode)(o,r):"macro"in r?(0,K.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,K.funcKeywordCode)(o,r)}t.KeywordCxt=he;const ge=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ye(e,t){let r,n,{dataLevel:o,dataNames:a,dataPathArr:i}=t;if(""===e)return Y.default.rootData;if("/"===e[0]){if(!ge.test(e))throw new Error("Invalid JSON-pointer: ".concat(e));r=e,n=Y.default.rootData}else{const t=ve.exec(e);if(!t)throw new Error("Invalid JSON-pointer: ".concat(e));const s=+t[1];if(r=t[2],"#"===r){if(s>=o)throw new Error(c("property/index",s));return i[o-s]}if(s>o)throw new Error(c("data",s));if(n=a[o-s],!r)return n}let s=n;const l=r.split("/");for(const u of l)u&&(n=(0,Q._)(B||(B=W(["","",""])),n,(0,Q.getProperty)((0,Z.unescapeJsonPointer)(u))),s=(0,Q._)($||($=W([""," && ",""])),s,n));return s;function c(e,t){return"Cannot access ".concat(e," ").concat(t," levels up, current level is ").concat(o)}}t.getData=ye},5264:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const h=r(8494),m=r(1e3),g=r(8518),v=r(9773);function y(e){const{gen:t,data:r,it:n}=e;t.if(n.parentData,(()=>t.assign(r,(0,h._)(c||(c=p(["","[","]"])),n.parentData,n.parentDataProperty))))}function b(e,t,r){if(void 0===r)throw new Error('keyword "'.concat(t,'" failed to compile'));return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,h.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:n,schema:o,parentSchema:a,it:i}=e,s=t.macro.call(i.self,o,a,i),l=b(r,n,s);!1!==i.opts.validateSchema&&i.self.validateSchema(s,!0);const c=r.name("valid");e.subschema({schema:s,schemaPath:h.nil,errSchemaPath:"".concat(i.errSchemaPath,"/").concat(n),topSchemaRef:l,compositeRule:!0},c),e.pass(c,(()=>e.error(!0)))},t.funcKeywordCode=function(e,t){var r;const{gen:c,keyword:w,schema:x,parentSchema:S,$data:A,it:k}=e;!function(e,t){let{schemaEnv:r}=e;if(t.async&&!r.$async)throw new Error("async keyword in sync schema")}(k,t);const C=!A&&t.compile?t.compile.call(k.self,x,S,k):t.validate,E=b(c,w,C),_=c.let("valid");function P(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.async?(0,h._)(s||(s=p(["await "]))):h.nil;const n=k.opts.passContext?m.default.this:m.default.self,o=!("compile"in t&&!A||!1===t.schema);c.assign(_,(0,h._)(l||(l=p(["","",""])),r,(0,g.callValidateCode)(e,E,n,o)),t.modifying)}function j(e){var r;c.if((0,h.not)(null!==(r=t.valid)&&void 0!==r?r:_),e)}e.block$data(_,(function(){if(!1===t.errors)P(),t.modifying&&y(e),j((()=>e.error()));else{const r=t.async?function(){const e=c.let("ruleErrs",null);return c.try((()=>P((0,h._)(n||(n=p(["await "]))))),(t=>c.assign(_,!1).if((0,h._)(o||(o=p([""," instanceof ",""])),t,k.ValidationError),(()=>c.assign(e,(0,h._)(a||(a=p(["",".errors"])),t))),(()=>c.throw(t))))),e}():function(){const e=(0,h._)(i||(i=p(["",".errors"])),E);return c.assign(e,null),P(h.nil),e}();t.modifying&&y(e),j((()=>function(e,t){const{gen:r}=e;r.if((0,h._)(u||(u=p(["Array.isArray(",")"])),t),(()=>{r.assign(m.default.vErrors,(0,h._)(d||(d=p([""," === null ? "," : ",".concat(",")"])),m.default.vErrors,t,m.default.vErrors,t)).assign(m.default.errors,(0,h._)(f||(f=p(["",".length"])),m.default.vErrors)),(0,v.extendErrors)(e)}),(()=>e.error()))}(e,r)))}})),e.ok(null!==(r=t.valid)&&void 0!==r?r:_)},t.validSchemaType=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return!t.length||t.some((t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&"undefined"==typeof e))},t.validateKeywordUsage=function(e,t,r){let{schema:n,opts:o,self:a,errSchemaPath:i}=e;if(Array.isArray(t.keyword)?!t.keyword.includes(r):t.keyword!==r)throw new Error("ajv implementation error");const s=t.dependencies;if(null===s||void 0===s?void 0:s.some((e=>!Object.prototype.hasOwnProperty.call(n,e))))throw new Error("parent schema must have dependencies of ".concat(r,": ").concat(s.join(",")));if(t.validateSchema){if(!t.validateSchema(n[r])){const e='keyword "'.concat(r,'" value is invalid at path "').concat(i,'": ')+a.errorsText(t.validateSchema.errors);if("log"!==o.validateSchema)throw new Error(e);a.logger.error(e)}}}},8414:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const c=r(8494),u=r(1646);t.getSubschema=function(e,t){let{keyword:r,schemaProp:a,schema:i,schemaPath:s,errSchemaPath:d,topSchemaRef:f}=t;if(void 0!==r&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){const t=e.schema[r];return void 0===a?{schema:t,schemaPath:(0,c._)(n||(n=l(["","",""])),e.schemaPath,(0,c.getProperty)(r)),errSchemaPath:"".concat(e.errSchemaPath,"/").concat(r)}:{schema:t[a],schemaPath:(0,c._)(o||(o=l(["","","",""])),e.schemaPath,(0,c.getProperty)(r),(0,c.getProperty)(a)),errSchemaPath:"".concat(e.errSchemaPath,"/").concat(r,"/").concat((0,u.escapeFragment)(a))}}if(void 0!==i){if(void 0===s||void 0===d||void 0===f)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:s,topSchemaRef:f,errSchemaPath:d}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,r){let{dataProp:n,dataPropType:o,data:d,dataTypes:f,propertyName:p}=r;if(void 0!==d&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=t;if(void 0!==n){const{errorPath:r,dataPathArr:d,opts:f}=t;m(h.let("data",(0,c._)(a||(a=l(["","",""])),t.data,(0,c.getProperty)(n)),!0)),e.errorPath=(0,c.str)(i||(i=l(["","",""])),r,(0,u.getErrorPath)(n,o,f.jsPropertySyntax)),e.parentDataProperty=(0,c._)(s||(s=l(["",""])),n),e.dataPathArr=[...d,e.parentDataProperty]}if(void 0!==d){m(d instanceof c.Name?d:h.let("data",d,!0)),void 0!==p&&(e.propertyName=p)}function m(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}f&&(e.dataTypes=f)},t.extendSubschemaMode=function(e,t){let{jtdDiscriminator:r,jtdMetadata:n,compositeRule:o,createErrors:a,allErrors:i}=t;void 0!==o&&(e.compositeRule=o),void 0!==a&&(e.createErrors=a),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=r,e.jtdMetadata=n}},9899:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var n=r(7683);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return n.KeywordCxt}});var o=r(8494);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return o.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return o.CodeGen}});const a=r(2323),i=r(8723),s=r(9675),l=r(7804),c=r(8494),u=r(2228),d=r(7839),f=r(1646),p=r(7301),h=r(2707),m=(e,t)=>new RegExp(e,t);m.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function w(e){var t,r,n,o,a,i,s,l,c,u,d,f,p,g,v,y,b,w,x,S,A,k,C,E,_;const P=e.strict,j=null===(t=e.code)||void 0===t?void 0:t.optimize,R=!0===j||void 0===j?1:j||0,O=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:m,N=null!==(o=e.uriResolver)&&void 0!==o?o:h.default;return{strictSchema:null===(i=null!==(a=e.strictSchema)&&void 0!==a?a:P)||void 0===i||i,strictNumbers:null===(l=null!==(s=e.strictNumbers)&&void 0!==s?s:P)||void 0===l||l,strictTypes:null!==(u=null!==(c=e.strictTypes)&&void 0!==c?c:P)&&void 0!==u?u:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:P)&&void 0!==f?f:"log",strictRequired:null!==(g=null!==(p=e.strictRequired)&&void 0!==p?p:P)&&void 0!==g&&g,code:e.code?{...e.code,optimize:R,regExp:O}:{optimize:R,regExp:O},loopRequired:null!==(v=e.loopRequired)&&void 0!==v?v:200,loopEnum:null!==(y=e.loopEnum)&&void 0!==y?y:200,meta:null===(b=e.meta)||void 0===b||b,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(x=e.inlineRefs)||void 0===x||x,schemaId:null!==(S=e.schemaId)&&void 0!==S?S:"$id",addUsedSchema:null===(A=e.addUsedSchema)||void 0===A||A,validateSchema:null===(k=e.validateSchema)||void 0===k||k,validateFormats:null===(C=e.validateFormats)||void 0===C||C,unicodeRegExp:null===(E=e.unicodeRegExp)||void 0===E||E,int32range:null===(_=e.int32range)||void 0===_||_,uriResolver:N}}class x{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...w(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:v,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,y,e,"NOT SUPPORTED"),S.call(this,b,e,"DEPRECATED","warn"),this._metaOpts=_.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=p;"id"===r&&(n={...p},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error('no schema with key or ref "'.concat(e,'"'))}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await o.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function o(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await l.call(this,t.missingSchema),a.call(this,e)}}function s(e){let{missingSchema:t,missingRef:r}=e;if(this.refs[t])throw new Error("AnySchema ".concat(t," is loaded but ").concat(r," cannot be resolved"))}async function l(e){const r=await c.call(this,e);this.refs[e]||await o.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function c(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r){let n,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema;if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);return this}if("object"===typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error("schema ".concat(t," must be string"))}return t=(0,u.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!0),this}addMetaSchema(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.opts.validateSchema;return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=A.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new l.SchemaEnv({schema:{},schemaId:r});if(t=l.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=A.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,u.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(R.call(this,r,t),!t)return(0,f.eachItem)(r,(e=>O.call(this,e))),this;T.call(this,t);const n={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,f.eachItem)(r,0===n.type.length?e=>O.call(this,e,n):e=>n.type.forEach((t=>O.call(this,e,n,t)))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex((t=>t.keyword===e));t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.errors,{separator:t=", ",dataVar:r="data"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e&&0!==e.length?e.map((e=>"".concat(r).concat(e.instancePath," ").concat(e.message))).reduce(((e,r)=>e+t+r)):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,a=o[e];n&&a&&(o[e]=M(a))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r){let n,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:this.opts.validateSchema,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.opts.addUsedSchema;const{schemaId:i}=this.opts;if("object"==typeof e)n=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let s=this._cache.get(e);if(void 0!==s)return s;r=(0,u.normalizeId)(n||r);const c=u.getSchemaRefs.call(this,e,r);return s=new l.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:c}),this._cache.set(s.schema,s),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=s),o&&this.validateSchema(e,!0),s}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error('schema with key or id "'.concat(e,'" already exists'))}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):l.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{l.compileSchema.call(this,e)}finally{this.opts=t}}}function S(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"error";for(const o in e){const a=o;a in t&&this.logger[n]("".concat(r,": option ").concat(o,". ").concat(e[a]))}}function A(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function C(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function _(){const e={...this.opts};for(const t of g)delete e[t];return e}t.default=x,x.ValidationError=a.default,x.MissingRefError=i.default;const P={log(){},warn(){},error(){}};const j=/^[a-z_$][a-z0-9_$:-]*$/i;function R(e,t){const{RULES:r}=this;if((0,f.eachItem)(e,(e=>{if(r.keywords[e])throw new Error("Keyword ".concat(e," is already defined"));if(!j.test(e))throw new Error("Keyword ".concat(e," has invalid name"))})),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function O(e,t,r){var n;const o=null===t||void 0===t?void 0:t.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:a}=this;let i=o?a.post:a.rules.find((e=>{let{type:t}=e;return t===r}));if(i||(i={type:r,rules:[]},a.rules.push(i)),a.keywords[e]=!0,!t)return;const s={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?N.call(this,i,s,t.before):i.rules.push(s),a.all[e]=s,null===(n=t.implements)||void 0===n||n.forEach((e=>this.addKeyword(e)))}function N(e,t,r){const n=e.rules.findIndex((e=>e.keyword===r));n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn("rule ".concat(r," is not defined")))}function T(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=M(t)),e.validateSchema=this.compile(t,!0))}const I={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function M(e){return{anyOf:[e,I]}}},4281:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(122);n.code='require("ajv/dist/runtime/equal").default',t.default=n},5784:(e,t)=>{"use strict";function r(e){const t=e.length;let r,n=0,o=0;for(;o=55296&&r<=56319&&o{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9392);n.code='require("ajv/dist/runtime/uri").default',t.default=n},2323:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},2182:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const c=r(8494),u=r(1646),d={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:e=>{let{params:{len:t}}=e;return(0,c.str)(n||(n=l(["must NOT have more than "," items"])),t)},params:e=>{let{params:{len:t}}=e;return(0,c._)(o||(o=l(["{limit: ","}"])),t)}},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?f(e,n):(0,u.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function f(e,t){const{gen:r,schema:n,data:o,keyword:d,it:f}=e;f.items=!0;const p=r.const("len",(0,c._)(a||(a=l(["",".length"])),o));if(!1===n)e.setParams({len:t.length}),e.pass((0,c._)(i||(i=l([""," <= ",""])),p,t.length));else if("object"==typeof n&&!(0,u.alwaysValidSchema)(f,n)){const n=r.var("valid",(0,c._)(s||(s=l([""," <= ",""])),p,t.length));r.if((0,c.not)(n),(()=>function(n){r.forRange("i",t.length,p,(t=>{e.subschema({keyword:d,dataProp:t,dataPropType:u.Type.Num},n),f.allErrors||r.if((0,c.not)(n),(()=>r.break()))}))}(n))),e.ok(n)}}t.validateAdditionalItems=f,t.default=d},5341:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(8518),u=r(8494),d=r(1e3),f=r(1646),p={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:e=>{let{params:t}=e;return(0,u._)(n||(n=l(["{additionalProperty: ","}"])),t.additionalProperty)}},code(e){const{gen:t,schema:r,parentSchema:n,data:p,errsCount:h,it:m}=e;if(!h)throw new Error("ajv implementation error");const{allErrors:g,opts:v}=m;if(m.props=!0,"all"!==v.removeAdditional&&(0,f.alwaysValidSchema)(m,r))return;const y=(0,c.allSchemaProperties)(n.properties),b=(0,c.allSchemaProperties)(n.patternProperties);function w(e){t.code((0,u._)(s||(s=l(["delete ","[","]"])),p,e))}function x(n){if("all"===v.removeAdditional||v.removeAdditional&&!1===r)w(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(g||t.break());if("object"==typeof r&&!(0,f.alwaysValidSchema)(m,r)){const r=t.name("valid");"failing"===v.removeAdditional?(S(n,r,!1),t.if((0,u.not)(r),(()=>{e.reset(),w(n)}))):(S(n,r),g||t.if((0,u.not)(r),(()=>t.break())))}}}function S(t,r,n){const o={keyword:"additionalProperties",dataProp:t,dataPropType:f.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(o,r)}t.forIn("key",p,(r=>{y.length||b.length?t.if(function(r){let o;if(y.length>8){const e=(0,f.schemaRefOrVal)(m,n.properties,"properties");o=(0,c.isOwnProperty)(t,e,r)}else o=y.length?(0,u.or)(...y.map((e=>(0,u._)(a||(a=l([""," === ",""])),r,e)))):u.nil;return b.length&&(o=(0,u.or)(o,...b.map((t=>(0,u._)(i||(i=l(["",".test(",")"])),(0,c.usePattern)(e,t),r))))),(0,u.not)(o)}(r),(()=>x(r))):x(r)})),e.ok((0,u._)(o||(o=l([""," === ",""])),h,d.default.errors))}};t.default=p},3943:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1646),o={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const a=t.name("valid");r.forEach(((t,r)=>{if((0,n.alwaysValidSchema)(o,t))return;const i=e.subschema({keyword:"allOf",schemaProp:r},a);e.ok(a),e.mergeEvaluated(i)}))}};t.default=o},7066:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(8518).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=n},2064:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const g=r(8494),v=r(1646),y={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:e=>{let{params:{min:t,max:r}}=e;return void 0===r?(0,g.str)(n||(n=m(["must contain at least "," valid item(s)"])),t):(0,g.str)(o||(o=m(["must contain at least "," and no more than "," valid item(s)"])),t,r)},params:e=>{let{params:{min:t,max:r}}=e;return void 0===r?(0,g._)(a||(a=m(["{minContains: ","}"])),t):(0,g._)(i||(i=m(["{minContains: ",", maxContains: ","}"])),t,r)}},code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:a}=e;let i,y;const{minContains:b,maxContains:w}=n;a.opts.next?(i=void 0===b?1:b,y=w):i=1;const x=t.const("len",(0,g._)(s||(s=m(["",".length"])),o));if(e.setParams({min:i,max:y}),void 0===y&&0===i)return void(0,v.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==y&&i>y)return(0,v.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,v.alwaysValidSchema)(a,r)){let t=(0,g._)(l||(l=m([""," >= ",""])),x,i);return void 0!==y&&(t=(0,g._)(c||(c=m([""," && "," <= ",""])),t,x,y)),void e.pass(t)}a.items=!0;const S=t.name("valid");function A(){const e=t.name("_valid"),r=t.let("count",0);k(e,(()=>t.if(e,(()=>function(e){t.code((0,g._)(d||(d=m(["","++"])),e)),void 0===y?t.if((0,g._)(f||(f=m([""," >= ",""])),e,i),(()=>t.assign(S,!0).break())):(t.if((0,g._)(p||(p=m([""," > ",""])),e,y),(()=>t.assign(S,!1).break())),1===i?t.assign(S,!0):t.if((0,g._)(h||(h=m([""," >= ",""])),e,i),(()=>t.assign(S,!0))))}(r)))))}function k(r,n){t.forRange("i",0,x,(t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:v.Type.Num,compositeRule:!0},r),n()}))}void 0===y&&1===i?k(S,(()=>t.if(S,(()=>t.break())))):0===i?(t.let(S,!0),void 0!==y&&t.if((0,g._)(u||(u=m(["",".length > 0"])),o),A)):(t.let(S,!1),A()),e.result(S,(()=>e.reset()))}};t.default=y},9344:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const s=r(8494),l=r(1646),c=r(8518);t.error={message:e=>{let{params:{property:t,depsCount:r,deps:o}}=e;const a=1===r?"property":"properties";return(0,s.str)(n||(n=i(["must have "," "," when property "," is present"])),a,o,t)},params:e=>{let{params:{property:t,depsCount:r,deps:n,missingProperty:a}}=e;return(0,s._)(o||(o=i(["{property: ",",\n missingProperty: ",",\n depsCount: ",",\n deps: ","}"])),t,a,r,n)}};const u={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,r]=function(e){let{schema:t}=e;const r={},n={};for(const o in t){if("__proto__"===o)continue;(Array.isArray(t[o])?r:n)[o]=t[o]}return[r,n]}(e);d(e,t),f(e,r)}};function d(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:r,data:n,it:o}=e;if(0===Object.keys(t).length)return;const l=r.let("missing");for(const u in t){const d=t[u];if(0===d.length)continue;const f=(0,c.propertyInData)(r,n,u,o.opts.ownProperties);e.setParams({property:u,depsCount:d.length,deps:d.join(", ")}),o.allErrors?r.if(f,(()=>{for(const t of d)(0,c.checkReportMissingProp)(e,t)})):(r.if((0,s._)(a||(a=i([""," && (",")"])),f,(0,c.checkMissingProp)(e,d,l))),(0,c.reportMissingProp)(e,l),r.else())}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.schema;const{gen:r,data:n,keyword:o,it:a}=e,i=r.name("valid");for(const s in t)(0,l.alwaysValidSchema)(a,t[s])||(r.if((0,c.propertyInData)(r,n,s,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:o,schemaProp:s},i);e.mergeValidEvaluated(t,i)}),(()=>r.var(i,!0))),e.ok(i))}t.validatePropertyDeps=d,t.validateSchemaDeps=f,t.default=u},7866:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l=r(1646),c={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:e=>{let{params:t}=e;return(0,s.str)(n||(n=i(['must match "','" schema'])),t.ifClause)},params:e=>{let{params:t}=e;return(0,s._)(o||(o=i(["{failingKeyword: ","}"])),t.ifClause)}},code(e){const{gen:t,parentSchema:r,it:n}=e;void 0===r.then&&void 0===r.else&&(0,l.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const o=u(n,"then"),c=u(n,"else");if(!o&&!c)return;const d=t.let("valid",!0),f=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);e.mergeEvaluated(t)}(),e.reset(),o&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(f,p("then",r),p("else",r))}else o?t.if(f,p("then")):t.if((0,s.not)(f),p("else"));function p(r,n){return()=>{const o=e.subschema({keyword:r},f);t.assign(d,f),e.mergeValidEvaluated(o,d),n?t.assign(n,(0,s._)(a||(a=i(["",""])),r)):e.setParams({ifClause:r})}}e.pass(d,(()=>e.error(!0)))}};function u(e,t){const r=e.schema[t];return void 0!==r&&!(0,l.alwaysValidSchema)(e,r)}t.default=c},2021:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(2182),o=r(9721),a=r(4253),i=r(9213),s=r(2064),l=r(9344),c=r(7482),u=r(5341),d=r(2480),f=r(5522),p=r(8144),h=r(7066),m=r(2324),g=r(3943),v=r(7866),y=r(6747);t.default=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const t=[p.default,h.default,m.default,g.default,v.default,y.default,c.default,u.default,l.default,d.default,f.default];return e?t.push(o.default,i.default):t.push(n.default,a.default),t.push(s.default),t}},4253:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const i=r(8494),s=r(1646),l=r(8518),c={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return u(e,"additionalItems",t);r.items=!0,(0,s.alwaysValidSchema)(r,t)||e.ok((0,l.validateArray)(e))}};function u(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.schema;const{gen:l,parentSchema:c,data:u,keyword:d,it:f}=e;!function(e){const{opts:n,errSchemaPath:o}=f,a=r.length,i=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(n.strictTuples&&!i){const e='"'.concat(d,'" is ').concat(a,"-tuple, but minItems or maxItems/").concat(t,' are not specified or different at path "').concat(o,'"');(0,s.checkStrictMode)(f,e,n.strictTuples)}}(c),f.opts.unevaluated&&r.length&&!0!==f.items&&(f.items=s.mergeEvaluated.items(l,r.length,f.items));const p=l.name("valid"),h=l.const("len",(0,i._)(n||(n=a(["",".length"])),u));r.forEach(((t,r)=>{(0,s.alwaysValidSchema)(f,t)||(l.if((0,i._)(o||(o=a([""," > ",""])),h,r),(()=>e.subschema({keyword:d,schemaProp:r,dataProp:r},p))),e.ok(p))}))}t.validateTuple=u,t.default=c},9213:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(8494),s=r(1646),l=r(8518),c=r(2182),u={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:e=>{let{params:{len:t}}=e;return(0,i.str)(n||(n=a(["must NOT have more than "," items"])),t)},params:e=>{let{params:{len:t}}=e;return(0,i._)(o||(o=a(["{limit: ","}"])),t)}},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,(0,s.alwaysValidSchema)(n,t)||(o?(0,c.validateAdditionalItems)(e,o):e.ok((0,l.validateArray)(e)))}};t.default=u},8144:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1646),o={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,n.alwaysValidSchema)(o,r))return void e.fail();const a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=o},2324:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l=r(1646),c={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:e=>{let{params:t}=e;return(0,s._)(n||(n=i(["{passingSchemas: ","}"])),t.passing)}},code(e){const{gen:t,schema:r,parentSchema:n,it:c}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(c.opts.discriminator&&n.discriminator)return;const u=r,d=t.let("valid",!1),f=t.let("passing",null),p=t.name("_valid");e.setParams({passing:f}),t.block((function(){u.forEach(((r,n)=>{let u;(0,l.alwaysValidSchema)(c,r)?t.var(p,!0):u=e.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},p),n>0&&t.if((0,s._)(o||(o=i([""," && ",""])),p,d)).assign(d,!1).assign(f,(0,s._)(a||(a=i(["[",", ","]"])),f,n)).else(),t.if(p,(()=>{t.assign(d,!0),t.assign(f,n),u&&e.mergeEvaluated(u,s.Name)}))}))})),e.result(d,(()=>e.reset()),(()=>e.error(!0)))}};t.default=c},5522:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(8518),s=r(8494),l=r(1646),c=r(1646),u={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:u,parentSchema:d,it:f}=e,{opts:p}=f,h=(0,i.allSchemaProperties)(r),m=h.filter((e=>(0,l.alwaysValidSchema)(f,r[e])));if(0===h.length||m.length===h.length&&(!f.opts.unevaluated||!0===f.props))return;const g=p.strictSchema&&!p.allowMatchingProperties&&d.properties,v=t.name("valid");!0===f.props||f.props instanceof s.Name||(f.props=(0,c.evaluatedPropsToName)(t,f.props));const{props:y}=f;function b(e){for(const t in g)new RegExp(e).test(t)&&(0,l.checkStrictMode)(f,"property ".concat(t," matches pattern ").concat(e," (use allowMatchingProperties)"))}function w(r){t.forIn("key",u,(l=>{t.if((0,s._)(n||(n=a(["",".test(",")"])),(0,i.usePattern)(e,r),l),(()=>{const n=m.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:l,dataPropType:c.Type.Str},v),f.opts.unevaluated&&!0!==y?t.assign((0,s._)(o||(o=a(["","[","]"])),y,l),!0):n||f.allErrors||t.if((0,s.not)(v),(()=>t.break()))}))}))}!function(){for(const e of h)g&&b(e),f.allErrors?w(e):(t.var(v,!0),w(e),t.if(v))}()}};t.default=u},9721:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4253),o={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,n.validateTuple)(e,"items")};t.default=o},2480:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(7683),o=r(8518),a=r(1646),i=r(5341),s={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:s,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===s.additionalProperties&&i.default.code(new n.KeywordCxt(c,i.default,"additionalProperties"));const u=(0,o.allSchemaProperties)(r);for(const n of u)c.definedProperties.add(n);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=a.mergeEvaluated.props(t,(0,a.toHash)(u),c.props));const d=u.filter((e=>!(0,a.alwaysValidSchema)(c,r[e])));if(0===d.length)return;const f=t.name("valid");for(const n of d)p(n)?h(n):(t.if((0,o.propertyInData)(t,l,n,c.opts.ownProperties)),h(n),c.allErrors||t.else().var(f,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(f);function p(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==r[e].default}function h(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},f)}}};t.default=s},7482:(e,t,r)=>{"use strict";var n,o=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const a=r(8494),i=r(1646),s={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:e=>{let{params:t}=e;return(0,a._)(n||(n=o(["{propertyName: ","}"])),t.propertyName)}},code(e){const{gen:t,schema:r,data:n,it:o}=e;if((0,i.alwaysValidSchema)(o,r))return;const s=t.name("valid");t.forIn("key",n,(r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,a.not)(s),(()=>{e.error(!0),o.allErrors||t.break()}))})),e.ok(s)}};t.default=s},6747:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1646),o={keyword:["then","else"],schemaType:["object","boolean"],code(e){let{keyword:t,parentSchema:r,it:o}=e;void 0===r.if&&(0,n.checkStrictMode)(o,'"'.concat(t,'" without "if" is ignored'))}};t.default=o},8518:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const b=r(8494),w=r(1646),x=r(1e3),S=r(1646);function A(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,b._)(a||(a=y(["Object.prototype.hasOwnProperty"])))})}function k(e,t,r){return(0,b._)(i||(i=y(["",".call(",", ",")"])),A(e),t,r)}function C(e,t,r,n){const o=(0,b._)(c||(c=y(["",""," === undefined"])),t,(0,b.getProperty)(r));return n?(0,b.or)(o,(0,b.not)(k(e,t,r))):o}function E(e){return e?Object.keys(e).filter((e=>"__proto__"!==e)):[]}t.checkReportMissingProp=function(e,t){const{gen:r,data:o,it:a}=e;r.if(C(r,o,t,a.opts.ownProperties),(()=>{e.setParams({missingProperty:(0,b._)(n||(n=y(["",""])),t)},!0),e.error()}))},t.checkMissingProp=function(e,t,r){let{gen:n,data:a,it:{opts:i}}=e;return(0,b.or)(...t.map((e=>(0,b.and)(C(n,a,e,i.ownProperties),(0,b._)(o||(o=y([""," = ",""])),r,e)))))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=A,t.isOwnProperty=k,t.propertyInData=function(e,t,r,n){const o=(0,b._)(s||(s=y(["",""," !== undefined"])),t,(0,b.getProperty)(r));return n?(0,b._)(l||(l=y([""," && ",""])),o,k(e,t,r)):o},t.noPropertyInData=C,t.allSchemaProperties=E,t.schemaProperties=function(e,t){return E(t).filter((r=>!(0,w.alwaysValidSchema)(e,t[r])))},t.callValidateCode=function(e,t,r,n){let{schemaCode:o,data:a,it:{gen:i,topSchemaRef:s,schemaPath:l,errorPath:c},it:h}=e;const m=n?(0,b._)(u||(u=y(["",", ",", ","",""])),o,a,s,l):a,g=[[x.default.instancePath,(0,b.strConcat)(x.default.instancePath,c)],[x.default.parentData,h.parentData],[x.default.parentDataProperty,h.parentDataProperty],[x.default.rootData,x.default.rootData]];h.opts.dynamicRef&&g.push([x.default.dynamicAnchors,x.default.dynamicAnchors]);const v=(0,b._)(d||(d=y(["",", ",""])),m,i.object(...g));return r!==b.nil?(0,b._)(f||(f=y(["",".call(",", ",")"])),t,r,v):(0,b._)(p||(p=y(["","(",")"])),t,v)};const _=(0,b._)(h||(h=y(["new RegExp"])));t.usePattern=function(e,t){let{gen:r,it:{opts:n}}=e;const o=n.unicodeRegExp?"u":"",{regExp:a}=n.code,i=a(t,o);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,b._)(m||(m=y(["","(",", ",")"])),"new RegExp"===a.code?_:(0,S.useFunc)(r,a),t,o)})},t.validateArray=function(e){const{gen:t,data:r,keyword:n,it:o}=e,a=t.name("valid");if(o.allErrors){const e=t.let("valid",!0);return i((()=>t.assign(e,!1))),e}return t.var(a,!0),i((()=>t.break())),a;function i(o){const i=t.const("len",(0,b._)(g||(g=y(["",".length"])),r));t.forRange("i",0,i,(r=>{e.subschema({keyword:n,dataProp:r,dataPropType:w.Type.Num},a),t.if((0,b.not)(a),o)}))}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some((e=>(0,w.alwaysValidSchema)(o,e)))&&!o.opts.unevaluated)return;const a=t.let("valid",!1),i=t.name("_valid");t.block((()=>r.forEach(((r,o)=>{const s=e.subschema({keyword:n,schemaProp:o,compositeRule:!0},i);t.assign(a,(0,b._)(v||(v=y([""," || ",""])),a,i));e.mergeValidEvaluated(s,i)||t.if((0,b.not)(a))})))),e.result(a,(()=>e.reset()),(()=>e.error(!0)))}},1406:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},6891:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1406),o=r(3902),a=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",n.default,o.default];t.default=a},3902:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f=r(166).default;Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const p=r(8723),h=r(8518),m=r(8494),g=r(1e3),v=r(7804),y=r(1646),b={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:a,schemaEnv:i,validateName:s,opts:l,self:c}=o,{root:u}=i;if(("#"===r||"#/"===r)&&a===u.baseId)return function(){if(i===u)return x(e,s,i,i.$async);const r=t.scopeValue("root",{ref:u});return x(e,(0,m._)(n||(n=f(["",".validate"])),r),u,u.$async)}();const d=v.resolveRef.call(c,u,a,r);if(void 0===d)throw new p.default(o.opts.uriResolver,a,r);return d instanceof v.SchemaEnv?function(t){const r=w(e,t);x(e,r,t,t.$async)}(d):function(n){const o=t.scopeValue("schema",!0===l.code.source?{ref:n,code:(0,m.stringify)(n)}:{ref:n}),a=t.name("valid"),i=e.subschema({schema:n,dataTypes:[],schemaPath:m.nil,topSchemaRef:o,errSchemaPath:r},a);e.mergeEvaluated(i),e.ok(a)}(d)}};function w(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,m._)(o||(o=f(["",".validate"])),r.scopeValue("wrapper",{ref:t}))}function x(e,t,r,n){const{gen:o,it:p}=e,{allErrors:v,schemaEnv:b,opts:w}=p,x=w.passContext?g.default.this:m.nil;function S(e){const t=(0,m._)(s||(s=f(["",".errors"])),e);o.assign(g.default.vErrors,(0,m._)(l||(l=f([""," === null ? "," : ",".concat(",")"])),g.default.vErrors,t,g.default.vErrors,t)),o.assign(g.default.errors,(0,m._)(c||(c=f(["",".length"])),g.default.vErrors))}function A(e){var t;if(!p.opts.unevaluated)return;const n=null===(t=null===r||void 0===r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==p.props)if(n&&!n.dynamicProps)void 0!==n.props&&(p.props=y.mergeEvaluated.props(o,n.props,p.props));else{const t=o.var("props",(0,m._)(u||(u=f(["",".evaluated.props"])),e));p.props=y.mergeEvaluated.props(o,t,p.props,m.Name)}if(!0!==p.items)if(n&&!n.dynamicItems)void 0!==n.items&&(p.items=y.mergeEvaluated.items(o,n.items,p.items));else{const t=o.var("items",(0,m._)(d||(d=f(["",".evaluated.items"])),e));p.items=y.mergeEvaluated.items(o,t,p.items,m.Name)}}n?function(){if(!b.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try((()=>{o.code((0,m._)(a||(a=f(["await ",""])),(0,h.callValidateCode)(e,t,x))),A(t),v||o.assign(r,!0)}),(e=>{o.if((0,m._)(i||(i=f(["!("," instanceof ",")"])),e,p.ValidationError),(()=>o.throw(e))),S(e),v||o.assign(r,!1)})),e.ok(r)}():e.result((0,h.callValidateCode)(e,t,x),(()=>A(t)),(()=>S(t)))}t.getValidate=w,t.callRef=x,t.default=b},5012:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(8494),c=r(3633),u=r(7804),d=r(1646),f={keyword:"discriminator",type:"object",schemaType:"object",error:{message:e=>{let{params:{discrError:t,tagName:r}}=e;return t===c.DiscrError.Tag?'tag "'.concat(r,'" must be string'):'value of tag "'.concat(r,'" must be in oneOf')},params:e=>{let{params:{discrError:t,tag:r,tagName:o}}=e;return(0,l._)(n||(n=s(["{error: ",", tag: ",", tagValue: ","}"])),t,o,r)}},code(e){const{gen:t,data:r,schema:n,parentSchema:f,it:p}=e,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const m=n.propertyName;if("string"!=typeof m)throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const g=t.let("valid",!1),v=t.const("tag",(0,l._)(o||(o=s(["","",""])),r,(0,l.getProperty)(m)));function y(r){const n=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(o,l.Name),n}t.if((0,l._)(a||(a=s(["typeof ",' == "string"'])),v),(()=>function(){const r=function(){var e;const t={},r=o(f);let n=!0;for(let s=0;se.error(!1,{discrError:c.DiscrError.Tag,tag:v,tagName:m}))),e.ok(g)}};t.default=f},3633:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(t.DiscrError||(t.DiscrError={}))},5915:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(6891),o=r(1335),a=r(2021),i=r(4999),s=r(2854),l=[n.default,o.default,(0,a.default)(),i.default,s.metadataVocabulary,s.contentVocabulary];t.default=l},3004:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const x=r(8494),S={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,x.str)(n||(n=w(['must match format "','"'])),t)},params:e=>{let{schemaCode:t}=e;return(0,x._)(o||(o=w(["{format: ","}"])),t)}},code(e,t){const{gen:r,data:n,$data:o,schema:S,schemaCode:A,it:k}=e,{opts:C,errSchemaPath:E,schemaEnv:_,self:P}=k;C.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:P.formats,code:C.code.formats}),m=r.const("fDef",(0,x._)(a||(a=w(["","[","]"])),o,A)),g=r.let("fType"),v=r.let("format");r.if((0,x._)(i||(i=w(["typeof ",' == "object" && !('," instanceof RegExp)"])),m,m),(()=>r.assign(g,(0,x._)(s||(s=w(["",'.type || "string"'])),m)).assign(v,(0,x._)(l||(l=w(["",".validate"])),m))),(()=>r.assign(g,(0,x._)(c||(c=w(['"string"'])))).assign(v,m))),e.fail$data((0,x.or)(!1===C.strictSchema?x.nil:(0,x._)(u||(u=w([""," && !",""])),A,v),function(){const e=_.$async?(0,x._)(d||(d=w(["(",".async ? await ","(",") : ","(","))"])),m,v,n,v,n):(0,x._)(f||(f=w(["","(",")"])),v,n),r=(0,x._)(p||(p=w(["(typeof ",' == "function" ? '," : ",".test(","))"])),v,e,v,n);return(0,x._)(h||(h=w([""," && "," !== true && "," === "," && !",""])),v,v,g,t,r)}()))}():function(){const o=P.formats[S];if(!o)return void function(){if(!1===C.strictSchema)return void P.logger.warn(e());throw new Error(e());function e(){return'unknown format "'.concat(S,'" ignored in schema at path "').concat(E,'"')}}();if(!0===o)return;const[a,i,s]=function(e){const t=e instanceof RegExp?(0,x.regexpCode)(e):C.code.formats?(0,x._)(m||(m=w(["","",""])),C.code.formats,(0,x.getProperty)(S)):void 0,n=r.scopeValue("formats",{key:S,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,(0,x._)(g||(g=w(["",".validate"])),n)];return["string",e,n]}(o);a===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!_.$async)throw new Error("async format in sync schema");return(0,x._)(v||(v=w(["await ","(",")"])),s,n)}return"function"==typeof i?(0,x._)(y||(y=w(["","(",")"])),s,n):(0,x._)(b||(b=w(["",".test(",")"])),s,n)}())}())}};t.default=S},4999:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=[r(3004).default];t.default=n},2854:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},716:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l=r(1646),c=r(4281),u={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:e=>{let{schemaCode:t}=e;return(0,s._)(n||(n=i(["{allowedValue: ","}"])),t)}},code(e){const{gen:t,data:r,$data:n,schemaCode:u,schema:d}=e;n||d&&"object"==typeof d?e.fail$data((0,s._)(o||(o=i(["!","(",", ",")"])),(0,l.useFunc)(t,c.default),r,u)):e.fail((0,s._)(a||(a=i([""," !== ",""])),d,r))}};t.default=u},5218:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(8494),c=r(1646),u=r(4281),d={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:e=>{let{schemaCode:t}=e;return(0,l._)(n||(n=s(["{allowedValues: ","}"])),t)}},code(e){const{gen:t,data:r,$data:n,schema:d,schemaCode:f,it:p}=e;if(!n&&0===d.length)throw new Error("enum must have non-empty array");const h=d.length>=p.opts.loopEnum;let m;const g=()=>null!==m&&void 0!==m?m:m=(0,c.useFunc)(t,u.default);let v;if(h||n)v=t.let("valid"),e.block$data(v,(function(){t.assign(v,!1),t.forOf("v",f,(e=>t.if((0,l._)(o||(o=s(["","(",", ",")"])),g(),r,e),(()=>t.assign(v,!0).break()))))}));else{if(!Array.isArray(d))throw new Error("ajv implementation error");const e=t.const("vSchema",f);v=(0,l.or)(...d.map(((t,n)=>function(e,t){const n=d[t];return"object"===typeof n&&null!==n?(0,l._)(a||(a=s(["","(",", ","[","])"])),g(),r,e,t):(0,l._)(i||(i=s([""," === ",""])),r,n)}(e,n))))}e.pass(v)}};t.default=d},1335:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(297),o=r(3642),a=r(4388),i=r(2465),s=r(5937),l=r(662),c=r(5741),u=r(2102),d=r(716),f=r(5218),p=[n.default,o.default,a.default,i.default,s.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},d.default,f.default];t.default=p},5741:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxItems"===t?"more":"fewer";return(0,s.str)(n||(n=i(["must NOT have "," than "," items"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,s._)(o||(o=i(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data((0,s._)(a||(a=i(["",".length "," ",""])),r,o,n))}};t.default=l},4388:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(8494),u=r(1646),d=r(5784),f={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxLength"===t?"more":"fewer";return(0,c.str)(n||(n=l(["must NOT have "," than "," characters"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=l(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n,it:o}=e,f="maxLength"===t?c.operators.GT:c.operators.LT,p=!1===o.opts.unicode?(0,c._)(a||(a=l(["",".length"])),r):(0,c._)(i||(i=l(["","(",")"])),(0,u.useFunc)(e.gen,d.default),r);e.fail$data((0,c._)(s||(s=l([""," "," ",""])),p,f,n))}};t.default=f},297:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l=s.operators,c={maximum:{okStr:"<=",ok:l.LTE,fail:l.GT},minimum:{okStr:">=",ok:l.GTE,fail:l.LT},exclusiveMaximum:{okStr:"<",ok:l.LT,fail:l.GTE},exclusiveMinimum:{okStr:">",ok:l.GT,fail:l.LTE}},u={message:e=>{let{keyword:t,schemaCode:r}=e;return(0,s.str)(n||(n=i(["must be "," ",""])),c[t].okStr,r)},params:e=>{let{keyword:t,schemaCode:r}=e;return(0,s._)(o||(o=i(["{comparison: ",", limit: ","}"])),c[t].okStr,r)}},d={keyword:Object.keys(c),type:"number",schemaType:"number",$data:!0,error:u,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,s._)(a||(a=i([""," "," "," || isNaN(",")"])),r,c[t].fail,n,r))}};t.default=d},5937:(e,t,r)=>{"use strict";var n,o,a,i=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const s=r(8494),l={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message(e){let{keyword:t,schemaCode:r}=e;const o="maxProperties"===t?"more":"fewer";return(0,s.str)(n||(n=i(["must NOT have "," than "," properties"])),o,r)},params:e=>{let{schemaCode:t}=e;return(0,s._)(o||(o=i(["{limit: ","}"])),t)}},code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data((0,s._)(a||(a=i(["Object.keys(",").length "," ",""])),r,o,n))}};t.default=l},3642:(e,t,r)=>{"use strict";var n,o,a,i,s,l=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const c=r(8494),u={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,c.str)(n||(n=l(["must be multiple of ",""])),t)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=l(["{multipleOf: ","}"])),t)}},code(e){const{gen:t,data:r,schemaCode:n,it:o}=e,u=o.opts.multipleOfPrecision,d=t.let("res"),f=u?(0,c._)(a||(a=l(["Math.abs(Math.round(",") - ",") > 1e-",""])),d,d,u):(0,c._)(i||(i=l([""," !== parseInt(",")"])),d,d);e.fail$data((0,c._)(s||(s=l(["("," === 0 || ("," = ","/",", ","))"])),n,d,r,n,f))}};t.default=u},2465:(e,t,r)=>{"use strict";var n,o,a,i,s=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const l=r(8518),c=r(8494),u={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:e=>{let{schemaCode:t}=e;return(0,c.str)(n||(n=s(['must match pattern "','"'])),t)},params:e=>{let{schemaCode:t}=e;return(0,c._)(o||(o=s(["{pattern: ","}"])),t)}},code(e){const{data:t,$data:r,schema:n,schemaCode:o,it:u}=e,d=u.opts.unicodeRegExp?"u":"",f=r?(0,c._)(a||(a=s(["(new RegExp(",", ","))"])),o,d):(0,l.usePattern)(e,n);e.fail$data((0,c._)(i||(i=s(["!",".test(",")"])),f,t))}};t.default=u},662:(e,t,r)=>{"use strict";var n,o,a=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const i=r(8518),s=r(8494),l=r(1646),c={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:e=>{let{params:{missingProperty:t}}=e;return(0,s.str)(n||(n=a(["must have required property '","'"])),t)},params:e=>{let{params:{missingProperty:t}}=e;return(0,s._)(o||(o=a(["{missingProperty: ","}"])),t)}},code(e){const{gen:t,schema:r,schemaCode:n,data:o,$data:a,it:c}=e,{opts:u}=c;if(!a&&0===r.length)return;const d=r.length>=u.loopRequired;if(c.allErrors?function(){if(d||a)e.block$data(s.nil,f);else for(const t of r)(0,i.checkReportMissingProp)(e,t)}():function(){const l=t.let("missing");if(d||a){const r=t.let("valid",!0);e.block$data(r,(()=>function(r,a){e.setParams({missingProperty:r}),t.forOf(r,n,(()=>{t.assign(a,(0,i.propertyInData)(t,o,r,u.ownProperties)),t.if((0,s.not)(a),(()=>{e.error(),t.break()}))}),s.nil)}(l,r))),e.ok(r)}else t.if((0,i.checkMissingProp)(e,r,l)),(0,i.reportMissingProp)(e,l),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null===t||void 0===t?void 0:t[e])&&!n.has(e)){const t=c.schemaEnv.baseId+c.errSchemaPath,r='required property "'.concat(e,'" is not defined at "').concat(t,'" (strictRequired)');(0,l.checkStrictMode)(c,r,c.opts.strictRequired)}}function f(){t.forOf("prop",n,(r=>{e.setParams({missingProperty:r}),t.if((0,i.noPropertyInData)(t,o,r,u.ownProperties),(()=>e.error()))}))}}};t.default=c},2102:(e,t,r)=>{"use strict";var n,o,a,i,s,l,c,u,d,f,p,h,m,g,v,y,b,w=r(166).default;Object.defineProperty(t,"__esModule",{value:!0});const x=r(7839),S=r(8494),A=r(1646),k=r(4281),C={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:e=>{let{params:{i:t,j:r}}=e;return(0,S.str)(n||(n=w(["must NOT have duplicate items (items ## "," and "," are identical)"])),r,t)},params:e=>{let{params:{i:t,j:r}}=e;return(0,S._)(o||(o=w(["{i: ",", j: ","}"])),t,r)}},code(e){const{gen:t,data:r,$data:n,schema:o,parentSchema:C,schemaCode:E,it:_}=e;if(!n&&!o)return;const P=t.let("valid"),j=C.items?(0,x.getSchemaTypes)(C.items):[];function R(n,o){const a=t.name("item"),i=(0,x.checkDataTypes)(j,a,_.opts.strictNumbers,x.DataType.Wrong),s=t.const("indices",(0,S._)(l||(l=w(["{}"]))));t.for((0,S._)(c||(c=w([";","--;"])),n),(()=>{t.let(a,(0,S._)(u||(u=w(["","[","]"])),r,n)),t.if(i,(0,S._)(d||(d=w(["continue"])))),j.length>1&&t.if((0,S._)(f||(f=w(["typeof ",' == "string"'])),a),(0,S._)(p||(p=w(["",' += "_"'])),a)),t.if((0,S._)(h||(h=w(["typeof ","[",'] == "number"'])),s,a),(()=>{t.assign(o,(0,S._)(m||(m=w(["","[","]"])),s,a)),e.error(),t.assign(P,!1).break()})).code((0,S._)(g||(g=w(["","[","] = ",""])),s,a,n))}))}function O(n,o){const a=(0,A.useFunc)(t,k.default),i=t.name("outer");t.label(i).for((0,S._)(v||(v=w([";","--;"])),n),(()=>t.for((0,S._)(y||(y=w([""," = ","; ","--;"])),o,n,o),(()=>t.if((0,S._)(b||(b=w(["","(","[","], ","[","])"])),a,r,n,r,o),(()=>{e.error(),t.assign(P,!1).break(i)}))))))}e.block$data(P,(function(){const n=t.let("i",(0,S._)(i||(i=w(["",".length"])),r)),o=t.let("j");e.setParams({i:n,j:o}),t.assign(P,!0),t.if((0,S._)(s||(s=w([""," > 1"])),n),(()=>(j.length>0&&!j.some((e=>"object"===e||"array"===e))?R:O)(n,o)))}),(0,S._)(a||(a=w([""," === false"])),E)),e.ok(P)}};t.default=C},9569:e=>{"use strict";var t=e.exports=function(e,t,n){"function"==typeof t&&(n=t,t={}),r(t,"function"==typeof(n=t.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function r(e,n,o,a,i,s,l,c,u,d){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var f in n(a,i,s,l,c,u,d),a){var p=a[f];if(Array.isArray(p)){if(f in t.arrayKeywords)for(var h=0;h{"use strict";var n=r(6596),o=r(7151),a=r(4431),i=Math.pow(2,31)-1;function s(e,t){var r,n=1;if(0===e)return t;if(0===t)return e;for(;e%2===0&&t%2===0;)e/=2,t/=2,n*=2;for(;e%2===0;)e/=2;for(;t;){for(;t%2===0;)t/=2;e>t&&(r=t,t=e,e=r),t-=e}return n*e}function l(e,t){var r,n=0;if(0===e)return t;if(0===t)return e;for(;0===(1&e)&&0===(1&t);)e>>>=1,t>>>=1,n++;for(;0===(1&e);)e>>>=1;for(;t;){for(;0===(1&t);)t>>>=1;e>t&&(r=t,t=e,e=r),t-=e}return e<1){if(r=e[0],t=e[1],!a(t))throw new TypeError("gcd()::invalid input argument. Accessor must be a function. Value: `"+t+"`.")}else r=e[0]}if((c=r.length)<2)return null;if(t){for(u=new Array(c),f=0;f{"use strict";var n=r(6270),o=r(6596),a=r(7151),i=r(4431);e.exports=function(){var e,t,r,s,l,c,u,d=arguments.length;for(e=new Array(d),u=0;u1){if(r=e[0],t=e[1],!i(t))throw new TypeError("lcm()::invalid input argument. Accessor must be a function. Value: `"+t+"`.")}else r=e[0]}if((s=r.length)<2)return null;if(t){for(l=new Array(s),u=0;u{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o,a;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(o=n;0!==o--;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(o=n;0!==o--;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return!1;for(o=n;0!==o--;){var i=a[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}},219:(e,t,r)=>{"use strict";var n=r(3763),o={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},a={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},i={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},s={};function l(e){return n.isMemo(e)?i:s[e.$$typeof]||o}s[n.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s[n.Memo]=i;var c=Object.defineProperty,u=Object.getOwnPropertyNames,d=Object.getOwnPropertySymbols,f=Object.getOwnPropertyDescriptor,p=Object.getPrototypeOf,h=Object.prototype;e.exports=function e(t,r,n){if("string"!==typeof r){if(h){var o=p(r);o&&o!==h&&e(t,o,n)}var i=u(r);d&&(i=i.concat(d(r)));for(var s=l(t),m=l(r),g=0;g{"use strict";var r="function"===typeof Symbol&&Symbol.for,n=r?Symbol.for("react.element"):60103,o=r?Symbol.for("react.portal"):60106,a=r?Symbol.for("react.fragment"):60107,i=r?Symbol.for("react.strict_mode"):60108,s=r?Symbol.for("react.profiler"):60114,l=r?Symbol.for("react.provider"):60109,c=r?Symbol.for("react.context"):60110,u=r?Symbol.for("react.async_mode"):60111,d=r?Symbol.for("react.concurrent_mode"):60111,f=r?Symbol.for("react.forward_ref"):60112,p=r?Symbol.for("react.suspense"):60113,h=r?Symbol.for("react.suspense_list"):60120,m=r?Symbol.for("react.memo"):60115,g=r?Symbol.for("react.lazy"):60116,v=r?Symbol.for("react.block"):60121,y=r?Symbol.for("react.fundamental"):60117,b=r?Symbol.for("react.responder"):60118,w=r?Symbol.for("react.scope"):60119;function x(e){if("object"===typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case u:case d:case a:case s:case i:case p:return e;default:switch(e=e&&e.$$typeof){case c:case f:case g:case m:case l:return e;default:return t}}case o:return t}}}function S(e){return x(e)===d}t.AsyncMode=u,t.ConcurrentMode=d,t.ContextConsumer=c,t.ContextProvider=l,t.Element=n,t.ForwardRef=f,t.Fragment=a,t.Lazy=g,t.Memo=m,t.Portal=o,t.Profiler=s,t.StrictMode=i,t.Suspense=p,t.isAsyncMode=function(e){return S(e)||x(e)===u},t.isConcurrentMode=S,t.isContextConsumer=function(e){return x(e)===c},t.isContextProvider=function(e){return x(e)===l},t.isElement=function(e){return"object"===typeof e&&null!==e&&e.$$typeof===n},t.isForwardRef=function(e){return x(e)===f},t.isFragment=function(e){return x(e)===a},t.isLazy=function(e){return x(e)===g},t.isMemo=function(e){return x(e)===m},t.isPortal=function(e){return x(e)===o},t.isProfiler=function(e){return x(e)===s},t.isStrictMode=function(e){return x(e)===i},t.isSuspense=function(e){return x(e)===p},t.isValidElementType=function(e){return"string"===typeof e||"function"===typeof e||e===a||e===d||e===s||e===i||e===p||e===h||"object"===typeof e&&null!==e&&(e.$$typeof===g||e.$$typeof===m||e.$$typeof===l||e.$$typeof===c||e.$$typeof===f||e.$$typeof===y||e.$$typeof===b||e.$$typeof===w||e.$$typeof===v)},t.typeOf=x},3763:(e,t,r)=>{"use strict";e.exports=r(4983)},7841:(e,t,r)=>{var n=r(9853),o=r(7424),a=r(9376),i=r(312),s=r(1163),l=r(2636),c=r(2322),u=r(6361),d=e=>Array.isArray(e)?e:[e],f=e=>void 0===e,p=e=>c(e)||Array.isArray(e)?Object.keys(e):[],h=(e,t)=>e.hasOwnProperty(t),m=e=>o(a(e)),g=e=>f(e)||Array.isArray(e)&&0===e.length,v=(e,t,r,n)=>t&&h(t,r)&&e&&h(e,r)&&n(e[r],t[r]),y=(e,t)=>f(e)&&0===t||f(t)&&0===e||n(e,t),b=e=>f(e)||n(e,{})||!0===e,w=e=>f(e)||n(e,{}),x=e=>f(e)||c(e)||!0===e||!1===e;function S(e,t){return!(!g(e)||!g(t))||n(m(e),m(t))}function A(e,t,r,o){var i=a(p(e).concat(p(t)));return!(!w(e)||!w(t))||(!w(e)||!p(t).length)&&((!w(t)||!p(e).length)&&i.every((function(r){var a=e[r],i=t[r];return Array.isArray(a)&&Array.isArray(i)?n(m(e),m(t)):!(Array.isArray(a)&&!Array.isArray(i))&&(!(Array.isArray(i)&&!Array.isArray(a))&&v(e,t,r,o))})))}function k(e,t,r,n){var o=i(e,n),a=i(t,n);return l(o,a,n).length===Math.max(o.length,a.length)}var C={title:n,uniqueItems:(e,t)=>f(e)&&!1===t||f(t)&&!1===e||n(e,t),minLength:y,minItems:y,minProperties:y,required:S,enum:S,type:function(e,t){return e=d(e),t=d(t),n(m(e),m(t))},items:function(e,t,r,o){return c(e)&&c(t)?o(e,t):Array.isArray(e)&&Array.isArray(t)?A(e,t,0,o):n(e,t)},anyOf:k,allOf:k,oneOf:k,properties:A,patternProperties:A,dependencies:A},E=["properties","patternProperties","dependencies","uniqueItems","minLength","minItems","minProperties","required"],_=["additionalProperties","additionalItems","contains","propertyNames","not"];e.exports=function e(t,r,o){if(o=s(o,{ignore:[]}),b(t)&&b(r))return!0;if(!x(t)||!x(r))throw new Error("Either of the values are not a JSON schema.");if(t===r)return!0;if(u(t)&&u(r))return t===r;if(void 0===t&&!1===r||void 0===r&&!1===t)return!1;if(f(t)&&!f(r)||!f(t)&&f(r))return!1;var i=a(Object.keys(t).concat(Object.keys(r)));if(o.ignore.length&&(i=i.filter((e=>-1===o.ignore.indexOf(e)))),!i.length)return!0;function l(t,r){return e(t,r,o)}return i.every((function(a){var i=t[a],s=r[a];if(-1!==_.indexOf(a))return e(i,s,o);var c=C[a];if(c||(c=n),n(i,s))return!0;if(-1===E.indexOf(a)&&(!h(t,a)&&h(r,a)||h(t,a)&&!h(r,a)))return i===s;var d=c(i,s,a,l);if(!u(d))throw new Error("Comparer must return true or false");return d}))}},6988:(e,t,r)=>{const n=r(819),o=r(3517),a=r(2322),i=r(9376),s=r(312),l=r(6757);const c=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),u=e=>a(e)||Array.isArray(e)?Object.keys(e):[],d=e=>!u(e).length&&!1!==e&&!0!==e;e.exports={allUniqueKeys:e=>i(o(e.map(u))),deleteUndefinedProps:function(e){for(const t in e)c(e,t)&&d(e[t])&&delete e[t];return e},getValues:(e,t)=>e.map((e=>e&&e[t])),has:c,isEmptySchema:d,isSchema:e=>a(e)||!0===e||!1===e,keys:u,notUndefined:e=>void 0!==e,uniqWith:s,withoutArr:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o{const n=r(7841),o=r(5491),{allUniqueKeys:a,deleteUndefinedProps:i,has:s,isSchema:l,notUndefined:c,uniqWith:u}=r(6988);function d(e,t,r){return a(r).reduce((function(r,o){const a=function(e,t){return e.map((function(e){if(e){if(!Array.isArray(e.items))return e.items;{const r=e.items[t];if(l(r))return r;if(s(e,"additionalItems"))return e.additionalItems}}}))}(e,o),i=u(a.filter(c),n);return r[o]=t(i,o),r}),[])}e.exports={keywords:["items","additionalItems"],resolver(e,t,r){const n=e.map((e=>e.items)),a=n.filter(c),s={};let u;var f;return a.every(l)?s.items=r.items(n):s.items=d(e,r.items,n),a.every(Array.isArray)?u=e.map((e=>e.additionalItems)):a.some(Array.isArray)&&(u=e.map((function(e){if(e)return Array.isArray(e.items)?e.additionalItems:e.items}))),u&&(s.additionalItems=r.additionalItems(u)),!1===s.additionalItems&&Array.isArray(s.items)&&(f=s.items,o(f,(function(e,t){!1===e&&f.splice(t,1)}))),i(s)}}},4503:(e,t,r)=>{const n=r(7841),o=r(5491),{allUniqueKeys:a,deleteUndefinedProps:i,getValues:s,keys:l,notUndefined:c,uniqWith:u,withoutArr:d}=r(6988);function f(e,t){return a(e).reduce((function(r,o){const a=s(e,o),i=u(a.filter(c),n);return r[o]=t(i,o),r}),{})}e.exports={keywords:["properties","patternProperties","additionalProperties"],resolver(e,t,r,n){n.ignoreAdditionalProperties||(e.forEach((function(t){const n=e.filter((e=>e!==t)),o=l(t.properties),a=l(t.patternProperties).map((e=>new RegExp(e)));n.forEach((function(e){const n=l(e.properties),i=n.filter((e=>a.some((t=>t.test(e)))));d(n,o,i).forEach((function(n){e.properties[n]=r.properties([e.properties[n],t.additionalProperties],n)}))}))})),e.forEach((function(t){const r=e.filter((e=>e!==t)),n=l(t.patternProperties);!1===t.additionalProperties&&r.forEach((function(e){const t=l(e.patternProperties);d(t,n).forEach((t=>delete e.patternProperties[t]))}))})));const a={additionalProperties:r.additionalProperties(e.map((e=>e.additionalProperties))),patternProperties:f(e.map((e=>e.patternProperties)),r.patternProperties),properties:f(e.map((e=>e.properties)),r.properties)};var s;return!1===a.additionalProperties&&o(s=a.properties,(function(e,t){!1===e&&delete s[t]})),i(a)}}},2093:(e,t,r)=>{const n=r(6434),o=r(7841),a=r(3192),i=r(7797),s=r(819),l=r(3517),c=r(1460),u=r(2636),d=r(9853),f=r(2322),p=r(3535),h=r(7424),m=r(9376),g=r(312),v=r(4503),y=r(6768),b=(e,t)=>-1!==e.indexOf(t),w=e=>f(e)||!0===e||!1===e,x=e=>!1===e,S=e=>!0===e,A=(e,t,r)=>r(e),k=e=>h(m(l(e))),C=e=>void 0!==e,E=e=>m(l(e.map(N))),_=e=>e[0],P=e=>Math.max.apply(Math,e),j=e=>Math.min.apply(Math,e);function R(e){let{allOf:t=[],...r}=e;return r=f(e)?r:e,[r,...t.map(R)]}function O(e,t){return e.map((e=>e&&e[t]))}function N(e){return f(e)||Array.isArray(e)?Object.keys(e):[]}function T(e,t){if(t=t||[],!e.length)return t;const r=e.slice(0).shift(),n=e.slice(1);return t.length?T(n,s(t.map((e=>r.map((t=>[t].concat(e))))))):T(n,r.map((e=>e)))}function I(e,t){let r;try{r=e.map((function(e){return JSON.stringify(e,null,2)})).join("\n")}catch(n){r=e.join(", ")}throw new Error('Could not resolve values for path:"'+t.join(".")+'". They are probably incompatible. Values: \n'+r)}function M(e,t,r,n,a,i){if(e.length){const s=a.complexResolvers[t];if(!s||!s.resolver)throw new Error("No resolver found for "+t);const l=r.map((t=>e.reduce(((e,r)=>(void 0!==t[r]&&(e[r]=t[r]),e)),{}))),c=g(l,o),u=s.keywords.reduce(((e,t)=>({...e,[t]:function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return n(e,null,i.concat(t,r))}})),{}),d=s.resolver(c,i.concat(t),u,a);return f(d)||I(c,i.concat(t)),d}}function F(e){return{required:e}}const D=["properties","patternProperties","definitions","dependencies"],z=["anyOf","oneOf"],L=["additionalProperties","additionalItems","contains","propertyNames","not","items"],B={type(e){if(e.some(Array.isArray)){const t=e.map((function(e){return Array.isArray(e)?e:[e]})),r=c.apply(null,t);if(1===r.length)return r[0];if(r.length>1)return m(r)}},dependencies:(e,t,r)=>E(e).reduce((function(t,n){const a=O(e,n);let i=g(a.filter(C),d);const s=i.filter(Array.isArray);if(s.length){if(s.length===i.length)t[n]=k(i);else{const e=i.filter(w),o=s.map(F);t[n]=r(e.concat(o),n)}return t}return i=g(i,o),t[n]=r(i,n),t}),{}),oneOf(e,t,r){const a=function(e,t){return e.map((function(e,r){try{return t(e,r)}catch(n){return}})).filter(C)}(T(n(e)),r),i=g(a,o);if(i.length)return i},not:e=>({anyOf:e}),pattern:e=>e.map((e=>"(?="+e+")")).join(""),multipleOf(e){let t=e.slice(0),r=1;for(;t.some((e=>!Number.isInteger(e)));)t=t.map((e=>10*e)),r*=10;return a(t)/r},enum(e){const t=u.apply(null,e.concat(d));if(t.length)return h(t)}};B.$id=_,B.$ref=_,B.$schema=_,B.additionalItems=A,B.additionalProperties=A,B.anyOf=B.oneOf,B.contains=A,B.default=_,B.definitions=B.dependencies,B.description=_,B.examples=e=>g(s(e),d),B.exclusiveMaximum=j,B.exclusiveMinimum=P,B.items=y,B.maximum=j,B.maxItems=j,B.maxLength=j,B.maxProperties=j,B.minimum=P,B.minItems=P,B.minLength=P,B.minProperties=P,B.properties=v,B.propertyNames=A,B.required=e=>k(e),B.title=_,B.uniqueItems=e=>e.some(S);const $={properties:v,items:y};function W(e,t,r){r=r||[],t=i(t,{ignoreAdditionalProperties:!1,resolvers:B,complexResolvers:$,deep:!0});const a=Object.entries(t.complexResolvers);const s=function e(i,s,l){i=n(i.filter(C)),l=l||[];const c=f(s)?s:{};if(!i.length)return;if(i.some(x))return!1;if(i.every(S))return!0;i=i.filter(f);const u=E(i);if(t.deep&&b(u,"allOf"))return W({allOf:i},t,r);const d=a.map((e=>{let[t,r]=e;return u.filter((e=>r.keywords.includes(e)))}));return d.forEach((e=>p(u,e))),u.forEach((function(r){const n=O(i,r),a=g(n.filter(C),function(e){return function(t,r){return o({[e]:t},{[e]:r})}}(r));if(1===a.length&&b(z,r))c[r]=a[0].map((t=>e([t],t)));else if(1!==a.length||b(D,r)||b(L,r)){const n=t.resolvers[r]||t.resolvers.defaultResolver;if(!n)throw new Error("No resolver found for key "+r+". You can provide a resolver for this keyword in the options, or provide a default resolver.");const o=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e(t,null,l.concat(r,n))};c[r]=n(a,l.concat(r),o,t),void 0===c[r]?I(a,l.concat(r)):void 0===c[r]&&delete c[r]}else c[r]=a[0]})),a.reduce(((r,n,o)=>{let[a,s]=n;return{...r,...M(d[o],a,i,e,t,l)}}),c)}(l(R(e)));return s}W.options={resolvers:B},e.exports=W},5492:(e,t)=>{var r=/~/,n=/~[01]/g;function o(e){switch(e){case"~1":return"/";case"~0":return"~"}throw new Error("Invalid tilde escape: "+e)}function a(e){return r.test(e)?e.replace(n,o):e}function i(e){if("string"===typeof e){if(""===(e=e.split("/"))[0])return e;throw new Error("Invalid JSON pointer.")}if(Array.isArray(e)){for(const t of e)if("string"!==typeof t&&"number"!==typeof t)throw new Error("Invalid JSON pointer. Must be of type string or number.");return e}throw new Error("Invalid JSON pointer.")}function s(e,t){if("object"!==typeof e)throw new Error("Invalid input object.");var r=(t=i(t)).length;if(1===r)return e;for(var n=1;ni,"undefined"===typeof e[n]&&(Array.isArray(e)&&"-"===n&&(n=e.length),o&&(""!==t[i]&&t[i]<1/0||"-"===t[i]?e[n]=[]:e[n]={})),!o)break;e=e[n]}var l=e[n];return void 0===r?delete e[n]:e[n]=r,l}(e,t,r)}t.get=s,t.set=l,t.compile=function(e){var t=i(e);return{get:function(e){return s(e,t)},set:function(e,r){return l(e,t,r)}}}},7685:(e,t,r)=>{var n=r(7937)(r(6552),"DataView");e.exports=n},8724:(e,t,r)=>{var n=r(7615),o=r(5051),a=r(2154),i=r(8734),s=r(2662);function l(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t{var n=r(7563),o=r(9935),a=r(4190),i=r(1946),s=r(1714);function l(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t{var n=r(7937)(r(6552),"Map");e.exports=n},4816:(e,t,r)=>{var n=r(7251),o=r(7159),a=r(438),i=r(9394),s=r(6874);function l(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t{var n=r(7937)(r(6552),"Promise");e.exports=n},2070:(e,t,r)=>{var n=r(7937)(r(6552),"Set");e.exports=n},8902:(e,t,r)=>{var n=r(4816),o=r(6179),a=r(6704);function i(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new n;++t{var n=r(7160),o=r(4545),a=r(793),i=r(7760),s=r(3892),l=r(6788);function c(e){var t=this.__data__=new n(e);this.size=t.size}c.prototype.clear=o,c.prototype.delete=a,c.prototype.get=i,c.prototype.has=s,c.prototype.set=l,e.exports=c},9812:(e,t,r)=>{var n=r(6552).Symbol;e.exports=n},2929:(e,t,r)=>{var n=r(6552).Uint8Array;e.exports=n},6600:(e,t,r)=>{var n=r(7937)(r(6552),"WeakMap");e.exports=n},1170:e=>{e.exports=function(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}},726:e=>{e.exports=function(e,t){for(var r=-1,n=null==e?0:e.length;++r{e.exports=function(e,t){for(var r=-1,n=null==e?0:e.length,o=0,a=[];++r{var n=r(8468);e.exports=function(e,t){return!!(null==e?0:e.length)&&n(e,t,0)>-1}},1558:e=>{e.exports=function(e,t,r){for(var n=-1,o=null==e?0:e.length;++n{var n=r(3343),o=r(2777),a=r(4052),i=r(4543),s=r(9194),l=r(1268),c=Object.prototype.hasOwnProperty;e.exports=function(e,t){var r=a(e),u=!r&&o(e),d=!r&&!u&&i(e),f=!r&&!u&&!d&&l(e),p=r||u||d||f,h=p?n(e.length,String):[],m=h.length;for(var g in e)!t&&!c.call(e,g)||p&&("length"==g||d&&("offset"==g||"parent"==g)||f&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||s(g,m))||h.push(g);return h}},149:e=>{e.exports=function(e,t){for(var r=-1,n=null==e?0:e.length,o=Array(n);++r{e.exports=function(e,t){for(var r=-1,n=t.length,o=e.length;++r{e.exports=function(e,t,r,n){var o=-1,a=null==e?0:e.length;for(n&&a&&(r=e[++o]);++o{e.exports=function(e,t){for(var r=-1,n=null==e?0:e.length;++r{var n=r(1775),o=r(3211);e.exports=function(e,t,r){(void 0!==r&&!o(e[t],r)||void 0===r&&!(t in e))&&n(e,t,r)}},8420:(e,t,r)=>{var n=r(1775),o=r(3211),a=Object.prototype.hasOwnProperty;e.exports=function(e,t,r){var i=e[t];a.call(e,t)&&o(i,r)&&(void 0!==r||t in e)||n(e,t,r)}},1340:(e,t,r)=>{var n=r(3211);e.exports=function(e,t){for(var r=e.length;r--;)if(n(e[r][0],t))return r;return-1}},1104:(e,t,r)=>{var n=r(6614),o=r(8673);e.exports=function(e,t){return e&&n(t,o(t),e)}},5119:(e,t,r)=>{var n=r(6614),o=r(474);e.exports=function(e,t){return e&&n(t,o(t),e)}},1775:(e,t,r)=>{var n=r(5654);e.exports=function(e,t,r){"__proto__"==t&&n?n(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}},7132:(e,t,r)=>{var n=r(5538),o=r(726),a=r(8420),i=r(1104),s=r(5119),l=r(4353),c=r(1980),u=r(8124),d=r(9075),f=r(9395),p=r(8592),h=r(6924),m=r(8268),g=r(8630),v=r(310),y=r(4052),b=r(4543),w=r(7887),x=r(6686),S=r(5921),A=r(8673),k=r(474),C="[object Arguments]",E="[object Function]",_="[object Object]",P={};P[C]=P["[object Array]"]=P["[object ArrayBuffer]"]=P["[object DataView]"]=P["[object Boolean]"]=P["[object Date]"]=P["[object Float32Array]"]=P["[object Float64Array]"]=P["[object Int8Array]"]=P["[object Int16Array]"]=P["[object Int32Array]"]=P["[object Map]"]=P["[object Number]"]=P[_]=P["[object RegExp]"]=P["[object Set]"]=P["[object String]"]=P["[object Symbol]"]=P["[object Uint8Array]"]=P["[object Uint8ClampedArray]"]=P["[object Uint16Array]"]=P["[object Uint32Array]"]=!0,P["[object Error]"]=P[E]=P["[object WeakMap]"]=!1,e.exports=function e(t,r,j,R,O,N){var T,I=1&r,M=2&r,F=4&r;if(j&&(T=O?j(t,R,O,N):j(t)),void 0!==T)return T;if(!x(t))return t;var D=y(t);if(D){if(T=m(t),!I)return c(t,T)}else{var z=h(t),L=z==E||"[object GeneratorFunction]"==z;if(b(t))return l(t,I);if(z==_||z==C||L&&!O){if(T=M||L?{}:v(t),!I)return M?d(t,s(T,t)):u(t,i(T,t))}else{if(!P[z])return O?t:{};T=g(t,z,I)}}N||(N=new n);var B=N.get(t);if(B)return B;N.set(t,T),S(t)?t.forEach((function(n){T.add(e(n,r,j,n,t,N))})):w(t)&&t.forEach((function(n,o){T.set(o,e(n,r,j,o,t,N))}));var $=D?void 0:(F?M?p:f:M?k:A)(t);return o($||t,(function(n,o){$&&(n=t[o=n]),a(T,o,e(n,r,j,o,t,N))})),T}},1817:(e,t,r)=>{var n=r(6686),o=Object.create,a=function(){function e(){}return function(t){if(!n(t))return{};if(o)return o(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();e.exports=a},8746:(e,t,r)=>{var n=r(8902),o=r(5866),a=r(1558),i=r(149),s=r(7574),l=r(8114);e.exports=function(e,t,r,c){var u=-1,d=o,f=!0,p=e.length,h=[],m=t.length;if(!p)return h;r&&(t=i(t,s(r))),c?(d=a,f=!1):t.length>=200&&(d=l,f=!1,t=new n(t));e:for(;++u{var n=r(4664),o=r(6516)(n);e.exports=o},5816:e=>{e.exports=function(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a{var n=r(8895),o=r(7116);e.exports=function e(t,r,a,i,s){var l=-1,c=t.length;for(a||(a=o),s||(s=[]);++l0&&a(u)?r>1?e(u,r-1,a,i,s):n(s,u):i||(s[s.length]=u)}return s}},4258:(e,t,r)=>{var n=r(5906)();e.exports=n},4664:(e,t,r)=>{var n=r(4258),o=r(8673);e.exports=function(e,t){return e&&n(e,t,o)}},2969:(e,t,r)=>{var n=r(5324),o=r(914);e.exports=function(e,t){for(var r=0,a=(t=n(t,e)).length;null!=e&&r{var n=r(8895),o=r(4052);e.exports=function(e,t,r){var a=t(e);return o(e)?a:n(a,r(e))}},6913:(e,t,r)=>{var n=r(9812),o=r(4552),a=r(6095),i=n?n.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":i&&i in Object(e)?o(e):a(e)}},6741:e=>{var t=Object.prototype.hasOwnProperty;e.exports=function(e,r){return null!=e&&t.call(e,r)}},7894:e=>{e.exports=function(e,t){return null!=e&&t in Object(e)}},8468:(e,t,r)=>{var n=r(5816),o=r(644),a=r(4020);e.exports=function(e,t,r){return t===t?a(e,t,r):n(e,o,r)}},1260:e=>{e.exports=function(e,t,r,n){for(var o=r-1,a=e.length;++o{var n=r(8902),o=r(5866),a=r(1558),i=r(149),s=r(7574),l=r(8114),c=Math.min;e.exports=function(e,t,r){for(var u=r?a:o,d=e[0].length,f=e.length,p=f,h=Array(f),m=1/0,g=[];p--;){var v=e[p];p&&t&&(v=i(v,s(t))),m=c(v.length,m),h[p]=!r&&(t||d>=120&&v.length>=120)?new n(p&&v):void 0}v=e[0];var y=-1,b=h[0];e:for(;++y{var n=r(6913),o=r(2761);e.exports=function(e){return o(e)&&"[object Arguments]"==n(e)}},6989:(e,t,r)=>{var n=r(6399),o=r(2761);e.exports=function e(t,r,a,i,s){return t===r||(null==t||null==r||!o(t)&&!o(r)?t!==t&&r!==r:n(t,r,a,i,e,s))}},6399:(e,t,r)=>{var n=r(5538),o=r(3668),a=r(9987),i=r(5752),s=r(6924),l=r(4052),c=r(4543),u=r(1268),d="[object Arguments]",f="[object Array]",p="[object Object]",h=Object.prototype.hasOwnProperty;e.exports=function(e,t,r,m,g,v){var y=l(e),b=l(t),w=y?f:s(e),x=b?f:s(t),S=(w=w==d?p:w)==p,A=(x=x==d?p:x)==p,k=w==x;if(k&&c(e)){if(!c(t))return!1;y=!0,S=!1}if(k&&!S)return v||(v=new n),y||u(e)?o(e,t,r,m,g,v):a(e,t,w,r,m,g,v);if(!(1&r)){var C=S&&h.call(e,"__wrapped__"),E=A&&h.call(t,"__wrapped__");if(C||E){var _=C?e.value():e,P=E?t.value():t;return v||(v=new n),g(_,P,r,m,v)}}return!!k&&(v||(v=new n),i(e,t,r,m,g,v))}},5791:(e,t,r)=>{var n=r(6924),o=r(2761);e.exports=function(e){return o(e)&&"[object Map]"==n(e)}},6532:(e,t,r)=>{var n=r(5538),o=r(6989);e.exports=function(e,t,r,a){var i=r.length,s=i,l=!a;if(null==e)return!s;for(e=Object(e);i--;){var c=r[i];if(l&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++i{e.exports=function(e){return e!==e}},6954:(e,t,r)=>{var n=r(1629),o=r(7857),a=r(6686),i=r(6996),s=/^\[object .+?Constructor\]$/,l=Function.prototype,c=Object.prototype,u=l.toString,d=c.hasOwnProperty,f=RegExp("^"+u.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!a(e)||o(e))&&(n(e)?f:s).test(i(e))}},449:(e,t,r)=>{var n=r(6924),o=r(2761);e.exports=function(e){return o(e)&&"[object Set]"==n(e)}},5428:(e,t,r)=>{var n=r(6913),o=r(6173),a=r(2761),i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1,e.exports=function(e){return a(e)&&o(e.length)&&!!i[n(e)]}},9096:(e,t,r)=>{var n=r(9256),o=r(5029),a=r(3279),i=r(4052),s=r(3932);e.exports=function(e){return"function"==typeof e?e:null==e?a:"object"==typeof e?i(e)?o(e[0],e[1]):n(e):s(e)}},3713:(e,t,r)=>{var n=r(6140),o=r(1143),a=Object.prototype.hasOwnProperty;e.exports=function(e){if(!n(e))return o(e);var t=[];for(var r in Object(e))a.call(e,r)&&"constructor"!=r&&t.push(r);return t}},8122:(e,t,r)=>{var n=r(6686),o=r(6140),a=r(3516),i=Object.prototype.hasOwnProperty;e.exports=function(e){if(!n(e))return a(e);var t=o(e),r=[];for(var s in e)("constructor"!=s||!t&&i.call(e,s))&&r.push(s);return r}},8883:(e,t,r)=>{var n=r(5652),o=r(6571);e.exports=function(e,t){var r=-1,a=o(e)?Array(e.length):[];return n(e,(function(e,n,o){a[++r]=t(e,n,o)})),a}},9256:(e,t,r)=>{var n=r(6532),o=r(3781),a=r(1310);e.exports=function(e){var t=o(e);return 1==t.length&&t[0][2]?a(t[0][0],t[0][1]):function(r){return r===e||n(r,e,t)}}},5029:(e,t,r)=>{var n=r(6989),o=r(3097),a=r(3366),i=r(2597),s=r(9417),l=r(1310),c=r(914);e.exports=function(e,t){return i(e)&&s(t)?l(c(e),t):function(r){var i=o(r,e);return void 0===i&&i===t?a(r,e):n(t,i,3)}}},3253:(e,t,r)=>{var n=r(5538),o=r(3868),a=r(4258),i=r(3223),s=r(6686),l=r(474),c=r(3737);e.exports=function e(t,r,u,d,f){t!==r&&a(r,(function(a,l){if(f||(f=new n),s(a))i(t,r,l,u,e,d,f);else{var p=d?d(c(t,l),a,l+"",t,r,f):void 0;void 0===p&&(p=a),o(t,l,p)}}),l)}},3223:(e,t,r)=>{var n=r(3868),o=r(4353),a=r(8710),i=r(1980),s=r(310),l=r(2777),c=r(4052),u=r(6272),d=r(4543),f=r(1629),p=r(6686),h=r(2322),m=r(1268),g=r(3737),v=r(1609);e.exports=function(e,t,r,y,b,w,x){var S=g(e,r),A=g(t,r),k=x.get(A);if(k)n(e,r,k);else{var C=w?w(S,A,r+"",e,t,x):void 0,E=void 0===C;if(E){var _=c(A),P=!_&&d(A),j=!_&&!P&&m(A);C=A,_||P||j?c(S)?C=S:u(S)?C=i(S):P?(E=!1,C=o(A,!0)):j?(E=!1,C=a(A,!0)):C=[]:h(A)||l(A)?(C=S,l(S)?C=v(S):p(S)&&!f(S)||(C=s(A))):E=!1}E&&(x.set(A,C),b(C,A,y,w,x),x.delete(A)),n(e,r,C)}}},2536:(e,t,r)=>{var n=r(149),o=r(2969),a=r(9096),i=r(8883),s=r(320),l=r(7574),c=r(5893),u=r(3279),d=r(4052);e.exports=function(e,t,r){t=t.length?n(t,(function(e){return d(e)?function(t){return o(t,1===e.length?e[0]:e)}:e})):[u];var f=-1;t=n(t,l(a));var p=i(e,(function(e,r,o){return{criteria:n(t,(function(t){return t(e)})),index:++f,value:e}}));return s(p,(function(e,t){return c(e,t,r)}))}},4008:(e,t,r)=>{var n=r(7449),o=r(3366);e.exports=function(e,t){return n(e,t,(function(t,r){return o(e,r)}))}},7449:(e,t,r)=>{var n=r(2969),o=r(9261),a=r(5324);e.exports=function(e,t,r){for(var i=-1,s=t.length,l={};++i{e.exports=function(e){return function(t){return null==t?void 0:t[e]}}},2866:(e,t,r)=>{var n=r(2969);e.exports=function(e){return function(t){return n(t,e)}}},6415:(e,t,r)=>{var n=r(149),o=r(8468),a=r(1260),i=r(7574),s=r(1980),l=Array.prototype.splice;e.exports=function(e,t,r,c){var u=c?a:o,d=-1,f=t.length,p=e;for(e===t&&(t=s(t)),r&&(p=n(e,i(r)));++d-1;)p!==e&&l.call(p,h,1),l.call(e,h,1);return e}},6487:e=>{e.exports=function(e,t,r,n,o){return o(e,(function(e,o,a){r=n?(n=!1,e):t(r,e,o,a)})),r}},5647:(e,t,r)=>{var n=r(3279),o=r(5636),a=r(6350);e.exports=function(e,t){return a(o(e,t,n),e+"")}},9261:(e,t,r)=>{var n=r(8420),o=r(5324),a=r(9194),i=r(6686),s=r(914);e.exports=function(e,t,r,l){if(!i(e))return e;for(var c=-1,u=(t=o(t,e)).length,d=u-1,f=e;null!=f&&++c{var n=r(2541),o=r(5654),a=r(3279),i=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:n(t),writable:!0})}:a;e.exports=i},3871:e=>{e.exports=function(e,t,r){var n=-1,o=e.length;t<0&&(t=-t>o?0:o+t),(r=r>o?o:r)<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n{e.exports=function(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}},3343:e=>{e.exports=function(e,t){for(var r=-1,n=Array(e);++r{var n=r(9812),o=r(149),a=r(4052),i=r(9841),s=n?n.prototype:void 0,l=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(a(t))return o(t,e)+"";if(i(t))return l?l.call(t):"";var r=t+"";return"0"==r&&1/t==-Infinity?"-0":r}},1141:(e,t,r)=>{var n=r(143),o=/^\s+/;e.exports=function(e){return e?e.slice(0,n(e)+1).replace(o,""):e}},7574:e=>{e.exports=function(e){return function(t){return e(t)}}},4416:(e,t,r)=>{var n=r(8902),o=r(5866),a=r(1558),i=r(8114),s=r(8182),l=r(2074);e.exports=function(e,t,r){var c=-1,u=o,d=e.length,f=!0,p=[],h=p;if(r)f=!1,u=a;else if(d>=200){var m=t?null:s(e);if(m)return l(m);f=!1,u=i,h=new n}else h=t?[]:p;e:for(;++c{var n=r(5324),o=r(4065),a=r(1676),i=r(914);e.exports=function(e,t){return t=n(t,e),null==(e=a(e,t))||delete e[i(o(t))]}},8114:e=>{e.exports=function(e,t){return e.has(t)}},46:(e,t,r)=>{var n=r(6272);e.exports=function(e){return n(e)?e:[]}},5111:(e,t,r)=>{var n=r(3279);e.exports=function(e){return"function"==typeof e?e:n}},5324:(e,t,r)=>{var n=r(4052),o=r(2597),a=r(4079),i=r(1069);e.exports=function(e,t){return n(e)?e:o(e,t)?[e]:a(i(e))}},1516:(e,t,r)=>{var n=r(2929);e.exports=function(e){var t=new e.constructor(e.byteLength);return new n(t).set(new n(e)),t}},4353:(e,t,r)=>{e=r.nmd(e);var n=r(6552),o=t&&!t.nodeType&&t,a=o&&e&&!e.nodeType&&e,i=a&&a.exports===o?n.Buffer:void 0,s=i?i.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var r=e.length,n=s?s(r):new e.constructor(r);return e.copy(n),n}},6806:(e,t,r)=>{var n=r(1516);e.exports=function(e,t){var r=t?n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}},8962:e=>{var t=/\w*$/;e.exports=function(e){var r=new e.constructor(e.source,t.exec(e));return r.lastIndex=e.lastIndex,r}},1295:(e,t,r)=>{var n=r(9812),o=n?n.prototype:void 0,a=o?o.valueOf:void 0;e.exports=function(e){return a?Object(a.call(e)):{}}},8710:(e,t,r)=>{var n=r(1516);e.exports=function(e,t){var r=t?n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}},6599:(e,t,r)=>{var n=r(9841);e.exports=function(e,t){if(e!==t){var r=void 0!==e,o=null===e,a=e===e,i=n(e),s=void 0!==t,l=null===t,c=t===t,u=n(t);if(!l&&!u&&!i&&e>t||i&&s&&c&&!l&&!u||o&&s&&c||!r&&c||!a)return 1;if(!o&&!i&&!u&&e{var n=r(6599);e.exports=function(e,t,r){for(var o=-1,a=e.criteria,i=t.criteria,s=a.length,l=r.length;++o=l?c:c*("desc"==r[o]?-1:1)}return e.index-t.index}},1980:e=>{e.exports=function(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r{var n=r(8420),o=r(1775);e.exports=function(e,t,r,a){var i=!r;r||(r={});for(var s=-1,l=t.length;++s{var n=r(6614),o=r(9621);e.exports=function(e,t){return n(e,o(e),t)}},9075:(e,t,r)=>{var n=r(6614),o=r(6326);e.exports=function(e,t){return n(e,o(e),t)}},3440:(e,t,r)=>{var n=r(6552)["__core-js_shared__"];e.exports=n},4570:(e,t,r)=>{var n=r(5647),o=r(929);e.exports=function(e){return n((function(t,r){var n=-1,a=r.length,i=a>1?r[a-1]:void 0,s=a>2?r[2]:void 0;for(i=e.length>3&&"function"==typeof i?(a--,i):void 0,s&&o(r[0],r[1],s)&&(i=a<3?void 0:i,a=1),t=Object(t);++n{var n=r(6571);e.exports=function(e,t){return function(r,o){if(null==r)return r;if(!n(r))return e(r,o);for(var a=r.length,i=t?a:-1,s=Object(r);(t?i--:++i{e.exports=function(e){return function(t,r,n){for(var o=-1,a=Object(t),i=n(t),s=i.length;s--;){var l=i[e?s:++o];if(!1===r(a[l],l,a))break}return t}}},8182:(e,t,r)=>{var n=r(2070),o=r(5713),a=r(2074),i=n&&1/a(new n([,-0]))[1]==1/0?function(e){return new n(e)}:o;e.exports=i},8385:(e,t,r)=>{var n=r(3253),o=r(6686);e.exports=function e(t,r,a,i,s,l){return o(t)&&o(r)&&(l.set(r,t),n(t,r,void 0,e,l),l.delete(r)),t}},6761:(e,t,r)=>{var n=r(2322);e.exports=function(e){return n(e)?void 0:e}},5654:(e,t,r)=>{var n=r(7937),o=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(t){}}();e.exports=o},3668:(e,t,r)=>{var n=r(8902),o=r(2587),a=r(8114);e.exports=function(e,t,r,i,s,l){var c=1&r,u=e.length,d=t.length;if(u!=d&&!(c&&d>u))return!1;var f=l.get(e),p=l.get(t);if(f&&p)return f==t&&p==e;var h=-1,m=!0,g=2&r?new n:void 0;for(l.set(e,t),l.set(t,e);++h{var n=r(9812),o=r(2929),a=r(3211),i=r(3668),s=r(4160),l=r(2074),c=n?n.prototype:void 0,u=c?c.valueOf:void 0;e.exports=function(e,t,r,n,c,d,f){switch(r){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!d(new o(e),new o(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return a(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var p=s;case"[object Set]":var h=1&n;if(p||(p=l),e.size!=t.size&&!h)return!1;var m=f.get(e);if(m)return m==t;n|=2,f.set(e,t);var g=i(p(e),p(t),n,c,d,f);return f.delete(e),g;case"[object Symbol]":if(u)return u.call(e)==u.call(t)}return!1}},5752:(e,t,r)=>{var n=r(9395),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,r,a,i,s){var l=1&r,c=n(e),u=c.length;if(u!=n(t).length&&!l)return!1;for(var d=u;d--;){var f=c[d];if(!(l?f in t:o.call(t,f)))return!1}var p=s.get(e),h=s.get(t);if(p&&h)return p==t&&h==e;var m=!0;s.set(e,t),s.set(t,e);for(var g=l;++d{var n=r(819),o=r(5636),a=r(6350);e.exports=function(e){return a(o(e,void 0,n),e+"")}},7105:(e,t,r)=>{var n="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g;e.exports=n},9395:(e,t,r)=>{var n=r(4262),o=r(9621),a=r(8673);e.exports=function(e){return n(e,a,o)}},8592:(e,t,r)=>{var n=r(4262),o=r(6326),a=r(474);e.exports=function(e){return n(e,a,o)}},2622:(e,t,r)=>{var n=r(705);e.exports=function(e,t){var r=e.__data__;return n(t)?r["string"==typeof t?"string":"hash"]:r.map}},3781:(e,t,r)=>{var n=r(9417),o=r(8673);e.exports=function(e){for(var t=o(e),r=t.length;r--;){var a=t[r],i=e[a];t[r]=[a,i,n(i)]}return t}},7937:(e,t,r)=>{var n=r(6954),o=r(4657);e.exports=function(e,t){var r=o(e,t);return n(r)?r:void 0}},5990:(e,t,r)=>{var n=r(3028)(Object.getPrototypeOf,Object);e.exports=n},4552:(e,t,r)=>{var n=r(9812),o=Object.prototype,a=o.hasOwnProperty,i=o.toString,s=n?n.toStringTag:void 0;e.exports=function(e){var t=a.call(e,s),r=e[s];try{e[s]=void 0;var n=!0}catch(l){}var o=i.call(e);return n&&(t?e[s]=r:delete e[s]),o}},9621:(e,t,r)=>{var n=r(7529),o=r(7828),a=Object.prototype.propertyIsEnumerable,i=Object.getOwnPropertySymbols,s=i?function(e){return null==e?[]:(e=Object(e),n(i(e),(function(t){return a.call(e,t)})))}:o;e.exports=s},6326:(e,t,r)=>{var n=r(8895),o=r(5990),a=r(9621),i=r(7828),s=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)n(t,a(e)),e=o(e);return t}:i;e.exports=s},6924:(e,t,r)=>{var n=r(7685),o=r(5204),a=r(5387),i=r(2070),s=r(6600),l=r(6913),c=r(6996),u="[object Map]",d="[object Promise]",f="[object Set]",p="[object WeakMap]",h="[object DataView]",m=c(n),g=c(o),v=c(a),y=c(i),b=c(s),w=l;(n&&w(new n(new ArrayBuffer(1)))!=h||o&&w(new o)!=u||a&&w(a.resolve())!=d||i&&w(new i)!=f||s&&w(new s)!=p)&&(w=function(e){var t=l(e),r="[object Object]"==t?e.constructor:void 0,n=r?c(r):"";if(n)switch(n){case m:return h;case g:return u;case v:return d;case y:return f;case b:return p}return t}),e.exports=w},4657:e=>{e.exports=function(e,t){return null==e?void 0:e[t]}},9057:(e,t,r)=>{var n=r(5324),o=r(2777),a=r(4052),i=r(9194),s=r(6173),l=r(914);e.exports=function(e,t,r){for(var c=-1,u=(t=n(t,e)).length,d=!1;++c{var n=r(5575);e.exports=function(){this.__data__=n?n(null):{},this.size=0}},5051:e=>{e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},2154:(e,t,r)=>{var n=r(5575),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(n){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return o.call(t,e)?t[e]:void 0}},8734:(e,t,r)=>{var n=r(5575),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return n?void 0!==t[e]:o.call(t,e)}},2662:(e,t,r)=>{var n=r(5575);e.exports=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=n&&void 0===t?"__lodash_hash_undefined__":t,this}},8268:e=>{var t=Object.prototype.hasOwnProperty;e.exports=function(e){var r=e.length,n=new e.constructor(r);return r&&"string"==typeof e[0]&&t.call(e,"index")&&(n.index=e.index,n.input=e.input),n}},8630:(e,t,r)=>{var n=r(1516),o=r(6806),a=r(8962),i=r(1295),s=r(8710);e.exports=function(e,t,r){var l=e.constructor;switch(t){case"[object ArrayBuffer]":return n(e);case"[object Boolean]":case"[object Date]":return new l(+e);case"[object DataView]":return o(e,r);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return s(e,r);case"[object Map]":case"[object Set]":return new l;case"[object Number]":case"[object String]":return new l(e);case"[object RegExp]":return a(e);case"[object Symbol]":return i(e)}}},310:(e,t,r)=>{var n=r(1817),o=r(5990),a=r(6140);e.exports=function(e){return"function"!=typeof e.constructor||a(e)?{}:n(o(e))}},7116:(e,t,r)=>{var n=r(9812),o=r(2777),a=r(4052),i=n?n.isConcatSpreadable:void 0;e.exports=function(e){return a(e)||o(e)||!!(i&&e&&e[i])}},9194:e=>{var t=/^(?:0|[1-9]\d*)$/;e.exports=function(e,r){var n=typeof e;return!!(r=null==r?9007199254740991:r)&&("number"==n||"symbol"!=n&&t.test(e))&&e>-1&&e%1==0&&e{var n=r(3211),o=r(6571),a=r(9194),i=r(6686);e.exports=function(e,t,r){if(!i(r))return!1;var s=typeof t;return!!("number"==s?o(r)&&a(t,r.length):"string"==s&&t in r)&&n(r[t],e)}},2597:(e,t,r)=>{var n=r(4052),o=r(9841),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=function(e,t){if(n(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!o(e))||(i.test(e)||!a.test(e)||null!=t&&e in Object(t))}},705:e=>{e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},7857:(e,t,r)=>{var n=r(3440),o=function(){var e=/[^.]+$/.exec(n&&n.keys&&n.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=function(e){return!!o&&o in e}},6140:e=>{var t=Object.prototype;e.exports=function(e){var r=e&&e.constructor;return e===("function"==typeof r&&r.prototype||t)}},9417:(e,t,r)=>{var n=r(6686);e.exports=function(e){return e===e&&!n(e)}},7563:e=>{e.exports=function(){this.__data__=[],this.size=0}},9935:(e,t,r)=>{var n=r(1340),o=Array.prototype.splice;e.exports=function(e){var t=this.__data__,r=n(t,e);return!(r<0)&&(r==t.length-1?t.pop():o.call(t,r,1),--this.size,!0)}},4190:(e,t,r)=>{var n=r(1340);e.exports=function(e){var t=this.__data__,r=n(t,e);return r<0?void 0:t[r][1]}},1946:(e,t,r)=>{var n=r(1340);e.exports=function(e){return n(this.__data__,e)>-1}},1714:(e,t,r)=>{var n=r(1340);e.exports=function(e,t){var r=this.__data__,o=n(r,e);return o<0?(++this.size,r.push([e,t])):r[o][1]=t,this}},7251:(e,t,r)=>{var n=r(8724),o=r(7160),a=r(5204);e.exports=function(){this.size=0,this.__data__={hash:new n,map:new(a||o),string:new n}}},7159:(e,t,r)=>{var n=r(2622);e.exports=function(e){var t=n(this,e).delete(e);return this.size-=t?1:0,t}},438:(e,t,r)=>{var n=r(2622);e.exports=function(e){return n(this,e).get(e)}},9394:(e,t,r)=>{var n=r(2622);e.exports=function(e){return n(this,e).has(e)}},6874:(e,t,r)=>{var n=r(2622);e.exports=function(e,t){var r=n(this,e),o=r.size;return r.set(e,t),this.size+=r.size==o?0:1,this}},4160:e=>{e.exports=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}},1310:e=>{e.exports=function(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}},8259:(e,t,r)=>{var n=r(5797);e.exports=function(e){var t=n(e,(function(e){return 500===r.size&&r.clear(),e})),r=t.cache;return t}},5575:(e,t,r)=>{var n=r(7937)(Object,"create");e.exports=n},1143:(e,t,r)=>{var n=r(3028)(Object.keys,Object);e.exports=n},3516:e=>{e.exports=function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}},6832:(e,t,r)=>{e=r.nmd(e);var n=r(7105),o=t&&!t.nodeType&&t,a=o&&e&&!e.nodeType&&e,i=a&&a.exports===o&&n.process,s=function(){try{var e=a&&a.require&&a.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(t){}}();e.exports=s},6095:e=>{var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},3028:e=>{e.exports=function(e,t){return function(r){return e(t(r))}}},5636:(e,t,r)=>{var n=r(1170),o=Math.max;e.exports=function(e,t,r){return t=o(void 0===t?e.length-1:t,0),function(){for(var a=arguments,i=-1,s=o(a.length-t,0),l=Array(s);++i{var n=r(2969),o=r(3871);e.exports=function(e,t){return t.length<2?e:n(e,o(t,0,-1))}},6552:(e,t,r)=>{var n=r(7105),o="object"==typeof self&&self&&self.Object===Object&&self,a=n||o||Function("return this")();e.exports=a},3737:e=>{e.exports=function(e,t){if(("constructor"!==t||"function"!==typeof e[t])&&"__proto__"!=t)return e[t]}},6179:e=>{e.exports=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this}},6704:e=>{e.exports=function(e){return this.__data__.has(e)}},2074:e=>{e.exports=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r}},6350:(e,t,r)=>{var n=r(8325),o=r(6578)(n);e.exports=o},6578:e=>{var t=Date.now;e.exports=function(e){var r=0,n=0;return function(){var o=t(),a=16-(o-n);if(n=o,a>0){if(++r>=800)return arguments[0]}else r=0;return e.apply(void 0,arguments)}}},4545:(e,t,r)=>{var n=r(7160);e.exports=function(){this.__data__=new n,this.size=0}},793:e=>{e.exports=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}},7760:e=>{e.exports=function(e){return this.__data__.get(e)}},3892:e=>{e.exports=function(e){return this.__data__.has(e)}},6788:(e,t,r)=>{var n=r(7160),o=r(5204),a=r(4816);e.exports=function(e,t){var r=this.__data__;if(r instanceof n){var i=r.__data__;if(!o||i.length<199)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new a(i)}return r.set(e,t),this.size=r.size,this}},4020:e=>{e.exports=function(e,t,r){for(var n=r-1,o=e.length;++n{var n=r(8259),o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,i=n((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(o,(function(e,r,n,o){t.push(n?o.replace(a,"$1"):r||e)})),t}));e.exports=i},914:(e,t,r)=>{var n=r(9841);e.exports=function(e){if("string"==typeof e||n(e))return e;var t=e+"";return"0"==t&&1/e==-Infinity?"-0":t}},6996:e=>{var t=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return t.call(e)}catch(r){}try{return e+""}catch(r){}}return""}},143:e=>{var t=/\s/;e.exports=function(e){for(var r=e.length;r--&&t.test(e.charAt(r)););return r}},6434:(e,t,r)=>{var n=r(7132);e.exports=function(e){return n(e,5)}},2541:e=>{e.exports=function(e){return function(){return e}}},1163:(e,t,r)=>{var n=r(5647),o=r(3211),a=r(929),i=r(474),s=Object.prototype,l=s.hasOwnProperty,c=n((function(e,t){e=Object(e);var r=-1,n=t.length,c=n>2?t[2]:void 0;for(c&&a(t[0],t[1],c)&&(n=1);++r{var n=r(1170),o=r(5647),a=r(8385),i=r(6777),s=o((function(e){return e.push(void 0,a),n(i,void 0,e)}));e.exports=s},3211:e=>{e.exports=function(e,t){return e===t||e!==e&&t!==t}},819:(e,t,r)=>{var n=r(755);e.exports=function(e){return(null==e?0:e.length)?n(e,1):[]}},3517:(e,t,r)=>{var n=r(755);e.exports=function(e){return(null==e?0:e.length)?n(e,Infinity):[]}},5491:(e,t,r)=>{var n=r(726),o=r(5652),a=r(5111),i=r(4052);e.exports=function(e,t){return(i(e)?n:o)(e,a(t))}},3097:(e,t,r)=>{var n=r(2969);e.exports=function(e,t,r){var o=null==e?void 0:n(e,t);return void 0===o?r:o}},2117:(e,t,r)=>{var n=r(6741),o=r(9057);e.exports=function(e,t){return null!=e&&o(e,t,n)}},3366:(e,t,r)=>{var n=r(7894),o=r(9057);e.exports=function(e,t){return null!=e&&o(e,t,n)}},3279:e=>{e.exports=function(e){return e}},1460:(e,t,r)=>{var n=r(149),o=r(8820),a=r(5647),i=r(46),s=a((function(e){var t=n(e,i);return t.length&&t[0]===e[0]?o(t):[]}));e.exports=s},2636:(e,t,r)=>{var n=r(149),o=r(8820),a=r(5647),i=r(46),s=r(4065),l=a((function(e){var t=s(e),r=n(e,i);return(t="function"==typeof t?t:void 0)&&r.pop(),r.length&&r[0]===e[0]?o(r,void 0,t):[]}));e.exports=l},2777:(e,t,r)=>{var n=r(5193),o=r(2761),a=Object.prototype,i=a.hasOwnProperty,s=a.propertyIsEnumerable,l=n(function(){return arguments}())?n:function(e){return o(e)&&i.call(e,"callee")&&!s.call(e,"callee")};e.exports=l},4052:e=>{var t=Array.isArray;e.exports=t},6571:(e,t,r)=>{var n=r(1629),o=r(6173);e.exports=function(e){return null!=e&&o(e.length)&&!n(e)}},6272:(e,t,r)=>{var n=r(6571),o=r(2761);e.exports=function(e){return o(e)&&n(e)}},6361:(e,t,r)=>{var n=r(6913),o=r(2761);e.exports=function(e){return!0===e||!1===e||o(e)&&"[object Boolean]"==n(e)}},4543:(e,t,r)=>{e=r.nmd(e);var n=r(6552),o=r(14),a=t&&!t.nodeType&&t,i=a&&e&&!e.nodeType&&e,s=i&&i.exports===a?n.Buffer:void 0,l=(s?s.isBuffer:void 0)||o;e.exports=l},4320:(e,t,r)=>{var n=r(3713),o=r(6924),a=r(2777),i=r(4052),s=r(6571),l=r(4543),c=r(6140),u=r(1268),d=Object.prototype.hasOwnProperty;e.exports=function(e){if(null==e)return!0;if(s(e)&&(i(e)||"string"==typeof e||"function"==typeof e.splice||l(e)||u(e)||a(e)))return!e.length;var t=o(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(c(e))return!n(e).length;for(var r in e)if(d.call(e,r))return!1;return!0}},9853:(e,t,r)=>{var n=r(6989);e.exports=function(e,t){return n(e,t)}},6641:(e,t,r)=>{var n=r(6989);e.exports=function(e,t,r){var o=(r="function"==typeof r?r:void 0)?r(e,t):void 0;return void 0===o?n(e,t,void 0,r):!!o}},1629:(e,t,r)=>{var n=r(6913),o=r(6686);e.exports=function(e){if(!o(e))return!1;var t=n(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},6173:e=>{e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},7887:(e,t,r)=>{var n=r(5791),o=r(7574),a=r(6832),i=a&&a.isMap,s=i?o(i):n;e.exports=s},9686:e=>{e.exports=function(e){return null==e}},9160:(e,t,r)=>{var n=r(6913),o=r(2761);e.exports=function(e){return"number"==typeof e||o(e)&&"[object Number]"==n(e)}},6686:e=>{e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},2761:e=>{e.exports=function(e){return null!=e&&"object"==typeof e}},2322:(e,t,r)=>{var n=r(6913),o=r(5990),a=r(2761),i=Function.prototype,s=Object.prototype,l=i.toString,c=s.hasOwnProperty,u=l.call(Object);e.exports=function(e){if(!a(e)||"[object Object]"!=n(e))return!1;var t=o(e);if(null===t)return!0;var r=c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&l.call(r)==u}},5921:(e,t,r)=>{var n=r(449),o=r(7574),a=r(6832),i=a&&a.isSet,s=i?o(i):n;e.exports=s},620:(e,t,r)=>{var n=r(6913),o=r(4052),a=r(2761);e.exports=function(e){return"string"==typeof e||!o(e)&&a(e)&&"[object String]"==n(e)}},9841:(e,t,r)=>{var n=r(6913),o=r(2761);e.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==n(e)}},1268:(e,t,r)=>{var n=r(5428),o=r(7574),a=r(6832),i=a&&a.isTypedArray,s=i?o(i):n;e.exports=s},8673:(e,t,r)=>{var n=r(3204),o=r(3713),a=r(6571);e.exports=function(e){return a(e)?n(e):o(e)}},474:(e,t,r)=>{var n=r(3204),o=r(8122),a=r(6571);e.exports=function(e){return a(e)?n(e,!0):o(e)}},4065:e=>{e.exports=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},5797:(e,t,r)=>{var n=r(4816);function o(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var i=e.apply(this,n);return r.cache=a.set(o,i)||a,i};return r.cache=new(o.Cache||n),r}o.Cache=n,e.exports=o},4677:(e,t,r)=>{var n=r(3253),o=r(4570)((function(e,t,r){n(e,t,r)}));e.exports=o},6777:(e,t,r)=>{var n=r(3253),o=r(4570)((function(e,t,r,o){n(e,t,r,o)}));e.exports=o},5713:e=>{e.exports=function(){}},1488:(e,t,r)=>{var n=r(149),o=r(7132),a=r(8140),i=r(5324),s=r(6614),l=r(6761),c=r(5857),u=r(8592),d=c((function(e,t){var r={};if(null==e)return r;var c=!1;t=n(t,(function(t){return t=i(t,e),c||(c=t.length>1),t})),s(e,u(e),r),c&&(r=o(r,7,l));for(var d=t.length;d--;)a(r,t[d]);return r}));e.exports=d},2616:(e,t,r)=>{var n=r(4008),o=r(5857)((function(e,t){return null==e?{}:n(e,t)}));e.exports=o},3932:(e,t,r)=>{var n=r(396),o=r(2866),a=r(2597),i=r(914);e.exports=function(e){return a(e)?n(i(e)):o(e)}},3535:(e,t,r)=>{var n=r(6415);e.exports=function(e,t){return e&&e.length&&t&&t.length?n(e,t):e}},2759:(e,t,r)=>{var n=r(9421),o=r(5652),a=r(9096),i=r(6487),s=r(4052);e.exports=function(e,t,r){var l=s(e)?n:i,c=arguments.length<3;return l(e,a(t,4),r,c,o)}},9613:(e,t,r)=>{var n=r(9261);e.exports=function(e,t,r){return null==e?e:n(e,t,r)}},7424:(e,t,r)=>{var n=r(755),o=r(2536),a=r(5647),i=r(929),s=a((function(e,t){if(null==e)return[];var r=t.length;return r>1&&i(e,t[0],t[1])?t=[]:r>2&&i(t[0],t[1],t[2])&&(t=[t[0]]),o(e,n(t,1),[])}));e.exports=s},7828:e=>{e.exports=function(){return[]}},14:e=>{e.exports=function(){return!1}},1247:(e,t,r)=>{var n=r(3343),o=r(5111),a=r(9140),i=4294967295,s=Math.min;e.exports=function(e,t){if((e=a(e))<1||e>9007199254740991)return[];var r=i,l=s(e,i);t=o(t),e-=i;for(var c=n(l,t);++r{var n=r(801),o=1/0;e.exports=function(e){return e?(e=n(e))===o||e===-1/0?17976931348623157e292*(e<0?-1:1):e===e?e:0:0===e?e:0}},9140:(e,t,r)=>{var n=r(7303);e.exports=function(e){var t=n(e),r=t%1;return t===t?r?t-r:t:0}},801:(e,t,r)=>{var n=r(1141),o=r(6686),a=r(9841),i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,l=/^0o[0-7]+$/i,c=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(a(e))return NaN;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=n(e);var r=s.test(e);return r||l.test(e)?c(e.slice(2),r?2:8):i.test(e)?NaN:+e}},615:(e,t,r)=>{var n=r(149),o=r(1980),a=r(4052),i=r(9841),s=r(4079),l=r(914),c=r(1069);e.exports=function(e){return a(e)?n(e,l):i(e)?[e]:o(s(c(e)))}},1609:(e,t,r)=>{var n=r(6614),o=r(474);e.exports=function(e){return n(e,o(e))}},1069:(e,t,r)=>{var n=r(8541);e.exports=function(e){return null==e?"":n(e)}},2717:(e,t,r)=>{var n=r(726),o=r(1817),a=r(4664),i=r(9096),s=r(5990),l=r(4052),c=r(4543),u=r(1629),d=r(6686),f=r(1268);e.exports=function(e,t,r){var p=l(e),h=p||c(e)||f(e);if(t=i(t,4),null==r){var m=e&&e.constructor;r=h?p?new m:[]:d(e)&&u(m)?o(s(e)):{}}return(h?n:a)(e,(function(e,n,o){return t(r,e,n,o)})),r}},450:(e,t,r)=>{var n=r(755),o=r(5647),a=r(4416),i=r(6272),s=o((function(e){return a(n(e,1,i,!0))}));e.exports=s},9376:(e,t,r)=>{var n=r(4416);e.exports=function(e){return e&&e.length?n(e):[]}},312:(e,t,r)=>{var n=r(4416);e.exports=function(e,t){return t="function"==typeof t?t:void 0,e&&e.length?n(e,void 0,t):[]}},6940:(e,t,r)=>{var n=r(8140);e.exports=function(e,t){return null==e||n(e,t)}},6757:(e,t,r)=>{var n=r(8746),o=r(5647),a=r(6272),i=o((function(e,t){return a(e)?n(e,t):[]}));e.exports=i},2730:(e,t,r)=>{"use strict";var n=r(5043),o=r(8853);function a(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
\n * @param idOverride\n * @returns {string}\n */\nexport default function useId(idOverride) {\n if (maybeReactUseId !== undefined) {\n const reactId = maybeReactUseId();\n return idOverride != null ? idOverride : reactId;\n }\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.\n return useGlobalId(idOverride);\n}","'use client';\n\n// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js\nimport * as React from 'react';\nimport { Timeout } from '../useTimeout/useTimeout';\nlet hadKeyboardEvent = true;\nlet hadFocusVisibleRecently = false;\nconst hadFocusVisibleRecentlyTimeout = new Timeout();\nconst inputTypesWhitelist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n};\n\n/**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} node\n * @returns {boolean}\n */\nfunction focusTriggersKeyboardModality(node) {\n const {\n type,\n tagName\n } = node;\n if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) {\n return true;\n }\n if (tagName === 'TEXTAREA' && !node.readOnly) {\n return true;\n }\n if (node.isContentEditable) {\n return true;\n }\n return false;\n}\n\n/**\n * Keep track of our keyboard modality state with `hadKeyboardEvent`.\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * @param {KeyboardEvent} event\n */\nfunction handleKeyDown(event) {\n if (event.metaKey || event.altKey || event.ctrlKey) {\n return;\n }\n hadKeyboardEvent = true;\n}\n\n/**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n */\nfunction handlePointerDown() {\n hadKeyboardEvent = false;\n}\nfunction handleVisibilityChange() {\n if (this.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n }\n}\nfunction prepare(doc) {\n doc.addEventListener('keydown', handleKeyDown, true);\n doc.addEventListener('mousedown', handlePointerDown, true);\n doc.addEventListener('pointerdown', handlePointerDown, true);\n doc.addEventListener('touchstart', handlePointerDown, true);\n doc.addEventListener('visibilitychange', handleVisibilityChange, true);\n}\nexport function teardown(doc) {\n doc.removeEventListener('keydown', handleKeyDown, true);\n doc.removeEventListener('mousedown', handlePointerDown, true);\n doc.removeEventListener('pointerdown', handlePointerDown, true);\n doc.removeEventListener('touchstart', handlePointerDown, true);\n doc.removeEventListener('visibilitychange', handleVisibilityChange, true);\n}\nfunction isFocusVisible(event) {\n const {\n target\n } = event;\n try {\n return target.matches(':focus-visible');\n } catch (error) {\n // Browsers not implementing :focus-visible will throw a SyntaxError.\n // We use our own heuristic for those browsers.\n // Rethrow might be better if it's not the expected error but do we really\n // want to crash if focus-visible malfunctioned?\n }\n\n // No need for validFocusTarget check. The user does that by attaching it to\n // focusable events only.\n return hadKeyboardEvent || focusTriggersKeyboardModality(target);\n}\nexport default function useIsFocusVisible() {\n const ref = React.useCallback(node => {\n if (node != null) {\n prepare(node.ownerDocument);\n }\n }, []);\n const isFocusVisibleRef = React.useRef(false);\n\n /**\n * Should be called if a blur event is fired\n */\n function handleBlurVisible() {\n // checking against potential state variable does not suffice if we focus and blur synchronously.\n // React wouldn't have time to trigger a re-render so `focusVisible` would be stale.\n // Ideally we would adjust `isFocusVisible(event)` to look at `relatedTarget` for blur events.\n // This doesn't work in IE11 due to https://github.com/facebook/react/issues/3751\n // TODO: check again if React releases their internal changes to focus event handling (https://github.com/facebook/react/pull/19186).\n if (isFocusVisibleRef.current) {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n hadFocusVisibleRecentlyTimeout.start(100, () => {\n hadFocusVisibleRecently = false;\n });\n isFocusVisibleRef.current = false;\n return true;\n }\n return false;\n }\n\n /**\n * Should be called if a blur event is fired\n */\n function handleFocusVisible(event) {\n if (isFocusVisible(event)) {\n isFocusVisibleRef.current = true;\n return true;\n }\n return false;\n }\n return {\n isFocusVisibleRef,\n onFocus: handleFocusVisible,\n onBlur: handleBlurVisible,\n ref\n };\n}","'use client';\n\nimport * as React from 'react';\nconst UNINITIALIZED = {};\n\n/**\n * A React.useRef() that is initialized lazily with a function. Note that it accepts an optional\n * initialization argument, so the initialization function doesn't need to be an inline closure.\n *\n * @usage\n * const ref = useLazyRef(sortColumns, columns)\n */\nexport default function useLazyRef(init, initArg) {\n const ref = React.useRef(UNINITIALIZED);\n if (ref.current === UNINITIALIZED) {\n ref.current = init(initArg);\n }\n return ref;\n}","'use client';\n\nimport * as React from 'react';\nconst EMPTY = [];\n\n/**\n * A React.useEffect equivalent that runs once, when the component is mounted.\n */\nexport default function useOnMount(fn) {\n /* eslint-disable react-hooks/exhaustive-deps */\n React.useEffect(fn, EMPTY);\n /* eslint-enable react-hooks/exhaustive-deps */\n}","'use client';\n\nimport useLazyRef from '../useLazyRef/useLazyRef';\nimport useOnMount from '../useOnMount/useOnMount';\nexport class Timeout {\n constructor() {\n this.currentId = null;\n this.clear = () => {\n if (this.currentId !== null) {\n clearTimeout(this.currentId);\n this.currentId = null;\n }\n };\n this.disposeEffect = () => {\n return this.clear;\n };\n }\n static create() {\n return new Timeout();\n }\n /**\n * Executes `fn` after `delay`, clearing any previously scheduled call.\n */\n start(delay, fn) {\n this.clear();\n this.currentId = setTimeout(() => {\n this.currentId = null;\n fn();\n }, delay);\n }\n}\nexport default function useTimeout() {\n const timeout = useLazyRef(Timeout.create).current;\n useOnMount(timeout.disposeEffect);\n return timeout;\n}","/**\n * @license React\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var b=Symbol.for(\"react.element\"),c=Symbol.for(\"react.portal\"),d=Symbol.for(\"react.fragment\"),e=Symbol.for(\"react.strict_mode\"),f=Symbol.for(\"react.profiler\"),g=Symbol.for(\"react.provider\"),h=Symbol.for(\"react.context\"),k=Symbol.for(\"react.server_context\"),l=Symbol.for(\"react.forward_ref\"),m=Symbol.for(\"react.suspense\"),n=Symbol.for(\"react.suspense_list\"),p=Symbol.for(\"react.memo\"),q=Symbol.for(\"react.lazy\"),t=Symbol.for(\"react.offscreen\"),u;u=Symbol.for(\"react.module.reference\");\nfunction v(a){if(\"object\"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}exports.ContextConsumer=h;exports.ContextProvider=g;exports.Element=b;exports.ForwardRef=l;exports.Fragment=d;exports.Lazy=q;exports.Memo=p;exports.Portal=c;exports.Profiler=f;exports.StrictMode=e;exports.Suspense=m;\nexports.SuspenseList=n;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return v(a)===h};exports.isContextProvider=function(a){return v(a)===g};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return v(a)===l};exports.isFragment=function(a){return v(a)===d};exports.isLazy=function(a){return v(a)===q};exports.isMemo=function(a){return v(a)===p};\nexports.isPortal=function(a){return v(a)===c};exports.isProfiler=function(a){return v(a)===f};exports.isStrictMode=function(a){return v(a)===e};exports.isSuspense=function(a){return v(a)===m};exports.isSuspenseList=function(a){return v(a)===n};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||\"object\"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};exports.typeOf=v;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","import type {AnySchemaObject} from \"./types\"\nimport AjvCore from \"./core\"\nimport draft7Vocabularies from \"./vocabularies/draft7\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport * as draft7MetaSchema from \"./refs/json-schema-draft-07.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\"\n\nclass Ajv extends AjvCore {\n _addVocabularies(): void {\n super._addVocabularies()\n draft7Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n","export abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n","import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(private condition: Code | boolean, nodes?: ChildNode[]) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(public name: Name, public args: Code, public async?: boolean) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n","import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record\n\ntype ScopeValues = {\n [Prefix in string]?: Map\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n","import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n","import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport * as URI from \"uri-js\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URI.URIComponents,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n","import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n","import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n","import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponents} from \"uri-js\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponents): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let baseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") baseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = baseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n","import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = typeof _jsonTypes[number]\n\nconst jsonTypes: Set = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n","import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs): MergeEvaluatedFunc {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc\n items: MergeEvaluatedFunc\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n","import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n","import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n","import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n","import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n","import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n","import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n","import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n","export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = {}\n readonly RULES: ValidationRules\n readonly _compilations: Set = new Set()\n private readonly _loading: {[Ref in string]?: Promise} = {}\n private readonly _cache: Map = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise\n validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate(schema: JTDSchemaType, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n validate(\n schema: T,\n data: unknown\n ): data is JTDDataType\n validate(schema: AsyncSchema, data: unknown | T): Promise\n validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise\n validate(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n data: unknown | T // to be validated\n ): boolean | Promise {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n compile(\n schema: T,\n _meta?: boolean\n ): ValidateFunction>\n compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction\n compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction\n compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync(\n schema: SchemaObject | JSONSchemaType,\n _meta?: boolean\n ): Promise>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise>\n compileAsync(schema: AsyncSchema, meta?: boolean): Promise>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise>\n compileAsync(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema(keyRef: string): AnyValidateFunction | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n","// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n","// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n","import * as uri from \"uri-js\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n","import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n","import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n","import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n","import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n","import type {CodeKeywordDefinition} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID')\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport idKeyword from \"./id\"\nimport refKeyword from \"./ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n {keyword: \"$comment\"},\n \"definitions\",\n idKeyword,\n refKeyword,\n]\n\nexport default core\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj | DiscrErrorObj\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch?.$ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n","import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n","import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft7Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n]\n\nexport default draft7Vocabularies\n","import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator\n | FormatValidator\n | AsyncFormatValidator\n | AsyncFormatValidator\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n","import type {Vocabulary} from \"../types\"\n\nexport const metadataVocabulary: Vocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n]\n\nexport const contentVocabulary: Vocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n]\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n","import type {ErrorObject, Vocabulary} from \"../../types\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport multipleOf, {MultipleOfError} from \"./multipleOf\"\nimport limitLength from \"./limitLength\"\nimport pattern, {PatternError} from \"./pattern\"\nimport limitProperties from \"./limitProperties\"\nimport required, {RequiredError} from \"./required\"\nimport limitItems from \"./limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"./uniqueItems\"\nimport constKeyword, {ConstError} from \"./const\"\nimport enumKeyword, {EnumError} from \"./enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators, Code} from \"../../compile/codegen\"\n\nconst ops = operators\n\ntype Kwd = \"maximum\" | \"minimum\" | \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n maximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n minimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n exclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n exclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitNumberError = ErrorObject<\n Kwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {data, $data, schema, schemaCode, it} = cxt\n // TODO regexp should be wrapped in try/catchs\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i,\n compare: FormatCompare\n): FormatDefinition {\n return {validate, compare}\n}\n\nexport const fullFormats: DefinedFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(time, compareTime),\n \"date-time\": fmtDef(date_time, compareDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n uri,\n \"uri-reference\":\n /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"uri-template\":\n /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n url: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n email:\n /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n hostname:\n /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/,\n ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: {type: \"number\", validate: validateInt32},\n // signed 64 bit integer\n int64: {type: \"number\", validate: validateInt64},\n // C-type float\n float: {type: \"number\", validate: validateNumber},\n // C-type double\n double: {type: \"number\", validate: validateNumber},\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n}\n\nexport const fastFormats: DefinedFormats = {\n ...fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareTime\n ),\n \"date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareDateTime\n ),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n email:\n /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n}\n\nexport const formatNames = Object.keys(fullFormats) as FormatName[]\n\nfunction isLeapYear(year: number): boolean {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches: string[] | null = DATE.exec(str)\n if (!matches) return false\n const year: number = +matches[1]\n const month: number = +matches[2]\n const day: number = +matches[3]\n return (\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n )\n}\n\nfunction compareDate(d1: string, d2: string): number | undefined {\n if (!(d1 && d2)) return undefined\n if (d1 > d2) return 1\n if (d1 < d2) return -1\n return 0\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i\n\nfunction time(str: string, withTimeZone?: boolean): boolean {\n const matches: string[] | null = TIME.exec(str)\n if (!matches) return false\n\n const hour: number = +matches[1]\n const minute: number = +matches[2]\n const second: number = +matches[3]\n const timeZone: string = matches[5]\n return (\n ((hour <= 23 && minute <= 59 && second <= 59) ||\n (hour === 23 && minute === 59 && second === 60)) &&\n (!withTimeZone || timeZone !== \"\")\n )\n}\n\nfunction compareTime(t1: string, t2: string): number | undefined {\n if (!(t1 && t2)) return undefined\n const a1 = TIME.exec(t1)\n const a2 = TIME.exec(t2)\n if (!(a1 && a2)) return undefined\n t1 = a1[1] + a1[2] + a1[3] + (a1[4] || \"\")\n t2 = a2[1] + a2[2] + a2[3] + (a2[4] || \"\")\n if (t1 > t2) return 1\n if (t1 < t2) return -1\n return 0\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction date_time(str: string): boolean {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true)\n}\n\nfunction compareDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR)\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR)\n const res = compareDate(d1, d2)\n if (res === undefined) return undefined\n return res || compareTime(t1, t2)\n}\n\nconst NOT_URI_FRAGMENT = /\\/|:/\nconst URI =\n /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n BYTE.lastIndex = 0\n return BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n return true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n if (Z_ANCHOR.test(str)) return false\n try {\n new RegExp(str)\n return true\n } catch (e) {\n return false\n }\n}\n","import {\n DefinedFormats,\n FormatMode,\n FormatName,\n formatNames,\n fastFormats,\n fullFormats,\n} from \"./formats\"\nimport formatLimit from \"./limit\"\nimport type Ajv from \"ajv\"\nimport type {Plugin, Format} from \"ajv\"\nimport {_, Name} from \"ajv/dist/compile/codegen\"\n\nexport {FormatMode, FormatName} from \"./formats\"\nexport {LimitFormatError} from \"./limit\"\nexport interface FormatOptions {\n mode?: FormatMode\n formats?: FormatName[]\n keywords?: boolean\n}\n\nexport type FormatsPluginOptions = FormatName[] | FormatOptions\n\nexport interface FormatsPlugin extends Plugin {\n get: (format: FormatName, mode?: FormatMode) => Format\n}\n\nconst fullName = new Name(\"fullFormats\")\nconst fastName = new Name(\"fastFormats\")\n\nconst formatsPlugin: FormatsPlugin = (\n ajv: Ajv,\n opts: FormatsPluginOptions = {keywords: true}\n): Ajv => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, fullFormats, fullName)\n return ajv\n }\n const [formats, exportName] =\n opts.mode === \"fast\" ? [fastFormats, fastName] : [fullFormats, fullName]\n const list = opts.formats || formatNames\n addFormats(ajv, list, formats, exportName)\n if (opts.keywords) formatLimit(ajv)\n return ajv\n}\n\nformatsPlugin.get = (name: FormatName, mode: FormatMode = \"full\"): Format => {\n const formats = mode === \"fast\" ? fastFormats : fullFormats\n const f = formats[name]\n if (!f) throw new Error(`Unknown format \"${name}\"`)\n return f\n}\n\nfunction addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {\n ajv.opts.code.formats ??= _`require(\"ajv-formats/dist/formats\").${exportName}`\n for (const f of list) ajv.addFormat(f, fs[f])\n}\n\nmodule.exports = exports = formatsPlugin\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default formatsPlugin\n","import type Ajv from \"ajv\"\nimport type {\n Plugin,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n Code,\n Name,\n ErrorObject,\n} from \"ajv\"\nimport type {AddedFormat} from \"ajv/dist/types\"\nimport type {Rule} from \"ajv/dist/compile/rules\"\nimport {KeywordCxt} from \"ajv\"\nimport {_, str, or, getProperty, operators} from \"ajv/dist/compile/codegen\"\n\ntype Kwd = \"formatMaximum\" | \"formatMinimum\" | \"formatExclusiveMaximum\" | \"formatExclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst ops = operators\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n formatMaximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n formatMinimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n formatExclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n formatExclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitFormatError = ErrorObject\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nexport const formatLimitDefinition: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const {gen, data, schemaCode, keyword, it} = cxt\n const {opts, self} = it\n if (!opts.validateFormats) return\n\n const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, \"format\")\n if (fCxt.$data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fmt = gen.const(\"fmt\", _`${fmts}[${fCxt.schemaCode}]`)\n cxt.fail$data(\n or(\n _`typeof ${fmt} != \"object\"`,\n _`${fmt} instanceof RegExp`,\n _`typeof ${fmt}.compare != \"function\"`,\n compareCode(fmt)\n )\n )\n }\n\n function validateFormat(): void {\n const format = fCxt.schema as string\n const fmtDef: AddedFormat | undefined = self.formats[format]\n if (!fmtDef || fmtDef === true) return\n if (\n typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\"\n ) {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`)\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined,\n })\n\n cxt.fail$data(compareCode(fmt))\n }\n\n function compareCode(fmt: Name): Code {\n return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0`\n }\n },\n dependencies: [\"format\"],\n}\n\nconst formatLimitPlugin: Plugin = (ajv: Ajv): Ajv => {\n ajv.addKeyword(formatLimitDefinition)\n return ajv\n}\n\nexport default formatLimitPlugin\n","import type {AnySchemaObject} from \"./types\"\nimport AjvCore from \"./core\"\nimport draft7Vocabularies from \"./vocabularies/draft7\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport * as draft7MetaSchema from \"./refs/json-schema-draft-07.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\"\n\nclass Ajv extends AjvCore {\n _addVocabularies(): void {\n super._addVocabularies()\n draft7Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n","export abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n","import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(private condition: Code | boolean, nodes?: ChildNode[]) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(public name: Name, public args: Code, public async?: boolean) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n","import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record\n\ntype ScopeValues = {\n [Prefix in string]?: Map\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n","import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n","import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport * as URI from \"uri-js\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URI.URIComponents,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n","import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n","import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n","import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponents} from \"uri-js\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponents): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let baseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") baseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = baseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n","import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = typeof _jsonTypes[number]\n\nconst jsonTypes: Set = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n","import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs): MergeEvaluatedFunc {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc\n items: MergeEvaluatedFunc\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n","import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n","import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n","import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n","import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n","import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n","import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n","import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n","export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = {}\n readonly RULES: ValidationRules\n readonly _compilations: Set = new Set()\n private readonly _loading: {[Ref in string]?: Promise} = {}\n private readonly _cache: Map = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise\n validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate(schema: JTDSchemaType, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n validate(\n schema: T,\n data: unknown\n ): data is JTDDataType\n validate(schema: AsyncSchema, data: unknown | T): Promise\n validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise\n validate(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n data: unknown | T // to be validated\n ): boolean | Promise {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n compile(\n schema: T,\n _meta?: boolean\n ): ValidateFunction>\n compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction\n compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction\n compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync(\n schema: SchemaObject | JSONSchemaType,\n _meta?: boolean\n ): Promise>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise>\n compileAsync(schema: AsyncSchema, meta?: boolean): Promise>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise>\n compileAsync(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema(keyRef: string): AnyValidateFunction | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n","// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n","// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n","import * as uri from \"uri-js\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n","import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n","import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n","import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n","import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n","import type {CodeKeywordDefinition} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID')\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport idKeyword from \"./id\"\nimport refKeyword from \"./ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n {keyword: \"$comment\"},\n \"definitions\",\n idKeyword,\n refKeyword,\n]\n\nexport default core\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj | DiscrErrorObj\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch?.$ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n","import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n","import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft7Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n]\n\nexport default draft7Vocabularies\n","import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator\n | FormatValidator\n | AsyncFormatValidator\n | AsyncFormatValidator\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n","import type {Vocabulary} from \"../types\"\n\nexport const metadataVocabulary: Vocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n]\n\nexport const contentVocabulary: Vocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n]\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n","import type {ErrorObject, Vocabulary} from \"../../types\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport multipleOf, {MultipleOfError} from \"./multipleOf\"\nimport limitLength from \"./limitLength\"\nimport pattern, {PatternError} from \"./pattern\"\nimport limitProperties from \"./limitProperties\"\nimport required, {RequiredError} from \"./required\"\nimport limitItems from \"./limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"./uniqueItems\"\nimport constKeyword, {ConstError} from \"./const\"\nimport enumKeyword, {EnumError} from \"./enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators, Code} from \"../../compile/codegen\"\n\nconst ops = operators\n\ntype Kwd = \"maximum\" | \"minimum\" | \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n maximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n minimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n exclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n exclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitNumberError = ErrorObject<\n Kwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {data, $data, schema, schemaCode, it} = cxt\n // TODO regexp should be wrapped in try/catchs\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i b ) {\n\t\t\tt = b;\n\t\t\tb = a;\n\t\t\ta = t;\n\t\t}\n\t\tb = b - a; // b=0 iff b=a\n\t}\n\t// Restore common factors of 2...\n\treturn k * a;\n} // end FUNCTION gcd()\n\n/**\n* FUNCTION: bitwise( a, b )\n*\tComputes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm and bitwise operations.\n*\n* @param {Number} a - safe integer\n* @param {Number} b - safe integer\n* @returns {Number} greatest common divisor\n*/\nfunction bitwise( a, b ) {\n\tvar k = 0,\n\t\tt;\n\t// Simple cases:\n\tif ( a === 0 ) {\n\t\treturn b;\n\t}\n\tif ( b === 0 ) {\n\t\treturn a;\n\t}\n\t// Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`...\n\twhile ( (a & 1) === 0 && (b & 1) === 0 ) {\n\t\ta >>>= 1; // right shift\n\t\tb >>>= 1; // right shift\n\t\tk++;\n\t}\n\t// Reduce `a` to an odd number...\n\twhile ( (a & 1) === 0 ) {\n\t\ta >>>= 1; // right shift\n\t}\n\t// Henceforth, `a` is always odd...\n\twhile ( b ) {\n\t\t// Remove all factors of 2 in `b`, as they are not common...\n\t\twhile ( (b & 1) === 0 ) {\n\t\t\tb >>>= 1; // right shift\n\t\t}\n\t\t// `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)...\n\t\tif ( a > b ) {\n\t\t\tt = b;\n\t\t\tb = a;\n\t\t\ta = t;\n\t\t}\n\t\tb = b - a; // b=0 iff b=a\n\t}\n\t// Restore common factors of 2...\n\treturn a << k;\n} // end FUNCTION bitwise()\n\n\n// GREATEST COMMON DIVISOR //\n\n/**\n* FUNCTION: compute( arr[, clbk] )\n*\tComputes the greatest common divisor.\n*\n* @param {Number[]|Number} arr - input array of integers\n* @param {Function|Number} [clbk] - accessor function for accessing array values\n* @returns {Number|Null} greatest common divisor or null\n*/\nfunction compute() {\n\tvar nargs = arguments.length,\n\t\targs,\n\t\tclbk,\n\t\tarr,\n\t\tlen,\n\t\ta, b,\n\t\ti;\n\n\t// Copy the input arguments to an array...\n\targs = new Array( nargs );\n\tfor ( i = 0; i < nargs; i++ ) {\n\t\targs[ i ] = arguments[ i ];\n\t}\n\t// Have we been provided with integer arguments?\n\tif ( isIntegerArray( args ) ) {\n\t\tif ( nargs === 2 ) {\n\t\t\ta = args[ 0 ];\n\t\t\tb = args[ 1 ];\n\t\t\tif ( a < 0 ) {\n\t\t\t\ta = -a;\n\t\t\t}\n\t\t\tif ( b < 0 ) {\n\t\t\t\tb = -b;\n\t\t\t}\n\t\t\tif ( a <= MAXINT && b <= MAXINT ) {\n\t\t\t\treturn bitwise( a, b );\n\t\t\t} else {\n\t\t\t\treturn gcd( a, b );\n\t\t\t}\n\t\t}\n\t\tarr = args;\n\t}\n\t// If not integers, ensure the first argument is an array...\n\telse if ( !isArray( args[ 0 ] ) ) {\n\t\tthrow new TypeError( 'gcd()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' );\n\t}\n\t// Have we been provided with more than one argument? If so, ensure that the accessor argument is a function...\n\telse if ( nargs > 1 ) {\n\t\tarr = args[ 0 ];\n\t\tclbk = args[ 1 ];\n\t\tif ( !isFunction( clbk ) ) {\n\t\t\tthrow new TypeError( 'gcd()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' );\n\t\t}\n\t}\n\t// We have been provided an array...\n\telse {\n\t\tarr = args[ 0 ];\n\t}\n\tlen = arr.length;\n\n\t// Check if a sufficient number of values have been provided...\n\tif ( len < 2 ) {\n\t\treturn null;\n\t}\n\t// If an accessor is provided, extract the array values...\n\tif ( clbk ) {\n\t\ta = new Array( len );\n\t\tfor ( i = 0; i < len; i++ ) {\n\t\t\ta[ i ] = clbk( arr[ i ], i );\n\t\t}\n\t\tarr = a;\n\t}\n\t// Given an input array, ensure all array values are integers...\n\tif ( nargs < 3 ) {\n\t\tif ( !isIntegerArray( arr ) ) {\n\t\t\tthrow new TypeError( 'gcd()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' );\n\t\t}\n\t}\n\t// Convert any negative integers to positive integers...\n\tfor ( i = 0; i < len; i++ ) {\n\t\ta = arr[ i ];\n\t\tif ( a < 0 ) {\n\t\t\tarr[ i ] = -a;\n\t\t}\n\t}\n\t// Exploit the fact that the gcd is an associative function...\n\ta = arr[ 0 ];\n\tfor ( i = 1; i < len; i++ ) {\n\t\tb = arr[ i ];\n\t\tif ( b <= MAXINT && a <= MAXINT ) {\n\t\t\ta = bitwise( a, b );\n\t\t} else {\n\t\t\ta = gcd( a, b );\n\t\t}\n\t}\n\treturn a;\n} // end FUNCTION compute()\n\n\n// EXPORTS //\n\nmodule.exports = compute;\n","'use strict';\n\n// MODULES //\n\nvar gcd = require( 'compute-gcd' ),\n\tisArray = require( 'validate.io-array' ),\n\tisIntegerArray = require( 'validate.io-integer-array' ),\n\tisFunction = require( 'validate.io-function' );\n\n\n// LEAST COMMON MULTIPLE //\n\n/**\n* FUNCTION: lcm( arr[, clbk] )\n*\tComputes the least common multiple (lcm).\n*\n* @param {Number[]|Number} arr - input array of integers\n* @param {Function|Number} [accessor] - accessor function for accessing array values\n* @returns {Number|Null} least common multiple or null\n*/\nfunction lcm() {\n\tvar nargs = arguments.length,\n\t\targs,\n\t\tclbk,\n\t\tarr,\n\t\tlen,\n\t\ta, b,\n\t\ti;\n\n\t// Copy the input arguments to an array...\n\targs = new Array( nargs );\n\tfor ( i = 0; i < nargs; i++ ) {\n\t\targs[ i ] = arguments[ i ];\n\t}\n\t// Have we been provided with integer arguments?\n\tif ( isIntegerArray( args ) ) {\n\t\tif ( nargs === 2 ) {\n\t\t\ta = args[ 0 ];\n\t\t\tb = args[ 1 ];\n\t\t\tif ( a < 0 ) {\n\t\t\t\ta = -a;\n\t\t\t}\n\t\t\tif ( b < 0 ) {\n\t\t\t\tb = -b;\n\t\t\t}\n\t\t\tif ( a === 0 || b === 0 ) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn ( a/gcd(a,b) ) * b;\n\t\t}\n\t\tarr = args;\n\t}\n\t// If not integers, ensure that the first argument is an array...\n\telse if ( !isArray( args[ 0 ] ) ) {\n\t\tthrow new TypeError( 'lcm()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' );\n\t}\n\t// Have we been provided with more than one argument? If so, ensure that the accessor argument is a function...\n\telse if ( nargs > 1 ) {\n\t\tarr = args[ 0 ];\n\t\tclbk = args[ 1 ];\n\t\tif ( !isFunction( clbk ) ) {\n\t\t\tthrow new TypeError( 'lcm()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' );\n\t\t}\n\t}\n\t// We have been provided an array...\n\telse {\n\t\tarr = args[ 0 ];\n\t}\n\tlen = arr.length;\n\n\t// Check if a sufficient number of values have been provided...\n\tif ( len < 2 ) {\n\t\treturn null;\n\t}\n\t// If an accessor is provided, extract the array values...\n\tif ( clbk ) {\n\t\ta = new Array( len );\n\t\tfor ( i = 0; i < len; i++ ) {\n\t\t\ta[ i ] = clbk( arr[ i ], i );\n\t\t}\n\t\tarr = a;\n\t}\n\t// Given an input array, ensure all array values are integers...\n\tif ( nargs < 3 ) {\n\t\tif ( !isIntegerArray( arr ) ) {\n\t\t\tthrow new TypeError( 'lcm()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' );\n\t\t}\n\t}\n\t// Convert any negative integers to positive integers...\n\tfor ( i = 0; i < len; i++ ) {\n\t\ta = arr[ i ];\n\t\tif ( a < 0 ) {\n\t\t\tarr[ i ] = -a;\n\t\t}\n\t}\n\t// Exploit the fact that the lcm is an associative function...\n\ta = arr[ 0 ];\n\tfor ( i = 1; i < len; i++ ) {\n\t\tb = arr[ i ];\n\t\tif ( a === 0 || b === 0 ) {\n\t\t\treturn 0;\n\t\t}\n\t\ta = ( a/gcd(a,b) ) * b;\n\t}\n\treturn a;\n} // end FUNCTION lcm()\n\n\n// EXPORTS //\n\nmodule.exports = lcm;\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","var isEqual = require('lodash/isEqual')\nvar sortBy = require('lodash/sortBy')\nvar uniq = require('lodash/uniq')\nvar uniqWith = require('lodash/uniqWith')\nvar defaults = require('lodash/defaults')\nvar intersectionWith = require('lodash/intersectionWith')\nvar isPlainObject = require('lodash/isPlainObject')\nvar isBoolean = require('lodash/isBoolean')\n\nvar normalizeArray = val => Array.isArray(val)\n ? val : [val]\nvar undef = val => val === undefined\nvar keys = obj => isPlainObject(obj) || Array.isArray(obj) ? Object.keys(obj) : []\nvar has = (obj, key) => obj.hasOwnProperty(key)\nvar stringArray = arr => sortBy(uniq(arr))\nvar undefEmpty = val => undef(val) || (Array.isArray(val) && val.length === 0)\nvar keyValEqual = (a, b, key, compare) => b && has(b, key) && a && has(a, key) && compare(a[key], b[key])\nvar undefAndZero = (a, b) => (undef(a) && b === 0) || (undef(b) && a === 0) || isEqual(a, b)\nvar falseUndefined = (a, b) => (undef(a) && b === false) || (undef(b) && a === false) || isEqual(a, b)\nvar emptySchema = schema => undef(schema) || isEqual(schema, {}) || schema === true\nvar emptyObjUndef = schema => undef(schema) || isEqual(schema, {})\nvar isSchema = val => undef(val) || isPlainObject(val) || val === true || val === false\n\nfunction undefArrayEqual(a, b) {\n if (undefEmpty(a) && undefEmpty(b)) {\n return true\n } else {\n return isEqual(stringArray(a), stringArray(b))\n }\n}\n\nfunction unsortedNormalizedArray(a, b) {\n a = normalizeArray(a)\n b = normalizeArray(b)\n return isEqual(stringArray(a), stringArray(b))\n}\n\nfunction schemaGroup(a, b, key, compare) {\n var allProps = uniq(keys(a).concat(keys(b)))\n if (emptyObjUndef(a) && emptyObjUndef(b)) {\n return true\n } else if (emptyObjUndef(a) && keys(b).length) {\n return false\n } else if (emptyObjUndef(b) && keys(a).length) {\n return false\n }\n\n return allProps.every(function(key) {\n var aVal = a[key]\n var bVal = b[key]\n if (Array.isArray(aVal) && Array.isArray(bVal)) {\n return isEqual(stringArray(a), stringArray(b))\n } else if (Array.isArray(aVal) && !Array.isArray(bVal)) {\n return false\n } else if (Array.isArray(bVal) && !Array.isArray(aVal)) {\n return false\n }\n return keyValEqual(a, b, key, compare)\n })\n}\n\nfunction items(a, b, key, compare) {\n if (isPlainObject(a) && isPlainObject(b)) {\n return compare(a, b)\n } else if (Array.isArray(a) && Array.isArray(b)) {\n return schemaGroup(a, b, key, compare)\n } else {\n return isEqual(a, b)\n }\n}\n\nfunction unsortedArray(a, b, key, compare) {\n var uniqueA = uniqWith(a, compare)\n var uniqueB = uniqWith(b, compare)\n var inter = intersectionWith(uniqueA, uniqueB, compare)\n return inter.length === Math.max(uniqueA.length, uniqueB.length)\n}\n\nvar comparers = {\n title: isEqual,\n uniqueItems: falseUndefined,\n minLength: undefAndZero,\n minItems: undefAndZero,\n minProperties: undefAndZero,\n required: undefArrayEqual,\n enum: undefArrayEqual,\n type: unsortedNormalizedArray,\n items: items,\n anyOf: unsortedArray,\n allOf: unsortedArray,\n oneOf: unsortedArray,\n properties: schemaGroup,\n patternProperties: schemaGroup,\n dependencies: schemaGroup\n}\n\nvar acceptsUndefined = [\n 'properties',\n 'patternProperties',\n 'dependencies',\n 'uniqueItems',\n 'minLength',\n 'minItems',\n 'minProperties',\n 'required'\n]\n\nvar schemaProps = ['additionalProperties', 'additionalItems', 'contains', 'propertyNames', 'not']\n\nfunction compare(a, b, options) {\n options = defaults(options, {\n ignore: []\n })\n\n if (emptySchema(a) && emptySchema(b)) {\n return true\n }\n\n if (!isSchema(a) || !isSchema(b)) {\n throw new Error('Either of the values are not a JSON schema.')\n }\n if (a === b) {\n return true\n }\n\n if (isBoolean(a) && isBoolean(b)) {\n return a === b\n }\n\n if ((a === undefined && b === false) || (b === undefined && a === false)) {\n return false\n }\n\n if ((undef(a) && !undef(b)) || (!undef(a) && undef(b))) {\n return false\n }\n\n var allKeys = uniq(Object.keys(a).concat(Object.keys(b)))\n\n if (options.ignore.length) {\n allKeys = allKeys.filter(k => options.ignore.indexOf(k) === -1)\n }\n\n if (!allKeys.length) {\n return true\n }\n\n function innerCompare(a, b) {\n return compare(a, b, options)\n }\n\n return allKeys.every(function(key) {\n var aValue = a[key]\n var bValue = b[key]\n\n if (schemaProps.indexOf(key) !== -1) {\n return compare(aValue, bValue, options)\n }\n\n var comparer = comparers[key]\n if (!comparer) {\n comparer = isEqual\n }\n\n // do simple lodash check first\n if (isEqual(aValue, bValue)) {\n return true\n }\n\n if (acceptsUndefined.indexOf(key) === -1) {\n if ((!has(a, key) && has(b, key)) || (has(a, key) && !has(b, key))) {\n return aValue === bValue\n }\n }\n\n var result = comparer(aValue, bValue, key, innerCompare)\n if (!isBoolean(result)) {\n throw new Error('Comparer must return true or false')\n }\n return result\n })\n}\n\nmodule.exports = compare\n","const flatten = require('lodash/flatten')\nconst flattenDeep = require('lodash/flattenDeep')\nconst isPlainObject = require('lodash/isPlainObject')\nconst uniq = require('lodash/uniq')\nconst uniqWith = require('lodash/uniqWith')\nconst without = require('lodash/without')\n\nfunction deleteUndefinedProps(returnObject) {\n // cleanup empty\n for (const prop in returnObject) {\n if (has(returnObject, prop) && isEmptySchema(returnObject[prop])) {\n delete returnObject[prop]\n }\n }\n return returnObject\n}\n\nconst allUniqueKeys = (arr) => uniq(flattenDeep(arr.map(keys)))\nconst getValues = (schemas, key) => schemas.map(schema => schema && schema[key])\nconst has = (obj, propName) => Object.prototype.hasOwnProperty.call(obj, propName)\nconst keys = obj => {\n if (isPlainObject(obj) || Array.isArray(obj)) {\n return Object.keys(obj)\n } else {\n return []\n }\n}\n\nconst notUndefined = (val) => val !== undefined\nconst isSchema = (val) => isPlainObject(val) || val === true || val === false\nconst isEmptySchema = (obj) => (!keys(obj).length) && obj !== false && obj !== true\nconst withoutArr = (arr, ...rest) => without.apply(null, [arr].concat(flatten(rest)))\n\nmodule.exports = {\n allUniqueKeys,\n deleteUndefinedProps,\n getValues,\n has,\n isEmptySchema,\n isSchema,\n keys,\n notUndefined,\n uniqWith,\n withoutArr\n}\n","\nconst compare = require('json-schema-compare')\nconst forEach = require('lodash/forEach')\nconst {\n allUniqueKeys,\n deleteUndefinedProps,\n has,\n isSchema,\n notUndefined,\n uniqWith\n} = require('../common')\n\nfunction removeFalseSchemasFromArray(target) {\n forEach(target, function(schema, index) {\n if (schema === false) {\n target.splice(index, 1)\n }\n })\n}\n\nfunction getItemSchemas(subSchemas, key) {\n return subSchemas.map(function(sub) {\n if (!sub) {\n return undefined\n }\n\n if (Array.isArray(sub.items)) {\n const schemaAtPos = sub.items[key]\n if (isSchema(schemaAtPos)) {\n return schemaAtPos\n } else if (has(sub, 'additionalItems')) {\n return sub.additionalItems\n }\n } else {\n return sub.items\n }\n\n return undefined\n })\n}\n\nfunction getAdditionalSchemas(subSchemas) {\n return subSchemas.map(function(sub) {\n if (!sub) {\n return undefined\n }\n if (Array.isArray(sub.items)) {\n return sub.additionalItems\n }\n return sub.items\n })\n}\n\n// Provide source when array\nfunction mergeItems(group, mergeSchemas, items) {\n const allKeys = allUniqueKeys(items)\n return allKeys.reduce(function(all, key) {\n const schemas = getItemSchemas(group, key)\n const compacted = uniqWith(schemas.filter(notUndefined), compare)\n all[key] = mergeSchemas(compacted, key)\n return all\n }, [])\n}\n\nmodule.exports = {\n keywords: ['items', 'additionalItems'],\n resolver(values, parents, mergers) {\n // const createSubMerger = groupKey => (schemas, key) => mergeSchemas(schemas, parents.concat(groupKey, key))\n const items = values.map(s => s.items)\n const itemsCompacted = items.filter(notUndefined)\n const returnObject = {}\n\n // if all items keyword values are schemas, we can merge them as simple schemas\n // if not we need to merge them as mixed\n if (itemsCompacted.every(isSchema)) {\n returnObject.items = mergers.items(items)\n } else {\n returnObject.items = mergeItems(values, mergers.items, items)\n }\n\n let schemasAtLastPos\n if (itemsCompacted.every(Array.isArray)) {\n schemasAtLastPos = values.map(s => s.additionalItems)\n } else if (itemsCompacted.some(Array.isArray)) {\n schemasAtLastPos = getAdditionalSchemas(values)\n }\n\n if (schemasAtLastPos) {\n returnObject.additionalItems = mergers.additionalItems(schemasAtLastPos)\n }\n\n if (returnObject.additionalItems === false && Array.isArray(returnObject.items)) {\n removeFalseSchemasFromArray(returnObject.items)\n }\n\n return deleteUndefinedProps(returnObject)\n }\n}\n","\nconst compare = require('json-schema-compare')\nconst forEach = require('lodash/forEach')\nconst {\n allUniqueKeys,\n deleteUndefinedProps,\n getValues,\n keys,\n notUndefined,\n uniqWith,\n withoutArr\n} = require('../common')\n\nfunction removeFalseSchemas(target) {\n forEach(target, function(schema, prop) {\n if (schema === false) {\n delete target[prop]\n }\n })\n}\n\nfunction mergeSchemaGroup(group, mergeSchemas) {\n const allKeys = allUniqueKeys(group)\n return allKeys.reduce(function(all, key) {\n const schemas = getValues(group, key)\n const compacted = uniqWith(schemas.filter(notUndefined), compare)\n all[key] = mergeSchemas(compacted, key)\n return all\n }, {})\n}\n\nmodule.exports = {\n keywords: ['properties', 'patternProperties', 'additionalProperties'],\n resolver(values, parents, mergers, options) {\n // first get rid of all non permitted properties\n if (!options.ignoreAdditionalProperties) {\n values.forEach(function(subSchema) {\n const otherSubSchemas = values.filter(s => s !== subSchema)\n const ownKeys = keys(subSchema.properties)\n const ownPatternKeys = keys(subSchema.patternProperties)\n const ownPatterns = ownPatternKeys.map(k => new RegExp(k))\n otherSubSchemas.forEach(function(other) {\n const allOtherKeys = keys(other.properties)\n const keysMatchingPattern = allOtherKeys.filter(k => ownPatterns.some(pk => pk.test(k)))\n const additionalKeys = withoutArr(allOtherKeys, ownKeys, keysMatchingPattern)\n additionalKeys.forEach(function(key) {\n other.properties[key] = mergers.properties([\n other.properties[key], subSchema.additionalProperties\n ], key)\n })\n })\n })\n\n // remove disallowed patternProperties\n values.forEach(function(subSchema) {\n const otherSubSchemas = values.filter(s => s !== subSchema)\n const ownPatternKeys = keys(subSchema.patternProperties)\n if (subSchema.additionalProperties === false) {\n otherSubSchemas.forEach(function(other) {\n const allOtherPatterns = keys(other.patternProperties)\n const additionalPatternKeys = withoutArr(allOtherPatterns, ownPatternKeys)\n additionalPatternKeys.forEach(key => delete other.patternProperties[key])\n })\n }\n })\n }\n\n const returnObject = {\n additionalProperties: mergers.additionalProperties(values.map(s => s.additionalProperties)),\n patternProperties: mergeSchemaGroup(values.map(s => s.patternProperties), mergers.patternProperties),\n properties: mergeSchemaGroup(values.map(s => s.properties), mergers.properties)\n }\n\n if (returnObject.additionalProperties === false) {\n removeFalseSchemas(returnObject.properties)\n }\n\n return deleteUndefinedProps(returnObject)\n }\n}\n","const cloneDeep = require('lodash/cloneDeep')\nconst compare = require('json-schema-compare')\nconst computeLcm = require('compute-lcm')\nconst defaultsDeep = require('lodash/defaultsDeep')\nconst flatten = require('lodash/flatten')\nconst flattenDeep = require('lodash/flattenDeep')\nconst intersection = require('lodash/intersection')\nconst intersectionWith = require('lodash/intersectionWith')\nconst isEqual = require('lodash/isEqual')\nconst isPlainObject = require('lodash/isPlainObject')\nconst pullAll = require('lodash/pullAll')\nconst sortBy = require('lodash/sortBy')\nconst uniq = require('lodash/uniq')\nconst uniqWith = require('lodash/uniqWith')\n\nconst propertiesResolver = require('./complex-resolvers/properties')\nconst itemsResolver = require('./complex-resolvers/items')\n\nconst contains = (arr, val) => arr.indexOf(val) !== -1\nconst isSchema = (val) => isPlainObject(val) || val === true || val === false\nconst isFalse = (val) => val === false\nconst isTrue = (val) => val === true\nconst schemaResolver = (compacted, key, mergeSchemas) => mergeSchemas(compacted)\nconst stringArray = (values) => sortBy(uniq(flattenDeep(values)))\nconst notUndefined = (val) => val !== undefined\nconst allUniqueKeys = (arr) => uniq(flattenDeep(arr.map(keys)))\n\n// resolvers\nconst first = compacted => compacted[0]\nconst required = compacted => stringArray(compacted)\nconst maximumValue = compacted => Math.max.apply(Math, compacted)\nconst minimumValue = compacted => Math.min.apply(Math, compacted)\nconst uniqueItems = compacted => compacted.some(isTrue)\nconst examples = compacted => uniqWith(flatten(compacted), isEqual)\n\nfunction compareProp(key) {\n return function(a, b) {\n return compare({\n [key]: a\n }, { [key]: b })\n }\n}\n\nfunction getAllOf(schema) {\n let { allOf = [], ...copy } = schema\n copy = isPlainObject(schema) ? copy : schema // if schema is boolean\n return [copy, ...allOf.map(getAllOf)]\n}\n\nfunction getValues(schemas, key) {\n return schemas.map(schema => schema && schema[key])\n}\n\nfunction tryMergeSchemaGroups(schemaGroups, mergeSchemas) {\n return schemaGroups.map(function(schemas, index) {\n try {\n return mergeSchemas(schemas, index)\n } catch (e) {\n return undefined\n }\n }).filter(notUndefined)\n}\n\nfunction keys(obj) {\n if (isPlainObject(obj) || Array.isArray(obj)) {\n return Object.keys(obj)\n } else {\n return []\n }\n}\n\nfunction getAnyOfCombinations(arrOfArrays, combinations) {\n combinations = combinations || []\n if (!arrOfArrays.length) {\n return combinations\n }\n\n const values = arrOfArrays.slice(0).shift()\n const rest = arrOfArrays.slice(1)\n if (combinations.length) {\n return getAnyOfCombinations(rest, flatten(combinations.map(combination => values.map(item => ([item].concat(combination))))))\n }\n return getAnyOfCombinations(rest, values.map(item => (item)))\n}\n\nfunction throwIncompatible(values, paths) {\n let asJSON\n try {\n asJSON = values.map(function(val) {\n return JSON.stringify(val, null, 2)\n }).join('\\n')\n } catch (variable) {\n asJSON = values.join(', ')\n }\n throw new Error('Could not resolve values for path:\"' + paths.join('.') + '\". They are probably incompatible. Values: \\n' + asJSON)\n}\n\nfunction callGroupResolver(complexKeywords, resolverName, schemas, mergeSchemas, options, parents) {\n if (complexKeywords.length) {\n const resolverConfig = options.complexResolvers[resolverName]\n if (!resolverConfig || !resolverConfig.resolver) {\n throw new Error('No resolver found for ' + resolverName)\n }\n\n // extract all keywords from all the schemas that have one or more\n // then remove all undefined ones and not unique\n const extractedKeywordsOnly = schemas.map(schema => complexKeywords.reduce((all, key) => {\n if (schema[key] !== undefined) all[key] = schema[key]\n return all\n }, {}))\n const unique = uniqWith(extractedKeywordsOnly, compare)\n\n // create mergers that automatically add the path of the keyword for use in the complex resolver\n const mergers = resolverConfig.keywords.reduce((all, key) => ({\n ...all,\n [key]: (schemas, extraKey = []) => mergeSchemas(schemas, null, parents.concat(key, extraKey))\n }), {})\n\n const result = resolverConfig.resolver(unique, parents.concat(resolverName), mergers, options)\n\n if (!isPlainObject(result)) {\n throwIncompatible(unique, parents.concat(resolverName))\n }\n\n return result\n }\n}\n\nfunction createRequiredMetaArray(arr) {\n return { required: arr }\n}\n\nconst schemaGroupProps = ['properties', 'patternProperties', 'definitions', 'dependencies']\nconst schemaArrays = ['anyOf', 'oneOf']\nconst schemaProps = [\n 'additionalProperties',\n 'additionalItems',\n 'contains',\n 'propertyNames',\n 'not',\n 'items'\n]\n\nconst defaultResolvers = {\n type(compacted) {\n if (compacted.some(Array.isArray)) {\n const normalized = compacted.map(function(val) {\n return Array.isArray(val)\n ? val\n : [val]\n })\n const common = intersection.apply(null, normalized)\n\n if (common.length === 1) {\n return common[0]\n } else if (common.length > 1) {\n return uniq(common)\n }\n }\n },\n dependencies(compacted, paths, mergeSchemas) {\n const allChildren = allUniqueKeys(compacted)\n\n return allChildren.reduce(function(all, childKey) {\n const childSchemas = getValues(compacted, childKey)\n let innerCompacted = uniqWith(childSchemas.filter(notUndefined), isEqual)\n\n // to support dependencies\n const innerArrays = innerCompacted.filter(Array.isArray)\n\n if (innerArrays.length) {\n if (innerArrays.length === innerCompacted.length) {\n all[childKey] = stringArray(innerCompacted)\n } else {\n const innerSchemas = innerCompacted.filter(isSchema)\n const arrayMetaScheams = innerArrays.map(createRequiredMetaArray)\n all[childKey] = mergeSchemas(innerSchemas.concat(arrayMetaScheams), childKey)\n }\n return all\n }\n\n innerCompacted = uniqWith(innerCompacted, compare)\n\n all[childKey] = mergeSchemas(innerCompacted, childKey)\n return all\n }, {})\n },\n oneOf(compacted, paths, mergeSchemas) {\n const combinations = getAnyOfCombinations(cloneDeep(compacted))\n const result = tryMergeSchemaGroups(combinations, mergeSchemas)\n const unique = uniqWith(result, compare)\n\n if (unique.length) {\n return unique\n }\n },\n not(compacted) {\n return { anyOf: compacted }\n },\n pattern(compacted) {\n return compacted.map(r => '(?=' + r + ')').join('')\n },\n multipleOf(compacted) {\n let integers = compacted.slice(0)\n let factor = 1\n while (integers.some(n => !Number.isInteger(n))) {\n integers = integers.map(n => n * 10)\n factor = factor * 10\n }\n return computeLcm(integers) / factor\n },\n enum(compacted) {\n const enums = intersectionWith.apply(null, compacted.concat(isEqual))\n if (enums.length) {\n return sortBy(enums)\n }\n }\n}\n\ndefaultResolvers.$id = first\ndefaultResolvers.$ref = first\ndefaultResolvers.$schema = first\ndefaultResolvers.additionalItems = schemaResolver\ndefaultResolvers.additionalProperties = schemaResolver\ndefaultResolvers.anyOf = defaultResolvers.oneOf\ndefaultResolvers.contains = schemaResolver\ndefaultResolvers.default = first\ndefaultResolvers.definitions = defaultResolvers.dependencies\ndefaultResolvers.description = first\ndefaultResolvers.examples = examples\ndefaultResolvers.exclusiveMaximum = minimumValue\ndefaultResolvers.exclusiveMinimum = maximumValue\ndefaultResolvers.items = itemsResolver\ndefaultResolvers.maximum = minimumValue\ndefaultResolvers.maxItems = minimumValue\ndefaultResolvers.maxLength = minimumValue\ndefaultResolvers.maxProperties = minimumValue\ndefaultResolvers.minimum = maximumValue\ndefaultResolvers.minItems = maximumValue\ndefaultResolvers.minLength = maximumValue\ndefaultResolvers.minProperties = maximumValue\ndefaultResolvers.properties = propertiesResolver\ndefaultResolvers.propertyNames = schemaResolver\ndefaultResolvers.required = required\ndefaultResolvers.title = first\ndefaultResolvers.uniqueItems = uniqueItems\n\nconst defaultComplexResolvers = {\n properties: propertiesResolver,\n items: itemsResolver\n}\n\nfunction merger(rootSchema, options, totalSchemas) {\n totalSchemas = totalSchemas || []\n options = defaultsDeep(options, {\n ignoreAdditionalProperties: false,\n resolvers: defaultResolvers,\n complexResolvers: defaultComplexResolvers,\n deep: true\n })\n\n const complexResolvers = Object.entries(options.complexResolvers)\n\n function mergeSchemas(schemas, base, parents) {\n schemas = cloneDeep(schemas.filter(notUndefined))\n parents = parents || []\n const merged = isPlainObject(base)\n ? base\n : {}\n\n // return undefined, an empty schema\n if (!schemas.length) {\n return\n }\n\n if (schemas.some(isFalse)) {\n return false\n }\n\n if (schemas.every(isTrue)) {\n return true\n }\n\n // there are no false and we don't need the true ones as they accept everything\n schemas = schemas.filter(isPlainObject)\n\n const allKeys = allUniqueKeys(schemas)\n if (options.deep && contains(allKeys, 'allOf')) {\n return merger({\n allOf: schemas\n }, options, totalSchemas)\n }\n\n const complexKeysArr = complexResolvers.map(([mainKeyWord, resolverConf]) =>\n allKeys.filter(k => resolverConf.keywords.includes(k)))\n\n // remove all complex keys before simple resolvers\n complexKeysArr.forEach(keys => pullAll(allKeys, keys))\n\n // call all simple resolvers for relevant keywords\n allKeys.forEach(function(key) {\n const values = getValues(schemas, key)\n const compacted = uniqWith(values.filter(notUndefined), compareProp(key))\n\n // arrayprops like anyOf and oneOf must be merged first, as they contains schemas\n // allOf is treated differently alltogether\n if (compacted.length === 1 && contains(schemaArrays, key)) {\n merged[key] = compacted[0].map(schema => mergeSchemas([schema], schema))\n // prop groups must always be resolved\n } else if (compacted.length === 1 && !contains(schemaGroupProps, key) && !contains(schemaProps, key)) {\n merged[key] = compacted[0]\n } else {\n const resolver = options.resolvers[key] || options.resolvers.defaultResolver\n if (!resolver) throw new Error('No resolver found for key ' + key + '. You can provide a resolver for this keyword in the options, or provide a default resolver.')\n\n const merger = (schemas, extraKey = []) => mergeSchemas(schemas, null, parents.concat(key, extraKey))\n merged[key] = resolver(compacted, parents.concat(key), merger, options)\n\n if (merged[key] === undefined) {\n throwIncompatible(compacted, parents.concat(key))\n } else if (merged[key] === undefined) {\n delete merged[key]\n }\n }\n })\n\n return complexResolvers.reduce((all, [resolverKeyword, config], index) => ({\n ...all,\n ...callGroupResolver(complexKeysArr[index], resolverKeyword, schemas, mergeSchemas, options, parents)\n }), merged)\n }\n\n const allSchemas = flattenDeep(getAllOf(rootSchema))\n const merged = mergeSchemas(allSchemas)\n\n return merged\n}\n\nmerger.options = {\n resolvers: defaultResolvers\n}\n\nmodule.exports = merger\n","var hasExcape = /~/\nvar escapeMatcher = /~[01]/g\nfunction escapeReplacer (m) {\n switch (m) {\n case '~1': return '/'\n case '~0': return '~'\n }\n throw new Error('Invalid tilde escape: ' + m)\n}\n\nfunction untilde (str) {\n if (!hasExcape.test(str)) return str\n return str.replace(escapeMatcher, escapeReplacer)\n}\n\nfunction setter (obj, pointer, value) {\n var part\n var hasNextPart\n\n for (var p = 1, len = pointer.length; p < len;) {\n if (pointer[p] === 'constructor' || pointer[p] === 'prototype' || pointer[p] === '__proto__') return obj\n\n part = untilde(pointer[p++])\n hasNextPart = len > p\n\n if (typeof obj[part] === 'undefined') {\n // support setting of /-\n if (Array.isArray(obj) && part === '-') {\n part = obj.length\n }\n\n // support nested objects/array when setting values\n if (hasNextPart) {\n if ((pointer[p] !== '' && pointer[p] < Infinity) || pointer[p] === '-') obj[part] = []\n else obj[part] = {}\n }\n }\n\n if (!hasNextPart) break\n obj = obj[part]\n }\n\n var oldValue = obj[part]\n if (value === undefined) delete obj[part]\n else obj[part] = value\n return oldValue\n}\n\nfunction compilePointer (pointer) {\n if (typeof pointer === 'string') {\n pointer = pointer.split('/')\n if (pointer[0] === '') return pointer\n throw new Error('Invalid JSON pointer.')\n } else if (Array.isArray(pointer)) {\n for (const part of pointer) {\n if (typeof part !== 'string' && typeof part !== 'number') {\n throw new Error('Invalid JSON pointer. Must be of type string or number.')\n }\n }\n return pointer\n }\n\n throw new Error('Invalid JSON pointer.')\n}\n\nfunction get (obj, pointer) {\n if (typeof obj !== 'object') throw new Error('Invalid input object.')\n pointer = compilePointer(pointer)\n var len = pointer.length\n if (len === 1) return obj\n\n for (var p = 1; p < len;) {\n obj = obj[untilde(pointer[p++])]\n if (len === p) return obj\n if (typeof obj !== 'object' || obj === null) return undefined\n }\n}\n\nfunction set (obj, pointer, value) {\n if (typeof obj !== 'object') throw new Error('Invalid input object.')\n pointer = compilePointer(pointer)\n if (pointer.length === 0) throw new Error('Invalid JSON pointer for set.')\n return setter(obj, pointer, value)\n}\n\nfunction compile (pointer) {\n var compiled = compilePointer(pointer)\n return {\n get: function (object) {\n return get(object, compiled)\n },\n set: function (object, value) {\n return set(object, compiled, value)\n }\n }\n}\n\nexports.get = get\nexports.set = set\nexports.compile = compile\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nmodule.exports = arrayEach;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nmodule.exports = arrayReduce;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignMergeValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var copyObject = require('./_copyObject'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nmodule.exports = baseAssign;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nmodule.exports = baseAssignIn;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var Stack = require('./_Stack'),\n arrayEach = require('./_arrayEach'),\n assignValue = require('./_assignValue'),\n baseAssign = require('./_baseAssign'),\n baseAssignIn = require('./_baseAssignIn'),\n cloneBuffer = require('./_cloneBuffer'),\n copyArray = require('./_copyArray'),\n copySymbols = require('./_copySymbols'),\n copySymbolsIn = require('./_copySymbolsIn'),\n getAllKeys = require('./_getAllKeys'),\n getAllKeysIn = require('./_getAllKeysIn'),\n getTag = require('./_getTag'),\n initCloneArray = require('./_initCloneArray'),\n initCloneByTag = require('./_initCloneByTag'),\n initCloneObject = require('./_initCloneObject'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isMap = require('./isMap'),\n isObject = require('./isObject'),\n isSet = require('./isSet'),\n keys = require('./keys'),\n keysIn = require('./keysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nmodule.exports = baseClone;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n arrayMap = require('./_arrayMap'),\n baseUnary = require('./_baseUnary'),\n cacheHas = require('./_cacheHas');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseDifference;\n","var baseForOwn = require('./_baseForOwn'),\n createBaseEach = require('./_createBaseEach');\n\n/**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\nvar baseEach = createBaseEach(baseForOwn);\n\nmodule.exports = baseEach;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseFlatten;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var baseFor = require('./_baseFor'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nmodule.exports = baseForOwn;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n}\n\nmodule.exports = baseHas;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n","/**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseIndexOfWith;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n arrayMap = require('./_arrayMap'),\n baseUnary = require('./_baseUnary'),\n cacheHas = require('./_cacheHas');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMin = Math.min;\n\n/**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\nfunction baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseIntersection;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nmodule.exports = baseIsMap;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nmodule.exports = baseIsSet;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var baseEach = require('./_baseEach'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n}\n\nmodule.exports = baseMap;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n","var Stack = require('./_Stack'),\n assignMergeValue = require('./_assignMergeValue'),\n baseFor = require('./_baseFor'),\n baseMergeDeep = require('./_baseMergeDeep'),\n isObject = require('./isObject'),\n keysIn = require('./keysIn'),\n safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nmodule.exports = baseMerge;\n","var assignMergeValue = require('./_assignMergeValue'),\n cloneBuffer = require('./_cloneBuffer'),\n cloneTypedArray = require('./_cloneTypedArray'),\n copyArray = require('./_copyArray'),\n initCloneObject = require('./_initCloneObject'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLikeObject = require('./isArrayLikeObject'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isPlainObject = require('./isPlainObject'),\n isTypedArray = require('./isTypedArray'),\n safeGet = require('./_safeGet'),\n toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n","var arrayMap = require('./_arrayMap'),\n baseGet = require('./_baseGet'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n baseSortBy = require('./_baseSortBy'),\n baseUnary = require('./_baseUnary'),\n compareMultiple = require('./_compareMultiple'),\n identity = require('./identity'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\nfunction baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(baseIteratee));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n}\n\nmodule.exports = baseOrderBy;\n","var basePickBy = require('./_basePickBy'),\n hasIn = require('./hasIn');\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n}\n\nmodule.exports = basePick;\n","var baseGet = require('./_baseGet'),\n baseSet = require('./_baseSet'),\n castPath = require('./_castPath');\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nmodule.exports = basePickBy;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n","var arrayMap = require('./_arrayMap'),\n baseIndexOf = require('./_baseIndexOf'),\n baseIndexOfWith = require('./_baseIndexOfWith'),\n baseUnary = require('./_baseUnary'),\n copyArray = require('./_copyArray');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\nfunction basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n}\n\nmodule.exports = basePullAll;\n","/**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\nfunction baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n}\n\nmodule.exports = baseReduce;\n","var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","var assignValue = require('./_assignValue'),\n castPath = require('./_castPath'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nmodule.exports = baseSet;\n","var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nmodule.exports = baseSlice;\n","/**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\nfunction baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n}\n\nmodule.exports = baseSortBy;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\n","var castPath = require('./_castPath'),\n last = require('./last'),\n parent = require('./_parent'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\nfunction baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n}\n\nmodule.exports = baseUnset;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\nfunction castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n}\n\nmodule.exports = castArrayLikeObject;\n","var identity = require('./identity');\n\n/**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\nfunction castFunction(value) {\n return typeof value == 'function' ? value : identity;\n}\n\nmodule.exports = castFunction;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nmodule.exports = cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nmodule.exports = cloneRegExp;\n","var Symbol = require('./_Symbol');\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nmodule.exports = cloneSymbol;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","var isSymbol = require('./isSymbol');\n\n/**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\nfunction compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n}\n\nmodule.exports = compareAscending;\n","var compareAscending = require('./_compareAscending');\n\n/**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\nfunction compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n}\n\nmodule.exports = compareMultiple;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","var copyObject = require('./_copyObject'),\n getSymbols = require('./_getSymbols');\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nmodule.exports = copySymbols;\n","var copyObject = require('./_copyObject'),\n getSymbolsIn = require('./_getSymbolsIn');\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nmodule.exports = copySymbolsIn;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nmodule.exports = createAssigner;\n","var isArrayLike = require('./isArrayLike');\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n}\n\nmodule.exports = createBaseEach;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\n","var baseMerge = require('./_baseMerge'),\n isObject = require('./isObject');\n\n/**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\nfunction customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n}\n\nmodule.exports = customDefaultsMerge;\n","var isPlainObject = require('./isPlainObject');\n\n/**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\nfunction customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n}\n\nmodule.exports = customOmitClone;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n","var flatten = require('./flatten'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\nfunction flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n}\n\nmodule.exports = flatRest;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbolsIn = require('./_getSymbolsIn'),\n keysIn = require('./keysIn');\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nmodule.exports = getAllKeysIn;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n","var arrayPush = require('./_arrayPush'),\n getPrototype = require('./_getPrototype'),\n getSymbols = require('./_getSymbols'),\n stubArray = require('./stubArray');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nmodule.exports = getSymbolsIn;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nmodule.exports = initCloneArray;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer'),\n cloneDataView = require('./_cloneDataView'),\n cloneRegExp = require('./_cloneRegExp'),\n cloneSymbol = require('./_cloneSymbol'),\n cloneTypedArray = require('./_cloneTypedArray');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nmodule.exports = initCloneByTag;\n","var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\n","var Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","var baseGet = require('./_baseGet'),\n baseSlice = require('./_baseSlice');\n\n/**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\nfunction parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n}\n\nmodule.exports = parent;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nmodule.exports = safeGet;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = cloneDeep;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","var baseRest = require('./_baseRest'),\n eq = require('./eq'),\n isIterateeCall = require('./_isIterateeCall'),\n keysIn = require('./keysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\nvar defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n});\n\nmodule.exports = defaults;\n","var apply = require('./_apply'),\n baseRest = require('./_baseRest'),\n customDefaultsMerge = require('./_customDefaultsMerge'),\n mergeWith = require('./mergeWith');\n\n/**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\nvar defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n});\n\nmodule.exports = defaultsDeep;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var baseFlatten = require('./_baseFlatten');\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nmodule.exports = flatten;\n","var baseFlatten = require('./_baseFlatten');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\nfunction flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n}\n\nmodule.exports = flattenDeep;\n","var arrayEach = require('./_arrayEach'),\n baseEach = require('./_baseEach'),\n castFunction = require('./_castFunction'),\n isArray = require('./isArray');\n\n/**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\nfunction forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, castFunction(iteratee));\n}\n\nmodule.exports = forEach;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","var baseHas = require('./_baseHas'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nfunction has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n}\n\nmodule.exports = has;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","var arrayMap = require('./_arrayMap'),\n baseIntersection = require('./_baseIntersection'),\n baseRest = require('./_baseRest'),\n castArrayLikeObject = require('./_castArrayLikeObject');\n\n/**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\nvar intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n});\n\nmodule.exports = intersection;\n","var arrayMap = require('./_arrayMap'),\n baseIntersection = require('./_baseIntersection'),\n baseRest = require('./_baseRest'),\n castArrayLikeObject = require('./_castArrayLikeObject'),\n last = require('./last');\n\n/**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\nvar intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n});\n\nmodule.exports = intersectionWith;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]';\n\n/**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\nfunction isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n}\n\nmodule.exports = isBoolean;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseKeys = require('./_baseKeys'),\n getTag = require('./_getTag'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLike = require('./isArrayLike'),\n isBuffer = require('./isBuffer'),\n isPrototype = require('./_isPrototype'),\n isTypedArray = require('./isTypedArray');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n setTag = '[object Set]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\nfunction isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n}\n\nmodule.exports = isEmpty;\n","var baseIsEqual = require('./_baseIsEqual');\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nmodule.exports = isEqual;\n","var baseIsEqual = require('./_baseIsEqual');\n\n/**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\nfunction isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n}\n\nmodule.exports = isEqualWith;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var baseIsMap = require('./_baseIsMap'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nmodule.exports = isMap;\n","/**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n return value == null;\n}\n\nmodule.exports = isNil;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar numberTag = '[object Number]';\n\n/**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\nfunction isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n}\n\nmodule.exports = isNumber;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","var baseIsSet = require('./_baseIsSet'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nmodule.exports = isSet;\n","var baseGetTag = require('./_baseGetTag'),\n isArray = require('./isArray'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nmodule.exports = isString;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nmodule.exports = last;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\nvar mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n});\n\nmodule.exports = mergeWith;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\n","var arrayMap = require('./_arrayMap'),\n baseClone = require('./_baseClone'),\n baseUnset = require('./_baseUnset'),\n castPath = require('./_castPath'),\n copyObject = require('./_copyObject'),\n customOmitClone = require('./_customOmitClone'),\n flatRest = require('./_flatRest'),\n getAllKeysIn = require('./_getAllKeysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\nvar omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n});\n\nmodule.exports = omit;\n","var basePick = require('./_basePick'),\n flatRest = require('./_flatRest');\n\n/**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\nvar pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n});\n\nmodule.exports = pick;\n","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","var basePullAll = require('./_basePullAll');\n\n/**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\nfunction pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n}\n\nmodule.exports = pullAll;\n","var arrayReduce = require('./_arrayReduce'),\n baseEach = require('./_baseEach'),\n baseIteratee = require('./_baseIteratee'),\n baseReduce = require('./_baseReduce'),\n isArray = require('./isArray');\n\n/**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\nfunction reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n}\n\nmodule.exports = reduce;\n","var baseSet = require('./_baseSet');\n\n/**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\nfunction set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n}\n\nmodule.exports = set;\n","var baseFlatten = require('./_baseFlatten'),\n baseOrderBy = require('./_baseOrderBy'),\n baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\nvar sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n});\n\nmodule.exports = sortBy;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var baseTimes = require('./_baseTimes'),\n castFunction = require('./_castFunction'),\n toInteger = require('./toInteger');\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used as references for the maximum length and index of an array. */\nvar MAX_ARRAY_LENGTH = 4294967295;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMin = Math.min;\n\n/**\n * Invokes the iteratee `n` times, returning an array of the results of\n * each invocation. The iteratee is invoked with one argument; (index).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.times(3, String);\n * // => ['0', '1', '2']\n *\n * _.times(4, _.constant(0));\n * // => [0, 0, 0, 0]\n */\nfunction times(n, iteratee) {\n n = toInteger(n);\n if (n < 1 || n > MAX_SAFE_INTEGER) {\n return [];\n }\n var index = MAX_ARRAY_LENGTH,\n length = nativeMin(n, MAX_ARRAY_LENGTH);\n\n iteratee = castFunction(iteratee);\n n -= MAX_ARRAY_LENGTH;\n\n var result = baseTimes(length, iteratee);\n while (++index < n) {\n iteratee(index);\n }\n return result;\n}\n\nmodule.exports = times;\n","var toNumber = require('./toNumber');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nmodule.exports = toFinite;\n","var toFinite = require('./toFinite');\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nmodule.exports = toInteger;\n","var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","var arrayMap = require('./_arrayMap'),\n copyArray = require('./_copyArray'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol'),\n stringToPath = require('./_stringToPath'),\n toKey = require('./_toKey'),\n toString = require('./toString');\n\n/**\n * Converts `value` to a property path array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Util\n * @param {*} value The value to convert.\n * @returns {Array} Returns the new property path array.\n * @example\n *\n * _.toPath('a.b.c');\n * // => ['a', 'b', 'c']\n *\n * _.toPath('a[0].b.c');\n * // => ['a', '0', 'b', 'c']\n */\nfunction toPath(value) {\n if (isArray(value)) {\n return arrayMap(value, toKey);\n }\n return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n}\n\nmodule.exports = toPath;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var arrayEach = require('./_arrayEach'),\n baseCreate = require('./_baseCreate'),\n baseForOwn = require('./_baseForOwn'),\n baseIteratee = require('./_baseIteratee'),\n getPrototype = require('./_getPrototype'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isTypedArray = require('./isTypedArray');\n\n/**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\nfunction transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = baseIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n}\n\nmodule.exports = transform;\n","var baseFlatten = require('./_baseFlatten'),\n baseRest = require('./_baseRest'),\n baseUniq = require('./_baseUniq'),\n isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\nvar union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n});\n\nmodule.exports = union;\n","var baseUniq = require('./_baseUniq');\n\n/**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\nfunction uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n}\n\nmodule.exports = uniq;\n","var baseUniq = require('./_baseUniq');\n\n/**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\nfunction uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n}\n\nmodule.exports = uniqWith;\n","var baseUnset = require('./_baseUnset');\n\n/**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\nfunction unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n}\n\nmodule.exports = unset;\n","var baseDifference = require('./_baseDifference'),\n baseRest = require('./_baseRest'),\n isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\nvar without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n});\n\nmodule.exports = without;\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3 value;\nexport const emptyRenderer = () => <> ;\n\nexport const defaultColumn = {\n Cell: defaultRenderer,\n width: 150,\n minWidth: 0,\n maxWidth: Number.MAX_SAFE_INTEGER,\n}\n\nfunction mergeProps(...propList) {\n return propList.reduce((props, next) => {\n const { style, className, ...rest } = next\n\n props = {\n ...props,\n ...rest,\n }\n\n if (style) {\n props.style = props.style\n ? { ...(props.style || {}), ...(style || {}) }\n : style\n }\n\n if (className) {\n props.className = props.className\n ? props.className + ' ' + className\n : className\n }\n\n if (props.className === '') {\n delete props.className\n }\n\n return props\n }, {})\n}\n\nfunction handlePropGetter(prevProps, userProps, meta) {\n // Handle a lambda, pass it the previous props\n if (typeof userProps === 'function') {\n return handlePropGetter({}, userProps(prevProps, meta))\n }\n\n // Handle an array, merge each item as separate props\n if (Array.isArray(userProps)) {\n return mergeProps(prevProps, ...userProps)\n }\n\n // Handle an object by default, merge the two objects\n return mergeProps(prevProps, userProps)\n}\n\nexport const makePropGetter = (hooks, meta = {}) => {\n return (userProps = {}) =>\n [...hooks, userProps].reduce(\n (prev, next) =>\n handlePropGetter(prev, next, {\n ...meta,\n userProps,\n }),\n {}\n )\n}\n\nexport const reduceHooks = (hooks, initial, meta = {}, allowUndefined) =>\n hooks.reduce((prev, next) => {\n const nextValue = next(prev, meta)\n if (process.env.NODE_ENV !== 'production') {\n if (!allowUndefined && typeof nextValue === 'undefined') {\n console.info(next)\n throw new Error(\n 'React Table: A reducer hook ☝️ just returned undefined! This is not allowed.'\n )\n }\n }\n return nextValue\n }, initial)\n\nexport const loopHooks = (hooks, context, meta = {}) =>\n hooks.forEach(hook => {\n const nextValue = hook(context, meta)\n if (process.env.NODE_ENV !== 'production') {\n if (typeof nextValue !== 'undefined') {\n console.info(hook, nextValue)\n throw new Error(\n 'React Table: A loop-type hook ☝️ just returned a value! This is not allowed.'\n )\n }\n }\n })\n\nexport function ensurePluginOrder(plugins, befores, pluginName, afters) {\n if (process.env.NODE_ENV !== 'production' && afters) {\n throw new Error(\n `Defining plugins in the \"after\" section of ensurePluginOrder is no longer supported (see plugin ${pluginName})`\n )\n }\n const pluginIndex = plugins.findIndex(\n plugin => plugin.pluginName === pluginName\n )\n\n if (pluginIndex === -1) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(`The plugin \"${pluginName}\" was not found in the plugin list!\nThis usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:\n\n ${pluginName}.pluginName = '${pluginName}'\n`)\n }\n }\n\n befores.forEach(before => {\n const beforeIndex = plugins.findIndex(\n plugin => plugin.pluginName === before\n )\n if (beforeIndex > -1 && beforeIndex > pluginIndex) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`\n )\n }\n }\n })\n}\n\nexport function functionalUpdate(updater, old) {\n return typeof updater === 'function' ? updater(old) : updater\n}\n\nexport function useGetLatest(obj) {\n const ref = React.useRef()\n ref.current = obj\n\n return React.useCallback(() => ref.current, [])\n}\n\n// SSR has issues with useLayoutEffect still, so use useEffect during SSR\nexport const safeUseLayoutEffect =\n typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nexport function useMountedLayoutEffect(fn, deps) {\n const mountedRef = React.useRef(false)\n\n safeUseLayoutEffect(() => {\n if (mountedRef.current) {\n fn()\n }\n mountedRef.current = true\n // eslint-disable-next-line\n }, deps)\n}\n\nexport function useAsyncDebounce(defaultFn, defaultWait = 0) {\n const debounceRef = React.useRef({})\n\n const getDefaultFn = useGetLatest(defaultFn)\n const getDefaultWait = useGetLatest(defaultWait)\n\n return React.useCallback(\n async (...args) => {\n if (!debounceRef.current.promise) {\n debounceRef.current.promise = new Promise((resolve, reject) => {\n debounceRef.current.resolve = resolve\n debounceRef.current.reject = reject\n })\n }\n\n if (debounceRef.current.timeout) {\n clearTimeout(debounceRef.current.timeout)\n }\n\n debounceRef.current.timeout = setTimeout(async () => {\n delete debounceRef.current.timeout\n try {\n debounceRef.current.resolve(await getDefaultFn()(...args))\n } catch (err) {\n debounceRef.current.reject(err)\n } finally {\n delete debounceRef.current.promise\n }\n }, getDefaultWait())\n\n return debounceRef.current.promise\n },\n [getDefaultFn, getDefaultWait]\n )\n}\n\nexport function makeRenderer(instance, column, meta = {}) {\n return (type, userProps = {}) => {\n const Comp = typeof type === 'string' ? column[type] : type\n\n if (typeof Comp === 'undefined') {\n console.info(column)\n throw new Error(renderErr)\n }\n\n return flexRender(Comp, { ...instance, column, ...meta, ...userProps })\n }\n}\n\nexport function flexRender(Comp, props) {\n return isReactComponent(Comp) ? : Comp\n}\n\nfunction isReactComponent(component) {\n return (\n isClassComponent(component) ||\n typeof component === 'function' ||\n isExoticComponent(component)\n )\n}\n\nfunction isClassComponent(component) {\n return (\n typeof component === 'function' &&\n (() => {\n const proto = Object.getPrototypeOf(component)\n return proto.prototype && proto.prototype.isReactComponent\n })()\n )\n}\n\nfunction isExoticComponent(component) {\n return (\n typeof component === 'object' &&\n typeof component.$$typeof === 'symbol' &&\n ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)\n )\n}\n","import { defaultColumn, emptyRenderer } from './publicUtils'\n\n// Find the depth of the columns\nexport function findMaxDepth(columns, depth = 0) {\n return columns.reduce((prev, curr) => {\n if (curr.columns) {\n return Math.max(prev, findMaxDepth(curr.columns, depth + 1))\n }\n return depth\n }, 0)\n}\n\n// Build the visible columns, headers and flat column list\nexport function linkColumnStructure(columns, parent, depth = 0) {\n return columns.map(column => {\n column = {\n ...column,\n parent,\n depth,\n }\n\n assignColumnAccessor(column)\n\n if (column.columns) {\n column.columns = linkColumnStructure(column.columns, column, depth + 1)\n }\n return column\n })\n}\n\nexport function flattenColumns(columns) {\n return flattenBy(columns, 'columns')\n}\n\nexport function assignColumnAccessor(column) {\n // First check for string accessor\n let { id, accessor, Header } = column\n\n if (typeof accessor === 'string') {\n id = id || accessor\n const accessorPath = accessor.split('.')\n accessor = row => getBy(row, accessorPath)\n }\n\n if (!id && typeof Header === 'string' && Header) {\n id = Header\n }\n\n if (!id && column.columns) {\n console.error(column)\n throw new Error('A column ID (or unique \"Header\" value) is required!')\n }\n\n if (!id) {\n console.error(column)\n throw new Error('A column ID (or string accessor) is required!')\n }\n\n Object.assign(column, {\n id,\n accessor,\n })\n\n return column\n}\n\nexport function decorateColumn(column, userDefaultColumn) {\n if (!userDefaultColumn) {\n throw new Error()\n }\n Object.assign(column, {\n // Make sure there is a fallback header, just in case\n Header: emptyRenderer,\n Footer: emptyRenderer,\n ...defaultColumn,\n ...userDefaultColumn,\n ...column,\n })\n\n Object.assign(column, {\n originalWidth: column.width,\n })\n\n return column\n}\n\n// Build the header groups from the bottom up\nexport function makeHeaderGroups(\n allColumns,\n defaultColumn,\n additionalHeaderProperties = () => ({})\n) {\n const headerGroups = []\n\n let scanColumns = allColumns\n\n let uid = 0\n const getUID = () => uid++\n\n while (scanColumns.length) {\n // The header group we are creating\n const headerGroup = {\n headers: [],\n }\n\n // The parent columns we're going to scan next\n const parentColumns = []\n\n const hasParents = scanColumns.some(d => d.parent)\n\n // Scan each column for parents\n scanColumns.forEach(column => {\n // What is the latest (last) parent column?\n let latestParentColumn = [...parentColumns].reverse()[0]\n\n let newParent\n\n if (hasParents) {\n // If the column has a parent, add it if necessary\n if (column.parent) {\n newParent = {\n ...column.parent,\n originalId: column.parent.id,\n id: `${column.parent.id}_${getUID()}`,\n headers: [column],\n ...additionalHeaderProperties(column),\n }\n } else {\n // If other columns have parents, we'll need to add a place holder if necessary\n const originalId = `${column.id}_placeholder`\n newParent = decorateColumn(\n {\n originalId,\n id: `${column.id}_placeholder_${getUID()}`,\n placeholderOf: column,\n headers: [column],\n ...additionalHeaderProperties(column),\n },\n defaultColumn\n )\n }\n\n // If the resulting parent columns are the same, just add\n // the column and increment the header span\n if (\n latestParentColumn &&\n latestParentColumn.originalId === newParent.originalId\n ) {\n latestParentColumn.headers.push(column)\n } else {\n parentColumns.push(newParent)\n }\n }\n\n headerGroup.headers.push(column)\n })\n\n headerGroups.push(headerGroup)\n\n // Start scanning the parent columns\n scanColumns = parentColumns\n }\n\n return headerGroups.reverse()\n}\n\nconst pathObjCache = new Map()\n\nexport function getBy(obj, path, def) {\n if (!path) {\n return obj\n }\n const cacheKey = typeof path === 'function' ? path : JSON.stringify(path)\n\n const pathObj =\n pathObjCache.get(cacheKey) ||\n (() => {\n const pathObj = makePathArray(path)\n pathObjCache.set(cacheKey, pathObj)\n return pathObj\n })()\n\n let val\n\n try {\n val = pathObj.reduce((cursor, pathPart) => cursor[pathPart], obj)\n } catch (e) {\n // continue regardless of error\n }\n return typeof val !== 'undefined' ? val : def\n}\n\nexport function getFirstDefined(...args) {\n for (let i = 0; i < args.length; i += 1) {\n if (typeof args[i] !== 'undefined') {\n return args[i]\n }\n }\n}\n\nexport function getElementDimensions(element) {\n const rect = element.getBoundingClientRect()\n const style = window.getComputedStyle(element)\n const margins = {\n left: parseInt(style.marginLeft),\n right: parseInt(style.marginRight),\n }\n const padding = {\n left: parseInt(style.paddingLeft),\n right: parseInt(style.paddingRight),\n }\n return {\n left: Math.ceil(rect.left),\n width: Math.ceil(rect.width),\n outerWidth: Math.ceil(\n rect.width + margins.left + margins.right + padding.left + padding.right\n ),\n marginLeft: margins.left,\n marginRight: margins.right,\n paddingLeft: padding.left,\n paddingRight: padding.right,\n scrollWidth: element.scrollWidth,\n }\n}\n\nexport function isFunction(a) {\n if (typeof a === 'function') {\n return a\n }\n}\n\nexport function flattenBy(arr, key) {\n const flat = []\n\n const recurse = arr => {\n arr.forEach(d => {\n if (!d[key]) {\n flat.push(d)\n } else {\n recurse(d[key])\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\nexport function expandRows(\n rows,\n { manualExpandedKey, expanded, expandSubRows = true }\n) {\n const expandedRows = []\n\n const handleRow = (row, addToExpandedRows = true) => {\n row.isExpanded =\n (row.original && row.original[manualExpandedKey]) || expanded[row.id]\n\n row.canExpand = row.subRows && !!row.subRows.length\n\n if (addToExpandedRows) {\n expandedRows.push(row)\n }\n\n if (row.subRows && row.subRows.length && row.isExpanded) {\n row.subRows.forEach(row => handleRow(row, expandSubRows))\n }\n }\n\n rows.forEach(row => handleRow(row))\n\n return expandedRows\n}\n\nexport function getFilterMethod(filter, userFilterTypes, filterTypes) {\n return (\n isFunction(filter) ||\n userFilterTypes[filter] ||\n filterTypes[filter] ||\n filterTypes.text\n )\n}\n\nexport function shouldAutoRemoveFilter(autoRemove, value, column) {\n return autoRemove ? autoRemove(value, column) : typeof value === 'undefined'\n}\n\nexport function unpreparedAccessWarning() {\n throw new Error(\n 'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'\n )\n}\n\nlet passiveSupported = null\nexport function passiveEventSupported() {\n // memoize support to avoid adding multiple test events\n if (typeof passiveSupported === 'boolean') return passiveSupported\n\n let supported = false\n try {\n const options = {\n get passive() {\n supported = true\n return false\n },\n }\n\n window.addEventListener('test', null, options)\n window.removeEventListener('test', null, options)\n } catch (err) {\n supported = false\n }\n passiveSupported = supported\n return passiveSupported\n}\n\n//\n\nconst reOpenBracket = /\\[/g\nconst reCloseBracket = /\\]/g\n\nfunction makePathArray(obj) {\n return (\n flattenDeep(obj)\n // remove all periods in parts\n .map(d => String(d).replace('.', '_'))\n // join parts using period\n .join('.')\n // replace brackets with periods\n .replace(reOpenBracket, '.')\n .replace(reCloseBracket, '')\n // split it back out on periods\n .split('.')\n )\n}\n\nfunction flattenDeep(arr, newArr = []) {\n if (!Array.isArray(arr)) {\n newArr.push(arr)\n } else {\n for (let i = 0; i < arr.length; i += 1) {\n flattenDeep(arr[i], newArr)\n }\n }\n return newArr\n}\n","const defaultGetTableProps = props => ({\n role: 'table',\n ...props,\n})\n\nconst defaultGetTableBodyProps = props => ({\n role: 'rowgroup',\n ...props,\n})\n\nconst defaultGetHeaderProps = (props, { column }) => ({\n key: `header_${column.id}`,\n colSpan: column.totalVisibleHeaderCount,\n role: 'columnheader',\n ...props,\n})\n\nconst defaultGetFooterProps = (props, { column }) => ({\n key: `footer_${column.id}`,\n colSpan: column.totalVisibleHeaderCount,\n ...props,\n})\n\nconst defaultGetHeaderGroupProps = (props, { index }) => ({\n key: `headerGroup_${index}`,\n role: 'row',\n ...props,\n})\n\nconst defaultGetFooterGroupProps = (props, { index }) => ({\n key: `footerGroup_${index}`,\n ...props,\n})\n\nconst defaultGetRowProps = (props, { row }) => ({\n key: `row_${row.id}`,\n role: 'row',\n ...props,\n})\n\nconst defaultGetCellProps = (props, { cell }) => ({\n key: `cell_${cell.row.id}_${cell.column.id}`,\n role: 'cell',\n ...props,\n})\n\nexport default function makeDefaultPluginHooks() {\n return {\n useOptions: [],\n stateReducers: [],\n useControlledState: [],\n columns: [],\n columnsDeps: [],\n allColumns: [],\n allColumnsDeps: [],\n accessValue: [],\n materializedColumns: [],\n materializedColumnsDeps: [],\n useInstanceAfterData: [],\n visibleColumns: [],\n visibleColumnsDeps: [],\n headerGroups: [],\n headerGroupsDeps: [],\n useInstanceBeforeDimensions: [],\n useInstance: [],\n prepareRow: [],\n getTableProps: [defaultGetTableProps],\n getTableBodyProps: [defaultGetTableBodyProps],\n getHeaderGroupProps: [defaultGetHeaderGroupProps],\n getFooterGroupProps: [defaultGetFooterGroupProps],\n getHeaderProps: [defaultGetHeaderProps],\n getFooterProps: [defaultGetFooterProps],\n getRowProps: [defaultGetRowProps],\n getCellProps: [defaultGetCellProps],\n useFinalInstance: [],\n }\n}\n","import React from 'react'\n\nimport {\n actions,\n functionalUpdate,\n useGetLatest,\n makePropGetter,\n useMountedLayoutEffect,\n} from '../publicUtils'\n\nactions.resetHiddenColumns = 'resetHiddenColumns'\nactions.toggleHideColumn = 'toggleHideColumn'\nactions.setHiddenColumns = 'setHiddenColumns'\nactions.toggleHideAllColumns = 'toggleHideAllColumns'\n\nexport const useColumnVisibility = hooks => {\n hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps]\n hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps]\n\n hooks.stateReducers.push(reducer)\n hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)\n hooks.headerGroupsDeps.push((deps, { instance }) => [\n ...deps,\n instance.state.hiddenColumns,\n ])\n hooks.useInstance.push(useInstance)\n}\n\nuseColumnVisibility.pluginName = 'useColumnVisibility'\n\nconst defaultGetToggleHiddenProps = (props, { column }) => [\n props,\n {\n onChange: e => {\n column.toggleHidden(!e.target.checked)\n },\n style: {\n cursor: 'pointer',\n },\n checked: column.isVisible,\n title: 'Toggle Column Visible',\n },\n]\n\nconst defaultGetToggleHideAllColumnsProps = (props, { instance }) => [\n props,\n {\n onChange: e => {\n instance.toggleHideAllColumns(!e.target.checked)\n },\n style: {\n cursor: 'pointer',\n },\n checked: !instance.allColumnsHidden && !instance.state.hiddenColumns.length,\n title: 'Toggle All Columns Hidden',\n indeterminate:\n !instance.allColumnsHidden && instance.state.hiddenColumns.length,\n },\n]\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n hiddenColumns: [],\n ...state,\n }\n }\n\n if (action.type === actions.resetHiddenColumns) {\n return {\n ...state,\n hiddenColumns: instance.initialState.hiddenColumns || [],\n }\n }\n\n if (action.type === actions.toggleHideColumn) {\n const should =\n typeof action.value !== 'undefined'\n ? action.value\n : !state.hiddenColumns.includes(action.columnId)\n\n const hiddenColumns = should\n ? [...state.hiddenColumns, action.columnId]\n : state.hiddenColumns.filter(d => d !== action.columnId)\n\n return {\n ...state,\n hiddenColumns,\n }\n }\n\n if (action.type === actions.setHiddenColumns) {\n return {\n ...state,\n hiddenColumns: functionalUpdate(action.value, state.hiddenColumns),\n }\n }\n\n if (action.type === actions.toggleHideAllColumns) {\n const shouldAll =\n typeof action.value !== 'undefined'\n ? action.value\n : !state.hiddenColumns.length\n\n return {\n ...state,\n hiddenColumns: shouldAll ? instance.allColumns.map(d => d.id) : [],\n }\n }\n}\n\nfunction useInstanceBeforeDimensions(instance) {\n const {\n headers,\n state: { hiddenColumns },\n } = instance\n\n const isMountedRef = React.useRef(false)\n\n if (!isMountedRef.current) {\n }\n\n const handleColumn = (column, parentVisible) => {\n column.isVisible = parentVisible && !hiddenColumns.includes(column.id)\n\n let totalVisibleHeaderCount = 0\n\n if (column.headers && column.headers.length) {\n column.headers.forEach(\n subColumn =>\n (totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible))\n )\n } else {\n totalVisibleHeaderCount = column.isVisible ? 1 : 0\n }\n\n column.totalVisibleHeaderCount = totalVisibleHeaderCount\n\n return totalVisibleHeaderCount\n }\n\n let totalVisibleHeaderCount = 0\n\n headers.forEach(\n subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))\n )\n}\n\nfunction useInstance(instance) {\n const {\n columns,\n flatHeaders,\n dispatch,\n allColumns,\n getHooks,\n state: { hiddenColumns },\n autoResetHiddenColumns = true,\n } = instance\n\n const getInstance = useGetLatest(instance)\n\n const allColumnsHidden = allColumns.length === hiddenColumns.length\n\n const toggleHideColumn = React.useCallback(\n (columnId, value) =>\n dispatch({ type: actions.toggleHideColumn, columnId, value }),\n [dispatch]\n )\n\n const setHiddenColumns = React.useCallback(\n value => dispatch({ type: actions.setHiddenColumns, value }),\n [dispatch]\n )\n\n const toggleHideAllColumns = React.useCallback(\n value => dispatch({ type: actions.toggleHideAllColumns, value }),\n [dispatch]\n )\n\n const getToggleHideAllColumnsProps = makePropGetter(\n getHooks().getToggleHideAllColumnsProps,\n { instance: getInstance() }\n )\n\n flatHeaders.forEach(column => {\n column.toggleHidden = value => {\n dispatch({\n type: actions.toggleHideColumn,\n columnId: column.id,\n value,\n })\n }\n\n column.getToggleHiddenProps = makePropGetter(\n getHooks().getToggleHiddenProps,\n {\n instance: getInstance(),\n column,\n }\n )\n })\n\n const getAutoResetHiddenColumns = useGetLatest(autoResetHiddenColumns)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetHiddenColumns()) {\n dispatch({ type: actions.resetHiddenColumns })\n }\n }, [dispatch, columns])\n\n Object.assign(instance, {\n allColumnsHidden,\n toggleHideColumn,\n setHiddenColumns,\n toggleHideAllColumns,\n getToggleHideAllColumnsProps,\n })\n}\n","import React from 'react'\n\n//\n\nimport {\n linkColumnStructure,\n flattenColumns,\n assignColumnAccessor,\n unpreparedAccessWarning,\n makeHeaderGroups,\n decorateColumn,\n} from '../utils'\n\nimport {\n useGetLatest,\n reduceHooks,\n actions,\n loopHooks,\n makePropGetter,\n makeRenderer,\n} from '../publicUtils'\n\nimport makeDefaultPluginHooks from '../makeDefaultPluginHooks'\n\nimport { useColumnVisibility } from './useColumnVisibility'\n\nconst defaultInitialState = {}\nconst defaultColumnInstance = {}\nconst defaultReducer = (state, action, prevState) => state\nconst defaultGetSubRows = (row, index) => row.subRows || []\nconst defaultGetRowId = (row, index, parent) =>\n `${parent ? [parent.id, index].join('.') : index}`\nconst defaultUseControlledState = d => d\n\nfunction applyDefaults(props) {\n const {\n initialState = defaultInitialState,\n defaultColumn = defaultColumnInstance,\n getSubRows = defaultGetSubRows,\n getRowId = defaultGetRowId,\n stateReducer = defaultReducer,\n useControlledState = defaultUseControlledState,\n ...rest\n } = props\n\n return {\n ...rest,\n initialState,\n defaultColumn,\n getSubRows,\n getRowId,\n stateReducer,\n useControlledState,\n }\n}\n\nexport const useTable = (props, ...plugins) => {\n // Apply default props\n props = applyDefaults(props)\n\n // Add core plugins\n plugins = [useColumnVisibility, ...plugins]\n\n // Create the table instance\n let instanceRef = React.useRef({})\n\n // Create a getter for the instance (helps avoid a lot of potential memory leaks)\n const getInstance = useGetLatest(instanceRef.current)\n\n // Assign the props, plugins and hooks to the instance\n Object.assign(getInstance(), {\n ...props,\n plugins,\n hooks: makeDefaultPluginHooks(),\n })\n\n // Allow plugins to register hooks as early as possible\n plugins.filter(Boolean).forEach(plugin => {\n plugin(getInstance().hooks)\n })\n\n // Consume all hooks and make a getter for them\n const getHooks = useGetLatest(getInstance().hooks)\n getInstance().getHooks = getHooks\n delete getInstance().hooks\n\n // Allow useOptions hooks to modify the options coming into the table\n Object.assign(\n getInstance(),\n reduceHooks(getHooks().useOptions, applyDefaults(props))\n )\n\n const {\n data,\n columns: userColumns,\n initialState,\n defaultColumn,\n getSubRows,\n getRowId,\n stateReducer,\n useControlledState,\n } = getInstance()\n\n // Setup user reducer ref\n const getStateReducer = useGetLatest(stateReducer)\n\n // Build the reducer\n const reducer = React.useCallback(\n (state, action) => {\n // Detect invalid actions\n if (!action.type) {\n console.info({ action })\n throw new Error('Unknown Action 👆')\n }\n\n // Reduce the state from all plugin reducers\n return [\n ...getHooks().stateReducers,\n // Allow the user to add their own state reducer(s)\n ...(Array.isArray(getStateReducer())\n ? getStateReducer()\n : [getStateReducer()]),\n ].reduce(\n (s, handler) => handler(s, action, state, getInstance()) || s,\n state\n )\n },\n [getHooks, getStateReducer, getInstance]\n )\n\n // Start the reducer\n const [reducerState, dispatch] = React.useReducer(reducer, undefined, () =>\n reducer(initialState, { type: actions.init })\n )\n\n // Allow the user to control the final state with hooks\n const state = reduceHooks(\n [...getHooks().useControlledState, useControlledState],\n reducerState,\n { instance: getInstance() }\n )\n\n Object.assign(getInstance(), {\n state,\n dispatch,\n })\n\n // Decorate All the columns\n const columns = React.useMemo(\n () =>\n linkColumnStructure(\n reduceHooks(getHooks().columns, userColumns, {\n instance: getInstance(),\n })\n ),\n [\n getHooks,\n getInstance,\n userColumns,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n ...reduceHooks(getHooks().columnsDeps, [], { instance: getInstance() }),\n ]\n )\n getInstance().columns = columns\n\n // Get the flat list of all columns and allow hooks to decorate\n // those columns (and trigger this memoization via deps)\n let allColumns = React.useMemo(\n () =>\n reduceHooks(getHooks().allColumns, flattenColumns(columns), {\n instance: getInstance(),\n }).map(assignColumnAccessor),\n [\n columns,\n getHooks,\n getInstance,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n ...reduceHooks(getHooks().allColumnsDeps, [], {\n instance: getInstance(),\n }),\n ]\n )\n getInstance().allColumns = allColumns\n\n // Access the row model using initial columns\n const [rows, flatRows, rowsById] = React.useMemo(() => {\n let rows = []\n let flatRows = []\n const rowsById = {}\n\n const allColumnsQueue = [...allColumns]\n\n while (allColumnsQueue.length) {\n const column = allColumnsQueue.shift()\n accessRowsForColumn({\n data,\n rows,\n flatRows,\n rowsById,\n column,\n getRowId,\n getSubRows,\n accessValueHooks: getHooks().accessValue,\n getInstance,\n })\n }\n\n return [rows, flatRows, rowsById]\n }, [allColumns, data, getRowId, getSubRows, getHooks, getInstance])\n\n Object.assign(getInstance(), {\n rows,\n initialRows: [...rows],\n flatRows,\n rowsById,\n // materializedColumns,\n })\n\n loopHooks(getHooks().useInstanceAfterData, getInstance())\n\n // Get the flat list of all columns AFTER the rows\n // have been access, and allow hooks to decorate\n // those columns (and trigger this memoization via deps)\n let visibleColumns = React.useMemo(\n () =>\n reduceHooks(getHooks().visibleColumns, allColumns, {\n instance: getInstance(),\n }).map(d => decorateColumn(d, defaultColumn)),\n [\n getHooks,\n allColumns,\n getInstance,\n defaultColumn,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n ...reduceHooks(getHooks().visibleColumnsDeps, [], {\n instance: getInstance(),\n }),\n ]\n )\n\n // Combine new visible columns with all columns\n allColumns = React.useMemo(() => {\n const columns = [...visibleColumns]\n\n allColumns.forEach(column => {\n if (!columns.find(d => d.id === column.id)) {\n columns.push(column)\n }\n })\n\n return columns\n }, [allColumns, visibleColumns])\n getInstance().allColumns = allColumns\n\n if (process.env.NODE_ENV !== 'production') {\n const duplicateColumns = allColumns.filter((column, i) => {\n return allColumns.findIndex(d => d.id === column.id) !== i\n })\n\n if (duplicateColumns.length) {\n console.info(allColumns)\n throw new Error(\n `Duplicate columns were found with ids: \"${duplicateColumns\n .map(d => d.id)\n .join(', ')}\" in the columns array above`\n )\n }\n }\n\n // Make the headerGroups\n const headerGroups = React.useMemo(\n () =>\n reduceHooks(\n getHooks().headerGroups,\n makeHeaderGroups(visibleColumns, defaultColumn),\n getInstance()\n ),\n [\n getHooks,\n visibleColumns,\n defaultColumn,\n getInstance,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n ...reduceHooks(getHooks().headerGroupsDeps, [], {\n instance: getInstance(),\n }),\n ]\n )\n getInstance().headerGroups = headerGroups\n\n // Get the first level of headers\n const headers = React.useMemo(\n () => (headerGroups.length ? headerGroups[0].headers : []),\n [headerGroups]\n )\n getInstance().headers = headers\n\n // Provide a flat header list for utilities\n getInstance().flatHeaders = headerGroups.reduce(\n (all, headerGroup) => [...all, ...headerGroup.headers],\n []\n )\n\n loopHooks(getHooks().useInstanceBeforeDimensions, getInstance())\n\n // Filter columns down to visible ones\n const visibleColumnsDep = visibleColumns\n .filter(d => d.isVisible)\n .map(d => d.id)\n .sort()\n .join('_')\n\n visibleColumns = React.useMemo(\n () => visibleColumns.filter(d => d.isVisible),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [visibleColumns, visibleColumnsDep]\n )\n getInstance().visibleColumns = visibleColumns\n\n // Header Visibility is needed by this point\n const [\n totalColumnsMinWidth,\n totalColumnsWidth,\n totalColumnsMaxWidth,\n ] = calculateHeaderWidths(headers)\n\n getInstance().totalColumnsMinWidth = totalColumnsMinWidth\n getInstance().totalColumnsWidth = totalColumnsWidth\n getInstance().totalColumnsMaxWidth = totalColumnsMaxWidth\n\n loopHooks(getHooks().useInstance, getInstance())\n\n // Each materialized header needs to be assigned a render function and other\n // prop getter properties here.\n ;[...getInstance().flatHeaders, ...getInstance().allColumns].forEach(\n column => {\n // Give columns/headers rendering power\n column.render = makeRenderer(getInstance(), column)\n\n // Give columns/headers a default getHeaderProps\n column.getHeaderProps = makePropGetter(getHooks().getHeaderProps, {\n instance: getInstance(),\n column,\n })\n\n // Give columns/headers a default getFooterProps\n column.getFooterProps = makePropGetter(getHooks().getFooterProps, {\n instance: getInstance(),\n column,\n })\n }\n )\n\n getInstance().headerGroups = React.useMemo(\n () =>\n headerGroups.filter((headerGroup, i) => {\n // Filter out any headers and headerGroups that don't have visible columns\n headerGroup.headers = headerGroup.headers.filter(column => {\n const recurse = headers =>\n headers.filter(column => {\n if (column.headers) {\n return recurse(column.headers)\n }\n return column.isVisible\n }).length\n if (column.headers) {\n return recurse(column.headers)\n }\n return column.isVisible\n })\n\n // Give headerGroups getRowProps\n if (headerGroup.headers.length) {\n headerGroup.getHeaderGroupProps = makePropGetter(\n getHooks().getHeaderGroupProps,\n { instance: getInstance(), headerGroup, index: i }\n )\n\n headerGroup.getFooterGroupProps = makePropGetter(\n getHooks().getFooterGroupProps,\n { instance: getInstance(), headerGroup, index: i }\n )\n\n return true\n }\n\n return false\n }),\n [headerGroups, getInstance, getHooks]\n )\n\n getInstance().footerGroups = [...getInstance().headerGroups].reverse()\n\n // The prepareRow function is absolutely necessary and MUST be called on\n // any rows the user wishes to be displayed.\n\n getInstance().prepareRow = React.useCallback(\n row => {\n row.getRowProps = makePropGetter(getHooks().getRowProps, {\n instance: getInstance(),\n row,\n })\n\n // Build the visible cells for each row\n row.allCells = allColumns.map(column => {\n const value = row.values[column.id]\n\n const cell = {\n column,\n row,\n value,\n }\n\n // Give each cell a getCellProps base\n cell.getCellProps = makePropGetter(getHooks().getCellProps, {\n instance: getInstance(),\n cell,\n })\n\n // Give each cell a renderer function (supports multiple renderers)\n cell.render = makeRenderer(getInstance(), column, {\n row,\n cell,\n value,\n })\n\n return cell\n })\n\n row.cells = visibleColumns.map(column =>\n row.allCells.find(cell => cell.column.id === column.id)\n )\n\n // need to apply any row specific hooks (useExpanded requires this)\n loopHooks(getHooks().prepareRow, row, { instance: getInstance() })\n },\n [getHooks, getInstance, allColumns, visibleColumns]\n )\n\n getInstance().getTableProps = makePropGetter(getHooks().getTableProps, {\n instance: getInstance(),\n })\n\n getInstance().getTableBodyProps = makePropGetter(\n getHooks().getTableBodyProps,\n {\n instance: getInstance(),\n }\n )\n\n loopHooks(getHooks().useFinalInstance, getInstance())\n\n return getInstance()\n}\n\nfunction calculateHeaderWidths(headers, left = 0) {\n let sumTotalMinWidth = 0\n let sumTotalWidth = 0\n let sumTotalMaxWidth = 0\n let sumTotalFlexWidth = 0\n\n headers.forEach(header => {\n let { headers: subHeaders } = header\n\n header.totalLeft = left\n\n if (subHeaders && subHeaders.length) {\n const [\n totalMinWidth,\n totalWidth,\n totalMaxWidth,\n totalFlexWidth,\n ] = calculateHeaderWidths(subHeaders, left)\n header.totalMinWidth = totalMinWidth\n header.totalWidth = totalWidth\n header.totalMaxWidth = totalMaxWidth\n header.totalFlexWidth = totalFlexWidth\n } else {\n header.totalMinWidth = header.minWidth\n header.totalWidth = Math.min(\n Math.max(header.minWidth, header.width),\n header.maxWidth\n )\n header.totalMaxWidth = header.maxWidth\n header.totalFlexWidth = header.canResize ? header.totalWidth : 0\n }\n if (header.isVisible) {\n left += header.totalWidth\n sumTotalMinWidth += header.totalMinWidth\n sumTotalWidth += header.totalWidth\n sumTotalMaxWidth += header.totalMaxWidth\n sumTotalFlexWidth += header.totalFlexWidth\n }\n })\n\n return [sumTotalMinWidth, sumTotalWidth, sumTotalMaxWidth, sumTotalFlexWidth]\n}\n\nfunction accessRowsForColumn({\n data,\n rows,\n flatRows,\n rowsById,\n column,\n getRowId,\n getSubRows,\n accessValueHooks,\n getInstance,\n}) {\n // Access the row's data column-by-column\n // We do it this way so we can incrementally add materialized\n // columns after the first pass and avoid excessive looping\n const accessRow = (originalRow, rowIndex, depth = 0, parent, parentRows) => {\n // Keep the original reference around\n const original = originalRow\n\n const id = getRowId(originalRow, rowIndex, parent)\n\n let row = rowsById[id]\n\n // If the row hasn't been created, let's make it\n if (!row) {\n row = {\n id,\n original,\n index: rowIndex,\n depth,\n cells: [{}], // This is a dummy cell\n }\n\n // Override common array functions (and the dummy cell's getCellProps function)\n // to show an error if it is accessed without calling prepareRow\n row.cells.map = unpreparedAccessWarning\n row.cells.filter = unpreparedAccessWarning\n row.cells.forEach = unpreparedAccessWarning\n row.cells[0].getCellProps = unpreparedAccessWarning\n\n // Create the cells and values\n row.values = {}\n\n // Push this row into the parentRows array\n parentRows.push(row)\n // Keep track of every row in a flat array\n flatRows.push(row)\n // Also keep track of every row by its ID\n rowsById[id] = row\n\n // Get the original subrows\n row.originalSubRows = getSubRows(originalRow, rowIndex)\n\n // Then recursively access them\n if (row.originalSubRows) {\n const subRows = []\n row.originalSubRows.forEach((d, i) =>\n accessRow(d, i, depth + 1, row, subRows)\n )\n // Keep the new subRows array on the row\n row.subRows = subRows\n }\n } else if (row.subRows) {\n // If the row exists, then it's already been accessed\n // Keep recursing, but don't worry about passing the\n // accumlator array (those rows already exist)\n row.originalSubRows.forEach((d, i) => accessRow(d, i, depth + 1, row))\n }\n\n // If the column has an accessor, use it to get a value\n if (column.accessor) {\n row.values[column.id] = column.accessor(\n originalRow,\n rowIndex,\n row,\n parentRows,\n data\n )\n }\n\n // Allow plugins to manipulate the column value\n row.values[column.id] = reduceHooks(\n accessValueHooks,\n row.values[column.id],\n {\n row,\n column,\n instance: getInstance(),\n },\n true\n )\n }\n\n data.forEach((originalRow, rowIndex) =>\n accessRow(originalRow, rowIndex, 0, undefined, rows)\n )\n}\n","import React from 'react'\n\nimport { expandRows } from '../utils'\n\nimport {\n useGetLatest,\n actions,\n useMountedLayoutEffect,\n makePropGetter,\n ensurePluginOrder,\n} from '../publicUtils'\n\n// Actions\nactions.resetExpanded = 'resetExpanded'\nactions.toggleRowExpanded = 'toggleRowExpanded'\nactions.toggleAllRowsExpanded = 'toggleAllRowsExpanded'\n\nexport const useExpanded = hooks => {\n hooks.getToggleAllRowsExpandedProps = [defaultGetToggleAllRowsExpandedProps]\n hooks.getToggleRowExpandedProps = [defaultGetToggleRowExpandedProps]\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n hooks.prepareRow.push(prepareRow)\n}\n\nuseExpanded.pluginName = 'useExpanded'\n\nconst defaultGetToggleAllRowsExpandedProps = (props, { instance }) => [\n props,\n {\n onClick: e => {\n instance.toggleAllRowsExpanded()\n },\n style: {\n cursor: 'pointer',\n },\n title: 'Toggle All Rows Expanded',\n },\n]\n\nconst defaultGetToggleRowExpandedProps = (props, { row }) => [\n props,\n {\n onClick: () => {\n row.toggleRowExpanded()\n },\n style: {\n cursor: 'pointer',\n },\n title: 'Toggle Row Expanded',\n },\n]\n\n// Reducer\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n expanded: {},\n ...state,\n }\n }\n\n if (action.type === actions.resetExpanded) {\n return {\n ...state,\n expanded: instance.initialState.expanded || {},\n }\n }\n\n if (action.type === actions.toggleAllRowsExpanded) {\n const { value } = action\n const { rowsById } = instance\n\n const isAllRowsExpanded =\n Object.keys(rowsById).length === Object.keys(state.expanded).length\n\n const expandAll = typeof value !== 'undefined' ? value : !isAllRowsExpanded\n\n if (expandAll) {\n const expanded = {}\n\n Object.keys(rowsById).forEach(rowId => {\n expanded[rowId] = true\n })\n\n return {\n ...state,\n expanded,\n }\n }\n\n return {\n ...state,\n expanded: {},\n }\n }\n\n if (action.type === actions.toggleRowExpanded) {\n const { id, value: setExpanded } = action\n const exists = state.expanded[id]\n\n const shouldExist =\n typeof setExpanded !== 'undefined' ? setExpanded : !exists\n\n if (!exists && shouldExist) {\n return {\n ...state,\n expanded: {\n ...state.expanded,\n [id]: true,\n },\n }\n } else if (exists && !shouldExist) {\n const { [id]: _, ...rest } = state.expanded\n return {\n ...state,\n expanded: rest,\n }\n } else {\n return state\n }\n }\n}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n rowsById,\n manualExpandedKey = 'expanded',\n paginateExpandedRows = true,\n expandSubRows = true,\n autoResetExpanded = true,\n getHooks,\n plugins,\n state: { expanded },\n dispatch,\n } = instance\n\n ensurePluginOrder(\n plugins,\n ['useSortBy', 'useGroupBy', 'usePivotColumns', 'useGlobalFilter'],\n 'useExpanded'\n )\n\n const getAutoResetExpanded = useGetLatest(autoResetExpanded)\n\n let isAllRowsExpanded = Boolean(\n Object.keys(rowsById).length && Object.keys(expanded).length\n )\n\n if (isAllRowsExpanded) {\n if (Object.keys(rowsById).some(id => !expanded[id])) {\n isAllRowsExpanded = false\n }\n }\n\n // Bypass any effects from firing when this changes\n useMountedLayoutEffect(() => {\n if (getAutoResetExpanded()) {\n dispatch({ type: actions.resetExpanded })\n }\n }, [dispatch, data])\n\n const toggleRowExpanded = React.useCallback(\n (id, value) => {\n dispatch({ type: actions.toggleRowExpanded, id, value })\n },\n [dispatch]\n )\n\n const toggleAllRowsExpanded = React.useCallback(\n value => dispatch({ type: actions.toggleAllRowsExpanded, value }),\n [dispatch]\n )\n\n const expandedRows = React.useMemo(() => {\n if (paginateExpandedRows) {\n return expandRows(rows, { manualExpandedKey, expanded, expandSubRows })\n }\n\n return rows\n }, [paginateExpandedRows, rows, manualExpandedKey, expanded, expandSubRows])\n\n const expandedDepth = React.useMemo(() => findExpandedDepth(expanded), [\n expanded,\n ])\n\n const getInstance = useGetLatest(instance)\n\n const getToggleAllRowsExpandedProps = makePropGetter(\n getHooks().getToggleAllRowsExpandedProps,\n { instance: getInstance() }\n )\n\n Object.assign(instance, {\n preExpandedRows: rows,\n expandedRows,\n rows: expandedRows,\n expandedDepth,\n isAllRowsExpanded,\n toggleRowExpanded,\n toggleAllRowsExpanded,\n getToggleAllRowsExpandedProps,\n })\n}\n\nfunction prepareRow(row, { instance: { getHooks }, instance }) {\n row.toggleRowExpanded = set => instance.toggleRowExpanded(row.id, set)\n\n row.getToggleRowExpandedProps = makePropGetter(\n getHooks().getToggleRowExpandedProps,\n {\n instance,\n row,\n }\n )\n}\n\nfunction findExpandedDepth(expanded) {\n let maxDepth = 0\n\n Object.keys(expanded).forEach(id => {\n const splitId = id.split('.')\n maxDepth = Math.max(maxDepth, splitId.length)\n })\n\n return maxDepth\n}\n","export const text = (rows, ids, filterValue) => {\n rows = rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return String(rowValue)\n .toLowerCase()\n .includes(String(filterValue).toLowerCase())\n })\n })\n return rows\n}\n\ntext.autoRemove = val => !val\n\nexport const exactText = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return rowValue !== undefined\n ? String(rowValue).toLowerCase() === String(filterValue).toLowerCase()\n : true\n })\n })\n}\n\nexactText.autoRemove = val => !val\n\nexport const exactTextCase = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return rowValue !== undefined\n ? String(rowValue) === String(filterValue)\n : true\n })\n })\n}\n\nexactTextCase.autoRemove = val => !val\n\nexport const includes = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return rowValue.includes(filterValue)\n })\n })\n}\n\nincludes.autoRemove = val => !val || !val.length\n\nexport const includesAll = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return (\n rowValue &&\n rowValue.length &&\n filterValue.every(val => rowValue.includes(val))\n )\n })\n })\n}\n\nincludesAll.autoRemove = val => !val || !val.length\n\nexport const includesSome = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return (\n rowValue &&\n rowValue.length &&\n filterValue.some(val => rowValue.includes(val))\n )\n })\n })\n}\n\nincludesSome.autoRemove = val => !val || !val.length\n\nexport const includesValue = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return filterValue.includes(rowValue)\n })\n })\n}\n\nincludesValue.autoRemove = val => !val || !val.length\n\nexport const exact = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return rowValue === filterValue\n })\n })\n}\n\nexact.autoRemove = val => typeof val === 'undefined'\n\nexport const equals = (rows, ids, filterValue) => {\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n // eslint-disable-next-line eqeqeq\n return rowValue == filterValue\n })\n })\n}\n\nequals.autoRemove = val => val == null\n\nexport const between = (rows, ids, filterValue) => {\n let [min, max] = filterValue || []\n\n min = typeof min === 'number' ? min : -Infinity\n max = typeof max === 'number' ? max : Infinity\n\n if (min > max) {\n const temp = min\n min = max\n max = temp\n }\n\n return rows.filter(row => {\n return ids.some(id => {\n const rowValue = row.values[id]\n return rowValue >= min && rowValue <= max\n })\n })\n}\n\nbetween.autoRemove = val =>\n !val || (typeof val[0] !== 'number' && typeof val[1] !== 'number')\n","import React from 'react'\n\nimport {\n getFirstDefined,\n getFilterMethod,\n shouldAutoRemoveFilter,\n} from '../utils'\n\nimport {\n actions,\n useGetLatest,\n functionalUpdate,\n useMountedLayoutEffect,\n} from '../publicUtils'\n\nimport * as filterTypes from '../filterTypes'\n\n// Actions\nactions.resetFilters = 'resetFilters'\nactions.setFilter = 'setFilter'\nactions.setAllFilters = 'setAllFilters'\n\nexport const useFilters = hooks => {\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n}\n\nuseFilters.pluginName = 'useFilters'\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n filters: [],\n ...state,\n }\n }\n\n if (action.type === actions.resetFilters) {\n return {\n ...state,\n filters: instance.initialState.filters || [],\n }\n }\n\n if (action.type === actions.setFilter) {\n const { columnId, filterValue } = action\n const { allColumns, filterTypes: userFilterTypes } = instance\n\n const column = allColumns.find(d => d.id === columnId)\n\n if (!column) {\n throw new Error(\n `React-Table: Could not find a column with id: ${columnId}`\n )\n }\n\n const filterMethod = getFilterMethod(\n column.filter,\n userFilterTypes || {},\n filterTypes\n )\n\n const previousfilter = state.filters.find(d => d.id === columnId)\n\n const newFilter = functionalUpdate(\n filterValue,\n previousfilter && previousfilter.value\n )\n\n //\n if (shouldAutoRemoveFilter(filterMethod.autoRemove, newFilter, column)) {\n return {\n ...state,\n filters: state.filters.filter(d => d.id !== columnId),\n }\n }\n\n if (previousfilter) {\n return {\n ...state,\n filters: state.filters.map(d => {\n if (d.id === columnId) {\n return { id: columnId, value: newFilter }\n }\n return d\n }),\n }\n }\n\n return {\n ...state,\n filters: [...state.filters, { id: columnId, value: newFilter }],\n }\n }\n\n if (action.type === actions.setAllFilters) {\n const { filters } = action\n const { allColumns, filterTypes: userFilterTypes } = instance\n\n return {\n ...state,\n // Filter out undefined values\n filters: functionalUpdate(filters, state.filters).filter(filter => {\n const column = allColumns.find(d => d.id === filter.id)\n const filterMethod = getFilterMethod(\n column.filter,\n userFilterTypes || {},\n filterTypes\n )\n\n if (\n shouldAutoRemoveFilter(filterMethod.autoRemove, filter.value, column)\n ) {\n return false\n }\n return true\n }),\n }\n }\n}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n flatRows,\n rowsById,\n allColumns,\n filterTypes: userFilterTypes,\n manualFilters,\n defaultCanFilter = false,\n disableFilters,\n state: { filters },\n dispatch,\n autoResetFilters = true,\n } = instance\n\n const setFilter = React.useCallback(\n (columnId, filterValue) => {\n dispatch({ type: actions.setFilter, columnId, filterValue })\n },\n [dispatch]\n )\n\n const setAllFilters = React.useCallback(\n filters => {\n dispatch({\n type: actions.setAllFilters,\n filters,\n })\n },\n [dispatch]\n )\n\n allColumns.forEach(column => {\n const {\n id,\n accessor,\n defaultCanFilter: columnDefaultCanFilter,\n disableFilters: columnDisableFilters,\n } = column\n\n // Determine if a column is filterable\n column.canFilter = accessor\n ? getFirstDefined(\n columnDisableFilters === true ? false : undefined,\n disableFilters === true ? false : undefined,\n true\n )\n : getFirstDefined(columnDefaultCanFilter, defaultCanFilter, false)\n\n // Provide the column a way of updating the filter value\n column.setFilter = val => setFilter(column.id, val)\n\n // Provide the current filter value to the column for\n // convenience\n const found = filters.find(d => d.id === id)\n column.filterValue = found && found.value\n })\n\n const [\n filteredRows,\n filteredFlatRows,\n filteredRowsById,\n ] = React.useMemo(() => {\n if (manualFilters || !filters.length) {\n return [rows, flatRows, rowsById]\n }\n\n const filteredFlatRows = []\n const filteredRowsById = {}\n\n // Filters top level and nested rows\n const filterRows = (rows, depth = 0) => {\n let filteredRows = rows\n\n filteredRows = filters.reduce(\n (filteredSoFar, { id: columnId, value: filterValue }) => {\n // Find the filters column\n const column = allColumns.find(d => d.id === columnId)\n\n if (!column) {\n return filteredSoFar\n }\n\n if (depth === 0) {\n column.preFilteredRows = filteredSoFar\n }\n\n const filterMethod = getFilterMethod(\n column.filter,\n userFilterTypes || {},\n filterTypes\n )\n\n if (!filterMethod) {\n console.warn(\n `Could not find a valid 'column.filter' for column with the ID: ${column.id}.`\n )\n return filteredSoFar\n }\n\n // Pass the rows, id, filterValue and column to the filterMethod\n // to get the filtered rows back\n column.filteredRows = filterMethod(\n filteredSoFar,\n [columnId],\n filterValue\n )\n\n return column.filteredRows\n },\n rows\n )\n\n // Apply the filter to any subRows\n // We technically could do this recursively in the above loop,\n // but that would severely hinder the API for the user, since they\n // would be required to do that recursion in some scenarios\n filteredRows.forEach(row => {\n filteredFlatRows.push(row)\n filteredRowsById[row.id] = row\n if (!row.subRows) {\n return\n }\n\n row.subRows =\n row.subRows && row.subRows.length > 0\n ? filterRows(row.subRows, depth + 1)\n : row.subRows\n })\n\n return filteredRows\n }\n\n return [filterRows(rows), filteredFlatRows, filteredRowsById]\n }, [\n manualFilters,\n filters,\n rows,\n flatRows,\n rowsById,\n allColumns,\n userFilterTypes,\n ])\n\n React.useMemo(() => {\n // Now that each filtered column has it's partially filtered rows,\n // lets assign the final filtered rows to all of the other columns\n const nonFilteredColumns = allColumns.filter(\n column => !filters.find(d => d.id === column.id)\n )\n\n // This essentially enables faceted filter options to be built easily\n // using every column's preFilteredRows value\n nonFilteredColumns.forEach(column => {\n column.preFilteredRows = filteredRows\n column.filteredRows = filteredRows\n })\n }, [filteredRows, filters, allColumns])\n\n const getAutoResetFilters = useGetLatest(autoResetFilters)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetFilters()) {\n dispatch({ type: actions.resetFilters })\n }\n }, [dispatch, manualFilters ? null : data])\n\n Object.assign(instance, {\n preFilteredRows: rows,\n preFilteredFlatRows: flatRows,\n preFilteredRowsById: rowsById,\n filteredRows,\n filteredFlatRows,\n filteredRowsById,\n rows: filteredRows,\n flatRows: filteredFlatRows,\n rowsById: filteredRowsById,\n setFilter,\n setAllFilters,\n })\n}\n","import React from 'react'\n\nimport {\n getFilterMethod,\n shouldAutoRemoveFilter,\n getFirstDefined,\n} from '../utils'\n\nimport {\n actions,\n useMountedLayoutEffect,\n functionalUpdate,\n useGetLatest,\n} from '../publicUtils'\n\nimport * as filterTypes from '../filterTypes'\n\n// Actions\nactions.resetGlobalFilter = 'resetGlobalFilter'\nactions.setGlobalFilter = 'setGlobalFilter'\n\nexport const useGlobalFilter = hooks => {\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n}\n\nuseGlobalFilter.pluginName = 'useGlobalFilter'\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.resetGlobalFilter) {\n return {\n ...state,\n globalFilter: instance.initialState.globalFilter || undefined,\n }\n }\n\n if (action.type === actions.setGlobalFilter) {\n const { filterValue } = action\n const { userFilterTypes } = instance\n\n const filterMethod = getFilterMethod(\n instance.globalFilter,\n userFilterTypes || {},\n filterTypes\n )\n\n const newFilter = functionalUpdate(filterValue, state.globalFilter)\n\n //\n if (shouldAutoRemoveFilter(filterMethod.autoRemove, newFilter)) {\n const { globalFilter, ...stateWithoutGlobalFilter } = state\n return stateWithoutGlobalFilter\n }\n\n return {\n ...state,\n globalFilter: newFilter,\n }\n }\n}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n flatRows,\n rowsById,\n allColumns,\n filterTypes: userFilterTypes,\n globalFilter,\n manualGlobalFilter,\n state: { globalFilter: globalFilterValue },\n dispatch,\n autoResetGlobalFilter = true,\n disableGlobalFilter,\n } = instance\n\n const setGlobalFilter = React.useCallback(\n filterValue => {\n dispatch({ type: actions.setGlobalFilter, filterValue })\n },\n [dispatch]\n )\n\n // TODO: Create a filter cache for incremental high speed multi-filtering\n // This gets pretty complicated pretty fast, since you have to maintain a\n // cache for each row group (top-level rows, and each row's recursive subrows)\n // This would make multi-filtering a lot faster though. Too far?\n\n const [\n globalFilteredRows,\n globalFilteredFlatRows,\n globalFilteredRowsById,\n ] = React.useMemo(() => {\n if (manualGlobalFilter || typeof globalFilterValue === 'undefined') {\n return [rows, flatRows, rowsById]\n }\n\n const filteredFlatRows = []\n const filteredRowsById = {}\n\n const filterMethod = getFilterMethod(\n globalFilter,\n userFilterTypes || {},\n filterTypes\n )\n\n if (!filterMethod) {\n console.warn(`Could not find a valid 'globalFilter' option.`)\n return rows\n }\n\n allColumns.forEach(column => {\n const { disableGlobalFilter: columnDisableGlobalFilter } = column\n\n column.canFilter = getFirstDefined(\n columnDisableGlobalFilter === true ? false : undefined,\n disableGlobalFilter === true ? false : undefined,\n true\n )\n })\n\n const filterableColumns = allColumns.filter(c => c.canFilter === true)\n\n // Filters top level and nested rows\n const filterRows = filteredRows => {\n filteredRows = filterMethod(\n filteredRows,\n filterableColumns.map(d => d.id),\n globalFilterValue\n )\n\n filteredRows.forEach(row => {\n filteredFlatRows.push(row)\n filteredRowsById[row.id] = row\n\n row.subRows =\n row.subRows && row.subRows.length\n ? filterRows(row.subRows)\n : row.subRows\n })\n\n return filteredRows\n }\n\n return [filterRows(rows), filteredFlatRows, filteredRowsById]\n }, [\n manualGlobalFilter,\n globalFilterValue,\n globalFilter,\n userFilterTypes,\n allColumns,\n rows,\n flatRows,\n rowsById,\n disableGlobalFilter,\n ])\n\n const getAutoResetGlobalFilter = useGetLatest(autoResetGlobalFilter)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetGlobalFilter()) {\n dispatch({ type: actions.resetGlobalFilter })\n }\n }, [dispatch, manualGlobalFilter ? null : data])\n\n Object.assign(instance, {\n preGlobalFilteredRows: rows,\n preGlobalFilteredFlatRows: flatRows,\n preGlobalFilteredRowsById: rowsById,\n globalFilteredRows,\n globalFilteredFlatRows,\n globalFilteredRowsById,\n rows: globalFilteredRows,\n flatRows: globalFilteredFlatRows,\n rowsById: globalFilteredRowsById,\n setGlobalFilter,\n disableGlobalFilter,\n })\n}\n","export function sum(values, aggregatedValues) {\n // It's faster to just add the aggregations together instead of\n // process leaf nodes individually\n return aggregatedValues.reduce(\n (sum, next) => sum + (typeof next === 'number' ? next : 0),\n 0\n )\n}\n\nexport function min(values) {\n let min = values[0] || 0\n\n values.forEach(value => {\n if (typeof value === 'number') {\n min = Math.min(min, value)\n }\n })\n\n return min\n}\n\nexport function max(values) {\n let max = values[0] || 0\n\n values.forEach(value => {\n if (typeof value === 'number') {\n max = Math.max(max, value)\n }\n })\n\n return max\n}\n\nexport function minMax(values) {\n let min = values[0] || 0\n let max = values[0] || 0\n\n values.forEach(value => {\n if (typeof value === 'number') {\n min = Math.min(min, value)\n max = Math.max(max, value)\n }\n })\n\n return `${min}..${max}`\n}\n\nexport function average(values) {\n return sum(null, values) / values.length\n}\n\nexport function median(values) {\n if (!values.length) {\n return null\n }\n\n const mid = Math.floor(values.length / 2)\n const nums = [...values].sort((a, b) => a - b)\n return values.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2\n}\n\nexport function unique(values) {\n return Array.from(new Set(values).values())\n}\n\nexport function uniqueCount(values) {\n return new Set(values).size\n}\n\nexport function count(values) {\n return values.length\n}\n","import React from 'react'\n\nimport * as aggregations from '../aggregations'\n\nimport { getFirstDefined, flattenBy } from '../utils'\n\nimport {\n actions,\n makePropGetter,\n ensurePluginOrder,\n useMountedLayoutEffect,\n useGetLatest,\n} from '../publicUtils'\n\nconst emptyArray = []\nconst emptyObject = {}\n\n// Actions\nactions.resetGroupBy = 'resetGroupBy'\nactions.setGroupBy = 'setGroupBy'\nactions.toggleGroupBy = 'toggleGroupBy'\n\nexport const useGroupBy = hooks => {\n hooks.getGroupByToggleProps = [defaultGetGroupByToggleProps]\n hooks.stateReducers.push(reducer)\n hooks.visibleColumnsDeps.push((deps, { instance }) => [\n ...deps,\n instance.state.groupBy,\n ])\n hooks.visibleColumns.push(visibleColumns)\n hooks.useInstance.push(useInstance)\n hooks.prepareRow.push(prepareRow)\n}\n\nuseGroupBy.pluginName = 'useGroupBy'\n\nconst defaultGetGroupByToggleProps = (props, { header }) => [\n props,\n {\n onClick: header.canGroupBy\n ? e => {\n e.persist()\n header.toggleGroupBy()\n }\n : undefined,\n style: {\n cursor: header.canGroupBy ? 'pointer' : undefined,\n },\n title: 'Toggle GroupBy',\n },\n]\n\n// Reducer\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n groupBy: [],\n ...state,\n }\n }\n\n if (action.type === actions.resetGroupBy) {\n return {\n ...state,\n groupBy: instance.initialState.groupBy || [],\n }\n }\n\n if (action.type === actions.setGroupBy) {\n const { value } = action\n return {\n ...state,\n groupBy: value,\n }\n }\n\n if (action.type === actions.toggleGroupBy) {\n const { columnId, value: setGroupBy } = action\n\n const resolvedGroupBy =\n typeof setGroupBy !== 'undefined'\n ? setGroupBy\n : !state.groupBy.includes(columnId)\n\n if (resolvedGroupBy) {\n return {\n ...state,\n groupBy: [...state.groupBy, columnId],\n }\n }\n\n return {\n ...state,\n groupBy: state.groupBy.filter(d => d !== columnId),\n }\n }\n}\n\nfunction visibleColumns(\n columns,\n {\n instance: {\n state: { groupBy },\n },\n }\n) {\n // Sort grouped columns to the start of the column list\n // before the headers are built\n\n const groupByColumns = groupBy\n .map(g => columns.find(col => col.id === g))\n .filter(Boolean)\n\n const nonGroupByColumns = columns.filter(col => !groupBy.includes(col.id))\n\n columns = [...groupByColumns, ...nonGroupByColumns]\n\n columns.forEach(column => {\n column.isGrouped = groupBy.includes(column.id)\n column.groupedIndex = groupBy.indexOf(column.id)\n })\n\n return columns\n}\n\nconst defaultUserAggregations = {}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n flatRows,\n rowsById,\n allColumns,\n flatHeaders,\n groupByFn = defaultGroupByFn,\n manualGroupBy,\n aggregations: userAggregations = defaultUserAggregations,\n plugins,\n state: { groupBy },\n dispatch,\n autoResetGroupBy = true,\n disableGroupBy,\n defaultCanGroupBy,\n getHooks,\n } = instance\n\n ensurePluginOrder(plugins, ['useColumnOrder', 'useFilters'], 'useGroupBy')\n\n const getInstance = useGetLatest(instance)\n\n allColumns.forEach(column => {\n const {\n accessor,\n defaultGroupBy: defaultColumnGroupBy,\n disableGroupBy: columnDisableGroupBy,\n } = column\n\n column.canGroupBy = accessor\n ? getFirstDefined(\n column.canGroupBy,\n columnDisableGroupBy === true ? false : undefined,\n disableGroupBy === true ? false : undefined,\n true\n )\n : getFirstDefined(\n column.canGroupBy,\n defaultColumnGroupBy,\n defaultCanGroupBy,\n false\n )\n\n if (column.canGroupBy) {\n column.toggleGroupBy = () => instance.toggleGroupBy(column.id)\n }\n\n column.Aggregated = column.Aggregated || column.Cell\n })\n\n const toggleGroupBy = React.useCallback(\n (columnId, value) => {\n dispatch({ type: actions.toggleGroupBy, columnId, value })\n },\n [dispatch]\n )\n\n const setGroupBy = React.useCallback(\n value => {\n dispatch({ type: actions.setGroupBy, value })\n },\n [dispatch]\n )\n\n flatHeaders.forEach(header => {\n header.getGroupByToggleProps = makePropGetter(\n getHooks().getGroupByToggleProps,\n { instance: getInstance(), header }\n )\n })\n\n const [\n groupedRows,\n groupedFlatRows,\n groupedRowsById,\n onlyGroupedFlatRows,\n onlyGroupedRowsById,\n nonGroupedFlatRows,\n nonGroupedRowsById,\n ] = React.useMemo(() => {\n if (manualGroupBy || !groupBy.length) {\n return [\n rows,\n flatRows,\n rowsById,\n emptyArray,\n emptyObject,\n flatRows,\n rowsById,\n ]\n }\n\n // Ensure that the list of filtered columns exist\n const existingGroupBy = groupBy.filter(g =>\n allColumns.find(col => col.id === g)\n )\n\n // Find the columns that can or are aggregating\n // Uses each column to aggregate rows into a single value\n const aggregateRowsToValues = (leafRows, groupedRows, depth) => {\n const values = {}\n\n allColumns.forEach(column => {\n // Don't aggregate columns that are in the groupBy\n if (existingGroupBy.includes(column.id)) {\n values[column.id] = groupedRows[0]\n ? groupedRows[0].values[column.id]\n : null\n return\n }\n\n // Aggregate the values\n let aggregateFn =\n typeof column.aggregate === 'function'\n ? column.aggregate\n : userAggregations[column.aggregate] ||\n aggregations[column.aggregate]\n\n if (aggregateFn) {\n // Get the columnValues to aggregate\n const groupedValues = groupedRows.map(row => row.values[column.id])\n\n // Get the columnValues to aggregate\n const leafValues = leafRows.map(row => {\n let columnValue = row.values[column.id]\n\n if (!depth && column.aggregateValue) {\n const aggregateValueFn =\n typeof column.aggregateValue === 'function'\n ? column.aggregateValue\n : userAggregations[column.aggregateValue] ||\n aggregations[column.aggregateValue]\n\n if (!aggregateValueFn) {\n console.info({ column })\n throw new Error(\n `React Table: Invalid column.aggregateValue option for column listed above`\n )\n }\n\n columnValue = aggregateValueFn(columnValue, row, column)\n }\n return columnValue\n })\n\n values[column.id] = aggregateFn(leafValues, groupedValues)\n } else if (column.aggregate) {\n console.info({ column })\n throw new Error(\n `React Table: Invalid column.aggregate option for column listed above`\n )\n } else {\n values[column.id] = null\n }\n })\n\n return values\n }\n\n let groupedFlatRows = []\n const groupedRowsById = {}\n const onlyGroupedFlatRows = []\n const onlyGroupedRowsById = {}\n const nonGroupedFlatRows = []\n const nonGroupedRowsById = {}\n\n // Recursively group the data\n const groupUpRecursively = (rows, depth = 0, parentId) => {\n // This is the last level, just return the rows\n if (depth === existingGroupBy.length) {\n return rows.map((row) => ({ ...row, depth }))\n }\n\n const columnId = existingGroupBy[depth]\n\n // Group the rows together for this level\n let rowGroupsMap = groupByFn(rows, columnId)\n\n // Peform aggregations for each group\n const aggregatedGroupedRows = Object.entries(rowGroupsMap).map(\n ([groupByVal, groupedRows], index) => {\n let id = `${columnId}:${groupByVal}`\n id = parentId ? `${parentId}>${id}` : id\n\n // First, Recurse to group sub rows before aggregation\n const subRows = groupUpRecursively(groupedRows, depth + 1, id)\n\n // Flatten the leaf rows of the rows in this group\n const leafRows = depth\n ? flattenBy(groupedRows, 'leafRows')\n : groupedRows\n\n const values = aggregateRowsToValues(leafRows, groupedRows, depth)\n\n const row = {\n id,\n isGrouped: true,\n groupByID: columnId,\n groupByVal,\n values,\n subRows,\n leafRows,\n depth,\n index,\n }\n\n subRows.forEach(subRow => {\n groupedFlatRows.push(subRow)\n groupedRowsById[subRow.id] = subRow\n if (subRow.isGrouped) {\n onlyGroupedFlatRows.push(subRow)\n onlyGroupedRowsById[subRow.id] = subRow\n } else {\n nonGroupedFlatRows.push(subRow)\n nonGroupedRowsById[subRow.id] = subRow\n }\n })\n\n return row\n }\n )\n\n return aggregatedGroupedRows\n }\n\n const groupedRows = groupUpRecursively(rows)\n\n groupedRows.forEach(subRow => {\n groupedFlatRows.push(subRow)\n groupedRowsById[subRow.id] = subRow\n if (subRow.isGrouped) {\n onlyGroupedFlatRows.push(subRow)\n onlyGroupedRowsById[subRow.id] = subRow\n } else {\n nonGroupedFlatRows.push(subRow)\n nonGroupedRowsById[subRow.id] = subRow\n }\n })\n\n // Assign the new data\n return [\n groupedRows,\n groupedFlatRows,\n groupedRowsById,\n onlyGroupedFlatRows,\n onlyGroupedRowsById,\n nonGroupedFlatRows,\n nonGroupedRowsById,\n ]\n }, [\n manualGroupBy,\n groupBy,\n rows,\n flatRows,\n rowsById,\n allColumns,\n userAggregations,\n groupByFn,\n ])\n\n const getAutoResetGroupBy = useGetLatest(autoResetGroupBy)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetGroupBy()) {\n dispatch({ type: actions.resetGroupBy })\n }\n }, [dispatch, manualGroupBy ? null : data])\n\n Object.assign(instance, {\n preGroupedRows: rows,\n preGroupedFlatRow: flatRows,\n preGroupedRowsById: rowsById,\n groupedRows,\n groupedFlatRows,\n groupedRowsById,\n onlyGroupedFlatRows,\n onlyGroupedRowsById,\n nonGroupedFlatRows,\n nonGroupedRowsById,\n rows: groupedRows,\n flatRows: groupedFlatRows,\n rowsById: groupedRowsById,\n toggleGroupBy,\n setGroupBy,\n })\n}\n\nfunction prepareRow(row) {\n row.allCells.forEach(cell => {\n // Grouped cells are in the groupBy and the pivot cell for the row\n cell.isGrouped = cell.column.isGrouped && cell.column.id === row.groupByID\n // Placeholder cells are any columns in the groupBy that are not grouped\n cell.isPlaceholder = !cell.isGrouped && cell.column.isGrouped\n // Aggregated cells are not grouped, not repeated, but still have subRows\n cell.isAggregated =\n !cell.isGrouped && !cell.isPlaceholder && row.subRows?.length\n })\n}\n\nexport function defaultGroupByFn(rows, columnId) {\n return rows.reduce((prev, row, i) => {\n // TODO: Might want to implement a key serializer here so\n // irregular column values can still be grouped if needed?\n const resKey = `${row.values[columnId]}`\n prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : []\n prev[resKey].push(row)\n return prev\n }, {})\n}\n","const reSplitAlphaNumeric = /([0-9]+)/gm\n\n// Mixed sorting is slow, but very inclusive of many edge cases.\n// It handles numbers, mixed alphanumeric combinations, and even\n// null, undefined, and Infinity\nexport const alphanumeric = (rowA, rowB, columnId) => {\n let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId)\n\n // Force to strings (or \"\" for unsupported types)\n a = toString(a)\n b = toString(b)\n\n // Split on number groups, but keep the delimiter\n // Then remove falsey split values\n a = a.split(reSplitAlphaNumeric).filter(Boolean)\n b = b.split(reSplitAlphaNumeric).filter(Boolean)\n\n // While\n while (a.length && b.length) {\n let aa = a.shift()\n let bb = b.shift()\n\n const an = parseInt(aa, 10)\n const bn = parseInt(bb, 10)\n\n const combo = [an, bn].sort()\n\n // Both are string\n if (isNaN(combo[0])) {\n if (aa > bb) {\n return 1\n }\n if (bb > aa) {\n return -1\n }\n continue\n }\n\n // One is a string, one is a number\n if (isNaN(combo[1])) {\n return isNaN(an) ? -1 : 1\n }\n\n // Both are numbers\n if (an > bn) {\n return 1\n }\n if (bn > an) {\n return -1\n }\n }\n\n return a.length - b.length\n}\nexport function datetime(rowA, rowB, columnId) {\n let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId)\n\n a = a.getTime()\n b = b.getTime()\n\n return compareBasic(a, b)\n}\n\nexport function basic(rowA, rowB, columnId) {\n let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId)\n\n return compareBasic(a, b)\n}\n\nexport function string(rowA, rowB, columnId) {\n let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId)\n\n a = a.split('').filter(Boolean)\n b = b.split('').filter(Boolean)\n\n while (a.length && b.length) {\n let aa = a.shift()\n let bb = b.shift()\n\n let alower = aa.toLowerCase()\n let blower = bb.toLowerCase()\n\n // Case insensitive comparison until characters match\n if (alower > blower) {\n return 1\n }\n if (blower > alower) {\n return -1\n }\n // If lowercase characters are identical\n if (aa > bb) {\n return 1\n }\n if (bb > aa) {\n return -1\n }\n continue\n }\n\n return a.length - b.length\n}\n\nexport function number(rowA, rowB, columnId) {\n let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId)\n\n const replaceNonNumeric = /[^0-9.]/gi\n\n a = Number(String(a).replace(replaceNonNumeric, ''))\n b = Number(String(b).replace(replaceNonNumeric, ''))\n\n return compareBasic(a, b)\n}\n\n// Utils\n\nfunction compareBasic(a, b) {\n return a === b ? 0 : a > b ? 1 : -1\n}\n\nfunction getRowValuesByColumnID(row1, row2, columnId) {\n return [row1.values[columnId], row2.values[columnId]]\n}\n\nfunction toString(a) {\n if (typeof a === 'number') {\n if (isNaN(a) || a === Infinity || a === -Infinity) {\n return ''\n }\n return String(a)\n }\n if (typeof a === 'string') {\n return a\n }\n return ''\n}\n","import React from 'react'\n\nimport {\n actions,\n ensurePluginOrder,\n defaultColumn,\n makePropGetter,\n useGetLatest,\n useMountedLayoutEffect,\n} from '../publicUtils'\n\nimport { getFirstDefined, isFunction } from '../utils'\n\nimport * as sortTypes from '../sortTypes'\n\n// Actions\nactions.resetSortBy = 'resetSortBy'\nactions.setSortBy = 'setSortBy'\nactions.toggleSortBy = 'toggleSortBy'\nactions.clearSortBy = 'clearSortBy'\n\ndefaultColumn.sortType = 'alphanumeric'\ndefaultColumn.sortDescFirst = false\n\nexport const useSortBy = hooks => {\n hooks.getSortByToggleProps = [defaultGetSortByToggleProps]\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n}\n\nuseSortBy.pluginName = 'useSortBy'\n\nconst defaultGetSortByToggleProps = (props, { instance, column }) => {\n const { isMultiSortEvent = e => e.shiftKey } = instance\n\n return [\n props,\n {\n onClick: column.canSort\n ? e => {\n e.persist()\n column.toggleSortBy(\n undefined,\n !instance.disableMultiSort && isMultiSortEvent(e)\n )\n }\n : undefined,\n style: {\n cursor: column.canSort ? 'pointer' : undefined,\n },\n title: column.canSort ? 'Toggle SortBy' : undefined,\n },\n ]\n}\n\n// Reducer\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n sortBy: [],\n ...state,\n }\n }\n\n if (action.type === actions.resetSortBy) {\n return {\n ...state,\n sortBy: instance.initialState.sortBy || [],\n }\n }\n\n if (action.type === actions.clearSortBy) {\n const { sortBy } = state\n const newSortBy = sortBy.filter(d => d.id !== action.columnId)\n\n return {\n ...state,\n sortBy: newSortBy,\n }\n }\n\n if (action.type === actions.setSortBy) {\n const { sortBy } = action\n return {\n ...state,\n sortBy,\n }\n }\n\n if (action.type === actions.toggleSortBy) {\n const { columnId, desc, multi } = action\n\n const {\n allColumns,\n disableMultiSort,\n disableSortRemove,\n disableMultiRemove,\n maxMultiSortColCount = Number.MAX_SAFE_INTEGER,\n } = instance\n\n const { sortBy } = state\n\n // Find the column for this columnId\n const column = allColumns.find(d => d.id === columnId)\n const { sortDescFirst } = column\n\n // Find any existing sortBy for this column\n const existingSortBy = sortBy.find(d => d.id === columnId)\n const existingIndex = sortBy.findIndex(d => d.id === columnId)\n const hasDescDefined = typeof desc !== 'undefined' && desc !== null\n\n let newSortBy = []\n\n // What should we do with this sort action?\n let sortAction\n\n if (!disableMultiSort && multi) {\n if (existingSortBy) {\n sortAction = 'toggle'\n } else {\n sortAction = 'add'\n }\n } else {\n // Normal mode\n if (existingIndex !== sortBy.length - 1 || sortBy.length !== 1) {\n sortAction = 'replace'\n } else if (existingSortBy) {\n sortAction = 'toggle'\n } else {\n sortAction = 'replace'\n }\n }\n\n // Handle toggle states that will remove the sortBy\n if (\n sortAction === 'toggle' && // Must be toggling\n !disableSortRemove && // If disableSortRemove, disable in general\n !hasDescDefined && // Must not be setting desc\n (multi ? !disableMultiRemove : true) && // If multi, don't allow if disableMultiRemove\n ((existingSortBy && // Finally, detect if it should indeed be removed\n existingSortBy.desc &&\n !sortDescFirst) ||\n (!existingSortBy.desc && sortDescFirst))\n ) {\n sortAction = 'remove'\n }\n\n if (sortAction === 'replace') {\n newSortBy = [\n {\n id: columnId,\n desc: hasDescDefined ? desc : sortDescFirst,\n },\n ]\n } else if (sortAction === 'add') {\n newSortBy = [\n ...sortBy,\n {\n id: columnId,\n desc: hasDescDefined ? desc : sortDescFirst,\n },\n ]\n // Take latest n columns\n newSortBy.splice(0, newSortBy.length - maxMultiSortColCount)\n } else if (sortAction === 'toggle') {\n // This flips (or sets) the\n newSortBy = sortBy.map(d => {\n if (d.id === columnId) {\n return {\n ...d,\n desc: hasDescDefined ? desc : !existingSortBy.desc,\n }\n }\n return d\n })\n } else if (sortAction === 'remove') {\n newSortBy = sortBy.filter(d => d.id !== columnId)\n }\n\n return {\n ...state,\n sortBy: newSortBy,\n }\n }\n}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n flatRows,\n allColumns,\n orderByFn = defaultOrderByFn,\n sortTypes: userSortTypes,\n manualSortBy,\n defaultCanSort,\n disableSortBy,\n flatHeaders,\n state: { sortBy },\n dispatch,\n plugins,\n getHooks,\n autoResetSortBy = true,\n } = instance\n\n ensurePluginOrder(\n plugins,\n ['useFilters', 'useGlobalFilter', 'useGroupBy', 'usePivotColumns'],\n 'useSortBy'\n )\n\n const setSortBy = React.useCallback(\n sortBy => {\n dispatch({ type: actions.setSortBy, sortBy })\n },\n [dispatch]\n )\n\n // Updates sorting based on a columnId, desc flag and multi flag\n const toggleSortBy = React.useCallback(\n (columnId, desc, multi) => {\n dispatch({ type: actions.toggleSortBy, columnId, desc, multi })\n },\n [dispatch]\n )\n\n // use reference to avoid memory leak in #1608\n const getInstance = useGetLatest(instance)\n\n // Add the getSortByToggleProps method to columns and headers\n flatHeaders.forEach(column => {\n const {\n accessor,\n canSort: defaultColumnCanSort,\n disableSortBy: columnDisableSortBy,\n id,\n } = column\n\n const canSort = accessor\n ? getFirstDefined(\n columnDisableSortBy === true ? false : undefined,\n disableSortBy === true ? false : undefined,\n true\n )\n : getFirstDefined(defaultCanSort, defaultColumnCanSort, false)\n\n column.canSort = canSort\n\n if (column.canSort) {\n column.toggleSortBy = (desc, multi) =>\n toggleSortBy(column.id, desc, multi)\n\n column.clearSortBy = () => {\n dispatch({ type: actions.clearSortBy, columnId: column.id })\n }\n }\n\n column.getSortByToggleProps = makePropGetter(\n getHooks().getSortByToggleProps,\n {\n instance: getInstance(),\n column,\n }\n )\n\n const columnSort = sortBy.find(d => d.id === id)\n column.isSorted = !!columnSort\n column.sortedIndex = sortBy.findIndex(d => d.id === id)\n column.isSortedDesc = column.isSorted ? columnSort.desc : undefined\n })\n\n const [sortedRows, sortedFlatRows] = React.useMemo(() => {\n if (manualSortBy || !sortBy.length) {\n return [rows, flatRows]\n }\n\n const sortedFlatRows = []\n\n // Filter out sortBys that correspond to non existing columns\n const availableSortBy = sortBy.filter(sort =>\n allColumns.find(col => col.id === sort.id)\n )\n\n const sortData = rows => {\n // Use the orderByFn to compose multiple sortBy's together.\n // This will also perform a stable sorting using the row index\n // if needed.\n const sortedData = orderByFn(\n rows,\n availableSortBy.map(sort => {\n // Support custom sorting methods for each column\n const column = allColumns.find(d => d.id === sort.id)\n\n if (!column) {\n throw new Error(\n `React-Table: Could not find a column with id: ${sort.id} while sorting`\n )\n }\n\n const { sortType } = column\n\n // Look up sortBy functions in this order:\n // column function\n // column string lookup on user sortType\n // column string lookup on built-in sortType\n // default function\n // default string lookup on user sortType\n // default string lookup on built-in sortType\n const sortMethod =\n isFunction(sortType) ||\n (userSortTypes || {})[sortType] ||\n sortTypes[sortType]\n\n if (!sortMethod) {\n throw new Error(\n `React-Table: Could not find a valid sortType of '${sortType}' for column '${sort.id}'.`\n )\n }\n\n // Return the correct sortFn.\n // This function should always return in ascending order\n return (a, b) => sortMethod(a, b, sort.id, sort.desc)\n }),\n // Map the directions\n availableSortBy.map(sort => {\n // Detect and use the sortInverted option\n const column = allColumns.find(d => d.id === sort.id)\n\n if (column && column.sortInverted) {\n return sort.desc\n }\n\n return !sort.desc\n })\n )\n\n // If there are sub-rows, sort them\n sortedData.forEach(row => {\n sortedFlatRows.push(row)\n if (!row.subRows || row.subRows.length === 0) {\n return\n }\n row.subRows = sortData(row.subRows)\n })\n\n return sortedData\n }\n\n return [sortData(rows), sortedFlatRows]\n }, [\n manualSortBy,\n sortBy,\n rows,\n flatRows,\n allColumns,\n orderByFn,\n userSortTypes,\n ])\n\n const getAutoResetSortBy = useGetLatest(autoResetSortBy)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetSortBy()) {\n dispatch({ type: actions.resetSortBy })\n }\n }, [manualSortBy ? null : data])\n\n Object.assign(instance, {\n preSortedRows: rows,\n preSortedFlatRows: flatRows,\n sortedRows,\n sortedFlatRows,\n rows: sortedRows,\n flatRows: sortedFlatRows,\n setSortBy,\n toggleSortBy,\n })\n}\n\nexport function defaultOrderByFn(arr, funcs, dirs) {\n return [...arr].sort((rowA, rowB) => {\n for (let i = 0; i < funcs.length; i += 1) {\n const sortFn = funcs[i]\n const desc = dirs[i] === false || dirs[i] === 'desc'\n const sortInt = sortFn(rowA, rowB)\n if (sortInt !== 0) {\n return desc ? -sortInt : sortInt\n }\n }\n return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index\n })\n}\n","import React from 'react'\n\n//\n\nimport {\n actions,\n ensurePluginOrder,\n functionalUpdate,\n useMountedLayoutEffect,\n useGetLatest,\n} from '../publicUtils'\n\nimport { expandRows } from '../utils'\n\nconst pluginName = 'usePagination'\n\n// Actions\nactions.resetPage = 'resetPage'\nactions.gotoPage = 'gotoPage'\nactions.setPageSize = 'setPageSize'\n\nexport const usePagination = hooks => {\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n}\n\nusePagination.pluginName = pluginName\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n pageSize: 10,\n pageIndex: 0,\n ...state,\n }\n }\n\n if (action.type === actions.resetPage) {\n return {\n ...state,\n pageIndex: instance.initialState.pageIndex || 0,\n }\n }\n\n if (action.type === actions.gotoPage) {\n const { pageCount, page } = instance\n const newPageIndex = functionalUpdate(action.pageIndex, state.pageIndex)\n let canNavigate = false\n\n if (newPageIndex > state.pageIndex) {\n // next page\n canNavigate =\n pageCount === -1\n ? page.length >= state.pageSize\n : newPageIndex < pageCount\n } else if (newPageIndex < state.pageIndex) {\n // prev page\n canNavigate = newPageIndex > -1\n }\n\n if (!canNavigate) {\n return state\n }\n\n return {\n ...state,\n pageIndex: newPageIndex,\n }\n }\n\n if (action.type === actions.setPageSize) {\n const { pageSize } = action\n const topRowIndex = state.pageSize * state.pageIndex\n const pageIndex = Math.floor(topRowIndex / pageSize)\n\n return {\n ...state,\n pageIndex,\n pageSize,\n }\n }\n}\n\nfunction useInstance(instance) {\n const {\n rows,\n autoResetPage = true,\n manualExpandedKey = 'expanded',\n plugins,\n pageCount: userPageCount,\n paginateExpandedRows = true,\n expandSubRows = true,\n state: {\n pageSize,\n pageIndex,\n expanded,\n globalFilter,\n filters,\n groupBy,\n sortBy,\n },\n dispatch,\n data,\n manualPagination,\n } = instance\n\n ensurePluginOrder(\n plugins,\n ['useGlobalFilter', 'useFilters', 'useGroupBy', 'useSortBy', 'useExpanded'],\n 'usePagination'\n )\n\n const getAutoResetPage = useGetLatest(autoResetPage)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetPage()) {\n dispatch({ type: actions.resetPage })\n }\n }, [\n dispatch,\n manualPagination ? null : data,\n globalFilter,\n filters,\n groupBy,\n sortBy,\n ])\n\n const pageCount = manualPagination\n ? userPageCount\n : Math.ceil(rows.length / pageSize)\n\n const pageOptions = React.useMemo(\n () =>\n pageCount > 0\n ? [...new Array(pageCount)].fill(null).map((d, i) => i)\n : [],\n [pageCount]\n )\n\n const page = React.useMemo(() => {\n let page\n\n if (manualPagination) {\n page = rows\n } else {\n const pageStart = pageSize * pageIndex\n const pageEnd = pageStart + pageSize\n\n page = rows.slice(pageStart, pageEnd)\n }\n\n if (paginateExpandedRows) {\n return page\n }\n\n return expandRows(page, { manualExpandedKey, expanded, expandSubRows })\n }, [\n expandSubRows,\n expanded,\n manualExpandedKey,\n manualPagination,\n pageIndex,\n pageSize,\n paginateExpandedRows,\n rows,\n ])\n\n const canPreviousPage = pageIndex > 0\n const canNextPage =\n pageCount === -1 ? page.length >= pageSize : pageIndex < pageCount - 1\n\n const gotoPage = React.useCallback(\n pageIndex => {\n dispatch({ type: actions.gotoPage, pageIndex })\n },\n [dispatch]\n )\n\n const previousPage = React.useCallback(() => {\n return gotoPage(old => old - 1)\n }, [gotoPage])\n\n const nextPage = React.useCallback(() => {\n return gotoPage(old => old + 1)\n }, [gotoPage])\n\n const setPageSize = React.useCallback(\n pageSize => {\n dispatch({ type: actions.setPageSize, pageSize })\n },\n [dispatch]\n )\n\n Object.assign(instance, {\n pageOptions,\n pageCount,\n page,\n canPreviousPage,\n canNextPage,\n gotoPage,\n previousPage,\n nextPage,\n setPageSize,\n })\n}\n","/* istanbul ignore file */\n\nimport {\n actions,\n makePropGetter,\n ensurePluginOrder,\n useMountedLayoutEffect,\n useGetLatest,\n} from '../publicUtils'\n\nimport { flattenColumns, getFirstDefined } from '../utils'\n\n// Actions\nactions.resetPivot = 'resetPivot'\nactions.togglePivot = 'togglePivot'\n\nexport const _UNSTABLE_usePivotColumns = hooks => {\n hooks.getPivotToggleProps = [defaultGetPivotToggleProps]\n hooks.stateReducers.push(reducer)\n hooks.useInstanceAfterData.push(useInstanceAfterData)\n hooks.allColumns.push(allColumns)\n hooks.accessValue.push(accessValue)\n hooks.materializedColumns.push(materializedColumns)\n hooks.materializedColumnsDeps.push(materializedColumnsDeps)\n hooks.visibleColumns.push(visibleColumns)\n hooks.visibleColumnsDeps.push(visibleColumnsDeps)\n hooks.useInstance.push(useInstance)\n hooks.prepareRow.push(prepareRow)\n}\n\n_UNSTABLE_usePivotColumns.pluginName = 'usePivotColumns'\n\nconst defaultPivotColumns = []\n\nconst defaultGetPivotToggleProps = (props, { header }) => [\n props,\n {\n onClick: header.canPivot\n ? e => {\n e.persist()\n header.togglePivot()\n }\n : undefined,\n style: {\n cursor: header.canPivot ? 'pointer' : undefined,\n },\n title: 'Toggle Pivot',\n },\n]\n\n// Reducer\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n pivotColumns: defaultPivotColumns,\n ...state,\n }\n }\n\n if (action.type === actions.resetPivot) {\n return {\n ...state,\n pivotColumns: instance.initialState.pivotColumns || defaultPivotColumns,\n }\n }\n\n if (action.type === actions.togglePivot) {\n const { columnId, value: setPivot } = action\n\n const resolvedPivot =\n typeof setPivot !== 'undefined'\n ? setPivot\n : !state.pivotColumns.includes(columnId)\n\n if (resolvedPivot) {\n return {\n ...state,\n pivotColumns: [...state.pivotColumns, columnId],\n }\n }\n\n return {\n ...state,\n pivotColumns: state.pivotColumns.filter(d => d !== columnId),\n }\n }\n}\n\nfunction useInstanceAfterData(instance) {\n instance.allColumns.forEach(column => {\n column.isPivotSource = instance.state.pivotColumns.includes(column.id)\n })\n}\n\nfunction allColumns(columns, { instance }) {\n columns.forEach(column => {\n column.isPivotSource = instance.state.pivotColumns.includes(column.id)\n column.uniqueValues = new Set()\n })\n return columns\n}\n\nfunction accessValue(value, { column }) {\n if (column.uniqueValues && typeof value !== 'undefined') {\n column.uniqueValues.add(value)\n }\n return value\n}\n\nfunction materializedColumns(materialized, { instance }) {\n const { allColumns, state } = instance\n\n if (!state.pivotColumns.length || !state.groupBy || !state.groupBy.length) {\n return materialized\n }\n\n const pivotColumns = state.pivotColumns\n .map(id => allColumns.find(d => d.id === id))\n .filter(Boolean)\n\n const sourceColumns = allColumns.filter(\n d =>\n !d.isPivotSource &&\n !state.groupBy.includes(d.id) &&\n !state.pivotColumns.includes(d.id)\n )\n\n const buildPivotColumns = (depth = 0, parent, pivotFilters = []) => {\n const pivotColumn = pivotColumns[depth]\n\n if (!pivotColumn) {\n return sourceColumns.map(sourceColumn => {\n // TODO: We could offer support here for renesting pivoted\n // columns inside copies of their header groups. For now,\n // that seems like it would be (1) overkill on nesting, considering\n // you already get nesting for every pivot level and (2)\n // really hard. :)\n\n return {\n ...sourceColumn,\n canPivot: false,\n isPivoted: true,\n parent,\n depth: depth,\n id: `${parent ? `${parent.id}.${sourceColumn.id}` : sourceColumn.id}`,\n accessor: (originalRow, i, row) => {\n if (pivotFilters.every(filter => filter(row))) {\n return row.values[sourceColumn.id]\n }\n },\n }\n })\n }\n\n const uniqueValues = Array.from(pivotColumn.uniqueValues).sort()\n\n return uniqueValues.map(uniqueValue => {\n const columnGroup = {\n ...pivotColumn,\n Header:\n pivotColumn.PivotHeader || typeof pivotColumn.header === 'string'\n ? `${pivotColumn.Header}: ${uniqueValue}`\n : uniqueValue,\n isPivotGroup: true,\n parent,\n depth,\n id: parent\n ? `${parent.id}.${pivotColumn.id}.${uniqueValue}`\n : `${pivotColumn.id}.${uniqueValue}`,\n pivotValue: uniqueValue,\n }\n\n columnGroup.columns = buildPivotColumns(depth + 1, columnGroup, [\n ...pivotFilters,\n row => row.values[pivotColumn.id] === uniqueValue,\n ])\n\n return columnGroup\n })\n }\n\n const newMaterialized = flattenColumns(buildPivotColumns())\n\n return [...materialized, ...newMaterialized]\n}\n\nfunction materializedColumnsDeps(\n deps,\n {\n instance: {\n state: { pivotColumns, groupBy },\n },\n }\n) {\n return [...deps, pivotColumns, groupBy]\n}\n\nfunction visibleColumns(visibleColumns, { instance: { state } }) {\n visibleColumns = visibleColumns.filter(d => !d.isPivotSource)\n\n if (state.pivotColumns.length && state.groupBy && state.groupBy.length) {\n visibleColumns = visibleColumns.filter(\n column => column.isGrouped || column.isPivoted\n )\n }\n\n return visibleColumns\n}\n\nfunction visibleColumnsDeps(deps, { instance }) {\n return [...deps, instance.state.pivotColumns, instance.state.groupBy]\n}\n\nfunction useInstance(instance) {\n const {\n columns,\n allColumns,\n flatHeaders,\n // pivotFn = defaultPivotFn,\n // manualPivot,\n getHooks,\n plugins,\n dispatch,\n autoResetPivot = true,\n manaulPivot,\n disablePivot,\n defaultCanPivot,\n } = instance\n\n ensurePluginOrder(plugins, ['useGroupBy'], 'usePivotColumns')\n\n const getInstance = useGetLatest(instance)\n\n allColumns.forEach(column => {\n const {\n accessor,\n defaultPivot: defaultColumnPivot,\n disablePivot: columnDisablePivot,\n } = column\n\n column.canPivot = accessor\n ? getFirstDefined(\n column.canPivot,\n columnDisablePivot === true ? false : undefined,\n disablePivot === true ? false : undefined,\n true\n )\n : getFirstDefined(\n column.canPivot,\n defaultColumnPivot,\n defaultCanPivot,\n false\n )\n\n if (column.canPivot) {\n column.togglePivot = () => instance.togglePivot(column.id)\n }\n\n column.Aggregated = column.Aggregated || column.Cell\n })\n\n const togglePivot = (columnId, value) => {\n dispatch({ type: actions.togglePivot, columnId, value })\n }\n\n flatHeaders.forEach(header => {\n header.getPivotToggleProps = makePropGetter(\n getHooks().getPivotToggleProps,\n {\n instance: getInstance(),\n header,\n }\n )\n })\n\n const getAutoResetPivot = useGetLatest(autoResetPivot)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetPivot()) {\n dispatch({ type: actions.resetPivot })\n }\n }, [dispatch, manaulPivot ? null : columns])\n\n Object.assign(instance, {\n togglePivot,\n })\n}\n\nfunction prepareRow(row) {\n row.allCells.forEach(cell => {\n // Grouped cells are in the pivotColumns and the pivot cell for the row\n cell.isPivoted = cell.column.isPivoted\n })\n}\n","import React from 'react'\n\nimport {\n actions,\n makePropGetter,\n ensurePluginOrder,\n useGetLatest,\n useMountedLayoutEffect,\n} from '../publicUtils'\n\nconst pluginName = 'useRowSelect'\n\n// Actions\nactions.resetSelectedRows = 'resetSelectedRows'\nactions.toggleAllRowsSelected = 'toggleAllRowsSelected'\nactions.toggleRowSelected = 'toggleRowSelected'\nactions.toggleAllPageRowsSelected = 'toggleAllPageRowsSelected'\n\nexport const useRowSelect = hooks => {\n hooks.getToggleRowSelectedProps = [defaultGetToggleRowSelectedProps]\n hooks.getToggleAllRowsSelectedProps = [defaultGetToggleAllRowsSelectedProps]\n hooks.getToggleAllPageRowsSelectedProps = [\n defaultGetToggleAllPageRowsSelectedProps,\n ]\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n hooks.prepareRow.push(prepareRow)\n}\n\nuseRowSelect.pluginName = pluginName\n\nconst defaultGetToggleRowSelectedProps = (props, { instance, row }) => {\n const { manualRowSelectedKey = 'isSelected' } = instance\n let checked = false\n\n if (row.original && row.original[manualRowSelectedKey]) {\n checked = true\n } else {\n checked = row.isSelected\n }\n\n return [\n props,\n {\n onChange: e => {\n row.toggleRowSelected(e.target.checked)\n },\n style: {\n cursor: 'pointer',\n },\n checked,\n title: 'Toggle Row Selected',\n indeterminate: row.isSomeSelected,\n },\n ]\n}\n\nconst defaultGetToggleAllRowsSelectedProps = (props, { instance }) => [\n props,\n {\n onChange: e => {\n instance.toggleAllRowsSelected(e.target.checked)\n },\n style: {\n cursor: 'pointer',\n },\n checked: instance.isAllRowsSelected,\n title: 'Toggle All Rows Selected',\n indeterminate: Boolean(\n !instance.isAllRowsSelected &&\n Object.keys(instance.state.selectedRowIds).length\n ),\n },\n]\n\nconst defaultGetToggleAllPageRowsSelectedProps = (props, { instance }) => [\n props,\n {\n onChange(e) {\n instance.toggleAllPageRowsSelected(e.target.checked)\n },\n style: {\n cursor: 'pointer',\n },\n checked: instance.isAllPageRowsSelected,\n title: 'Toggle All Current Page Rows Selected',\n indeterminate: Boolean(\n !instance.isAllPageRowsSelected &&\n instance.page.some(({ id }) => instance.state.selectedRowIds[id])\n ),\n },\n]\n\n// eslint-disable-next-line max-params\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n selectedRowIds: {},\n ...state,\n }\n }\n\n if (action.type === actions.resetSelectedRows) {\n return {\n ...state,\n selectedRowIds: instance.initialState.selectedRowIds || {},\n }\n }\n\n if (action.type === actions.toggleAllRowsSelected) {\n const { value: setSelected } = action\n const {\n isAllRowsSelected,\n rowsById,\n nonGroupedRowsById = rowsById,\n } = instance\n\n const selectAll =\n typeof setSelected !== 'undefined' ? setSelected : !isAllRowsSelected\n\n // Only remove/add the rows that are visible on the screen\n // Leave all the other rows that are selected alone.\n const selectedRowIds = Object.assign({}, state.selectedRowIds)\n\n if (selectAll) {\n Object.keys(nonGroupedRowsById).forEach(rowId => {\n selectedRowIds[rowId] = true\n })\n } else {\n Object.keys(nonGroupedRowsById).forEach(rowId => {\n delete selectedRowIds[rowId]\n })\n }\n\n return {\n ...state,\n selectedRowIds,\n }\n }\n\n if (action.type === actions.toggleRowSelected) {\n const { id, value: setSelected } = action\n const { rowsById, selectSubRows = true, getSubRows } = instance\n const isSelected = state.selectedRowIds[id]\n const shouldExist =\n typeof setSelected !== 'undefined' ? setSelected : !isSelected\n\n if (isSelected === shouldExist) {\n return state\n }\n\n const newSelectedRowIds = { ...state.selectedRowIds }\n\n const handleRowById = id => {\n const row = rowsById[id]\n\n if (row) {\n if (!row.isGrouped) {\n if (shouldExist) {\n newSelectedRowIds[id] = true\n } else {\n delete newSelectedRowIds[id]\n }\n }\n\n if (selectSubRows && getSubRows(row)) {\n return getSubRows(row).forEach(row => handleRowById(row.id))\n }\n }\n }\n\n handleRowById(id)\n\n return {\n ...state,\n selectedRowIds: newSelectedRowIds,\n }\n }\n\n if (action.type === actions.toggleAllPageRowsSelected) {\n const { value: setSelected } = action\n const {\n page,\n rowsById,\n selectSubRows = true,\n isAllPageRowsSelected,\n getSubRows,\n } = instance\n\n const selectAll =\n typeof setSelected !== 'undefined' ? setSelected : !isAllPageRowsSelected\n\n const newSelectedRowIds = { ...state.selectedRowIds }\n\n const handleRowById = id => {\n const row = rowsById[id]\n\n if (!row.isGrouped) {\n if (selectAll) {\n newSelectedRowIds[id] = true\n } else {\n delete newSelectedRowIds[id]\n }\n }\n\n if (selectSubRows && getSubRows(row)) {\n return getSubRows(row).forEach(row => handleRowById(row.id))\n }\n }\n\n page.forEach(row => handleRowById(row.id))\n\n return {\n ...state,\n selectedRowIds: newSelectedRowIds,\n }\n }\n return state\n}\n\nfunction useInstance(instance) {\n const {\n data,\n rows,\n getHooks,\n plugins,\n rowsById,\n nonGroupedRowsById = rowsById,\n autoResetSelectedRows = true,\n state: { selectedRowIds },\n selectSubRows = true,\n dispatch,\n page,\n getSubRows,\n } = instance\n\n ensurePluginOrder(\n plugins,\n ['useFilters', 'useGroupBy', 'useSortBy', 'useExpanded', 'usePagination'],\n 'useRowSelect'\n )\n\n const selectedFlatRows = React.useMemo(() => {\n const selectedFlatRows = []\n\n rows.forEach(row => {\n const isSelected = selectSubRows\n ? getRowIsSelected(row, selectedRowIds, getSubRows)\n : !!selectedRowIds[row.id]\n row.isSelected = !!isSelected\n row.isSomeSelected = isSelected === null\n\n if (isSelected) {\n selectedFlatRows.push(row)\n }\n })\n\n return selectedFlatRows\n }, [rows, selectSubRows, selectedRowIds, getSubRows])\n\n let isAllRowsSelected = Boolean(\n Object.keys(nonGroupedRowsById).length && Object.keys(selectedRowIds).length\n )\n\n let isAllPageRowsSelected = isAllRowsSelected\n\n if (isAllRowsSelected) {\n if (Object.keys(nonGroupedRowsById).some(id => !selectedRowIds[id])) {\n isAllRowsSelected = false\n }\n }\n\n if (!isAllRowsSelected) {\n if (page && page.length && page.some(({ id }) => !selectedRowIds[id])) {\n isAllPageRowsSelected = false\n }\n }\n\n const getAutoResetSelectedRows = useGetLatest(autoResetSelectedRows)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetSelectedRows()) {\n dispatch({ type: actions.resetSelectedRows })\n }\n }, [dispatch, data])\n\n const toggleAllRowsSelected = React.useCallback(\n value => dispatch({ type: actions.toggleAllRowsSelected, value }),\n [dispatch]\n )\n\n const toggleAllPageRowsSelected = React.useCallback(\n value => dispatch({ type: actions.toggleAllPageRowsSelected, value }),\n [dispatch]\n )\n\n const toggleRowSelected = React.useCallback(\n (id, value) => dispatch({ type: actions.toggleRowSelected, id, value }),\n [dispatch]\n )\n\n const getInstance = useGetLatest(instance)\n\n const getToggleAllRowsSelectedProps = makePropGetter(\n getHooks().getToggleAllRowsSelectedProps,\n { instance: getInstance() }\n )\n\n const getToggleAllPageRowsSelectedProps = makePropGetter(\n getHooks().getToggleAllPageRowsSelectedProps,\n { instance: getInstance() }\n )\n\n Object.assign(instance, {\n selectedFlatRows,\n isAllRowsSelected,\n isAllPageRowsSelected,\n toggleRowSelected,\n toggleAllRowsSelected,\n getToggleAllRowsSelectedProps,\n getToggleAllPageRowsSelectedProps,\n toggleAllPageRowsSelected,\n })\n}\n\nfunction prepareRow(row, { instance }) {\n row.toggleRowSelected = set => instance.toggleRowSelected(row.id, set)\n\n row.getToggleRowSelectedProps = makePropGetter(\n instance.getHooks().getToggleRowSelectedProps,\n { instance: instance, row }\n )\n}\n\nfunction getRowIsSelected(row, selectedRowIds, getSubRows) {\n if (selectedRowIds[row.id]) {\n return true\n }\n\n const subRows = getSubRows(row)\n\n if (subRows && subRows.length) {\n let allChildrenSelected = true\n let someSelected = false\n\n subRows.forEach(subRow => {\n // Bail out early if we know both of these\n if (someSelected && !allChildrenSelected) {\n return\n }\n\n if (getRowIsSelected(subRow, selectedRowIds, getSubRows)) {\n someSelected = true\n } else {\n allChildrenSelected = false\n }\n })\n return allChildrenSelected ? true : someSelected ? null : false\n }\n\n return false\n}\n","import React from 'react'\n\nimport {\n actions,\n functionalUpdate,\n useMountedLayoutEffect,\n useGetLatest,\n} from '../publicUtils'\n\nconst defaultInitialRowStateAccessor = row => ({})\nconst defaultInitialCellStateAccessor = cell => ({})\n\n// Actions\nactions.setRowState = 'setRowState'\nactions.setCellState = 'setCellState'\nactions.resetRowState = 'resetRowState'\n\nexport const useRowState = hooks => {\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n hooks.prepareRow.push(prepareRow)\n}\n\nuseRowState.pluginName = 'useRowState'\n\nfunction reducer(state, action, previousState, instance) {\n const {\n initialRowStateAccessor = defaultInitialRowStateAccessor,\n initialCellStateAccessor = defaultInitialCellStateAccessor,\n rowsById,\n } = instance\n\n if (action.type === actions.init) {\n return {\n rowState: {},\n ...state,\n }\n }\n\n if (action.type === actions.resetRowState) {\n return {\n ...state,\n rowState: instance.initialState.rowState || {},\n }\n }\n\n if (action.type === actions.setRowState) {\n const { rowId, value } = action\n\n const oldRowState =\n typeof state.rowState[rowId] !== 'undefined'\n ? state.rowState[rowId]\n : initialRowStateAccessor(rowsById[rowId])\n\n return {\n ...state,\n rowState: {\n ...state.rowState,\n [rowId]: functionalUpdate(value, oldRowState),\n },\n }\n }\n\n if (action.type === actions.setCellState) {\n const { rowId, columnId, value } = action\n\n const oldRowState =\n typeof state.rowState[rowId] !== 'undefined'\n ? state.rowState[rowId]\n : initialRowStateAccessor(rowsById[rowId])\n\n const oldCellState =\n typeof oldRowState?.cellState?.[columnId] !== 'undefined'\n ? oldRowState.cellState[columnId]\n : initialCellStateAccessor(\n rowsById[rowId]?.cells?.find(cell => cell.column.id === columnId)\n )\n\n return {\n ...state,\n rowState: {\n ...state.rowState,\n [rowId]: {\n ...oldRowState,\n cellState: {\n ...(oldRowState.cellState || {}),\n [columnId]: functionalUpdate(value, oldCellState),\n },\n },\n },\n }\n }\n}\n\nfunction useInstance(instance) {\n const { autoResetRowState = true, data, dispatch } = instance\n\n const setRowState = React.useCallback(\n (rowId, value) =>\n dispatch({\n type: actions.setRowState,\n rowId,\n value,\n }),\n [dispatch]\n )\n\n const setCellState = React.useCallback(\n (rowId, columnId, value) =>\n dispatch({\n type: actions.setCellState,\n rowId,\n columnId,\n value,\n }),\n [dispatch]\n )\n\n const getAutoResetRowState = useGetLatest(autoResetRowState)\n\n useMountedLayoutEffect(() => {\n if (getAutoResetRowState()) {\n dispatch({ type: actions.resetRowState })\n }\n }, [data])\n\n Object.assign(instance, {\n setRowState,\n setCellState,\n })\n}\n\nfunction prepareRow(row, { instance }) {\n const {\n initialRowStateAccessor = defaultInitialRowStateAccessor,\n initialCellStateAccessor = defaultInitialCellStateAccessor,\n state: { rowState },\n } = instance\n\n if (row) {\n row.state =\n typeof rowState[row.id] !== 'undefined'\n ? rowState[row.id]\n : initialRowStateAccessor(row)\n\n row.setState = updater => {\n return instance.setRowState(row.id, updater)\n }\n\n row.cells.forEach(cell => {\n if (!row.state.cellState) {\n row.state.cellState = {}\n }\n\n cell.state =\n typeof row.state.cellState[cell.column.id] !== 'undefined'\n ? row.state.cellState[cell.column.id]\n : initialCellStateAccessor(cell)\n\n cell.setState = updater => {\n return instance.setCellState(row.id, cell.column.id, updater)\n }\n })\n }\n}\n","import React from 'react'\n\nimport { functionalUpdate, actions } from '../publicUtils'\n\n// Actions\nactions.resetColumnOrder = 'resetColumnOrder'\nactions.setColumnOrder = 'setColumnOrder'\n\nexport const useColumnOrder = hooks => {\n hooks.stateReducers.push(reducer)\n hooks.visibleColumnsDeps.push((deps, { instance }) => {\n return [...deps, instance.state.columnOrder]\n })\n hooks.visibleColumns.push(visibleColumns)\n hooks.useInstance.push(useInstance)\n}\n\nuseColumnOrder.pluginName = 'useColumnOrder'\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n columnOrder: [],\n ...state,\n }\n }\n\n if (action.type === actions.resetColumnOrder) {\n return {\n ...state,\n columnOrder: instance.initialState.columnOrder || [],\n }\n }\n\n if (action.type === actions.setColumnOrder) {\n return {\n ...state,\n columnOrder: functionalUpdate(action.columnOrder, state.columnOrder),\n }\n }\n}\n\nfunction visibleColumns(\n columns,\n {\n instance: {\n state: { columnOrder },\n },\n }\n) {\n // If there is no order, return the normal columns\n if (!columnOrder || !columnOrder.length) {\n return columns\n }\n\n const columnOrderCopy = [...columnOrder]\n\n // If there is an order, make a copy of the columns\n const columnsCopy = [...columns]\n\n // And make a new ordered array of the columns\n const columnsInOrder = []\n\n // Loop over the columns and place them in order into the new array\n while (columnsCopy.length && columnOrderCopy.length) {\n const targetColumnId = columnOrderCopy.shift()\n const foundIndex = columnsCopy.findIndex(d => d.id === targetColumnId)\n if (foundIndex > -1) {\n columnsInOrder.push(columnsCopy.splice(foundIndex, 1)[0])\n }\n }\n\n // If there are any columns left, add them to the end\n return [...columnsInOrder, ...columnsCopy]\n}\n\nfunction useInstance(instance) {\n const { dispatch } = instance\n\n instance.setColumnOrder = React.useCallback(\n columnOrder => {\n return dispatch({ type: actions.setColumnOrder, columnOrder })\n },\n [dispatch]\n )\n}\n","import React from 'react'\n\nimport {\n actions,\n defaultColumn,\n makePropGetter,\n useGetLatest,\n ensurePluginOrder,\n useMountedLayoutEffect,\n} from '../publicUtils'\n\nimport { getFirstDefined, passiveEventSupported } from '../utils'\n\n// Default Column\ndefaultColumn.canResize = true\n\n// Actions\nactions.columnStartResizing = 'columnStartResizing'\nactions.columnResizing = 'columnResizing'\nactions.columnDoneResizing = 'columnDoneResizing'\nactions.resetResize = 'resetResize'\n\nexport const useResizeColumns = hooks => {\n hooks.getResizerProps = [defaultGetResizerProps]\n hooks.getHeaderProps.push({\n style: {\n position: 'relative',\n },\n })\n hooks.stateReducers.push(reducer)\n hooks.useInstance.push(useInstance)\n hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)\n}\n\nconst defaultGetResizerProps = (props, { instance, header }) => {\n const { dispatch } = instance\n\n const onResizeStart = (e, header) => {\n let isTouchEvent = false\n if (e.type === 'touchstart') {\n // lets not respond to multiple touches (e.g. 2 or 3 fingers)\n if (e.touches && e.touches.length > 1) {\n return\n }\n isTouchEvent = true\n }\n const headersToResize = getLeafHeaders(header)\n const headerIdWidths = headersToResize.map(d => [d.id, d.totalWidth])\n\n const clientX = isTouchEvent ? Math.round(e.touches[0].clientX) : e.clientX\n\n let raf\n let mostRecentClientX\n\n const dispatchEnd = () => {\n window.cancelAnimationFrame(raf)\n raf = null\n dispatch({ type: actions.columnDoneResizing })\n }\n const dispatchMove = () => {\n window.cancelAnimationFrame(raf)\n raf = null\n dispatch({ type: actions.columnResizing, clientX: mostRecentClientX })\n }\n\n const scheduleDispatchMoveOnNextAnimationFrame = clientXPos => {\n mostRecentClientX = clientXPos\n if (!raf) {\n raf = window.requestAnimationFrame(dispatchMove)\n }\n }\n\n const handlersAndEvents = {\n mouse: {\n moveEvent: 'mousemove',\n moveHandler: e => scheduleDispatchMoveOnNextAnimationFrame(e.clientX),\n upEvent: 'mouseup',\n upHandler: e => {\n document.removeEventListener(\n 'mousemove',\n handlersAndEvents.mouse.moveHandler\n )\n document.removeEventListener(\n 'mouseup',\n handlersAndEvents.mouse.upHandler\n )\n dispatchEnd()\n },\n },\n touch: {\n moveEvent: 'touchmove',\n moveHandler: e => {\n if (e.cancelable) {\n e.preventDefault()\n e.stopPropagation()\n }\n scheduleDispatchMoveOnNextAnimationFrame(e.touches[0].clientX)\n return false\n },\n upEvent: 'touchend',\n upHandler: e => {\n document.removeEventListener(\n handlersAndEvents.touch.moveEvent,\n handlersAndEvents.touch.moveHandler\n )\n document.removeEventListener(\n handlersAndEvents.touch.upEvent,\n handlersAndEvents.touch.moveHandler\n )\n dispatchEnd()\n },\n },\n }\n\n const events = isTouchEvent\n ? handlersAndEvents.touch\n : handlersAndEvents.mouse\n const passiveIfSupported = passiveEventSupported()\n ? { passive: false }\n : false\n document.addEventListener(\n events.moveEvent,\n events.moveHandler,\n passiveIfSupported\n )\n document.addEventListener(\n events.upEvent,\n events.upHandler,\n passiveIfSupported\n )\n\n dispatch({\n type: actions.columnStartResizing,\n columnId: header.id,\n columnWidth: header.totalWidth,\n headerIdWidths,\n clientX,\n })\n }\n\n return [\n props,\n {\n onMouseDown: e => e.persist() || onResizeStart(e, header),\n onTouchStart: e => e.persist() || onResizeStart(e, header),\n style: {\n cursor: 'col-resize',\n },\n draggable: false,\n role: 'separator',\n },\n ]\n}\n\nuseResizeColumns.pluginName = 'useResizeColumns'\n\nfunction reducer(state, action) {\n if (action.type === actions.init) {\n return {\n columnResizing: {\n columnWidths: {},\n },\n ...state,\n }\n }\n\n if (action.type === actions.resetResize) {\n return {\n ...state,\n columnResizing: {\n columnWidths: {},\n },\n }\n }\n\n if (action.type === actions.columnStartResizing) {\n const { clientX, columnId, columnWidth, headerIdWidths } = action\n\n return {\n ...state,\n columnResizing: {\n ...state.columnResizing,\n startX: clientX,\n headerIdWidths,\n columnWidth,\n isResizingColumn: columnId,\n },\n }\n }\n\n if (action.type === actions.columnResizing) {\n const { clientX } = action\n const { startX, columnWidth, headerIdWidths = [] } = state.columnResizing\n\n const deltaX = clientX - startX\n const percentageDeltaX = deltaX / columnWidth\n\n const newColumnWidths = {}\n\n headerIdWidths.forEach(([headerId, headerWidth]) => {\n newColumnWidths[headerId] = Math.max(\n headerWidth + headerWidth * percentageDeltaX,\n 0\n )\n })\n\n return {\n ...state,\n columnResizing: {\n ...state.columnResizing,\n columnWidths: {\n ...state.columnResizing.columnWidths,\n ...newColumnWidths,\n },\n },\n }\n }\n\n if (action.type === actions.columnDoneResizing) {\n return {\n ...state,\n columnResizing: {\n ...state.columnResizing,\n startX: null,\n isResizingColumn: null,\n },\n }\n }\n}\n\nconst useInstanceBeforeDimensions = instance => {\n const {\n flatHeaders,\n disableResizing,\n getHooks,\n state: { columnResizing },\n } = instance\n\n const getInstance = useGetLatest(instance)\n\n flatHeaders.forEach(header => {\n const canResize = getFirstDefined(\n header.disableResizing === true ? false : undefined,\n disableResizing === true ? false : undefined,\n true\n )\n\n header.canResize = canResize\n header.width =\n columnResizing.columnWidths[header.id] ||\n header.originalWidth ||\n header.width\n header.isResizing = columnResizing.isResizingColumn === header.id\n\n if (canResize) {\n header.getResizerProps = makePropGetter(getHooks().getResizerProps, {\n instance: getInstance(),\n header,\n })\n }\n })\n}\n\nfunction useInstance(instance) {\n const { plugins, dispatch, autoResetResize = true, columns } = instance\n\n ensurePluginOrder(plugins, ['useAbsoluteLayout'], 'useResizeColumns')\n\n const getAutoResetResize = useGetLatest(autoResetResize)\n useMountedLayoutEffect(() => {\n if (getAutoResetResize()) {\n dispatch({ type: actions.resetResize })\n }\n }, [columns])\n\n const resetResizing = React.useCallback(\n () => dispatch({ type: actions.resetResize }),\n [dispatch]\n )\n\n Object.assign(instance, {\n resetResizing,\n })\n}\n\nfunction getLeafHeaders(header) {\n const leafHeaders = []\n const recurseHeader = header => {\n if (header.columns && header.columns.length) {\n header.columns.map(recurseHeader)\n }\n leafHeaders.push(header)\n }\n recurseHeader(header)\n return leafHeaders\n}\n","const cellStyles = {\n position: 'absolute',\n top: 0,\n}\n\nexport const useAbsoluteLayout = hooks => {\n hooks.getTableBodyProps.push(getRowStyles)\n hooks.getRowProps.push(getRowStyles)\n hooks.getHeaderGroupProps.push(getRowStyles)\n hooks.getFooterGroupProps.push(getRowStyles)\n\n hooks.getHeaderProps.push((props, { column }) => [\n props,\n {\n style: {\n ...cellStyles,\n left: `${column.totalLeft}px`,\n width: `${column.totalWidth}px`,\n },\n },\n ])\n\n hooks.getCellProps.push((props, { cell }) => [\n props,\n {\n style: {\n ...cellStyles,\n left: `${cell.column.totalLeft}px`,\n width: `${cell.column.totalWidth}px`,\n },\n },\n ])\n\n hooks.getFooterProps.push((props, { column }) => [\n props,\n {\n style: {\n ...cellStyles,\n left: `${column.totalLeft}px`,\n width: `${column.totalWidth}px`,\n },\n },\n ])\n}\n\nuseAbsoluteLayout.pluginName = 'useAbsoluteLayout'\n\nconst getRowStyles = (props, { instance }) => [\n props,\n {\n style: {\n position: 'relative',\n width: `${instance.totalColumnsWidth}px`,\n },\n },\n]\n","const cellStyles = {\n display: 'inline-block',\n boxSizing: 'border-box',\n}\n\nconst getRowStyles = (props, { instance }) => [\n props,\n {\n style: {\n display: 'flex',\n width: `${instance.totalColumnsWidth}px`,\n },\n },\n]\n\nexport const useBlockLayout = hooks => {\n hooks.getRowProps.push(getRowStyles)\n hooks.getHeaderGroupProps.push(getRowStyles)\n hooks.getFooterGroupProps.push(getRowStyles)\n\n hooks.getHeaderProps.push((props, { column }) => [\n props,\n {\n style: {\n ...cellStyles,\n width: `${column.totalWidth}px`,\n },\n },\n ])\n\n hooks.getCellProps.push((props, { cell }) => [\n props,\n {\n style: {\n ...cellStyles,\n width: `${cell.column.totalWidth}px`,\n },\n },\n ])\n\n hooks.getFooterProps.push((props, { column }) => [\n props,\n {\n style: {\n ...cellStyles,\n width: `${column.totalWidth}px`,\n },\n },\n ])\n}\n\nuseBlockLayout.pluginName = 'useBlockLayout'\n","export function useFlexLayout(hooks) {\n hooks.getTableProps.push(getTableProps)\n hooks.getRowProps.push(getRowStyles)\n hooks.getHeaderGroupProps.push(getRowStyles)\n hooks.getFooterGroupProps.push(getRowStyles)\n hooks.getHeaderProps.push(getHeaderProps)\n hooks.getCellProps.push(getCellProps)\n hooks.getFooterProps.push(getFooterProps)\n}\n\nuseFlexLayout.pluginName = 'useFlexLayout'\n\nconst getTableProps = (props, { instance }) => [\n props,\n {\n style: {\n minWidth: `${instance.totalColumnsMinWidth}px`,\n },\n },\n]\n\nconst getRowStyles = (props, { instance }) => [\n props,\n {\n style: {\n display: 'flex',\n flex: '1 0 auto',\n minWidth: `${instance.totalColumnsMinWidth}px`,\n },\n },\n]\n\nconst getHeaderProps = (props, { column }) => [\n props,\n {\n style: {\n boxSizing: 'border-box',\n flex: column.totalFlexWidth\n ? `${column.totalFlexWidth} 0 auto`\n : undefined,\n minWidth: `${column.totalMinWidth}px`,\n width: `${column.totalWidth}px`,\n },\n },\n]\n\nconst getCellProps = (props, { cell }) => [\n props,\n {\n style: {\n boxSizing: 'border-box',\n flex: `${cell.column.totalFlexWidth} 0 auto`,\n minWidth: `${cell.column.totalMinWidth}px`,\n width: `${cell.column.totalWidth}px`,\n },\n },\n]\n\nconst getFooterProps = (props, { column }) => [\n props,\n {\n style: {\n boxSizing: 'border-box',\n flex: column.totalFlexWidth\n ? `${column.totalFlexWidth} 0 auto`\n : undefined,\n minWidth: `${column.totalMinWidth}px`,\n width: `${column.totalWidth}px`,\n },\n },\n]\n","import { actions } from '../publicUtils'\n\n// Actions\nactions.columnStartResizing = 'columnStartResizing'\nactions.columnResizing = 'columnResizing'\nactions.columnDoneResizing = 'columnDoneResizing'\nactions.resetResize = 'resetResize'\n\nexport function useGridLayout(hooks) {\n hooks.stateReducers.push(reducer)\n hooks.getTableProps.push(getTableProps)\n hooks.getHeaderProps.push(getHeaderProps)\n hooks.getRowProps.push(getRowProps)\n}\n\nuseGridLayout.pluginName = 'useGridLayout'\n\nconst getTableProps = (props, { instance }) => {\n const gridTemplateColumns = instance.visibleColumns.map(column => {\n if (instance.state.gridLayout.columnWidths[column.id])\n return `${instance.state.gridLayout.columnWidths[column.id]}px`\n // When resizing, lock the width of all unset columns\n // instead of using user-provided width or defaultColumn width,\n // which could potentially be 'auto' or 'fr' units that don't scale linearly\n if (instance.state.columnResizing?.isResizingColumn)\n return `${instance.state.gridLayout.startWidths[column.id]}px`\n if (typeof column.width === 'number') return `${column.width}px`\n return column.width\n })\n return [\n props,\n {\n style: {\n display: `grid`,\n gridTemplateColumns: gridTemplateColumns.join(` `),\n },\n },\n ]\n}\n\nconst getHeaderProps = (props, { column }) => [\n props,\n {\n id: `header-cell-${column.id}`,\n style: {\n position: `sticky`, //enables a scroll wrapper to be placed around the table and have sticky headers\n gridColumn: `span ${column.totalVisibleHeaderCount}`,\n },\n },\n]\n\nconst getRowProps = (props, { row }) => {\n if (row.isExpanded) {\n return [\n props,\n {\n style: {\n gridColumn: `1 / ${row.cells.length + 1}`,\n },\n },\n ]\n }\n return [props, {}]\n}\n\nfunction reducer(state, action, previousState, instance) {\n if (action.type === actions.init) {\n return {\n gridLayout: {\n columnWidths: {},\n },\n ...state,\n }\n }\n\n if (action.type === actions.resetResize) {\n return {\n ...state,\n gridLayout: {\n columnWidths: {},\n },\n }\n }\n\n if (action.type === actions.columnStartResizing) {\n const { columnId, headerIdWidths } = action\n const columnWidth = getElementWidth(columnId)\n\n if (columnWidth !== undefined) {\n const startWidths = instance.visibleColumns.reduce(\n (acc, column) => ({\n ...acc,\n [column.id]: getElementWidth(column.id),\n }),\n {}\n )\n const minWidths = instance.visibleColumns.reduce(\n (acc, column) => ({\n ...acc,\n [column.id]: column.minWidth,\n }),\n {}\n )\n const maxWidths = instance.visibleColumns.reduce(\n (acc, column) => ({\n ...acc,\n [column.id]: column.maxWidth,\n }),\n {}\n )\n\n const headerIdGridWidths = headerIdWidths.map(([headerId]) => [\n headerId,\n getElementWidth(headerId),\n ])\n\n return {\n ...state,\n gridLayout: {\n ...state.gridLayout,\n startWidths,\n minWidths,\n maxWidths,\n headerIdGridWidths,\n columnWidth,\n },\n }\n } else {\n return state\n }\n }\n\n if (action.type === actions.columnResizing) {\n const { clientX } = action\n const { startX } = state.columnResizing\n const {\n columnWidth,\n minWidths,\n maxWidths,\n headerIdGridWidths = [],\n } = state.gridLayout\n\n const deltaX = clientX - startX\n const percentageDeltaX = deltaX / columnWidth\n\n const newColumnWidths = {}\n\n headerIdGridWidths.forEach(([headerId, headerWidth]) => {\n newColumnWidths[headerId] = Math.min(\n Math.max(\n minWidths[headerId],\n headerWidth + headerWidth * percentageDeltaX\n ),\n maxWidths[headerId]\n )\n })\n\n return {\n ...state,\n gridLayout: {\n ...state.gridLayout,\n columnWidths: {\n ...state.gridLayout.columnWidths,\n ...newColumnWidths,\n },\n },\n }\n }\n\n if (action.type === actions.columnDoneResizing) {\n return {\n ...state,\n gridLayout: {\n ...state.gridLayout,\n startWidths: {},\n minWidths: {},\n maxWidths: {},\n },\n }\n }\n}\n\nfunction getElementWidth(columnId) {\n const width = document.getElementById(`header-cell-${columnId}`)?.offsetWidth\n\n if (width !== undefined) {\n return width\n }\n}\n","if (process.env.NODE_ENV === 'production') {\n module.exports = require('./dist/react-table.production.min.js')\n} else {\n module.exports = require('./dist/react-table.development.js')\n}\n","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","export function merge(...sets:Array):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}","import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n","import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n","'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see \n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n","/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author Gary Court\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = ((\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;","import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n","'use strict';\n\n/**\n* FUNCTION: isArray( value )\n*\tValidates if a value is an array.\n*\n* @param {*} value - value to be validated\n* @returns {Boolean} boolean indicating whether value is an array\n*/\nfunction isArray( value ) {\n\treturn Object.prototype.toString.call( value ) === '[object Array]';\n} // end FUNCTION isArray()\n\n// EXPORTS //\n\nmodule.exports = Array.isArray || isArray;\n","/**\n*\n*\tVALIDATE: function\n*\n*\n*\tDESCRIPTION:\n*\t\t- Validates if a value is a function.\n*\n*\n*\tNOTES:\n*\t\t[1]\n*\n*\n*\tTODO:\n*\t\t[1]\n*\n*\n*\tLICENSE:\n*\t\tMIT\n*\n*\tCopyright (c) 2014. Athan Reines.\n*\n*\n*\tAUTHOR:\n*\t\tAthan Reines. kgryte@gmail.com. 2014.\n*\n*/\n\n'use strict';\n\n/**\n* FUNCTION: isFunction( value )\n*\tValidates if a value is a function.\n*\n* @param {*} value - value to be validated\n* @returns {Boolean} boolean indicating whether value is a function\n*/\nfunction isFunction( value ) {\n\treturn ( typeof value === 'function' );\n} // end FUNCTION isFunction()\n\n\n// EXPORTS //\n\nmodule.exports = isFunction;\n","/**\n*\n*\tVALIDATE: integer-array\n*\n*\n*\tDESCRIPTION:\n*\t\t- Validates if a value is an integer array.\n*\n*\n*\tNOTES:\n*\t\t[1]\n*\n*\n*\tTODO:\n*\t\t[1]\n*\n*\n*\tLICENSE:\n*\t\tMIT\n*\n*\tCopyright (c) 2015. Athan Reines.\n*\n*\n*\tAUTHOR:\n*\t\tAthan Reines. kgryte@gmail.com. 2015.\n*\n*/\n\n'use strict';\n\n// MODULES //\n\nvar isArray = require( 'validate.io-array' ),\n\tisInteger = require( 'validate.io-integer' );\n\n\n// IS INTEGER ARRAY //\n\n/**\n* FUNCTION: isIntegerArray( value )\n*\tValidates if a value is an integer array.\n*\n* @param {*} value - value to be validated\n* @returns {Boolean} boolean indicating if a value is an integer array\n*/\nfunction isIntegerArray( value ) {\n\tvar len;\n\tif ( !isArray( value ) ) {\n\t\treturn false;\n\t}\n\tlen = value.length;\n\tif ( !len ) {\n\t\treturn false;\n\t}\n\tfor ( var i = 0; i < len; i++ ) {\n\t\tif ( !isInteger( value[i] ) ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n} // end FUNCTION isIntegerArray()\n\n\n// EXPORTS //\n\nmodule.exports = isIntegerArray;\n","/**\n*\n*\tVALIDATE: integer\n*\n*\n*\tDESCRIPTION:\n*\t\t- Validates if a value is an integer.\n*\n*\n*\tNOTES:\n*\t\t[1]\n*\n*\n*\tTODO:\n*\t\t[1]\n*\n*\n*\tLICENSE:\n*\t\tMIT\n*\n*\tCopyright (c) 2014. Athan Reines.\n*\n*\n*\tAUTHOR:\n*\t\tAthan Reines. kgryte@gmail.com. 2014.\n*\n*/\n\n'use strict';\n\n// MODULES //\n\nvar isNumber = require( 'validate.io-number' );\n\n\n// ISINTEGER //\n\n/**\n* FUNCTION: isInteger( value )\n*\tValidates if a value is an integer.\n*\n* @param {Number} value - value to be validated\n* @returns {Boolean} boolean indicating whether value is an integer\n*/\nfunction isInteger( value ) {\n\treturn isNumber( value ) && value%1 === 0;\n} // end FUNCTION isInteger()\n\n\n// EXPORTS //\n\nmodule.exports = isInteger;\n","/**\n*\n*\tVALIDATE: number\n*\n*\n*\tDESCRIPTION:\n*\t\t- Validates if a value is a number.\n*\n*\n*\tNOTES:\n*\t\t[1]\n*\n*\n*\tTODO:\n*\t\t[1]\n*\n*\n*\tLICENSE:\n*\t\tMIT\n*\n*\tCopyright (c) 2014. Athan Reines.\n*\n*\n*\tAUTHOR:\n*\t\tAthan Reines. kgryte@gmail.com. 2014.\n*\n*/\n\n'use strict';\n\n/**\n* FUNCTION: isNumber( value )\n*\tValidates if a value is a number.\n*\n* @param {*} value - value to be validated\n* @returns {Boolean} boolean indicating whether value is a number\n*/\nfunction isNumber( value ) {\n\treturn ( typeof value === 'number' || Object.prototype.toString.call( value ) === '[object Number]' ) && value.valueOf() === value.valueOf();\n} // end FUNCTION isNumber()\n\n\n// EXPORTS //\n\nmodule.exports = isNumber;\n","function _extends() {\n module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n return _extends.apply(this, arguments);\n}\nmodule.exports = _extends, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\nmodule.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\nmodule.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return e;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var t,\n e = {},\n r = Object.prototype,\n n = r.hasOwnProperty,\n o = Object.defineProperty || function (t, e, r) {\n t[e] = r.value;\n },\n i = \"function\" == typeof Symbol ? Symbol : {},\n a = i.iterator || \"@@iterator\",\n c = i.asyncIterator || \"@@asyncIterator\",\n u = i.toStringTag || \"@@toStringTag\";\n function define(t, e, r) {\n return Object.defineProperty(t, e, {\n value: r,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), t[e];\n }\n try {\n define({}, \"\");\n } catch (t) {\n define = function define(t, e, r) {\n return t[e] = r;\n };\n }\n function wrap(t, e, r, n) {\n var i = e && e.prototype instanceof Generator ? e : Generator,\n a = Object.create(i.prototype),\n c = new Context(n || []);\n return o(a, \"_invoke\", {\n value: makeInvokeMethod(t, r, c)\n }), a;\n }\n function tryCatch(t, e, r) {\n try {\n return {\n type: \"normal\",\n arg: t.call(e, r)\n };\n } catch (t) {\n return {\n type: \"throw\",\n arg: t\n };\n }\n }\n e.wrap = wrap;\n var h = \"suspendedStart\",\n l = \"suspendedYield\",\n f = \"executing\",\n s = \"completed\",\n y = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var p = {};\n define(p, a, function () {\n return this;\n });\n var d = Object.getPrototypeOf,\n v = d && d(d(values([])));\n v && v !== r && n.call(v, a) && (p = v);\n var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);\n function defineIteratorMethods(t) {\n [\"next\", \"throw\", \"return\"].forEach(function (e) {\n define(t, e, function (t) {\n return this._invoke(e, t);\n });\n });\n }\n function AsyncIterator(t, e) {\n function invoke(r, o, i, a) {\n var c = tryCatch(t[r], t, o);\n if (\"throw\" !== c.type) {\n var u = c.arg,\n h = u.value;\n return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) {\n invoke(\"next\", t, i, a);\n }, function (t) {\n invoke(\"throw\", t, i, a);\n }) : e.resolve(h).then(function (t) {\n u.value = t, i(u);\n }, function (t) {\n return invoke(\"throw\", t, i, a);\n });\n }\n a(c.arg);\n }\n var r;\n o(this, \"_invoke\", {\n value: function value(t, n) {\n function callInvokeWithMethodAndArg() {\n return new e(function (e, r) {\n invoke(t, n, e, r);\n });\n }\n return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(e, r, n) {\n var o = h;\n return function (i, a) {\n if (o === f) throw new Error(\"Generator is already running\");\n if (o === s) {\n if (\"throw\" === i) throw a;\n return {\n value: t,\n done: !0\n };\n }\n for (n.method = i, n.arg = a;;) {\n var c = n.delegate;\n if (c) {\n var u = maybeInvokeDelegate(c, n);\n if (u) {\n if (u === y) continue;\n return u;\n }\n }\n if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) {\n if (o === h) throw o = s, n.arg;\n n.dispatchException(n.arg);\n } else \"return\" === n.method && n.abrupt(\"return\", n.arg);\n o = f;\n var p = tryCatch(e, r, n);\n if (\"normal\" === p.type) {\n if (o = n.done ? s : l, p.arg === y) continue;\n return {\n value: p.arg,\n done: n.done\n };\n }\n \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg);\n }\n };\n }\n function maybeInvokeDelegate(e, r) {\n var n = r.method,\n o = e.iterator[n];\n if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y;\n var i = tryCatch(o, e.iterator, r.arg);\n if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y;\n var a = i.arg;\n return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y);\n }\n function pushTryEntry(t) {\n var e = {\n tryLoc: t[0]\n };\n 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);\n }\n function resetTryEntry(t) {\n var e = t.completion || {};\n e.type = \"normal\", delete e.arg, t.completion = e;\n }\n function Context(t) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], t.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(e) {\n if (e || \"\" === e) {\n var r = e[a];\n if (r) return r.call(e);\n if (\"function\" == typeof e.next) return e;\n if (!isNaN(e.length)) {\n var o = -1,\n i = function next() {\n for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;\n return next.value = t, next.done = !0, next;\n };\n return i.next = i;\n }\n }\n throw new TypeError(_typeof(e) + \" is not iterable\");\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), o(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) {\n var e = \"function\" == typeof t && t.constructor;\n return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name));\n }, e.mark = function (t) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t;\n }, e.awrap = function (t) {\n return {\n __await: t\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {\n return this;\n }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {\n void 0 === i && (i = Promise);\n var a = new AsyncIterator(wrap(t, r, n, o), i);\n return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {\n return t.done ? t.value : a.next();\n });\n }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () {\n return this;\n }), define(g, \"toString\", function () {\n return \"[object Generator]\";\n }), e.keys = function (t) {\n var e = Object(t),\n r = [];\n for (var n in e) r.push(n);\n return r.reverse(), function next() {\n for (; r.length;) {\n var t = r.pop();\n if (t in e) return next.value = t, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, e.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(e) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);\n },\n stop: function stop() {\n this.done = !0;\n var t = this.tryEntries[0].completion;\n if (\"throw\" === t.type) throw t.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(e) {\n if (this.done) throw e;\n var r = this;\n function handle(n, o) {\n return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o;\n }\n for (var o = this.tryEntries.length - 1; o >= 0; --o) {\n var i = this.tryEntries[o],\n a = i.completion;\n if (\"root\" === i.tryLoc) return handle(\"end\");\n if (i.tryLoc <= this.prev) {\n var c = n.call(i, \"catchLoc\"),\n u = n.call(i, \"finallyLoc\");\n if (c && u) {\n if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);\n if (this.prev < i.finallyLoc) return handle(i.finallyLoc);\n } else if (c) {\n if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);\n } else {\n if (!u) throw new Error(\"try statement without catch or finally\");\n if (this.prev < i.finallyLoc) return handle(i.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(t, e) {\n for (var r = this.tryEntries.length - 1; r >= 0; --r) {\n var o = this.tryEntries[r];\n if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) {\n var i = o;\n break;\n }\n }\n i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);\n var a = i ? i.completion : {};\n return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a);\n },\n complete: function complete(t, e) {\n if (\"throw\" === t.type) throw t.arg;\n return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y;\n },\n finish: function finish(t) {\n for (var e = this.tryEntries.length - 1; e >= 0; --e) {\n var r = this.tryEntries[e];\n if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;\n }\n },\n \"catch\": function _catch(t) {\n for (var e = this.tryEntries.length - 1; e >= 0; --e) {\n var r = this.tryEntries[e];\n if (r.tryLoc === t) {\n var n = r.completion;\n if (\"throw\" === n.type) {\n var o = n.arg;\n resetTryEntry(r);\n }\n return o;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(e, r, n) {\n return this.delegate = {\n iterator: values(e),\n resultName: r,\n nextLoc: n\n }, \"next\" === this.method && (this.arg = t), y;\n }\n }, e;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n return Object.freeze(Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw)\n }\n }));\n}\nmodule.exports = _taggedTemplateLiteral, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(o);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + \"d855a71b\" + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"frontend:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkfrontend\"] = self[\"webpackChunkfrontend\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `
`,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n initialized = initialMatches.every(\n (m) =>\n m.route.loader &&\n m.route.loader.hydrate !== true &&\n ((loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined))\n );\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since iot's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch {}\n\nexport interface DataRouteMatch extends RouteMatch {}\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n future: {\n v7_relativeSplatPath: boolean;\n };\n}\n\nexport const NavigationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a ``.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * ``.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey,\n Path extends string\n>(pattern: PathPattern | Path): PathMatch | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by ``s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, future, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n {outlet}\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params : Partial\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { future } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial | string,\n dataRouterState?: RemixRouter[\"state\"],\n future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under ) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent to .`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n \n {renderedMatches}\n \n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n

💿 Hey developer 👋

\n

\n You can provide a way better UX than this when your app throws errors\n by providing your own ErrorBoundary or{\" \"}\n errorElement prop on your route.\n

\n \n );\n }\n\n return (\n <>\n

Unexpected Application Error!

\n

{message}

\n {stack ?
{stack}
: null}\n {devInfo}\n \n );\n}\n\nconst defaultErrorElement = ;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n \n \n \n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n \n {children}\n \n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null,\n future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n loaderData[match.route.id] === undefined &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = ;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n \n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n \n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_relativeSplatPath: boolean;\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n // Only accept future flags relevant to rendering behavior\n // routing flags should be accessed via router.future\n future?: Partial>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a