2023-11-01 21:27:41 -07:00

573 lines
250 KiB
JavaScript

var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var lib={},boolean$1={};Object.defineProperty(boolean$1,"__esModule",{value:!0});boolean$1.boolean=void 0;const boolean=function(o){switch(Object.prototype.toString.call(o)){case"[object String]":return["true","t","yes","y","on","1"].includes(o.trim().toLowerCase());case"[object Number]":return o.valueOf()===1;case"[object Boolean]":return o.valueOf();default:return!1}};boolean$1.boolean=boolean;var isBooleanable$1={};Object.defineProperty(isBooleanable$1,"__esModule",{value:!0});isBooleanable$1.isBooleanable=void 0;const isBooleanable=function(o){switch(Object.prototype.toString.call(o)){case"[object String]":return["true","t","yes","y","on","1","false","f","no","n","off","0"].includes(o.trim().toLowerCase());case"[object Number]":return[0,1].includes(o.valueOf());case"[object Boolean]":return!0;default:return!1}};isBooleanable$1.isBooleanable=isBooleanable;(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.isBooleanable=o.boolean=void 0;const r=boolean$1;Object.defineProperty(o,"boolean",{enumerable:!0,get:function(){return r.boolean}});const n=isBooleanable$1;Object.defineProperty(o,"isBooleanable",{enumerable:!0,get:function(){return n.isBooleanable}})})(lib);const PUBLIC_APP_URL={}.PUBLIC_APP_URL||"https://app.pockethost.io",PUBLIC_APEX_DOMAIN={}.PUBLIC_APEX_DOMAIN||"pockethost.io",PUBLIC_BLOG_URL={}.PUBLIC_BLOG_URL||"https://pockethost.io",PUBLIC_HTTP_PROTOCOL={}.PUBLIC_HTTP_PROTOCOL||"https:",PUBLIC_MOTHERSHIP_URL={}.PUBLIC_MOTHERSHIP_URL||"https://pockethost-central.pockethost.io",PUBLIC_DEBUG=lib.boolean({}.PUBLIC_DEBUG||"true"),WWW_URL=(o="")=>`${PUBLIC_BLOG_URL}/${o}`,DOCS_URL=(o="")=>WWW_URL(`docs/${o}`),APP_URL=(o="")=>`${PUBLIC_APP_URL}/${o}`,INSTANCE_URL=(o,r="")=>`${PUBLIC_HTTP_PROTOCOL}//${o}.${PUBLIC_APEX_DOMAIN}/${r}`,INSTANCE_ADMIN_URL=(o,r="")=>INSTANCE_URL(o,`_/${r}`),FTP_URL=o=>`ftp://${encodeURIComponent(o)}@ftp.sfo-1.${PUBLIC_APEX_DOMAIN}`;console.log({PUBLIC_APEX_DOMAIN,PUBLIC_APP_URL,PUBLIC_BLOG_URL,PUBLIC_DEBUG,PUBLIC_HTTP_PROTOCOL,PUBLIC_MOTHERSHIP_URL});function keys(o){let r=keysOfNonArray(o);return Array.isArray(o)&&(r=r.filter(n=>n!=="length")),r}function keysOfNonArray(o){return o?Object.getOwnPropertyNames(o):[]}function forOwnOfNonArray(o,r){return forEachOfArray(keysOfNonArray(o),n=>r(o[n],n)),o}function forEach(o,r){return Array.isArray(o)?forEachOfArray(o,r):forOwnOfNonArray(o,r),o}function forEachOfArray(o,r){for(let n=0,a=o.length;n<a&&r(o[n],n)!==!1;++n);}function values(o){return keys(o).map(r=>o[r])}function map(o,r){const n=[];return forEach(o,(a,c)=>{n.push(r(a,c))}),n}function doReduce(o,r,n,a,c){return o(r,(l,u)=>{c?(a=l,c=!1):a=n(a,l,u)}),a}function reduce(o,r,n){return doReduce(forEach,o,r,n,arguments.length<3)}let random=o=>crypto.getRandomValues(new Uint8Array(o)),customRandom=(o,r,n)=>{let a=(2<<Math.log(o.length-1)/Math.LN2)-1,c=-~(1.6*a*r/o.length);return(l=r)=>{let u="";for(;;){let d=n(c),h=c;for(;h--;)if(u+=o[d[h]&a]||"",u.length===l)return u}}},customAlphabet=(o,r=21)=>customRandom(o,r,random),nanoid$1=(o=21)=>crypto.getRandomValues(new Uint8Array(o)).reduce((r,n)=>(n&=63,n<36?r+=n.toString(36):n<62?r+=(n-26).toString(36).toUpperCase():n>62?r+="-":r+="_",r),"");const ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=(o=0)=>r=>`\x1B[${r+o}m`,wrapAnsi256=(o=0)=>r=>`\x1B[${38+o};5;${r}m`,wrapAnsi16m=(o=0)=>(r,n,a)=>`\x1B[${38+o};2;${r};${n};${a}m`,styles$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(styles$1.modifier);const foregroundColorNames=Object.keys(styles$1.color),backgroundColorNames=Object.keys(styles$1.bgColor);[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){const o=new Map;for(const[r,n]of Object.entries(styles$1)){for(const[a,c]of Object.entries(n))styles$1[a]={open:`\x1B[${c[0]}m`,close:`\x1B[${c[1]}m`},n[a]=styles$1[a],o.set(c[0],c[1]);Object.defineProperty(styles$1,r,{value:n,enumerable:!1})}return Object.defineProperty(styles$1,"codes",{value:o,enumerable:!1}),styles$1.color.close="\x1B[39m",styles$1.bgColor.close="\x1B[49m",styles$1.color.ansi=wrapAnsi16(),styles$1.color.ansi256=wrapAnsi256(),styles$1.color.ansi16m=wrapAnsi16m(),styles$1.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),Object.defineProperties(styles$1,{rgbToAnsi256:{value(r,n,a){return r===n&&n===a?r<8?16:r>248?231:Math.round((r-8)/247*24)+232:16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(a/255*5)},enumerable:!1},hexToRgb:{value(r){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(r.toString(16));if(!n)return[0,0,0];let[a]=n;a.length===3&&(a=[...a].map(l=>l+l).join(""));const c=Number.parseInt(a,16);return[c>>16&255,c>>8&255,c&255]},enumerable:!1},hexToAnsi256:{value:r=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(r)),enumerable:!1},ansi256ToAnsi:{value(r){if(r<8)return 30+r;if(r<16)return 90+(r-8);let n,a,c;if(r>=232)n=((r-232)*10+8)/255,a=n,c=n;else{r-=16;const d=r%36;n=Math.floor(r/36)/5,a=Math.floor(d/6)/5,c=d%6/5}const l=Math.max(n,a,c)*2;if(l===0)return 30;let u=30+(Math.round(c)<<2|Math.round(a)<<1|Math.round(n));return l===2&&(u+=60),u},enumerable:!1},rgbToAnsi:{value:(r,n,a)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(r,n,a)),enumerable:!1},hexToAnsi:{value:r=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(r)),enumerable:!1}}),styles$1}const ansiStyles=assembleStyles(),ansiStyles$1=ansiStyles,level=(()=>{if(navigator.userAgentData){const o=navigator.userAgentData.brands.find(({brand:r})=>r==="Chromium");if(o&&o.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),colorSupport=level!==0&&{level,hasBasic:!0,has256:level>=2,has16m:level>=3},supportsColor={stdout:colorSupport,stderr:colorSupport},supportsColor$1=supportsColor;function stringReplaceAll(o,r,n){let a=o.indexOf(r);if(a===-1)return o;const c=r.length;let l=0,u="";do u+=o.slice(l,a)+r+n,l=a+c,a=o.indexOf(r,l);while(a!==-1);return u+=o.slice(l),u}function stringEncaseCRLFWithFirstIndex(o,r,n,a){let c=0,l="";do{const u=o[a-1]==="\r";l+=o.slice(c,u?a-1:a)+r+(u?`\r
`:`
`)+n,c=a+1,a=o.indexOf(`
`,c)}while(a!==-1);return l+=o.slice(c),l}const{stdout:stdoutColor,stderr:stderrColor}=supportsColor$1,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles=Object.create(null),applyOptions=(o,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=stdoutColor?stdoutColor.level:0;o.level=r.level===void 0?n:r.level},chalkFactory=o=>{const r=(...n)=>n.join(" ");return applyOptions(r,o),Object.setPrototypeOf(r,createChalk.prototype),r};function createChalk(o){return chalkFactory(o)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[o,r]of Object.entries(ansiStyles$1))styles[o]={get(){const n=createBuilder(this,createStyler(r.open,r.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,o,{value:n}),n}};styles.visible={get(){const o=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:o}),o}};const getModelAnsi=(o,r,n,...a)=>o==="rgb"?r==="ansi16m"?ansiStyles$1[n].ansi16m(...a):r==="ansi256"?ansiStyles$1[n].ansi256(ansiStyles$1.rgbToAnsi256(...a)):ansiStyles$1[n].ansi(ansiStyles$1.rgbToAnsi(...a)):o==="hex"?getModelAnsi("rgb",r,n,...ansiStyles$1.hexToRgb(...a)):ansiStyles$1[n][o](...a),usedModels=["rgb","hex","ansi256"];for(const o of usedModels){styles[o]={get(){const{level:n}=this;return function(...a){const c=createStyler(getModelAnsi(o,levelMapping[n],"color",...a),ansiStyles$1.color.close,this[STYLER]);return createBuilder(this,c,this[IS_EMPTY])}}};const r="bg"+o[0].toUpperCase()+o.slice(1);styles[r]={get(){const{level:n}=this;return function(...a){const c=createStyler(getModelAnsi(o,levelMapping[n],"bgColor",...a),ansiStyles$1.bgColor.close,this[STYLER]);return createBuilder(this,c,this[IS_EMPTY])}}}}const proto=Object.defineProperties(()=>{},{...styles,level:{enumerable:!0,get(){return this[GENERATOR].level},set(o){this[GENERATOR].level=o}}}),createStyler=(o,r,n)=>{let a,c;return n===void 0?(a=o,c=r):(a=n.openAll+o,c=r+n.closeAll),{open:o,close:r,openAll:a,closeAll:c,parent:n}},createBuilder=(o,r,n)=>{const a=(...c)=>applyStyle(a,c.length===1?""+c[0]:c.join(" "));return Object.setPrototypeOf(a,proto),a[GENERATOR]=o,a[STYLER]=r,a[IS_EMPTY]=n,a},applyStyle=(o,r)=>{if(o.level<=0||!r)return o[IS_EMPTY]?"":r;let n=o[STYLER];if(n===void 0)return r;const{openAll:a,closeAll:c}=n;if(r.includes("\x1B"))for(;n!==void 0;)r=stringReplaceAll(r,n.close,n.open),n=n.parent;const l=r.indexOf(`
`);return l!==-1&&(r=stringEncaseCRLFWithFirstIndex(r,c,a,l)),a+r+c};Object.defineProperties(createChalk.prototype,styles);const chalk=createChalk();createChalk({level:stderrColor?stderrColor.level:0});const chalk$1=chalk;var stringify$1={exports:{}};(function(o,r){r=o.exports=n,r.getSerialize=a;function n(c,l,u,d){return JSON.stringify(c,a(l,d),u)}function a(c,l){var u=[],d=[];return l==null&&(l=function(h,f){return u[0]===f?"[Circular ~]":"[Circular ~."+d.slice(0,u.indexOf(f)).join(".")+"]"}),function(h,f){if(u.length>0){var y=u.indexOf(this);~y?u.splice(y+1):u.push(this),~y?d.splice(y,1/0,h):d.push(h),~u.indexOf(f)&&(f=l.call(this,h,f))}else u.push(f);return c==null?f:c.call(this,h,f)}}})(stringify$1,stringify$1.exports);var stringifyExports=stringify$1.exports;const stringify=getDefaultExportFromCjs(stringifyExports);function mergeConfig(o,...r){const n={...o};for(const a of r)for(const c in a)if(Object.prototype.hasOwnProperty.call(a,c)){const l=a[c];l!==void 0&&(n[c]=l)}return n}function mkSingleton(o){let r;return n=>{if(r&&n)throw console.error(new Error().stack),new Error("Attempted to initialize service twice.");if(!r&&!n)throw console.error(new Error().stack),new Error("Attempted to use service before initialization.");return r||(r=o(n)),r}}const isLevelGt=(o,r)=>LogLevels[o]>LogLevels[r],isLevelGte=(o,r)=>LogLevels[o]>=LogLevels[r];var LogLevelName=(o=>(o.Trace="trace",o.Raw="raw",o.Debug="debug",o.Info="info",o.Warn="warn",o.Error="error",o.Abort="abort",o))(LogLevelName||{});const LogLevelConsoleMap={trace:console.trace,raw:console.log,debug:console.debug,info:console.info,warn:console.warn,error:console.error,abort:console.error},LogLevels={trace:0,raw:1,debug:2,info:3,warn:4,error:5,abort:6},MAX_BUF=1e3;let _curIdx=0;const _buf=[],createLogger=o=>{const r=mergeConfig({level:"debug",errorTrace:!1,pfx:[""]},o),{pfx:n,errorTrace:a,level:c}=r,l=k=>[new Date().toISOString(),k,...n].filter(O=>!!O).map(O=>`[${O}]`).join(" "),u=(k,...O)=>{_buf.length<MAX_BUF?_buf.push(O):(_buf[_curIdx]=O,_curIdx++,_curIdx===MAX_BUF&&(_curIdx=0)),isLevelGte(k,c)&&LogLevelConsoleMap[k](...O.map(P=>{const U=typeof P;return U==="string"&&P.match(/\n/)?stringify(P,null,2):U==="function"?`<<function ${stringify(P.toString())}>>`:U==="object"?stringify(P,null,2):P}))},d=(...k)=>{u("raw",l("RAW"),...k)},h=(...k)=>{u("trace",l("TRACE"),...k)},f=(...k)=>{u("debug",l(chalk$1.blueBright("DBG")),...k)},y=(...k)=>{u("info",...isLevelGt("info",c)?[l(chalk$1.gray("INFO")),...k]:k)},v=(...k)=>{u("warn",l(chalk$1.yellow(chalk$1.cyanBright("WARN"))),...k)},T=(...k)=>{u("error",l(chalk$1.bgRed("ERROR")),...k),u("debug",l(chalk$1.bgRed("ERROR")),new Error().stack),a&&(console.error("========== ERROR TRACEBACK BEGIN =============="),[..._buf.slice(_curIdx,MAX_BUF),..._buf.slice(0,_curIdx)].forEach(O=>{console.error(...O)}),console.error("========== ERROR TRACEBACK END =============="))},I=(...k)=>{throw u("abort",!0,l(chalk$1.bgRed("ABORT")),...k),new Error(`Fatal error: ${stringify(k)}`)},b=(k,O)=>createLogger({...r,...O,pfx:[...r.pfx,k]}),g={raw:d,dbg:f,warn:v,info:y,error:T,create:b,child:k=>b(stringify(k)),trace:h,debug:f,breadcrumb:k=>(n.push(k),g),abort:I,shutdown(){f("Logger shutting down")}};return g},LoggerService=mkSingleton((o={})=>createLogger(o)),createTimerManager=o=>{const{dbg:r,error:n}=LoggerService().create("timerManager");let a=0;const c={};let l=!1;const u=(f,y)=>{if(l)throw new Error("Already shut down");const v=a++,T=setTimeout(async()=>{I();try{await f()}catch(b){n(b)}},y),I=()=>{clearTimeout(T),delete c[v]};return c[v]=I,I};return{add:u,shutdown:()=>{l=!0,r(`Canceling ${values(c.length).length} timers`),forEach(c,f=>f()),r("done",c)},repeat:(f,y,v=!0)=>{let T;const I=async()=>{await f()&&!l&&(T=u(I,y))};return u(I,v?0:y),()=>{T==null||T(),T=void 0}}}};function assertExists(o,r="Value does not exist"){if(typeof o>"u")throw new Error(r)}function assert(o,r){if(!o)throw new Error(r||"Assertion failure")}var parser$5={};parser$5.load=function(o,r,n={}){var a,c,l;for(a in r)l=r[a],n[a]=(c=o[a])!=null?c:l;return n};parser$5.overwrite=function(o,r,n={}){var a,c;for(a in o)c=o[a],r[a]!==void 0&&(n[a]=c);return n};var DLList$2;DLList$2=class{constructor(r,n){this.incr=r,this.decr=n,this._first=null,this._last=null,this.length=0}push(r){var n;this.length++,typeof this.incr=="function"&&this.incr(),n={value:r,prev:this._last,next:null},this._last!=null?(this._last.next=n,this._last=n):this._first=this._last=n}shift(){var r;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),r=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,r}first(){if(this._first!=null)return this._first.value}getArray(){var r,n,a;for(r=this._first,a=[];r!=null;)a.push((n=r,r=r.next,n.value));return a}forEachShift(r){var n;for(n=this.shift();n!=null;)r(n),n=this.shift()}debug(){var r,n,a,c,l;for(r=this._first,l=[];r!=null;)l.push((n=r,r=r.next,{value:n.value,prev:(a=n.prev)!=null?a.value:void 0,next:(c=n.next)!=null?c.value:void 0}));return l}};var DLList_1=DLList$2;function asyncGeneratorStep$6(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$6(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$6(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$6(l,a,c,u,d,"throw",h)}u(void 0)})}}var Events$3;Events$3=class{constructor(r){if(this.instance=r,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(n,a)=>this._addListener(n,"many",a),this.instance.once=(n,a)=>this._addListener(n,"once",a),this.instance.removeAllListeners=(n=null)=>n!=null?delete this._events[n]:this._events={}}_addListener(r,n,a){var c;return(c=this._events)[r]==null&&(c[r]=[]),this._events[r].push({cb:a,status:n}),this.instance}listenerCount(r){return this._events[r]!=null?this._events[r].length:0}trigger(r,...n){var a=this;return _asyncToGenerator$6(function*(){var c,l;try{return r!=="debug"&&a.trigger("debug",`Event triggered: ${r}`,n),a._events[r]==null?void 0:(a._events[r]=a._events[r].filter(function(u){return u.status!=="none"}),l=a._events[r].map(function(){var u=_asyncToGenerator$6(function*(d){var h,f;if(d.status!=="none"){d.status==="once"&&(d.status="none");try{return f=typeof d.cb=="function"?d.cb(...n):void 0,typeof(f!=null?f.then:void 0)=="function"?yield f:f}catch(y){return h=y,a.trigger("error",h),null}}});return function(d){return u.apply(this,arguments)}}()),(yield Promise.all(l)).find(function(u){return u!=null}))}catch(u){return c=u,a.trigger("error",c),null}})()}};var Events_1=Events$3,DLList$1,Events$2,Queues;DLList$1=DLList_1;Events$2=Events_1;Queues=class{constructor(r){this.Events=new Events$2(this),this._length=0,this._lists=(function(){var n,a,c;for(c=[],n=1,a=r;1<=a?n<=a:n>=a;1<=a?++n:--n)c.push(new DLList$1(()=>this.incr(),()=>this.decr()));return c}).call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(r){return this._lists[r.options.priority].push(r)}queued(r){return r!=null?this._lists[r].length:this._length}shiftAll(r){return this._lists.forEach(function(n){return n.forEachShift(r)})}getFirst(r=this._lists){var n,a,c;for(n=0,a=r.length;n<a;n++)if(c=r[n],c.length>0)return c;return[]}shiftLastFrom(r){return this.getFirst(this._lists.slice(r).reverse()).shift()}};var Queues_1=Queues,BottleneckError$4;BottleneckError$4=class extends Error{};var BottleneckError_1=BottleneckError$4;function asyncGeneratorStep$5(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$5(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$5(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$5(l,a,c,u,d,"throw",h)}u(void 0)})}}var BottleneckError$3,DEFAULT_PRIORITY,Job,NUM_PRIORITIES,parser$4;NUM_PRIORITIES=10;DEFAULT_PRIORITY=5;parser$4=parser$5;BottleneckError$3=BottleneckError_1;Job=class{constructor(r,n,a,c,l,u,d,h){this.task=r,this.args=n,this.rejectOnDrop=l,this.Events=u,this._states=d,this.Promise=h,this.options=parser$4.load(a,c),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===c.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((f,y)=>{this._resolve=f,this._reject=y}),this.retryCount=0}_sanitizePriority(r){var n;return n=~~r!==r?DEFAULT_PRIORITY:r,n<0?0:n>NUM_PRIORITIES-1?NUM_PRIORITIES-1:n}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:r,message:n="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(r??new BottleneckError$3(n)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(r){var n;if(n=this._states.jobStatus(this.options.id),!(n===r||r==="DONE"&&n===null))throw new BottleneckError$3(`Invalid job status ${n}, expected ${r}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(r,n){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:r,blocked:n})}doRun(){return this.retryCount===0?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(r,n,a,c){var l=this;return _asyncToGenerator$5(function*(){var u,d,h;l.retryCount===0?(l._assertStatus("RUNNING"),l._states.next(l.options.id)):l._assertStatus("EXECUTING"),d={args:l.args,options:l.options,retryCount:l.retryCount},l.Events.trigger("executing",d);try{if(h=yield r!=null?r.schedule(l.options,l.task,...l.args):l.task(...l.args),n())return l.doDone(d),yield c(l.options,d),l._assertStatus("DONE"),l._resolve(h)}catch(f){return u=f,l._onFailure(u,d,n,a,c)}})()}doExpire(r,n,a){var c,l;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),l={args:this.args,options:this.options,retryCount:this.retryCount},c=new BottleneckError$3(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(c,l,r,n,a)}_onFailure(r,n,a,c,l){var u=this;return _asyncToGenerator$5(function*(){var d,h;if(a())return d=yield u.Events.trigger("failed",r,n),d!=null?(h=~~d,u.Events.trigger("retry",`Retrying ${u.options.id} after ${h} ms`,n),u.retryCount++,c(h)):(u.doDone(n),yield l(u.options,n),u._assertStatus("DONE"),u._reject(r))})()}doDone(r){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",r)}};var Job_1=Job;function asyncGeneratorStep$4(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$4(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$4(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$4(l,a,c,u,d,"throw",h)}u(void 0)})}}var BottleneckError$2,LocalDatastore,parser$3;parser$3=parser$5;BottleneckError$2=BottleneckError_1;LocalDatastore=class{constructor(r,n,a){this.instance=r,this.storeOptions=n,this.clientId=this.instance._randomIndex(),parser$3.load(a,a,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var r;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(r=this.heartbeat=setInterval(()=>{var n,a,c,l,u;if(l=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&l>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=l,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&l>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var d=this.storeOptions;if(n=d.reservoirIncreaseAmount,c=d.reservoirIncreaseMaximum,u=d.reservoir,this._lastReservoirIncrease=l,a=c!=null?Math.min(n,c-u):n,a>0)return this.storeOptions.reservoir+=a,this.instance._drainAll(this.computeCapacity())}},this.heartbeatInterval)).unref=="function"?r.unref():void 0:clearInterval(this.heartbeat)}__publish__(r){var n=this;return _asyncToGenerator$4(function*(){return yield n.yieldLoop(),n.instance.Events.trigger("message",r.toString())})()}__disconnect__(r){var n=this;return _asyncToGenerator$4(function*(){return yield n.yieldLoop(),clearInterval(n.heartbeat),n.Promise.resolve()})()}yieldLoop(r=0){return new this.Promise(function(n,a){return setTimeout(n,r)})}computePenalty(){var r;return(r=this.storeOptions.penalty)!=null?r:15*this.storeOptions.minTime||5e3}__updateSettings__(r){var n=this;return _asyncToGenerator$4(function*(){return yield n.yieldLoop(),parser$3.overwrite(r,r,n.storeOptions),n._startHeartbeat(),n.instance._drainAll(n.computeCapacity()),!0})()}__running__(){var r=this;return _asyncToGenerator$4(function*(){return yield r.yieldLoop(),r._running})()}__queued__(){var r=this;return _asyncToGenerator$4(function*(){return yield r.yieldLoop(),r.instance.queued()})()}__done__(){var r=this;return _asyncToGenerator$4(function*(){return yield r.yieldLoop(),r._done})()}__groupCheck__(r){var n=this;return _asyncToGenerator$4(function*(){return yield n.yieldLoop(),n._nextRequest+n.timeout<r})()}computeCapacity(){var r,n,a=this.storeOptions;return r=a.maxConcurrent,n=a.reservoir,r!=null&&n!=null?Math.min(r-this._running,n):r!=null?r-this._running:n??null}conditionsCheck(r){var n;return n=this.computeCapacity(),n==null||r<=n}__incrementReservoir__(r){var n=this;return _asyncToGenerator$4(function*(){var a;return yield n.yieldLoop(),a=n.storeOptions.reservoir+=r,n.instance._drainAll(n.computeCapacity()),a})()}__currentReservoir__(){var r=this;return _asyncToGenerator$4(function*(){return yield r.yieldLoop(),r.storeOptions.reservoir})()}isBlocked(r){return this._unblockTime>=r}check(r,n){return this.conditionsCheck(r)&&this._nextRequest-n<=0}__check__(r){var n=this;return _asyncToGenerator$4(function*(){var a;return yield n.yieldLoop(),a=Date.now(),n.check(r,a)})()}__register__(r,n,a){var c=this;return _asyncToGenerator$4(function*(){var l,u;return yield c.yieldLoop(),l=Date.now(),c.conditionsCheck(n)?(c._running+=n,c.storeOptions.reservoir!=null&&(c.storeOptions.reservoir-=n),u=Math.max(c._nextRequest-l,0),c._nextRequest=l+u+c.storeOptions.minTime,{success:!0,wait:u,reservoir:c.storeOptions.reservoir}):{success:!1}})()}strategyIsBlock(){return this.storeOptions.strategy===3}__submit__(r,n){var a=this;return _asyncToGenerator$4(function*(){var c,l,u;if(yield a.yieldLoop(),a.storeOptions.maxConcurrent!=null&&n>a.storeOptions.maxConcurrent)throw new BottleneckError$2(`Impossible to add a job having a weight of ${n} to a limiter having a maxConcurrent setting of ${a.storeOptions.maxConcurrent}`);return l=Date.now(),u=a.storeOptions.highWater!=null&&r===a.storeOptions.highWater&&!a.check(n,l),c=a.strategyIsBlock()&&(u||a.isBlocked(l)),c&&(a._unblockTime=l+a.computePenalty(),a._nextRequest=a._unblockTime+a.storeOptions.minTime,a.instance._dropAllQueued()),{reachedHWM:u,blocked:c,strategy:a.storeOptions.strategy}})()}__free__(r,n){var a=this;return _asyncToGenerator$4(function*(){return yield a.yieldLoop(),a._running-=n,a._done+=n,a.instance._drainAll(a.computeCapacity()),{running:a._running}})()}};var LocalDatastore_1=LocalDatastore,Scripts$2={};const require$$0={"blacklist_client.lua":`local blacklist = ARGV[num_static_argv + 1]
if redis.call('zscore', client_last_seen_key, blacklist) then
redis.call('zadd', client_last_seen_key, 0, blacklist)
end
return {}
`,"check.lua":`local weight = tonumber(ARGV[num_static_argv + 1])
local capacity = process_tick(now, false)['capacity']
local nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))
return conditions_check(capacity, weight) and nextRequest - now <= 0
`,"conditions_check.lua":`local conditions_check = function (capacity, weight)
return capacity == nil or weight <= capacity
end
`,"current_reservoir.lua":`return process_tick(now, false)['reservoir']
`,"done.lua":`process_tick(now, false)
return tonumber(redis.call('hget', settings_key, 'done'))
`,"free.lua":`local index = ARGV[num_static_argv + 1]
redis.call('zadd', job_expirations_key, 0, index)
return process_tick(now, false)['running']
`,"get_time.lua":`redis.replicate_commands()
local get_time = function ()
local time = redis.call('time')
return tonumber(time[1]..string.sub(time[2], 1, 3))
end
`,"group_check.lua":`return not (redis.call('exists', settings_key) == 1)
`,"heartbeat.lua":`process_tick(now, true)
`,"increment_reservoir.lua":`local incr = tonumber(ARGV[num_static_argv + 1])
redis.call('hincrby', settings_key, 'reservoir', incr)
local reservoir = process_tick(now, true)['reservoir']
local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
refresh_expiration(0, 0, groupTimeout)
return reservoir
`,"init.lua":`local clear = tonumber(ARGV[num_static_argv + 1])
local limiter_version = ARGV[num_static_argv + 2]
local num_local_argv = num_static_argv + 2
if clear == 1 then
redis.call('del', unpack(KEYS))
end
if redis.call('exists', settings_key) == 0 then
-- Create
local args = {'hmset', settings_key}
for i = num_local_argv + 1, #ARGV do
table.insert(args, ARGV[i])
end
redis.call(unpack(args))
redis.call('hmset', settings_key,
'nextRequest', now,
'lastReservoirRefresh', now,
'lastReservoirIncrease', now,
'running', 0,
'done', 0,
'unblockTime', 0,
'capacityPriorityCounter', 0
)
else
-- Apply migrations
local settings = redis.call('hmget', settings_key,
'id',
'version'
)
local id = settings[1]
local current_version = settings[2]
if current_version ~= limiter_version then
local version_digits = {}
for k, v in string.gmatch(current_version, "([^.]+)") do
table.insert(version_digits, tonumber(k))
end
-- 2.10.0
if version_digits[2] < 10 then
redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')
redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')
redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')
redis.call('hsetnx', settings_key, 'done', 0)
redis.call('hset', settings_key, 'version', '2.10.0')
end
-- 2.11.1
if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then
if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then
redis.call('hmset', settings_key,
'lastReservoirRefresh', now,
'version', '2.11.1'
)
end
end
-- 2.14.0
if version_digits[2] < 14 then
local old_running_key = 'b_'..id..'_running'
local old_executing_key = 'b_'..id..'_executing'
if redis.call('exists', old_running_key) == 1 then
redis.call('rename', old_running_key, job_weights_key)
end
if redis.call('exists', old_executing_key) == 1 then
redis.call('rename', old_executing_key, job_expirations_key)
end
redis.call('hset', settings_key, 'version', '2.14.0')
end
-- 2.15.2
if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then
redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)
redis.call('hset', settings_key, 'version', '2.15.2')
end
-- 2.17.0
if version_digits[2] < 17 then
redis.call('hsetnx', settings_key, 'clientTimeout', 10000)
redis.call('hset', settings_key, 'version', '2.17.0')
end
-- 2.18.0
if version_digits[2] < 18 then
redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')
redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')
redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')
redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)
redis.call('hset', settings_key, 'version', '2.18.0')
end
end
process_tick(now, false)
end
local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
refresh_expiration(0, 0, groupTimeout)
return {}
`,"process_tick.lua":`local process_tick = function (now, always_publish)
local compute_capacity = function (maxConcurrent, running, reservoir)
if maxConcurrent ~= nil and reservoir ~= nil then
return math.min((maxConcurrent - running), reservoir)
elseif maxConcurrent ~= nil then
return maxConcurrent - running
elseif reservoir ~= nil then
return reservoir
else
return nil
end
end
local settings = redis.call('hmget', settings_key,
'id',
'maxConcurrent',
'running',
'reservoir',
'reservoirRefreshInterval',
'reservoirRefreshAmount',
'lastReservoirRefresh',
'reservoirIncreaseInterval',
'reservoirIncreaseAmount',
'reservoirIncreaseMaximum',
'lastReservoirIncrease',
'capacityPriorityCounter',
'clientTimeout'
)
local id = settings[1]
local maxConcurrent = tonumber(settings[2])
local running = tonumber(settings[3])
local reservoir = tonumber(settings[4])
local reservoirRefreshInterval = tonumber(settings[5])
local reservoirRefreshAmount = tonumber(settings[6])
local lastReservoirRefresh = tonumber(settings[7])
local reservoirIncreaseInterval = tonumber(settings[8])
local reservoirIncreaseAmount = tonumber(settings[9])
local reservoirIncreaseMaximum = tonumber(settings[10])
local lastReservoirIncrease = tonumber(settings[11])
local capacityPriorityCounter = tonumber(settings[12])
local clientTimeout = tonumber(settings[13])
local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)
--
-- Process 'running' changes
--
local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)
if #expired > 0 then
redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)
local flush_batch = function (batch, acc)
local weights = redis.call('hmget', job_weights_key, unpack(batch))
redis.call('hdel', job_weights_key, unpack(batch))
local clients = redis.call('hmget', job_clients_key, unpack(batch))
redis.call('hdel', job_clients_key, unpack(batch))
-- Calculate sum of removed weights
for i = 1, #weights do
acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)
end
-- Calculate sum of removed weights by client
local client_weights = {}
for i = 1, #clients do
local removed = tonumber(weights[i]) or 0
if removed > 0 then
acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed
end
end
end
local acc = {
['total'] = 0,
['client_weights'] = {}
}
local batch_size = 1000
-- Compute changes to Zsets and apply changes to Hashes
for i = 1, #expired, batch_size do
local batch = {}
for j = i, math.min(i + batch_size - 1, #expired) do
table.insert(batch, expired[j])
end
flush_batch(batch, acc)
end
-- Apply changes to Zsets
if acc['total'] > 0 then
redis.call('hincrby', settings_key, 'done', acc['total'])
running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))
end
for client, weight in pairs(acc['client_weights']) do
redis.call('zincrby', client_running_key, -weight, client)
end
end
--
-- Process 'reservoir' changes
--
local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil
if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then
reservoir = reservoirRefreshAmount
redis.call('hmset', settings_key,
'reservoir', reservoir,
'lastReservoirRefresh', now
)
end
local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil
if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then
local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)
local incr = reservoirIncreaseAmount * num_intervals
if reservoirIncreaseMaximum ~= nil then
incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))
end
if incr > 0 then
reservoir = (reservoir or 0) + incr
end
redis.call('hmset', settings_key,
'reservoir', reservoir,
'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)
)
end
--
-- Clear unresponsive clients
--
local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))
local unresponsive_lookup = {}
local terminated_clients = {}
for i = 1, #unresponsive do
unresponsive_lookup[unresponsive[i]] = true
if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then
table.insert(terminated_clients, unresponsive[i])
end
end
if #terminated_clients > 0 then
redis.call('zrem', client_running_key, unpack(terminated_clients))
redis.call('hdel', client_num_queued_key, unpack(terminated_clients))
redis.call('zrem', client_last_registered_key, unpack(terminated_clients))
redis.call('zrem', client_last_seen_key, unpack(terminated_clients))
end
--
-- Broadcast capacity changes
--
local final_capacity = compute_capacity(maxConcurrent, running, reservoir)
if always_publish or (initial_capacity ~= nil and final_capacity == nil) then
-- always_publish or was not unlimited, now unlimited
redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))
elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then
-- capacity was increased
-- send the capacity message to the limiter having the lowest number of running jobs
-- the tiebreaker is the limiter having not registered a job in the longest time
local lowest_concurrency_value = nil
local lowest_concurrency_clients = {}
local lowest_concurrency_last_registered = {}
local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')
for i = 1, #client_concurrencies, 2 do
local client = client_concurrencies[i]
local concurrency = tonumber(client_concurrencies[i+1])
if (
lowest_concurrency_value == nil or lowest_concurrency_value == concurrency
) and (
not unresponsive_lookup[client]
) and (
tonumber(redis.call('hget', client_num_queued_key, client)) > 0
) then
lowest_concurrency_value = concurrency
table.insert(lowest_concurrency_clients, client)
local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))
table.insert(lowest_concurrency_last_registered, last_registered)
end
end
if #lowest_concurrency_clients > 0 then
local position = 1
local earliest = lowest_concurrency_last_registered[1]
for i,v in ipairs(lowest_concurrency_last_registered) do
if v < earliest then
position = i
earliest = v
end
end
local next_client = lowest_concurrency_clients[position]
redis.call('publish', 'b_'..id,
'capacity-priority:'..(final_capacity or '')..
':'..next_client..
':'..capacityPriorityCounter
)
redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')
else
redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))
end
end
return {
['capacity'] = final_capacity,
['running'] = running,
['reservoir'] = reservoir
}
end
`,"queued.lua":`local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))
local valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')
local client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))
local sum = 0
for i = 1, #client_queued do
sum = sum + tonumber(client_queued[i])
end
return sum
`,"refresh_expiration.lua":`local refresh_expiration = function (now, nextRequest, groupTimeout)
if groupTimeout ~= nil then
local ttl = (nextRequest + groupTimeout) - now
for i = 1, #KEYS do
redis.call('pexpire', KEYS[i], ttl)
end
end
end
`,"refs.lua":`local settings_key = KEYS[1]
local job_weights_key = KEYS[2]
local job_expirations_key = KEYS[3]
local job_clients_key = KEYS[4]
local client_running_key = KEYS[5]
local client_num_queued_key = KEYS[6]
local client_last_registered_key = KEYS[7]
local client_last_seen_key = KEYS[8]
local now = tonumber(ARGV[1])
local client = ARGV[2]
local num_static_argv = 2
`,"register.lua":`local index = ARGV[num_static_argv + 1]
local weight = tonumber(ARGV[num_static_argv + 2])
local expiration = tonumber(ARGV[num_static_argv + 3])
local state = process_tick(now, false)
local capacity = state['capacity']
local reservoir = state['reservoir']
local settings = redis.call('hmget', settings_key,
'nextRequest',
'minTime',
'groupTimeout'
)
local nextRequest = tonumber(settings[1])
local minTime = tonumber(settings[2])
local groupTimeout = tonumber(settings[3])
if conditions_check(capacity, weight) then
redis.call('hincrby', settings_key, 'running', weight)
redis.call('hset', job_weights_key, index, weight)
if expiration ~= nil then
redis.call('zadd', job_expirations_key, now + expiration, index)
end
redis.call('hset', job_clients_key, index, client)
redis.call('zincrby', client_running_key, weight, client)
redis.call('hincrby', client_num_queued_key, client, -1)
redis.call('zadd', client_last_registered_key, now, client)
local wait = math.max(nextRequest - now, 0)
local newNextRequest = now + wait + minTime
if reservoir == nil then
redis.call('hset', settings_key,
'nextRequest', newNextRequest
)
else
reservoir = reservoir - weight
redis.call('hmset', settings_key,
'reservoir', reservoir,
'nextRequest', newNextRequest
)
end
refresh_expiration(now, newNextRequest, groupTimeout)
return {true, wait, reservoir}
else
return {false}
end
`,"register_client.lua":`local queued = tonumber(ARGV[num_static_argv + 1])
-- Could have been re-registered concurrently
if not redis.call('zscore', client_last_seen_key, client) then
redis.call('zadd', client_running_key, 0, client)
redis.call('hset', client_num_queued_key, client, queued)
redis.call('zadd', client_last_registered_key, 0, client)
end
redis.call('zadd', client_last_seen_key, now, client)
return {}
`,"running.lua":`return process_tick(now, false)['running']
`,"submit.lua":`local queueLength = tonumber(ARGV[num_static_argv + 1])
local weight = tonumber(ARGV[num_static_argv + 2])
local capacity = process_tick(now, false)['capacity']
local settings = redis.call('hmget', settings_key,
'id',
'maxConcurrent',
'highWater',
'nextRequest',
'strategy',
'unblockTime',
'penalty',
'minTime',
'groupTimeout'
)
local id = settings[1]
local maxConcurrent = tonumber(settings[2])
local highWater = tonumber(settings[3])
local nextRequest = tonumber(settings[4])
local strategy = tonumber(settings[5])
local unblockTime = tonumber(settings[6])
local penalty = tonumber(settings[7])
local minTime = tonumber(settings[8])
local groupTimeout = tonumber(settings[9])
if maxConcurrent ~= nil and weight > maxConcurrent then
return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)
end
local reachedHWM = (highWater ~= nil and queueLength == highWater
and not (
conditions_check(capacity, weight)
and nextRequest - now <= 0
)
)
local blocked = strategy == 3 and (reachedHWM or unblockTime >= now)
if blocked then
local computedPenalty = penalty
if computedPenalty == nil then
if minTime == 0 then
computedPenalty = 5000
else
computedPenalty = 15 * minTime
end
end
local newNextRequest = now + computedPenalty + minTime
redis.call('hmset', settings_key,
'unblockTime', now + computedPenalty,
'nextRequest', newNextRequest
)
local clients_queued_reset = redis.call('hkeys', client_num_queued_key)
local queued_reset = {}
for i = 1, #clients_queued_reset do
table.insert(queued_reset, clients_queued_reset[i])
table.insert(queued_reset, 0)
end
redis.call('hmset', client_num_queued_key, unpack(queued_reset))
redis.call('publish', 'b_'..id, 'blocked:')
refresh_expiration(now, newNextRequest, groupTimeout)
end
if not blocked and not reachedHWM then
redis.call('hincrby', client_num_queued_key, client, 1)
end
return {reachedHWM, blocked, strategy}
`,"update_settings.lua":`local args = {'hmset', settings_key}
for i = num_static_argv + 1, #ARGV do
table.insert(args, ARGV[i])
end
redis.call(unpack(args))
process_tick(now, true)
local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
refresh_expiration(0, 0, groupTimeout)
return {}
`,"validate_client.lua":`if not redis.call('zscore', client_last_seen_key, client) then
return redis.error_reply('UNKNOWN_CLIENT')
end
redis.call('zadd', client_last_seen_key, now, client)
`,"validate_keys.lua":`if not (redis.call('exists', settings_key) == 1) then
return redis.error_reply('SETTINGS_KEY_NOT_FOUND')
end
`};(function(o){var r,n,a;n=require$$0,r={refs:n["refs.lua"],validate_keys:n["validate_keys.lua"],validate_client:n["validate_client.lua"],refresh_expiration:n["refresh_expiration.lua"],process_tick:n["process_tick.lua"],conditions_check:n["conditions_check.lua"],get_time:n["get_time.lua"]},o.allKeys=function(c){return[`b_${c}_settings`,`b_${c}_job_weights`,`b_${c}_job_expirations`,`b_${c}_job_clients`,`b_${c}_client_running`,`b_${c}_client_num_queued`,`b_${c}_client_last_registered`,`b_${c}_client_last_seen`]},a={init:{keys:o.allKeys,headers:["process_tick"],refresh_expiration:!0,code:n["init.lua"]},group_check:{keys:o.allKeys,headers:[],refresh_expiration:!1,code:n["group_check.lua"]},register_client:{keys:o.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:n["register_client.lua"]},blacklist_client:{keys:o.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["blacklist_client.lua"]},heartbeat:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["heartbeat.lua"]},update_settings:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["update_settings.lua"]},running:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["running.lua"]},queued:{keys:o.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["queued.lua"]},done:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["done.lua"]},check:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:n["check.lua"]},submit:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["submit.lua"]},register:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["register.lua"]},free:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["free.lua"]},current_reservoir:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["current_reservoir.lua"]},increment_reservoir:{keys:o.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["increment_reservoir.lua"]}},o.names=Object.keys(a),o.keys=function(c,l){return a[c].keys(l)},o.payload=function(c){var l;return l=a[c],Array.prototype.concat(r.refs,l.headers.map(function(u){return r[u]}),l.refresh_expiration?r.refresh_expiration:"",l.code).join(`
`)}})(Scripts$2);function asyncGeneratorStep$3(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$3(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$3(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$3(l,a,c,u,d,"throw",h)}u(void 0)})}}var Events$1,RedisConnection$1,Scripts$1,parser$2;parser$2=parser$5;Events$1=Events_1;Scripts$1=Scripts$2;RedisConnection$1=(function(){class RedisConnection{constructor(options={}){parser$2.load(options,this.defaults,this),this.Redis==null&&(this.Redis=eval("require")("redis")),this.Events==null&&(this.Events=new Events$1(this)),this.terminated=!1,this.client==null&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>this._loadScripts()).then(()=>({client:this.client,subscriber:this.subscriber}))}_setup(o,r){return o.setMaxListeners(0),new this.Promise((n,a)=>(o.on("error",c=>this.Events.trigger("error",c)),r&&o.on("message",(c,l)=>{var u;return(u=this.limiters[c])!=null?u._store.onMessage(c,l):void 0}),o.ready?n():o.once("ready",n)))}_loadScript(o){return new this.Promise((r,n)=>{var a;return a=Scripts$1.payload(o),this.client.multi([["script","load",a]]).exec((c,l)=>c!=null?n(c):(this.shas[o]=l[0],r(l[0])))})}_loadScripts(){return this.Promise.all(Scripts$1.names.map(o=>this._loadScript(o)))}__runCommand__(o){var r=this;return _asyncToGenerator$3(function*(){return yield r.ready,new r.Promise((n,a)=>r.client.multi([o]).exec_atomic(function(c,l){return c!=null?a(c):n(l[0])}))})()}__addLimiter__(o){return this.Promise.all([o.channel(),o.channel_client()].map(r=>new this.Promise((n,a)=>{var c;return c=l=>{if(l===r)return this.subscriber.removeListener("subscribe",c),this.limiters[r]=o,n()},this.subscriber.on("subscribe",c),this.subscriber.subscribe(r)})))}__removeLimiter__(o){var r=this;return this.Promise.all([o.channel(),o.channel_client()].map(function(){var n=_asyncToGenerator$3(function*(a){return r.terminated||(yield new r.Promise((c,l)=>r.subscriber.unsubscribe(a,function(u,d){if(u!=null)return l(u);if(d===a)return c()}))),delete r.limiters[a]});return function(a){return n.apply(this,arguments)}}()))}__scriptArgs__(o,r,n,a){var c;return c=Scripts$1.keys(o,r),[this.shas[o],c.length].concat(c,n,a)}__scriptFn__(o){return this.client.evalsha.bind(this.client)}disconnect(o=!0){var r,n,a,c;for(c=Object.keys(this.limiters),r=0,a=c.length;r<a;r++)n=c[r],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(o),this.subscriber.end(o),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise,Events:null},RedisConnection}).call(void 0);var RedisConnection_1=RedisConnection$1;function _slicedToArray$1(o,r){return _arrayWithHoles$1(o)||_iterableToArrayLimit$1(o,r)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$1(o,r){var n=[],a=!0,c=!1,l=void 0;try{for(var u=o[Symbol.iterator](),d;!(a=(d=u.next()).done)&&(n.push(d.value),!(r&&n.length===r));a=!0);}catch(h){c=!0,l=h}finally{try{!a&&u.return!=null&&u.return()}finally{if(c)throw l}}return n}function _arrayWithHoles$1(o){if(Array.isArray(o))return o}function asyncGeneratorStep$2(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$2(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$2(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$2(l,a,c,u,d,"throw",h)}u(void 0)})}}var Events,IORedisConnection$1,Scripts,parser$1;parser$1=parser$5;Events=Events_1;Scripts=Scripts$2;IORedisConnection$1=(function(){class IORedisConnection{constructor(options={}){parser$1.load(options,this.defaults,this),this.Redis==null&&(this.Redis=eval("require")("ioredis")),this.Events==null&&(this.Events=new Events(this)),this.terminated=!1,this.clusterNodes!=null?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):this.client!=null&&this.client.duplicate==null?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(this.client==null&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber}))}_setup(o,r){return o.setMaxListeners(0),new this.Promise((n,a)=>(o.on("error",c=>this.Events.trigger("error",c)),r&&o.on("message",(c,l)=>{var u;return(u=this.limiters[c])!=null?u._store.onMessage(c,l):void 0}),o.status==="ready"?n():o.once("ready",n)))}_loadScripts(){return Scripts.names.forEach(o=>this.client.defineCommand(o,{lua:Scripts.payload(o)}))}__runCommand__(o){var r=this;return _asyncToGenerator$2(function*(){var n;yield r.ready;var a=yield r.client.pipeline([o]).exec(),c=_slicedToArray$1(a,1),l=_slicedToArray$1(c[0],2);return l[0],n=l[1],n})()}__addLimiter__(o){return this.Promise.all([o.channel(),o.channel_client()].map(r=>new this.Promise((n,a)=>this.subscriber.subscribe(r,()=>(this.limiters[r]=o,n())))))}__removeLimiter__(o){var r=this;return[o.channel(),o.channel_client()].forEach(function(){var n=_asyncToGenerator$2(function*(a){return r.terminated||(yield r.subscriber.unsubscribe(a)),delete r.limiters[a]});return function(a){return n.apply(this,arguments)}}())}__scriptArgs__(o,r,n,a){var c;return c=Scripts.keys(o,r),[c.length].concat(c,n,a)}__scriptFn__(o){return this.client[o].bind(this.client)}disconnect(o=!0){var r,n,a,c;for(c=Object.keys(this.limiters),r=0,a=c.length;r<a;r++)n=c[r],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,o?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise,Events:null},IORedisConnection}).call(void 0);var IORedisConnection_1=IORedisConnection$1;function _slicedToArray(o,r){return _arrayWithHoles(o)||_iterableToArrayLimit(o,r)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit(o,r){var n=[],a=!0,c=!1,l=void 0;try{for(var u=o[Symbol.iterator](),d;!(a=(d=u.next()).done)&&(n.push(d.value),!(r&&n.length===r));a=!0);}catch(h){c=!0,l=h}finally{try{!a&&u.return!=null&&u.return()}finally{if(c)throw l}}return n}function _arrayWithHoles(o){if(Array.isArray(o))return o}function asyncGeneratorStep$1(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator$1(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep$1(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep$1(l,a,c,u,d,"throw",h)}u(void 0)})}}var BottleneckError$1,IORedisConnection,RedisConnection,RedisDatastore,parser;parser=parser$5;BottleneckError$1=BottleneckError_1;RedisConnection=RedisConnection_1;IORedisConnection=IORedisConnection_1;RedisDatastore=class{constructor(r,n,a){this.instance=r,this.storeOptions=n,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),parser.load(a,a,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=this.connection!=null,this.connection==null&&(this.connection=this.instance.datastore==="redis"?new RedisConnection({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):this.instance.datastore==="ioredis"?new IORedisConnection({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then(c=>(this.clients=c,this.runScript("init",this.prepareInitSettings(this.clearDatastore)))).then(()=>this.connection.__addLimiter__(this.instance)).then(()=>this.runScript("register_client",[this.instance.queued()])).then(()=>{var c;return typeof(c=this.heartbeat=setInterval(()=>this.runScript("heartbeat",[]).catch(l=>this.instance.Events.trigger("error",l)),this.heartbeatInterval)).unref=="function"&&c.unref(),this.clients})}__publish__(r){var n=this;return _asyncToGenerator$1(function*(){var a,c=yield n.ready;return a=c.client,a.publish(n.instance.channel(),`message:${r.toString()}`)})()}onMessage(r,n){var a=this;return _asyncToGenerator$1(function*(){var c,l,u,d,h,f,y,v,T,I;try{y=n.indexOf(":");var b=[n.slice(0,y),n.slice(y+1)];if(I=b[0],u=b[1],I==="capacity")return yield a.instance._drainAll(u.length>0?~~u:void 0);if(I==="capacity-priority"){var R=u.split(":"),$=_slicedToArray(R,3);return T=$[0],v=$[1],l=$[2],c=T.length>0?~~T:void 0,v===a.clientId?(d=yield a.instance._drainAll(c),f=c!=null?c-(d||0):"",yield a.clients.client.publish(a.instance.channel(),`capacity-priority:${f}::${l}`)):v===""?(clearTimeout(a.capacityPriorityCounters[l]),delete a.capacityPriorityCounters[l],a.instance._drainAll(c)):a.capacityPriorityCounters[l]=setTimeout(_asyncToGenerator$1(function*(){var g;try{return delete a.capacityPriorityCounters[l],yield a.runScript("blacklist_client",[v]),yield a.instance._drainAll(c)}catch(k){return g=k,a.instance.Events.trigger("error",g)}}),1e3)}else{if(I==="message")return a.instance.Events.trigger("message",u);if(I==="blocked")return yield a.instance._dropAllQueued()}}catch(g){return h=g,a.instance.Events.trigger("error",h)}})()}__disconnect__(r){return clearInterval(this.heartbeat),this.sharedConnection?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(r)}runScript(r,n){var a=this;return _asyncToGenerator$1(function*(){return r==="init"||r==="register_client"||(yield a.ready),new a.Promise((c,l)=>{var u,d;return u=[Date.now(),a.clientId].concat(n),a.instance.Events.trigger("debug",`Calling Redis script: ${r}.lua`,u),d=a.connection.__scriptArgs__(r,a.originalId,u,function(h,f){return h!=null?l(h):c(f)}),a.connection.__scriptFn__(r)(...d)}).catch(c=>c.message==="SETTINGS_KEY_NOT_FOUND"?r==="heartbeat"?a.Promise.resolve():a.runScript("init",a.prepareInitSettings(!1)).then(()=>a.runScript(r,n)):c.message==="UNKNOWN_CLIENT"?a.runScript("register_client",[a.instance.queued()]).then(()=>a.runScript(r,n)):a.Promise.reject(c))})()}prepareArray(r){var n,a,c,l;for(c=[],n=0,a=r.length;n<a;n++)l=r[n],c.push(l!=null?l.toString():"");return c}prepareObject(r){var n,a,c;n=[];for(a in r)c=r[a],n.push(a,c!=null?c.toString():"");return n}prepareInitSettings(r){var n;return n=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout})),n.unshift(r?1:0,this.instance.version),n}convertBool(r){return!!r}__updateSettings__(r){var n=this;return _asyncToGenerator$1(function*(){return yield n.runScript("update_settings",n.prepareObject(r)),parser.overwrite(r,r,n.storeOptions)})()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var r=this;return _asyncToGenerator$1(function*(){return r.convertBool(yield r.runScript("group_check",[]))})()}__incrementReservoir__(r){return this.runScript("increment_reservoir",[r])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(r){var n=this;return _asyncToGenerator$1(function*(){return n.convertBool(yield n.runScript("check",n.prepareArray([r])))})()}__register__(r,n,a){var c=this;return _asyncToGenerator$1(function*(){var l,u,d,h=yield c.runScript("register",c.prepareArray([r,n,a])),f=_slicedToArray(h,3);return u=f[0],d=f[1],l=f[2],{success:c.convertBool(u),wait:d,reservoir:l}})()}__submit__(r,n){var a=this;return _asyncToGenerator$1(function*(){var c,l,u,d,h;try{var f=yield a.runScript("submit",a.prepareArray([r,n])),y=_slicedToArray(f,3);return d=y[0],c=y[1],h=y[2],{reachedHWM:a.convertBool(d),blocked:a.convertBool(c),strategy:h}}catch(I){if(l=I,l.message.indexOf("OVERWEIGHT")===0){var v=l.message.split(":"),T=_slicedToArray(v,3);throw T[0],n=T[1],u=T[2],new BottleneckError$1(`Impossible to add a job having a weight of ${n} to a limiter having a maxConcurrent setting of ${u}`)}else throw l}})()}__free__(r,n){var a=this;return _asyncToGenerator$1(function*(){var c;return c=yield a.runScript("free",a.prepareArray([r])),{running:c}})()}};var RedisDatastore_1=RedisDatastore,BottleneckError,States;BottleneckError=BottleneckError_1;States=class{constructor(r){this.status=r,this._jobs={},this.counts=this.status.map(function(){return 0})}next(r){var n,a;if(n=this._jobs[r],a=n+1,n!=null&&a<this.status.length)return this.counts[n]--,this.counts[a]++,this._jobs[r]++;if(n!=null)return this.counts[n]--,delete this._jobs[r]}start(r){var n;return n=0,this._jobs[r]=n,this.counts[n]++}remove(r){var n;return n=this._jobs[r],n!=null&&(this.counts[n]--,delete this._jobs[r]),n!=null}jobStatus(r){var n;return(n=this.status[this._jobs[r]])!=null?n:null}statusJobs(r){var n,a,c,l,u;if(r!=null){if(a=this.status.indexOf(r),a<0)throw new BottleneckError(`status must be one of ${this.status.join(", ")}`);c=this._jobs,l=[];for(n in c)u=c[n],u===a&&l.push(n);return l}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((r,n,a)=>(r[this.status[a]]=n,r),{})}};var States_1=States;function asyncGeneratorStep(o,r,n,a,c,l,u){try{var d=o[l](u),h=d.value}catch(f){n(f);return}d.done?r(h):Promise.resolve(h).then(a,c)}function _asyncToGenerator(o){return function(){var r=this,n=arguments;return new Promise(function(a,c){var l=o.apply(r,n);function u(h){asyncGeneratorStep(l,a,c,u,d,"next",h)}function d(h){asyncGeneratorStep(l,a,c,u,d,"throw",h)}u(void 0)})}}var DLList,Sync;DLList=DLList_1;Sync=class{constructor(r,n){this.schedule=this.schedule.bind(this),this.name=r,this.Promise=n,this._running=0,this._queue=new DLList}isEmpty(){return this._queue.length===0}_tryToRun(){var r=this;return _asyncToGenerator(function*(){var n,a,c,l,u,d,h;if(r._running<1&&r._queue.length>0){r._running++;var f=r._queue.shift();return h=f.task,n=f.args,u=f.resolve,l=f.reject,a=yield _asyncToGenerator(function*(){try{return d=yield h(...n),function(){return u(d)}}catch(y){return c=y,function(){return l(c)}}})(),r._running--,r._tryToRun(),a()}})()}schedule(r,...n){var a,c,l;return l=c=null,a=new this.Promise(function(u,d){return l=u,c=d}),this._queue.push({task:r,args:n,resolve:l,reject:c}),this._tryToRun(),a}};var Sync_1=Sync;const version="2.19.5",require$$8={version};var Group_1,hasRequiredGroup;function requireGroup(){if(hasRequiredGroup)return Group_1;hasRequiredGroup=1;function o(T,I){return a(T)||n(T,I)||r()}function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function n(T,I){var b=[],R=!0,$=!1,g=void 0;try{for(var k=T[Symbol.iterator](),O;!(R=(O=k.next()).done)&&(b.push(O.value),!(I&&b.length===I));R=!0);}catch(P){$=!0,g=P}finally{try{!R&&k.return!=null&&k.return()}finally{if($)throw g}}return b}function a(T){if(Array.isArray(T))return T}function c(T,I,b,R,$,g,k){try{var O=T[g](k),P=O.value}catch(U){b(U);return}O.done?I(P):Promise.resolve(P).then(R,$)}function l(T){return function(){var I=this,b=arguments;return new Promise(function(R,$){var g=T.apply(I,b);function k(P){c(g,R,$,k,O,"next",P)}function O(P){c(g,R,$,k,O,"throw",P)}k(void 0)})}}var u,d,h,f,y,v;return v=parser$5,u=Events_1,f=RedisConnection_1,h=IORedisConnection_1,y=Scripts$2,d=(function(){class T{constructor(b={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=b,v.load(this.limiterOptions,this.defaults,this),this.Events=new u(this),this.instances={},this.Bottleneck=requireBottleneck(),this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new f(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new h(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(b=""){var R;return(R=this.instances[b])!=null?R:(()=>{var $;return $=this.instances[b]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${b}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",$,b),$})()}deleteKey(b=""){var R=this;return l(function*(){var $,g;return g=R.instances[b],R.connection&&($=yield R.connection.__runCommand__(["del",...y.allKeys(`${R.id}-${b}`)])),g!=null&&(delete R.instances[b],yield g.disconnect()),g!=null||$>0})()}limiters(){var b,R,$,g;R=this.instances,$=[];for(b in R)g=R[b],$.push({key:b,limiter:g});return $}keys(){return Object.keys(this.instances)}clusterKeys(){var b=this;return l(function*(){var R,$,g,k,O,P,U,m,w;if(b.connection==null)return b.Promise.resolve(b.keys());for(P=[],R=null,w=`b_${b.id}-`.length,$=9;R!==0;){var D=yield b.connection.__runCommand__(["scan",R??0,"match",`b_${b.id}-*_settings`,"count",1e4]),G=o(D,2);for(m=G[0],g=G[1],R=~~m,k=0,U=g.length;k<U;k++)O=g[k],P.push(O.slice(w,-$))}return P})()}_startAutoCleanup(){var b=this,R;return clearInterval(this.interval),typeof(R=this.interval=setInterval(l(function*(){var $,g,k,O,P,U;P=Date.now(),k=b.instances,O=[];for(g in k){U=k[g];try{(yield U._store.__groupCheck__(P))?O.push(b.deleteKey(g)):O.push(void 0)}catch(m){$=m,O.push(U.Events.trigger("error",$))}}return O}),this.timeout/2)).unref=="function"?R.unref():void 0}updateSettings(b={}){if(v.overwrite(b,this.defaults,this),v.overwrite(b,b,this.limiterOptions),b.timeout!=null)return this._startAutoCleanup()}disconnect(b=!0){var R;if(!this.sharedConnection)return(R=this.connection)!=null?R.disconnect(b):void 0}}return T.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},T}).call(void 0),Group_1=d,Group_1}var Batcher_1,hasRequiredBatcher;function requireBatcher(){if(hasRequiredBatcher)return Batcher_1;hasRequiredBatcher=1;var o,r,n;return n=parser$5,r=Events_1,o=(function(){class a{constructor(l={}){this.options=l,n.load(this.options,this.defaults,this),this.Events=new r(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((l,u)=>this._resolve=l)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(l){var u;return this._arr.push(l),u=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),u}}return a.prototype.defaults={maxTime:null,maxSize:null,Promise},a}).call(void 0),Batcher_1=o,Batcher_1}var Bottleneck_1,hasRequiredBottleneck;function requireBottleneck(){if(hasRequiredBottleneck)return Bottleneck_1;hasRequiredBottleneck=1;function o(P,U){return l(P)||r(P,U)||a()}function r(P,U){var m=[],w=!0,D=!1,G=void 0;try{for(var B=P[Symbol.iterator](),V;!(w=(V=B.next()).done)&&(m.push(V.value),!(U&&m.length===U));w=!0);}catch(z){D=!0,G=z}finally{try{!w&&B.return!=null&&B.return()}finally{if(D)throw G}}return m}function n(P){return l(P)||c(P)||a()}function a(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function c(P){if(Symbol.iterator in Object(P)||Object.prototype.toString.call(P)==="[object Arguments]")return Array.from(P)}function l(P){if(Array.isArray(P))return P}function u(P,U,m,w,D,G,B){try{var V=P[G](B),z=V.value}catch(te){m(te);return}V.done?U(z):Promise.resolve(z).then(w,D)}function d(P){return function(){var U=this,m=arguments;return new Promise(function(w,D){var G=P.apply(U,m);function B(z){u(G,w,D,B,V,"next",z)}function V(z){u(G,w,D,B,V,"throw",z)}B(void 0)})}}var h,f,y,v,T,I,b,R,$,g,k,O=[].splice;return I=10,f=5,k=parser$5,b=Queues_1,v=Job_1,T=LocalDatastore_1,R=RedisDatastore_1,y=Events_1,$=States_1,g=Sync_1,h=(function(){class P{constructor(m={},...w){var D,G;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(m,w),k.load(m,this.instanceDefaults,this),this._queues=new b(I),this._scheduled={},this._states=new $(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new y(this),this._submitLock=new g("submit",this.Promise),this._registerLock=new g("register",this.Promise),G=k.load(m,this.storeDefaults,{}),this._store=(function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return D=k.load(m,this.redisStoreDefaults,{}),new R(this,G,D);if(this.datastore==="local")return D=k.load(m,this.localStoreDefaults,{}),new T(this,G,D);throw new P.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}).call(this),this._queues.on("leftzero",()=>{var B;return(B=this._store.heartbeat)!=null&&typeof B.ref=="function"?B.ref():void 0}),this._queues.on("zero",()=>{var B;return(B=this._store.heartbeat)!=null&&typeof B.unref=="function"?B.unref():void 0})}_validateOptions(m,w){if(!(m!=null&&typeof m=="object"&&w.length===0))throw new P.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(m){return this._store.__publish__(m)}disconnect(m=!0){return this._store.__disconnect__(m)}chain(m){return this._limiter=m,this}queued(m){return this._queues.queued(m)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(m){return this._states.jobStatus(m)}jobs(m){return this._states.statusJobs(m)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(m=1){return this._store.__check__(m)}_clearGlobalState(m){return this._scheduled[m]!=null?(clearTimeout(this._scheduled[m].expiration),delete this._scheduled[m],!0):!1}_free(m,w,D,G){var B=this;return d(function*(){var V,z;try{var te=yield B._store.__free__(m,D.weight);if(z=te.running,B.Events.trigger("debug",`Freed ${D.id}`,G),z===0&&B.empty())return B.Events.trigger("idle")}catch(Z){return V=Z,B.Events.trigger("error",V)}})()}_run(m,w,D){var G,B,V;return w.doRun(),G=this._clearGlobalState.bind(this,m),V=this._run.bind(this,m,w),B=this._free.bind(this,m,w),this._scheduled[m]={timeout:setTimeout(()=>w.doExecute(this._limiter,G,V,B),D),expiration:w.options.expiration!=null?setTimeout(function(){return w.doExpire(G,V,B)},D+w.options.expiration):void 0,job:w}}_drainOne(m){return this._registerLock.schedule(()=>{var w,D,G,B,V;if(this.queued()===0)return this.Promise.resolve(null);V=this._queues.getFirst();var z=G=V.first();return B=z.options,w=z.args,m!=null&&B.weight>m?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${B.id}`,{args:w,options:B}),D=this._randomIndex(),this._store.__register__(D,B.weight,B.expiration).then(({success:te,wait:Z,reservoir:he})=>{var ue;return this.Events.trigger("debug",`Drained ${B.id}`,{success:te,args:w,options:B}),te?(V.shift(),ue=this.empty(),ue&&this.Events.trigger("empty"),he===0&&this.Events.trigger("depleted",ue),this._run(D,G,Z),this.Promise.resolve(B.weight)):this.Promise.resolve(null)}))})}_drainAll(m,w=0){return this._drainOne(m).then(D=>{var G;return D!=null?(G=m!=null?m-D:m,this._drainAll(G,w+D)):this.Promise.resolve(w)}).catch(D=>this.Events.trigger("error",D))}_dropAllQueued(m){return this._queues.shiftAll(function(w){return w.doDrop({message:m})})}stop(m={}){var w,D;return m=k.load(m,this.stopDefaults),D=G=>{var B;return B=()=>{var V;return V=this._states.counts,V[0]+V[1]+V[2]+V[3]===G},new this.Promise((V,z)=>B()?V():this.on("done",()=>{if(B())return this.removeAllListeners("done"),V()}))},w=m.dropWaitingJobs?(this._run=function(G,B){return B.doDrop({message:m.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var G,B,V;B=this._scheduled;for(G in B)V=B[G],this.jobStatus(V.job.options.id)==="RUNNING"&&(clearTimeout(V.timeout),clearTimeout(V.expiration),V.job.doDrop({message:m.dropErrorMessage}));return this._dropAllQueued(m.dropErrorMessage),D(0)}))):this.schedule({priority:I-1,weight:0},()=>D(1)),this._receive=function(G){return G._reject(new P.prototype.BottleneckError(m.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new P.prototype.BottleneckError("stop() has already been called")),w}_addToQueue(m){var w=this;return d(function*(){var D,G,B,V,z,te,Z;D=m.args,V=m.options;try{var he=yield w._store.__submit__(w.queued(),V.weight);z=he.reachedHWM,G=he.blocked,Z=he.strategy}catch(ue){return B=ue,w.Events.trigger("debug",`Could not queue ${V.id}`,{args:D,options:V,error:B}),m.doDrop({error:B}),!1}return G?(m.doDrop(),!0):z&&(te=Z===P.prototype.strategy.LEAK?w._queues.shiftLastFrom(V.priority):Z===P.prototype.strategy.OVERFLOW_PRIORITY?w._queues.shiftLastFrom(V.priority+1):Z===P.prototype.strategy.OVERFLOW?m:void 0,te!=null&&te.doDrop(),te==null||Z===P.prototype.strategy.OVERFLOW)?(te==null&&m.doDrop(),z):(m.doQueue(z,G),w._queues.push(m),yield w._drainAll(),z)})()}_receive(m){return this._states.jobStatus(m.options.id)!=null?(m._reject(new P.prototype.BottleneckError(`A job with the same id already exists (id=${m.options.id})`)),!1):(m.doReceive(),this._submitLock.schedule(this._addToQueue,m))}submit(...m){var w,D,G,B,V,z,te;if(typeof m[0]=="function"){var Z,he,ue,me;V=m,Z=V,he=n(Z),D=he[0],m=he.slice(1),ue=O.call(m,-1),me=o(ue,1),w=me[0],B=k.load({},this.jobDefaults)}else{var ye,J,F,A;z=m,ye=z,J=n(ye),B=J[0],D=J[1],m=J.slice(2),F=O.call(m,-1),A=o(F,1),w=A[0],B=k.load(B,this.jobDefaults)}return te=(...M)=>new this.Promise(function(N,p){return D(...M,function(...E){return(E[0]!=null?p:N)(E)})}),G=new v(te,m,B,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),G.promise.then(function(M){return typeof w=="function"?w(...M):void 0}).catch(function(M){return Array.isArray(M)?typeof w=="function"?w(...M):void 0:typeof w=="function"?w(M):void 0}),this._receive(G)}schedule(...m){var w,D,G;if(typeof m[0]=="function"){var B=m,V=n(B);G=V[0],m=V.slice(1),D={}}else{var z=m,te=n(z);D=te[0],G=te[1],m=te.slice(2)}return w=new v(G,m,D,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(w),w.promise}wrap(m){var w,D;return w=this.schedule.bind(this),D=function(...B){return w(m.bind(this),...B)},D.withOptions=function(G,...B){return w(G,m,...B)},D}updateSettings(m={}){var w=this;return d(function*(){return yield w._store.__updateSettings__(k.overwrite(m,w.storeDefaults)),k.overwrite(m,w.instanceDefaults,w),w})()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(m=0){return this._store.__incrementReservoir__(m)}}return P.default=P,P.Events=y,P.version=P.prototype.version=require$$8.version,P.strategy=P.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},P.BottleneckError=P.prototype.BottleneckError=BottleneckError_1,P.Group=P.prototype.Group=requireGroup(),P.RedisConnection=P.prototype.RedisConnection=RedisConnection_1,P.IORedisConnection=P.prototype.IORedisConnection=IORedisConnection_1,P.Batcher=P.prototype.Batcher=requireBatcher(),P.prototype.jobDefaults={priority:f,weight:1,expiration:null,id:"<no-id>"},P.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:P.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},P.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},P.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},P.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},P.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},P}).call(void 0),Bottleneck_1=h,Bottleneck_1}requireBottleneck();const nanoid=customAlphabet("abcdefghijklmnopqrstuvwxyz"),newId=()=>nanoid(15);var ajv={exports:{}},core$2={},validate={},boolSchema={},errors={},codegen={},code$1={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.regexpCode=o.getEsmExportName=o.getProperty=o.safeStringify=o.stringify=o.strConcat=o.addCodeArg=o.str=o._=o.nil=o._Code=o.Name=o.IDENTIFIER=o._CodeOrName=void 0;class r{}o._CodeOrName=r,o.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends r{constructor(k){if(super(),!o.IDENTIFIER.test(k))throw new Error("CodeGen: name must be a valid identifier");this.str=k}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}o.Name=n;class a extends r{constructor(k){super(),this._items=typeof k=="string"?[k]:k}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const k=this._items[0];return k===""||k==='""'}get str(){var k;return(k=this._str)!==null&&k!==void 0?k:this._str=this._items.reduce((O,P)=>`${O}${P}`,"")}get names(){var k;return(k=this._names)!==null&&k!==void 0?k:this._names=this._items.reduce((O,P)=>(P instanceof n&&(O[P.str]=(O[P.str]||0)+1),O),{})}}o._Code=a,o.nil=new a("");function c(g,...k){const O=[g[0]];let P=0;for(;P<k.length;)d(O,k[P]),O.push(g[++P]);return new a(O)}o._=c;const l=new a("+");function u(g,...k){const O=[I(g[0])];let P=0;for(;P<k.length;)O.push(l),d(O,k[P]),O.push(l,I(g[++P]));return h(O),new a(O)}o.str=u;function d(g,k){k instanceof a?g.push(...k._items):k instanceof n?g.push(k):g.push(v(k))}o.addCodeArg=d;function h(g){let k=1;for(;k<g.length-1;){if(g[k]===l){const O=f(g[k-1],g[k+1]);if(O!==void 0){g.splice(k-1,3,O);continue}g[k++]="+"}k++}}function f(g,k){if(k==='""')return g;if(g==='""')return k;if(typeof g=="string")return k instanceof n||g[g.length-1]!=='"'?void 0:typeof k!="string"?`${g.slice(0,-1)}${k}"`:k[0]==='"'?g.slice(0,-1)+k.slice(1):void 0;if(typeof k=="string"&&k[0]==='"'&&!(g instanceof n))return`"${g}${k.slice(1)}`}function y(g,k){return k.emptyStr()?g:g.emptyStr()?k:u`${g}${k}`}o.strConcat=y;function v(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:I(Array.isArray(g)?g.join(","):g)}function T(g){return new a(I(g))}o.stringify=T;function I(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o.safeStringify=I;function b(g){return typeof g=="string"&&o.IDENTIFIER.test(g)?new a(`.${g}`):c`[${g}]`}o.getProperty=b;function R(g){if(typeof g=="string"&&o.IDENTIFIER.test(g))return new a(`${g}`);throw new Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}o.getEsmExportName=R;function $(g){return new a(g.toString())}o.regexpCode=$})(code$1);var scope={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.ValueScope=o.ValueScopeName=o.Scope=o.varKinds=o.UsedValueState=void 0;const r=code$1;class n extends Error{constructor(f){super(`CodeGen: "code" for ${f} not defined`),this.value=f.value}}var a;(function(h){h[h.Started=0]="Started",h[h.Completed=1]="Completed"})(a=o.UsedValueState||(o.UsedValueState={})),o.varKinds={const:new r.Name("const"),let:new r.Name("let"),var:new r.Name("var")};class c{constructor({prefixes:f,parent:y}={}){this._names={},this._prefixes=f,this._parent=y}toName(f){return f instanceof r.Name?f:this.name(f)}name(f){return new r.Name(this._newName(f))}_newName(f){const y=this._names[f]||this._nameGroup(f);return`${f}${y.index++}`}_nameGroup(f){var y,v;if(!((v=(y=this._parent)===null||y===void 0?void 0:y._prefixes)===null||v===void 0)&&v.has(f)||this._prefixes&&!this._prefixes.has(f))throw new Error(`CodeGen: prefix "${f}" is not allowed in this scope`);return this._names[f]={prefix:f,index:0}}}o.Scope=c;class l extends r.Name{constructor(f,y){super(y),this.prefix=f}setValue(f,{property:y,itemIndex:v}){this.value=f,this.scopePath=(0,r._)`.${new r.Name(y)}[${v}]`}}o.ValueScopeName=l;const u=(0,r._)`\n`;class d extends c{constructor(f){super(f),this._values={},this._scope=f.scope,this.opts={...f,_n:f.lines?u:r.nil}}get(){return this._scope}name(f){return new l(f,this._newName(f))}value(f,y){var v;if(y.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const T=this.toName(f),{prefix:I}=T,b=(v=y.key)!==null&&v!==void 0?v:y.ref;let R=this._values[I];if(R){const k=R.get(b);if(k)return k}else R=this._values[I]=new Map;R.set(b,T);const $=this._scope[I]||(this._scope[I]=[]),g=$.length;return $[g]=y.ref,T.setValue(y,{property:I,itemIndex:g}),T}getValue(f,y){const v=this._values[f];if(v)return v.get(y)}scopeRefs(f,y=this._values){return this._reduceValues(y,v=>{if(v.scopePath===void 0)throw new Error(`CodeGen: name "${v}" has no value`);return(0,r._)`${f}${v.scopePath}`})}scopeCode(f=this._values,y,v){return this._reduceValues(f,T=>{if(T.value===void 0)throw new Error(`CodeGen: name "${T}" has no value`);return T.value.code},y,v)}_reduceValues(f,y,v={},T){let I=r.nil;for(const b in f){const R=f[b];if(!R)continue;const $=v[b]=v[b]||new Map;R.forEach(g=>{if($.has(g))return;$.set(g,a.Started);let k=y(g);if(k){const O=this.opts.es5?o.varKinds.var:o.varKinds.const;I=(0,r._)`${I}${O} ${g} = ${k};${this.opts._n}`}else if(k=T==null?void 0:T(g))I=(0,r._)`${I}${k}${this.opts._n}`;else throw new n(g);$.set(g,a.Completed)})}return I}}o.ValueScope=d})(scope);(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.or=o.and=o.not=o.CodeGen=o.operators=o.varKinds=o.ValueScopeName=o.ValueScope=o.Scope=o.Name=o.regexpCode=o.stringify=o.getProperty=o.nil=o.strConcat=o.str=o._=void 0;const r=code$1,n=scope;var a=code$1;Object.defineProperty(o,"_",{enumerable:!0,get:function(){return a._}}),Object.defineProperty(o,"str",{enumerable:!0,get:function(){return a.str}}),Object.defineProperty(o,"strConcat",{enumerable:!0,get:function(){return a.strConcat}}),Object.defineProperty(o,"nil",{enumerable:!0,get:function(){return a.nil}}),Object.defineProperty(o,"getProperty",{enumerable:!0,get:function(){return a.getProperty}}),Object.defineProperty(o,"stringify",{enumerable:!0,get:function(){return a.stringify}}),Object.defineProperty(o,"regexpCode",{enumerable:!0,get:function(){return a.regexpCode}}),Object.defineProperty(o,"Name",{enumerable:!0,get:function(){return a.Name}});var c=scope;Object.defineProperty(o,"Scope",{enumerable:!0,get:function(){return c.Scope}}),Object.defineProperty(o,"ValueScope",{enumerable:!0,get:function(){return c.ValueScope}}),Object.defineProperty(o,"ValueScopeName",{enumerable:!0,get:function(){return c.ValueScopeName}}),Object.defineProperty(o,"varKinds",{enumerable:!0,get:function(){return c.varKinds}}),o.operators={GT:new r._Code(">"),GTE:new r._Code(">="),LT:new r._Code("<"),LTE:new r._Code("<="),EQ:new r._Code("==="),NEQ:new r._Code("!=="),NOT:new r._Code("!"),OR:new r._Code("||"),AND:new r._Code("&&"),ADD:new r._Code("+")};class l{optimizeNodes(){return this}optimizeNames(p,E){return this}}class u extends l{constructor(p,E,q){super(),this.varKind=p,this.name=E,this.rhs=q}render({es5:p,_n:E}){const q=p?n.varKinds.var:this.varKind,x=this.rhs===void 0?"":` = ${this.rhs}`;return`${q} ${this.name}${x};`+E}optimizeNames(p,E){if(p[this.name.str])return this.rhs&&(this.rhs=Z(this.rhs,p,E)),this}get names(){return this.rhs instanceof r._CodeOrName?this.rhs.names:{}}}class d extends l{constructor(p,E,q){super(),this.lhs=p,this.rhs=E,this.sideEffects=q}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,E){if(!(this.lhs instanceof r.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=Z(this.rhs,p,E),this}get names(){const p=this.lhs instanceof r.Name?{}:{...this.lhs.names};return te(p,this.rhs)}}class h extends d{constructor(p,E,q,x){super(p,q,x),this.op=E}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}}class f extends l{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}}class y extends l{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}}class v extends l{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}}class T extends l{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,E){return this.code=Z(this.code,p,E),this}get names(){return this.code instanceof r._CodeOrName?this.code.names:{}}}class I extends l{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce((E,q)=>E+q.render(p),"")}optimizeNodes(){const{nodes:p}=this;let E=p.length;for(;E--;){const q=p[E].optimizeNodes();Array.isArray(q)?p.splice(E,1,...q):q?p[E]=q:p.splice(E,1)}return p.length>0?this:void 0}optimizeNames(p,E){const{nodes:q}=this;let x=q.length;for(;x--;){const K=q[x];K.optimizeNames(p,E)||(he(p,K.names),q.splice(x,1))}return q.length>0?this:void 0}get names(){return this.nodes.reduce((p,E)=>z(p,E.names),{})}}class b extends I{render(p){return"{"+p._n+super.render(p)+"}"+p._n}}class R extends I{}class $ extends b{}$.kind="else";class g extends b{constructor(p,E){super(E),this.condition=p}render(p){let E=`if(${this.condition})`+super.render(p);return this.else&&(E+="else "+this.else.render(p)),E}optimizeNodes(){super.optimizeNodes();const p=this.condition;if(p===!0)return this.nodes;let E=this.else;if(E){const q=E.optimizeNodes();E=this.else=Array.isArray(q)?new $(q):q}if(E)return p===!1?E instanceof g?E:E.nodes:this.nodes.length?this:new g(ue(p),E instanceof g?[E]:E.nodes);if(!(p===!1||!this.nodes.length))return this}optimizeNames(p,E){var q;if(this.else=(q=this.else)===null||q===void 0?void 0:q.optimizeNames(p,E),!!(super.optimizeNames(p,E)||this.else))return this.condition=Z(this.condition,p,E),this}get names(){const p=super.names;return te(p,this.condition),this.else&&z(p,this.else.names),p}}g.kind="if";class k extends b{}k.kind="for";class O extends k{constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,E){if(super.optimizeNames(p,E))return this.iteration=Z(this.iteration,p,E),this}get names(){return z(super.names,this.iteration.names)}}class P extends k{constructor(p,E,q,x){super(),this.varKind=p,this.name=E,this.from=q,this.to=x}render(p){const E=p.es5?n.varKinds.var:this.varKind,{name:q,from:x,to:K}=this;return`for(${E} ${q}=${x}; ${q}<${K}; ${q}++)`+super.render(p)}get names(){const p=te(super.names,this.from);return te(p,this.to)}}class U extends k{constructor(p,E,q,x){super(),this.loop=p,this.varKind=E,this.name=q,this.iterable=x}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,E){if(super.optimizeNames(p,E))return this.iterable=Z(this.iterable,p,E),this}get names(){return z(super.names,this.iterable.names)}}class m extends b{constructor(p,E,q){super(),this.name=p,this.args=E,this.async=q}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}}m.kind="func";class w extends I{render(p){return"return "+super.render(p)}}w.kind="return";class D extends b{render(p){let E="try"+super.render(p);return this.catch&&(E+=this.catch.render(p)),this.finally&&(E+=this.finally.render(p)),E}optimizeNodes(){var p,E;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),(E=this.finally)===null||E===void 0||E.optimizeNodes(),this}optimizeNames(p,E){var q,x;return super.optimizeNames(p,E),(q=this.catch)===null||q===void 0||q.optimizeNames(p,E),(x=this.finally)===null||x===void 0||x.optimizeNames(p,E),this}get names(){const p=super.names;return this.catch&&z(p,this.catch.names),this.finally&&z(p,this.finally.names),p}}class G extends b{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}}G.kind="catch";class B extends b{render(p){return"finally"+super.render(p)}}B.kind="finally";class V{constructor(p,E={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...E,_n:E.lines?`
`:""},this._extScope=p,this._scope=new n.Scope({parent:p}),this._nodes=[new R]}toString(){return this._root.render(this.opts)}name(p){return this._scope.name(p)}scopeName(p){return this._extScope.name(p)}scopeValue(p,E){const q=this._extScope.value(p,E);return(this._values[q.prefix]||(this._values[q.prefix]=new Set)).add(q),q}getScopeValue(p,E){return this._extScope.getValue(p,E)}scopeRefs(p){return this._extScope.scopeRefs(p,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(p,E,q,x){const K=this._scope.toName(E);return q!==void 0&&x&&(this._constants[K.str]=q),this._leafNode(new u(p,K,q)),K}const(p,E,q){return this._def(n.varKinds.const,p,E,q)}let(p,E,q){return this._def(n.varKinds.let,p,E,q)}var(p,E,q){return this._def(n.varKinds.var,p,E,q)}assign(p,E,q){return this._leafNode(new d(p,E,q))}add(p,E){return this._leafNode(new h(p,o.operators.ADD,E))}code(p){return typeof p=="function"?p():p!==r.nil&&this._leafNode(new T(p)),this}object(...p){const E=["{"];for(const[q,x]of p)E.length>1&&E.push(","),E.push(q),(q!==x||this.opts.es5)&&(E.push(":"),(0,r.addCodeArg)(E,x));return E.push("}"),new r._Code(E)}if(p,E,q){if(this._blockNode(new g(p)),E&&q)this.code(E).else().code(q).endIf();else if(E)this.code(E).endIf();else if(q)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(p){return this._elseNode(new g(p))}else(){return this._elseNode(new $)}endIf(){return this._endBlockNode(g,$)}_for(p,E){return this._blockNode(p),E&&this.code(E).endFor(),this}for(p,E){return this._for(new O(p),E)}forRange(p,E,q,x,K=this.opts.es5?n.varKinds.var:n.varKinds.let){const Y=this._scope.toName(p);return this._for(new P(K,Y,E,q),()=>x(Y))}forOf(p,E,q,x=n.varKinds.const){const K=this._scope.toName(p);if(this.opts.es5){const Y=E instanceof r.Name?E:this.var("_arr",E);return this.forRange("_i",0,(0,r._)`${Y}.length`,X=>{this.var(K,(0,r._)`${Y}[${X}]`),q(K)})}return this._for(new U("of",x,K,E),()=>q(K))}forIn(p,E,q,x=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(p,(0,r._)`Object.keys(${E})`,q);const K=this._scope.toName(p);return this._for(new U("in",x,K,E),()=>q(K))}endFor(){return this._endBlockNode(k)}label(p){return this._leafNode(new f(p))}break(p){return this._leafNode(new y(p))}return(p){const E=new w;if(this._blockNode(E),this.code(p),E.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(w)}try(p,E,q){if(!E&&!q)throw new Error('CodeGen: "try" without "catch" and "finally"');const x=new D;if(this._blockNode(x),this.code(p),E){const K=this.name("e");this._currNode=x.catch=new G(K),E(K)}return q&&(this._currNode=x.finally=new B,this.code(q)),this._endBlockNode(G,B)}throw(p){return this._leafNode(new v(p))}block(p,E){return this._blockStarts.push(this._nodes.length),p&&this.code(p).endBlock(E),this}endBlock(p){const E=this._blockStarts.pop();if(E===void 0)throw new Error("CodeGen: not in self-balancing block");const q=this._nodes.length-E;if(q<0||p!==void 0&&q!==p)throw new Error(`CodeGen: wrong number of nodes: ${q} vs ${p} expected`);return this._nodes.length=E,this}func(p,E=r.nil,q,x){return this._blockNode(new m(p,E,q)),x&&this.code(x).endFunc(),this}endFunc(){return this._endBlockNode(m)}optimize(p=1){for(;p-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(p){return this._currNode.nodes.push(p),this}_blockNode(p){this._currNode.nodes.push(p),this._nodes.push(p)}_endBlockNode(p,E){const q=this._currNode;if(q instanceof p||E&&q instanceof E)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${E?`${p.kind}/${E.kind}`:p.kind}"`)}_elseNode(p){const E=this._currNode;if(!(E instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=E.else=p,this}get _root(){return this._nodes[0]}get _currNode(){const p=this._nodes;return p[p.length-1]}set _currNode(p){const E=this._nodes;E[E.length-1]=p}}o.CodeGen=V;function z(N,p){for(const E in p)N[E]=(N[E]||0)+(p[E]||0);return N}function te(N,p){return p instanceof r._CodeOrName?z(N,p.names):N}function Z(N,p,E){if(N instanceof r.Name)return q(N);if(!x(N))return N;return new r._Code(N._items.reduce((K,Y)=>(Y instanceof r.Name&&(Y=q(Y)),Y instanceof r._Code?K.push(...Y._items):K.push(Y),K),[]));function q(K){const Y=E[K.str];return Y===void 0||p[K.str]!==1?K:(delete p[K.str],Y)}function x(K){return K instanceof r._Code&&K._items.some(Y=>Y instanceof r.Name&&p[Y.str]===1&&E[Y.str]!==void 0)}}function he(N,p){for(const E in p)N[E]=(N[E]||0)-(p[E]||0)}function ue(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,r._)`!${M(N)}`}o.not=ue;const me=A(o.operators.AND);function ye(...N){return N.reduce(me)}o.and=ye;const J=A(o.operators.OR);function F(...N){return N.reduce(J)}o.or=F;function A(N){return(p,E)=>p===r.nil?E:E===r.nil?p:(0,r._)`${M(p)} ${N} ${M(E)}`}function M(N){return N instanceof r.Name?N:(0,r._)`(${N})`}})(codegen);var util={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.checkStrictMode=o.getErrorPath=o.Type=o.useFunc=o.setEvaluated=o.evaluatedPropsToName=o.mergeEvaluated=o.eachItem=o.unescapeJsonPointer=o.escapeJsonPointer=o.escapeFragment=o.unescapeFragment=o.schemaRefOrVal=o.schemaHasRulesButRef=o.schemaHasRules=o.checkUnknownRules=o.alwaysValidSchema=o.toHash=void 0;const r=codegen,n=code$1;function a(m){const w={};for(const D of m)w[D]=!0;return w}o.toHash=a;function c(m,w){return typeof w=="boolean"?w:Object.keys(w).length===0?!0:(l(m,w),!u(w,m.self.RULES.all))}o.alwaysValidSchema=c;function l(m,w=m.schema){const{opts:D,self:G}=m;if(!D.strictSchema||typeof w=="boolean")return;const B=G.RULES.keywords;for(const V in w)B[V]||U(m,`unknown keyword: "${V}"`)}o.checkUnknownRules=l;function u(m,w){if(typeof m=="boolean")return!m;for(const D in m)if(w[D])return!0;return!1}o.schemaHasRules=u;function d(m,w){if(typeof m=="boolean")return!m;for(const D in m)if(D!=="$ref"&&w.all[D])return!0;return!1}o.schemaHasRulesButRef=d;function h({topSchemaRef:m,schemaPath:w},D,G,B){if(!B){if(typeof D=="number"||typeof D=="boolean")return D;if(typeof D=="string")return(0,r._)`${D}`}return(0,r._)`${m}${w}${(0,r.getProperty)(G)}`}o.schemaRefOrVal=h;function f(m){return T(decodeURIComponent(m))}o.unescapeFragment=f;function y(m){return encodeURIComponent(v(m))}o.escapeFragment=y;function v(m){return typeof m=="number"?`${m}`:m.replace(/~/g,"~0").replace(/\//g,"~1")}o.escapeJsonPointer=v;function T(m){return m.replace(/~1/g,"/").replace(/~0/g,"~")}o.unescapeJsonPointer=T;function I(m,w){if(Array.isArray(m))for(const D of m)w(D);else w(m)}o.eachItem=I;function b({mergeNames:m,mergeToName:w,mergeValues:D,resultToName:G}){return(B,V,z,te)=>{const Z=z===void 0?V:z instanceof r.Name?(V instanceof r.Name?m(B,V,z):w(B,V,z),z):V instanceof r.Name?(w(B,z,V),V):D(V,z);return te===r.Name&&!(Z instanceof r.Name)?G(B,Z):Z}}o.mergeEvaluated={props:b({mergeNames:(m,w,D)=>m.if((0,r._)`${D} !== true && ${w} !== undefined`,()=>{m.if((0,r._)`${w} === true`,()=>m.assign(D,!0),()=>m.assign(D,(0,r._)`${D} || {}`).code((0,r._)`Object.assign(${D}, ${w})`))}),mergeToName:(m,w,D)=>m.if((0,r._)`${D} !== true`,()=>{w===!0?m.assign(D,!0):(m.assign(D,(0,r._)`${D} || {}`),$(m,D,w))}),mergeValues:(m,w)=>m===!0?!0:{...m,...w},resultToName:R}),items:b({mergeNames:(m,w,D)=>m.if((0,r._)`${D} !== true && ${w} !== undefined`,()=>m.assign(D,(0,r._)`${w} === true ? true : ${D} > ${w} ? ${D} : ${w}`)),mergeToName:(m,w,D)=>m.if((0,r._)`${D} !== true`,()=>m.assign(D,w===!0?!0:(0,r._)`${D} > ${w} ? ${D} : ${w}`)),mergeValues:(m,w)=>m===!0?!0:Math.max(m,w),resultToName:(m,w)=>m.var("items",w)})};function R(m,w){if(w===!0)return m.var("props",!0);const D=m.var("props",(0,r._)`{}`);return w!==void 0&&$(m,D,w),D}o.evaluatedPropsToName=R;function $(m,w,D){Object.keys(D).forEach(G=>m.assign((0,r._)`${w}${(0,r.getProperty)(G)}`,!0))}o.setEvaluated=$;const g={};function k(m,w){return m.scopeValue("func",{ref:w,code:g[w.code]||(g[w.code]=new n._Code(w.code))})}o.useFunc=k;var O;(function(m){m[m.Num=0]="Num",m[m.Str=1]="Str"})(O=o.Type||(o.Type={}));function P(m,w,D){if(m instanceof r.Name){const G=w===O.Num;return D?G?(0,r._)`"[" + ${m} + "]"`:(0,r._)`"['" + ${m} + "']"`:G?(0,r._)`"/" + ${m}`:(0,r._)`"/" + ${m}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return D?(0,r.getProperty)(m).toString():"/"+v(m)}o.getErrorPath=P;function U(m,w,D=m.opts.strictSchema){if(D){if(w=`strict mode: ${w}`,D===!0)throw new Error(w);m.self.logger.warn(w)}}o.checkStrictMode=U})(util);var names$1={};Object.defineProperty(names$1,"__esModule",{value:!0});const codegen_1$t=codegen,names={data:new codegen_1$t.Name("data"),valCxt:new codegen_1$t.Name("valCxt"),instancePath:new codegen_1$t.Name("instancePath"),parentData:new codegen_1$t.Name("parentData"),parentDataProperty:new codegen_1$t.Name("parentDataProperty"),rootData:new codegen_1$t.Name("rootData"),dynamicAnchors:new codegen_1$t.Name("dynamicAnchors"),vErrors:new codegen_1$t.Name("vErrors"),errors:new codegen_1$t.Name("errors"),this:new codegen_1$t.Name("this"),self:new codegen_1$t.Name("self"),scope:new codegen_1$t.Name("scope"),json:new codegen_1$t.Name("json"),jsonPos:new codegen_1$t.Name("jsonPos"),jsonLen:new codegen_1$t.Name("jsonLen"),jsonPart:new codegen_1$t.Name("jsonPart")};names$1.default=names;(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.extendErrors=o.resetErrorsCount=o.reportExtraError=o.reportError=o.keyword$DataError=o.keywordError=void 0;const r=codegen,n=util,a=names$1;o.keywordError={message:({keyword:$})=>(0,r.str)`must pass "${$}" keyword validation`},o.keyword$DataError={message:({keyword:$,schemaType:g})=>g?(0,r.str)`"${$}" keyword must be ${g} ($data)`:(0,r.str)`"${$}" keyword is invalid ($data)`};function c($,g=o.keywordError,k,O){const{it:P}=$,{gen:U,compositeRule:m,allErrors:w}=P,D=v($,g,k);O??(m||w)?h(U,D):f(P,(0,r._)`[${D}]`)}o.reportError=c;function l($,g=o.keywordError,k){const{it:O}=$,{gen:P,compositeRule:U,allErrors:m}=O,w=v($,g,k);h(P,w),U||m||f(O,a.default.vErrors)}o.reportExtraError=l;function u($,g){$.assign(a.default.errors,g),$.if((0,r._)`${a.default.vErrors} !== null`,()=>$.if(g,()=>$.assign((0,r._)`${a.default.vErrors}.length`,g),()=>$.assign(a.default.vErrors,null)))}o.resetErrorsCount=u;function d({gen:$,keyword:g,schemaValue:k,data:O,errsCount:P,it:U}){if(P===void 0)throw new Error("ajv implementation error");const m=$.name("err");$.forRange("i",P,a.default.errors,w=>{$.const(m,(0,r._)`${a.default.vErrors}[${w}]`),$.if((0,r._)`${m}.instancePath === undefined`,()=>$.assign((0,r._)`${m}.instancePath`,(0,r.strConcat)(a.default.instancePath,U.errorPath))),$.assign((0,r._)`${m}.schemaPath`,(0,r.str)`${U.errSchemaPath}/${g}`),U.opts.verbose&&($.assign((0,r._)`${m}.schema`,k),$.assign((0,r._)`${m}.data`,O))})}o.extendErrors=d;function h($,g){const k=$.const("err",g);$.if((0,r._)`${a.default.vErrors} === null`,()=>$.assign(a.default.vErrors,(0,r._)`[${k}]`),(0,r._)`${a.default.vErrors}.push(${k})`),$.code((0,r._)`${a.default.errors}++`)}function f($,g){const{gen:k,validateName:O,schemaEnv:P}=$;P.$async?k.throw((0,r._)`new ${$.ValidationError}(${g})`):(k.assign((0,r._)`${O}.errors`,g),k.return(!1))}const y={keyword:new r.Name("keyword"),schemaPath:new r.Name("schemaPath"),params:new r.Name("params"),propertyName:new r.Name("propertyName"),message:new r.Name("message"),schema:new r.Name("schema"),parentSchema:new r.Name("parentSchema")};function v($,g,k){const{createErrors:O}=$.it;return O===!1?(0,r._)`{}`:T($,g,k)}function T($,g,k={}){const{gen:O,it:P}=$,U=[I(P,k),b($,k)];return R($,g,U),O.object(...U)}function I({errorPath:$},{instancePath:g}){const k=g?(0,r.str)`${$}${(0,n.getErrorPath)(g,n.Type.Str)}`:$;return[a.default.instancePath,(0,r.strConcat)(a.default.instancePath,k)]}function b({keyword:$,it:{errSchemaPath:g}},{schemaPath:k,parentSchema:O}){let P=O?g:(0,r.str)`${g}/${$}`;return k&&(P=(0,r.str)`${P}${(0,n.getErrorPath)(k,n.Type.Str)}`),[y.schemaPath,P]}function R($,{params:g,message:k},O){const{keyword:P,data:U,schemaValue:m,it:w}=$,{opts:D,propertyName:G,topSchemaRef:B,schemaPath:V}=w;O.push([y.keyword,P],[y.params,typeof g=="function"?g($):g||(0,r._)`{}`]),D.messages&&O.push([y.message,typeof k=="function"?k($):k]),D.verbose&&O.push([y.schema,m],[y.parentSchema,(0,r._)`${B}${V}`],[a.default.data,U]),G&&O.push([y.propertyName,G])}})(errors);Object.defineProperty(boolSchema,"__esModule",{value:!0});boolSchema.boolOrEmptySchema=boolSchema.topBoolOrEmptySchema=void 0;const errors_1$2=errors,codegen_1$s=codegen,names_1$6=names$1,boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(o){const{gen:r,schema:n,validateName:a}=o;n===!1?falseSchemaError(o,!1):typeof n=="object"&&n.$async===!0?r.return(names_1$6.default.data):(r.assign((0,codegen_1$s._)`${a}.errors`,null),r.return(!0))}boolSchema.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(o,r){const{gen:n,schema:a}=o;a===!1?(n.var(r,!1),falseSchemaError(o)):n.var(r,!0)}boolSchema.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(o,r){const{gen:n,data:a}=o,c={gen:n,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:o};(0,errors_1$2.reportError)(c,boolError,void 0,r)}var dataType={},rules={};Object.defineProperty(rules,"__esModule",{value:!0});rules.getRules=rules.isJSONType=void 0;const _jsonTypes=["string","number","integer","boolean","null","object","array"],jsonTypes=new Set(_jsonTypes);function isJSONType(o){return typeof o=="string"&&jsonTypes.has(o)}rules.isJSONType=isJSONType;function getRules(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}rules.getRules=getRules;var applicability={};Object.defineProperty(applicability,"__esModule",{value:!0});applicability.shouldUseRule=applicability.shouldUseGroup=applicability.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:o,self:r},n){const a=r.RULES.types[n];return a&&a!==!0&&shouldUseGroup(o,a)}applicability.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(o,r){return r.rules.some(n=>shouldUseRule(o,n))}applicability.shouldUseGroup=shouldUseGroup;function shouldUseRule(o,r){var n;return o[r.keyword]!==void 0||((n=r.definition.implements)===null||n===void 0?void 0:n.some(a=>o[a]!==void 0))}applicability.shouldUseRule=shouldUseRule;(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.reportTypeError=o.checkDataTypes=o.checkDataType=o.coerceAndCheckDataType=o.getJSONTypes=o.getSchemaTypes=o.DataType=void 0;const r=rules,n=applicability,a=errors,c=codegen,l=util;var u;(function(O){O[O.Correct=0]="Correct",O[O.Wrong=1]="Wrong"})(u=o.DataType||(o.DataType={}));function d(O){const P=h(O.type);if(P.includes("null")){if(O.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!P.length&&O.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');O.nullable===!0&&P.push("null")}return P}o.getSchemaTypes=d;function h(O){const P=Array.isArray(O)?O:O?[O]:[];if(P.every(r.isJSONType))return P;throw new Error("type must be JSONType or JSONType[]: "+P.join(","))}o.getJSONTypes=h;function f(O,P){const{gen:U,data:m,opts:w}=O,D=v(P,w.coerceTypes),G=P.length>0&&!(D.length===0&&P.length===1&&(0,n.schemaHasRulesForType)(O,P[0]));if(G){const B=R(P,m,w.strictNumbers,u.Wrong);U.if(B,()=>{D.length?T(O,P,D):g(O)})}return G}o.coerceAndCheckDataType=f;const y=new Set(["string","number","integer","boolean","null"]);function v(O,P){return P?O.filter(U=>y.has(U)||P==="array"&&U==="array"):[]}function T(O,P,U){const{gen:m,data:w,opts:D}=O,G=m.let("dataType",(0,c._)`typeof ${w}`),B=m.let("coerced",(0,c._)`undefined`);D.coerceTypes==="array"&&m.if((0,c._)`${G} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>m.assign(w,(0,c._)`${w}[0]`).assign(G,(0,c._)`typeof ${w}`).if(R(P,w,D.strictNumbers),()=>m.assign(B,w))),m.if((0,c._)`${B} !== undefined`);for(const z of U)(y.has(z)||z==="array"&&D.coerceTypes==="array")&&V(z);m.else(),g(O),m.endIf(),m.if((0,c._)`${B} !== undefined`,()=>{m.assign(w,B),I(O,B)});function V(z){switch(z){case"string":m.elseIf((0,c._)`${G} == "number" || ${G} == "boolean"`).assign(B,(0,c._)`"" + ${w}`).elseIf((0,c._)`${w} === null`).assign(B,(0,c._)`""`);return;case"number":m.elseIf((0,c._)`${G} == "boolean" || ${w} === null
|| (${G} == "string" && ${w} && ${w} == +${w})`).assign(B,(0,c._)`+${w}`);return;case"integer":m.elseIf((0,c._)`${G} === "boolean" || ${w} === null
|| (${G} === "string" && ${w} && ${w} == +${w} && !(${w} % 1))`).assign(B,(0,c._)`+${w}`);return;case"boolean":m.elseIf((0,c._)`${w} === "false" || ${w} === 0 || ${w} === null`).assign(B,!1).elseIf((0,c._)`${w} === "true" || ${w} === 1`).assign(B,!0);return;case"null":m.elseIf((0,c._)`${w} === "" || ${w} === 0 || ${w} === false`),m.assign(B,null);return;case"array":m.elseIf((0,c._)`${G} === "string" || ${G} === "number"
|| ${G} === "boolean" || ${w} === null`).assign(B,(0,c._)`[${w}]`)}}}function I({gen:O,parentData:P,parentDataProperty:U},m){O.if((0,c._)`${P} !== undefined`,()=>O.assign((0,c._)`${P}[${U}]`,m))}function b(O,P,U,m=u.Correct){const w=m===u.Correct?c.operators.EQ:c.operators.NEQ;let D;switch(O){case"null":return(0,c._)`${P} ${w} null`;case"array":D=(0,c._)`Array.isArray(${P})`;break;case"object":D=(0,c._)`${P} && typeof ${P} == "object" && !Array.isArray(${P})`;break;case"integer":D=G((0,c._)`!(${P} % 1) && !isNaN(${P})`);break;case"number":D=G();break;default:return(0,c._)`typeof ${P} ${w} ${O}`}return m===u.Correct?D:(0,c.not)(D);function G(B=c.nil){return(0,c.and)((0,c._)`typeof ${P} == "number"`,B,U?(0,c._)`isFinite(${P})`:c.nil)}}o.checkDataType=b;function R(O,P,U,m){if(O.length===1)return b(O[0],P,U,m);let w;const D=(0,l.toHash)(O);if(D.array&&D.object){const G=(0,c._)`typeof ${P} != "object"`;w=D.null?G:(0,c._)`!${P} || ${G}`,delete D.null,delete D.array,delete D.object}else w=c.nil;D.number&&delete D.integer;for(const G in D)w=(0,c.and)(w,b(G,P,U,m));return w}o.checkDataTypes=R;const $={message:({schema:O})=>`must be ${O}`,params:({schema:O,schemaValue:P})=>typeof O=="string"?(0,c._)`{type: ${O}}`:(0,c._)`{type: ${P}}`};function g(O){const P=k(O);(0,a.reportError)(P,$)}o.reportTypeError=g;function k(O){const{gen:P,data:U,schema:m}=O,w=(0,l.schemaRefOrVal)(O,m,"type");return{gen:P,keyword:"type",data:U,schema:m.type,schemaCode:w,schemaValue:w,parentSchema:m,params:{},it:O}}})(dataType);var defaults={};Object.defineProperty(defaults,"__esModule",{value:!0});defaults.assignDefaults=void 0;const codegen_1$r=codegen,util_1$p=util;function assignDefaults(o,r){const{properties:n,items:a}=o.schema;if(r==="object"&&n)for(const c in n)assignDefault(o,c,n[c].default);else r==="array"&&Array.isArray(a)&&a.forEach((c,l)=>assignDefault(o,l,c.default))}defaults.assignDefaults=assignDefaults;function assignDefault(o,r,n){const{gen:a,compositeRule:c,data:l,opts:u}=o;if(n===void 0)return;const d=(0,codegen_1$r._)`${l}${(0,codegen_1$r.getProperty)(r)}`;if(c){(0,util_1$p.checkStrictMode)(o,`default is ignored for: ${d}`);return}let h=(0,codegen_1$r._)`${d} === undefined`;u.useDefaults==="empty"&&(h=(0,codegen_1$r._)`${h} || ${d} === null || ${d} === ""`),a.if(h,(0,codegen_1$r._)`${d} = ${(0,codegen_1$r.stringify)(n)}`)}var keyword={},code={};Object.defineProperty(code,"__esModule",{value:!0});code.validateUnion=code.validateArray=code.usePattern=code.callValidateCode=code.schemaProperties=code.allSchemaProperties=code.noPropertyInData=code.propertyInData=code.isOwnProperty=code.hasPropFunc=code.reportMissingProp=code.checkMissingProp=code.checkReportMissingProp=void 0;const codegen_1$q=codegen,util_1$o=util,names_1$5=names$1,util_2$1=util;function checkReportMissingProp(o,r){const{gen:n,data:a,it:c}=o;n.if(noPropertyInData(n,a,r,c.opts.ownProperties),()=>{o.setParams({missingProperty:(0,codegen_1$q._)`${r}`},!0),o.error()})}code.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen:o,data:r,it:{opts:n}},a,c){return(0,codegen_1$q.or)(...a.map(l=>(0,codegen_1$q.and)(noPropertyInData(o,r,l,n.ownProperties),(0,codegen_1$q._)`${c} = ${l}`)))}code.checkMissingProp=checkMissingProp;function reportMissingProp(o,r){o.setParams({missingProperty:r},!0),o.error()}code.reportMissingProp=reportMissingProp;function hasPropFunc(o){return o.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,codegen_1$q._)`Object.prototype.hasOwnProperty`})}code.hasPropFunc=hasPropFunc;function isOwnProperty(o,r,n){return(0,codegen_1$q._)`${hasPropFunc(o)}.call(${r}, ${n})`}code.isOwnProperty=isOwnProperty;function propertyInData(o,r,n,a){const c=(0,codegen_1$q._)`${r}${(0,codegen_1$q.getProperty)(n)} !== undefined`;return a?(0,codegen_1$q._)`${c} && ${isOwnProperty(o,r,n)}`:c}code.propertyInData=propertyInData;function noPropertyInData(o,r,n,a){const c=(0,codegen_1$q._)`${r}${(0,codegen_1$q.getProperty)(n)} === undefined`;return a?(0,codegen_1$q.or)(c,(0,codegen_1$q.not)(isOwnProperty(o,r,n))):c}code.noPropertyInData=noPropertyInData;function allSchemaProperties(o){return o?Object.keys(o).filter(r=>r!=="__proto__"):[]}code.allSchemaProperties=allSchemaProperties;function schemaProperties(o,r){return allSchemaProperties(r).filter(n=>!(0,util_1$o.alwaysValidSchema)(o,r[n]))}code.schemaProperties=schemaProperties;function callValidateCode({schemaCode:o,data:r,it:{gen:n,topSchemaRef:a,schemaPath:c,errorPath:l},it:u},d,h,f){const y=f?(0,codegen_1$q._)`${o}, ${r}, ${a}${c}`:r,v=[[names_1$5.default.instancePath,(0,codegen_1$q.strConcat)(names_1$5.default.instancePath,l)],[names_1$5.default.parentData,u.parentData],[names_1$5.default.parentDataProperty,u.parentDataProperty],[names_1$5.default.rootData,names_1$5.default.rootData]];u.opts.dynamicRef&&v.push([names_1$5.default.dynamicAnchors,names_1$5.default.dynamicAnchors]);const T=(0,codegen_1$q._)`${y}, ${n.object(...v)}`;return h!==codegen_1$q.nil?(0,codegen_1$q._)`${d}.call(${h}, ${T})`:(0,codegen_1$q._)`${d}(${T})`}code.callValidateCode=callValidateCode;const newRegExp=(0,codegen_1$q._)`new RegExp`;function usePattern({gen:o,it:{opts:r}},n){const a=r.unicodeRegExp?"u":"",{regExp:c}=r.code,l=c(n,a);return o.scopeValue("pattern",{key:l.toString(),ref:l,code:(0,codegen_1$q._)`${c.code==="new RegExp"?newRegExp:(0,util_2$1.useFunc)(o,c)}(${n}, ${a})`})}code.usePattern=usePattern;function validateArray(o){const{gen:r,data:n,keyword:a,it:c}=o,l=r.name("valid");if(c.allErrors){const d=r.let("valid",!0);return u(()=>r.assign(d,!1)),d}return r.var(l,!0),u(()=>r.break()),l;function u(d){const h=r.const("len",(0,codegen_1$q._)`${n}.length`);r.forRange("i",0,h,f=>{o.subschema({keyword:a,dataProp:f,dataPropType:util_1$o.Type.Num},l),r.if((0,codegen_1$q.not)(l),d)})}}code.validateArray=validateArray;function validateUnion(o){const{gen:r,schema:n,keyword:a,it:c}=o;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(h=>(0,util_1$o.alwaysValidSchema)(c,h))&&!c.opts.unevaluated)return;const u=r.let("valid",!1),d=r.name("_valid");r.block(()=>n.forEach((h,f)=>{const y=o.subschema({keyword:a,schemaProp:f,compositeRule:!0},d);r.assign(u,(0,codegen_1$q._)`${u} || ${d}`),o.mergeValidEvaluated(y,d)||r.if((0,codegen_1$q.not)(u))})),o.result(u,()=>o.reset(),()=>o.error(!0))}code.validateUnion=validateUnion;Object.defineProperty(keyword,"__esModule",{value:!0});keyword.validateKeywordUsage=keyword.validSchemaType=keyword.funcKeywordCode=keyword.macroKeywordCode=void 0;const codegen_1$p=codegen,names_1$4=names$1,code_1$9=code,errors_1$1=errors;function macroKeywordCode(o,r){const{gen:n,keyword:a,schema:c,parentSchema:l,it:u}=o,d=r.macro.call(u.self,c,l,u),h=useKeyword(n,a,d);u.opts.validateSchema!==!1&&u.self.validateSchema(d,!0);const f=n.name("valid");o.subschema({schema:d,schemaPath:codegen_1$p.nil,errSchemaPath:`${u.errSchemaPath}/${a}`,topSchemaRef:h,compositeRule:!0},f),o.pass(f,()=>o.error(!0))}keyword.macroKeywordCode=macroKeywordCode;function funcKeywordCode(o,r){var n;const{gen:a,keyword:c,schema:l,parentSchema:u,$data:d,it:h}=o;checkAsyncKeyword(h,r);const f=!d&&r.compile?r.compile.call(h.self,l,u,h):r.validate,y=useKeyword(a,c,f),v=a.let("valid");o.block$data(v,T),o.ok((n=r.valid)!==null&&n!==void 0?n:v);function T(){if(r.errors===!1)R(),r.modifying&&modifyData(o),$(()=>o.error());else{const g=r.async?I():b();r.modifying&&modifyData(o),$(()=>addErrs(o,g))}}function I(){const g=a.let("ruleErrs",null);return a.try(()=>R((0,codegen_1$p._)`await `),k=>a.assign(v,!1).if((0,codegen_1$p._)`${k} instanceof ${h.ValidationError}`,()=>a.assign(g,(0,codegen_1$p._)`${k}.errors`),()=>a.throw(k))),g}function b(){const g=(0,codegen_1$p._)`${y}.errors`;return a.assign(g,null),R(codegen_1$p.nil),g}function R(g=r.async?(0,codegen_1$p._)`await `:codegen_1$p.nil){const k=h.opts.passContext?names_1$4.default.this:names_1$4.default.self,O=!("compile"in r&&!d||r.schema===!1);a.assign(v,(0,codegen_1$p._)`${g}${(0,code_1$9.callValidateCode)(o,y,k,O)}`,r.modifying)}function $(g){var k;a.if((0,codegen_1$p.not)((k=r.valid)!==null&&k!==void 0?k:v),g)}}keyword.funcKeywordCode=funcKeywordCode;function modifyData(o){const{gen:r,data:n,it:a}=o;r.if(a.parentData,()=>r.assign(n,(0,codegen_1$p._)`${a.parentData}[${a.parentDataProperty}]`))}function addErrs(o,r){const{gen:n}=o;n.if((0,codegen_1$p._)`Array.isArray(${r})`,()=>{n.assign(names_1$4.default.vErrors,(0,codegen_1$p._)`${names_1$4.default.vErrors} === null ? ${r} : ${names_1$4.default.vErrors}.concat(${r})`).assign(names_1$4.default.errors,(0,codegen_1$p._)`${names_1$4.default.vErrors}.length`),(0,errors_1$1.extendErrors)(o)},()=>o.error())}function checkAsyncKeyword({schemaEnv:o},r){if(r.async&&!o.$async)throw new Error("async keyword in sync schema")}function useKeyword(o,r,n){if(n===void 0)throw new Error(`keyword "${r}" failed to compile`);return o.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,codegen_1$p.stringify)(n)})}function validSchemaType(o,r,n=!1){return!r.length||r.some(a=>a==="array"?Array.isArray(o):a==="object"?o&&typeof o=="object"&&!Array.isArray(o):typeof o==a||n&&typeof o>"u")}keyword.validSchemaType=validSchemaType;function validateKeywordUsage({schema:o,opts:r,self:n,errSchemaPath:a},c,l){if(Array.isArray(c.keyword)?!c.keyword.includes(l):c.keyword!==l)throw new Error("ajv implementation error");const u=c.dependencies;if(u!=null&&u.some(d=>!Object.prototype.hasOwnProperty.call(o,d)))throw new Error(`parent schema must have dependencies of ${l}: ${u.join(",")}`);if(c.validateSchema&&!c.validateSchema(o[l])){const h=`keyword "${l}" value is invalid at path "${a}": `+n.errorsText(c.validateSchema.errors);if(r.validateSchema==="log")n.logger.error(h);else throw new Error(h)}}keyword.validateKeywordUsage=validateKeywordUsage;var subschema={};Object.defineProperty(subschema,"__esModule",{value:!0});subschema.extendSubschemaMode=subschema.extendSubschemaData=subschema.getSubschema=void 0;const codegen_1$o=codegen,util_1$n=util;function getSubschema(o,{keyword:r,schemaProp:n,schema:a,schemaPath:c,errSchemaPath:l,topSchemaRef:u}){if(r!==void 0&&a!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(r!==void 0){const d=o.schema[r];return n===void 0?{schema:d,schemaPath:(0,codegen_1$o._)`${o.schemaPath}${(0,codegen_1$o.getProperty)(r)}`,errSchemaPath:`${o.errSchemaPath}/${r}`}:{schema:d[n],schemaPath:(0,codegen_1$o._)`${o.schemaPath}${(0,codegen_1$o.getProperty)(r)}${(0,codegen_1$o.getProperty)(n)}`,errSchemaPath:`${o.errSchemaPath}/${r}/${(0,util_1$n.escapeFragment)(n)}`}}if(a!==void 0){if(c===void 0||l===void 0||u===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:c,topSchemaRef:u,errSchemaPath:l}}throw new Error('either "keyword" or "schema" must be passed')}subschema.getSubschema=getSubschema;function extendSubschemaData(o,r,{dataProp:n,dataPropType:a,data:c,dataTypes:l,propertyName:u}){if(c!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=r;if(n!==void 0){const{errorPath:f,dataPathArr:y,opts:v}=r,T=d.let("data",(0,codegen_1$o._)`${r.data}${(0,codegen_1$o.getProperty)(n)}`,!0);h(T),o.errorPath=(0,codegen_1$o.str)`${f}${(0,util_1$n.getErrorPath)(n,a,v.jsPropertySyntax)}`,o.parentDataProperty=(0,codegen_1$o._)`${n}`,o.dataPathArr=[...y,o.parentDataProperty]}if(c!==void 0){const f=c instanceof codegen_1$o.Name?c:d.let("data",c,!0);h(f),u!==void 0&&(o.propertyName=u)}l&&(o.dataTypes=l);function h(f){o.data=f,o.dataLevel=r.dataLevel+1,o.dataTypes=[],r.definedProperties=new Set,o.parentData=r.data,o.dataNames=[...r.dataNames,f]}}subschema.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(o,{jtdDiscriminator:r,jtdMetadata:n,compositeRule:a,createErrors:c,allErrors:l}){a!==void 0&&(o.compositeRule=a),c!==void 0&&(o.createErrors=c),l!==void 0&&(o.allErrors=l),o.jtdDiscriminator=r,o.jtdMetadata=n}subschema.extendSubschemaMode=extendSubschemaMode;var resolve$1={},fastDeepEqual=function o(r,n){if(r===n)return!0;if(r&&n&&typeof r=="object"&&typeof n=="object"){if(r.constructor!==n.constructor)return!1;var a,c,l;if(Array.isArray(r)){if(a=r.length,a!=n.length)return!1;for(c=a;c--!==0;)if(!o(r[c],n[c]))return!1;return!0}if(r.constructor===RegExp)return r.source===n.source&&r.flags===n.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===n.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===n.toString();if(l=Object.keys(r),a=l.length,a!==Object.keys(n).length)return!1;for(c=a;c--!==0;)if(!Object.prototype.hasOwnProperty.call(n,l[c]))return!1;for(c=a;c--!==0;){var u=l[c];if(!o(r[u],n[u]))return!1}return!0}return r!==r&&n!==n},jsonSchemaTraverse={exports:{}},traverse$1=jsonSchemaTraverse.exports=function(o,r,n){typeof r=="function"&&(n=r,r={}),n=r.cb||n;var a=typeof n=="function"?n:n.pre||function(){},c=n.post||function(){};_traverse(r,a,c,o,"",o)};traverse$1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};traverse$1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};traverse$1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};traverse$1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(o,r,n,a,c,l,u,d,h,f){if(a&&typeof a=="object"&&!Array.isArray(a)){r(a,c,l,u,d,h,f);for(var y in a){var v=a[y];if(Array.isArray(v)){if(y in traverse$1.arrayKeywords)for(var T=0;T<v.length;T++)_traverse(o,r,n,v[T],c+"/"+y+"/"+T,l,c,y,a,T)}else if(y in traverse$1.propsKeywords){if(v&&typeof v=="object")for(var I in v)_traverse(o,r,n,v[I],c+"/"+y+"/"+escapeJsonPtr(I),l,c,y,a,I)}else(y in traverse$1.keywords||o.allKeys&&!(y in traverse$1.skipKeywords))&&_traverse(o,r,n,v,c+"/"+y,l,c,y,a)}n(a,c,l,u,d,h,f)}}function escapeJsonPtr(o){return o.replace(/~/g,"~0").replace(/\//g,"~1")}var jsonSchemaTraverseExports=jsonSchemaTraverse.exports;Object.defineProperty(resolve$1,"__esModule",{value:!0});resolve$1.getSchemaRefs=resolve$1.resolveUrl=resolve$1.normalizeId=resolve$1._getFullPath=resolve$1.getFullPath=resolve$1.inlineRef=void 0;const util_1$m=util,equal$2=fastDeepEqual,traverse=jsonSchemaTraverseExports,SIMPLE_INLINED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function inlineRef(o,r=!0){return typeof o=="boolean"?!0:r===!0?!hasRef(o):r?countKeys(o)<=r:!1}resolve$1.inlineRef=inlineRef;const REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(o){for(const r in o){if(REF_KEYWORDS.has(r))return!0;const n=o[r];if(Array.isArray(n)&&n.some(hasRef)||typeof n=="object"&&hasRef(n))return!0}return!1}function countKeys(o){let r=0;for(const n in o){if(n==="$ref")return 1/0;if(r++,!SIMPLE_INLINED.has(n)&&(typeof o[n]=="object"&&(0,util_1$m.eachItem)(o[n],a=>r+=countKeys(a)),r===1/0))return 1/0}return r}function getFullPath(o,r="",n){n!==!1&&(r=normalizeId(r));const a=o.parse(r);return _getFullPath(o,a)}resolve$1.getFullPath=getFullPath;function _getFullPath(o,r){return o.serialize(r).split("#")[0]+"#"}resolve$1._getFullPath=_getFullPath;const TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(o){return o?o.replace(TRAILING_SLASH_HASH,""):""}resolve$1.normalizeId=normalizeId;function resolveUrl(o,r,n){return n=normalizeId(n),o.resolve(r,n)}resolve$1.resolveUrl=resolveUrl;const ANCHOR=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(o,r){if(typeof o=="boolean")return{};const{schemaId:n,uriResolver:a}=this.opts,c=normalizeId(o[n]||r),l={"":c},u=getFullPath(a,c,!1),d={},h=new Set;return traverse(o,{allKeys:!0},(v,T,I,b)=>{if(b===void 0)return;const R=u+T;let $=l[b];typeof v[n]=="string"&&($=g.call(this,v[n])),k.call(this,v.$anchor),k.call(this,v.$dynamicAnchor),l[T]=$;function g(O){const P=this.opts.uriResolver.resolve;if(O=normalizeId($?P($,O):O),h.has(O))throw y(O);h.add(O);let U=this.refs[O];return typeof U=="string"&&(U=this.refs[U]),typeof U=="object"?f(v,U.schema,O):O!==normalizeId(R)&&(O[0]==="#"?(f(v,d[O],O),d[O]=v):this.refs[O]=R),O}function k(O){if(typeof O=="string"){if(!ANCHOR.test(O))throw new Error(`invalid anchor "${O}"`);g.call(this,`#${O}`)}}}),d;function f(v,T,I){if(T!==void 0&&!equal$2(v,T))throw y(I)}function y(v){return new Error(`reference "${v}" resolves to more than one schema`)}}resolve$1.getSchemaRefs=getSchemaRefs;Object.defineProperty(validate,"__esModule",{value:!0});validate.getData=validate.KeywordCxt=validate.validateFunctionCode=void 0;const boolSchema_1=boolSchema,dataType_1$1=dataType,applicability_1=applicability,dataType_2=dataType,defaults_1=defaults,keyword_1=keyword,subschema_1=subschema,codegen_1$n=codegen,names_1$3=names$1,resolve_1$2=resolve$1,util_1$l=util,errors_1=errors;function validateFunctionCode(o){if(isSchemaObj(o)&&(checkKeywords(o),schemaCxtHasRules(o))){topSchemaObjCode(o);return}validateFunction(o,()=>(0,boolSchema_1.topBoolOrEmptySchema)(o))}validate.validateFunctionCode=validateFunctionCode;function validateFunction({gen:o,validateName:r,schema:n,schemaEnv:a,opts:c},l){c.code.es5?o.func(r,(0,codegen_1$n._)`${names_1$3.default.data}, ${names_1$3.default.valCxt}`,a.$async,()=>{o.code((0,codegen_1$n._)`"use strict"; ${funcSourceUrl(n,c)}`),destructureValCxtES5(o,c),o.code(l)}):o.func(r,(0,codegen_1$n._)`${names_1$3.default.data}, ${destructureValCxt(c)}`,a.$async,()=>o.code(funcSourceUrl(n,c)).code(l))}function destructureValCxt(o){return(0,codegen_1$n._)`{${names_1$3.default.instancePath}="", ${names_1$3.default.parentData}, ${names_1$3.default.parentDataProperty}, ${names_1$3.default.rootData}=${names_1$3.default.data}${o.dynamicRef?(0,codegen_1$n._)`, ${names_1$3.default.dynamicAnchors}={}`:codegen_1$n.nil}}={}`}function destructureValCxtES5(o,r){o.if(names_1$3.default.valCxt,()=>{o.var(names_1$3.default.instancePath,(0,codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.instancePath}`),o.var(names_1$3.default.parentData,(0,codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.parentData}`),o.var(names_1$3.default.parentDataProperty,(0,codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.parentDataProperty}`),o.var(names_1$3.default.rootData,(0,codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.rootData}`),r.dynamicRef&&o.var(names_1$3.default.dynamicAnchors,(0,codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.dynamicAnchors}`)},()=>{o.var(names_1$3.default.instancePath,(0,codegen_1$n._)`""`),o.var(names_1$3.default.parentData,(0,codegen_1$n._)`undefined`),o.var(names_1$3.default.parentDataProperty,(0,codegen_1$n._)`undefined`),o.var(names_1$3.default.rootData,names_1$3.default.data),r.dynamicRef&&o.var(names_1$3.default.dynamicAnchors,(0,codegen_1$n._)`{}`)})}function topSchemaObjCode(o){const{schema:r,opts:n,gen:a}=o;validateFunction(o,()=>{n.$comment&&r.$comment&&commentKeyword(o),checkNoDefault(o),a.let(names_1$3.default.vErrors,null),a.let(names_1$3.default.errors,0),n.unevaluated&&resetEvaluated(o),typeAndKeywords(o),returnResults(o)})}function resetEvaluated(o){const{gen:r,validateName:n}=o;o.evaluated=r.const("evaluated",(0,codegen_1$n._)`${n}.evaluated`),r.if((0,codegen_1$n._)`${o.evaluated}.dynamicProps`,()=>r.assign((0,codegen_1$n._)`${o.evaluated}.props`,(0,codegen_1$n._)`undefined`)),r.if((0,codegen_1$n._)`${o.evaluated}.dynamicItems`,()=>r.assign((0,codegen_1$n._)`${o.evaluated}.items`,(0,codegen_1$n._)`undefined`))}function funcSourceUrl(o,r){const n=typeof o=="object"&&o[r.schemaId];return n&&(r.code.source||r.code.process)?(0,codegen_1$n._)`/*# sourceURL=${n} */`:codegen_1$n.nil}function subschemaCode(o,r){if(isSchemaObj(o)&&(checkKeywords(o),schemaCxtHasRules(o))){subSchemaObjCode(o,r);return}(0,boolSchema_1.boolOrEmptySchema)(o,r)}function schemaCxtHasRules({schema:o,self:r}){if(typeof o=="boolean")return!o;for(const n in o)if(r.RULES.all[n])return!0;return!1}function isSchemaObj(o){return typeof o.schema!="boolean"}function subSchemaObjCode(o,r){const{schema:n,gen:a,opts:c}=o;c.$comment&&n.$comment&&commentKeyword(o),updateContext(o),checkAsyncSchema(o);const l=a.const("_errs",names_1$3.default.errors);typeAndKeywords(o,l),a.var(r,(0,codegen_1$n._)`${l} === ${names_1$3.default.errors}`)}function checkKeywords(o){(0,util_1$l.checkUnknownRules)(o),checkRefsAndKeywords(o)}function typeAndKeywords(o,r){if(o.opts.jtd)return schemaKeywords(o,[],!1,r);const n=(0,dataType_1$1.getSchemaTypes)(o.schema),a=(0,dataType_1$1.coerceAndCheckDataType)(o,n);schemaKeywords(o,n,!a,r)}function checkRefsAndKeywords(o){const{schema:r,errSchemaPath:n,opts:a,self:c}=o;r.$ref&&a.ignoreKeywordsWithRef&&(0,util_1$l.schemaHasRulesButRef)(r,c.RULES)&&c.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function checkNoDefault(o){const{schema:r,opts:n}=o;r.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,util_1$l.checkStrictMode)(o,"default is ignored in the schema root")}function updateContext(o){const r=o.schema[o.opts.schemaId];r&&(o.baseId=(0,resolve_1$2.resolveUrl)(o.opts.uriResolver,o.baseId,r))}function checkAsyncSchema(o){if(o.schema.$async&&!o.schemaEnv.$async)throw new Error("async schema in sync schema")}function commentKeyword({gen:o,schemaEnv:r,schema:n,errSchemaPath:a,opts:c}){const l=n.$comment;if(c.$comment===!0)o.code((0,codegen_1$n._)`${names_1$3.default.self}.logger.log(${l})`);else if(typeof c.$comment=="function"){const u=(0,codegen_1$n.str)`${a}/$comment`,d=o.scopeValue("root",{ref:r.root});o.code((0,codegen_1$n._)`${names_1$3.default.self}.opts.$comment(${l}, ${u}, ${d}.schema)`)}}function returnResults(o){const{gen:r,schemaEnv:n,validateName:a,ValidationError:c,opts:l}=o;n.$async?r.if((0,codegen_1$n._)`${names_1$3.default.errors} === 0`,()=>r.return(names_1$3.default.data),()=>r.throw((0,codegen_1$n._)`new ${c}(${names_1$3.default.vErrors})`)):(r.assign((0,codegen_1$n._)`${a}.errors`,names_1$3.default.vErrors),l.unevaluated&&assignEvaluated(o),r.return((0,codegen_1$n._)`${names_1$3.default.errors} === 0`))}function assignEvaluated({gen:o,evaluated:r,props:n,items:a}){n instanceof codegen_1$n.Name&&o.assign((0,codegen_1$n._)`${r}.props`,n),a instanceof codegen_1$n.Name&&o.assign((0,codegen_1$n._)`${r}.items`,a)}function schemaKeywords(o,r,n,a){const{gen:c,schema:l,data:u,allErrors:d,opts:h,self:f}=o,{RULES:y}=f;if(l.$ref&&(h.ignoreKeywordsWithRef||!(0,util_1$l.schemaHasRulesButRef)(l,y))){c.block(()=>keywordCode(o,"$ref",y.all.$ref.definition));return}h.jtd||checkStrictTypes(o,r),c.block(()=>{for(const T of y.rules)v(T);v(y.post)});function v(T){(0,applicability_1.shouldUseGroup)(l,T)&&(T.type?(c.if((0,dataType_2.checkDataType)(T.type,u,h.strictNumbers)),iterateKeywords(o,T),r.length===1&&r[0]===T.type&&n&&(c.else(),(0,dataType_2.reportTypeError)(o)),c.endIf()):iterateKeywords(o,T),d||c.if((0,codegen_1$n._)`${names_1$3.default.errors} === ${a||0}`))}}function iterateKeywords(o,r){const{gen:n,schema:a,opts:{useDefaults:c}}=o;c&&(0,defaults_1.assignDefaults)(o,r.type),n.block(()=>{for(const l of r.rules)(0,applicability_1.shouldUseRule)(a,l)&&keywordCode(o,l.keyword,l.definition,r.type)})}function checkStrictTypes(o,r){o.schemaEnv.meta||!o.opts.strictTypes||(checkContextTypes(o,r),o.opts.allowUnionTypes||checkMultipleTypes(o,r),checkKeywordTypes(o,o.dataTypes))}function checkContextTypes(o,r){if(r.length){if(!o.dataTypes.length){o.dataTypes=r;return}r.forEach(n=>{includesType(o.dataTypes,n)||strictTypesError(o,`type "${n}" not allowed by context "${o.dataTypes.join(",")}"`)}),o.dataTypes=o.dataTypes.filter(n=>includesType(r,n))}}function checkMultipleTypes(o,r){r.length>1&&!(r.length===2&&r.includes("null"))&&strictTypesError(o,"use allowUnionTypes to allow union type keyword")}function checkKeywordTypes(o,r){const n=o.self.RULES.all;for(const a in n){const c=n[a];if(typeof c=="object"&&(0,applicability_1.shouldUseRule)(o.schema,c)){const{type:l}=c.definition;l.length&&!l.some(u=>hasApplicableType(r,u))&&strictTypesError(o,`missing type "${l.join(",")}" for keyword "${a}"`)}}}function hasApplicableType(o,r){return o.includes(r)||r==="number"&&o.includes("integer")}function includesType(o,r){return o.includes(r)||r==="integer"&&o.includes("number")}function strictTypesError(o,r){const n=o.schemaEnv.baseId+o.errSchemaPath;r+=` at "${n}" (strictTypes)`,(0,util_1$l.checkStrictMode)(o,r,o.opts.strictTypes)}class KeywordCxt{constructor(r,n,a){if((0,keyword_1.validateKeywordUsage)(r,n,a),this.gen=r.gen,this.allErrors=r.allErrors,this.keyword=a,this.data=r.data,this.schema=r.schema[a],this.$data=n.$data&&r.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,util_1$l.schemaRefOrVal)(r,this.schema,a,this.$data),this.schemaType=n.schemaType,this.parentSchema=r.schema,this.params={},this.it=r,this.def=n,this.$data)this.schemaCode=r.gen.const("vSchema",getData(this.$data,r));else if(this.schemaCode=this.schemaValue,!(0,keyword_1.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${a} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=r.gen.const("_errs",names_1$3.default.errors))}result(r,n,a){this.failResult((0,codegen_1$n.not)(r),n,a)}failResult(r,n,a){this.gen.if(r),a?a():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(r,n){this.failResult((0,codegen_1$n.not)(r),void 0,n)}fail(r){if(r===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(r),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(r){if(!this.$data)return this.fail(r);const{schemaCode:n}=this;this.fail((0,codegen_1$n._)`${n} !== undefined && (${(0,codegen_1$n.or)(this.invalid$data(),r)})`)}error(r,n,a){if(n){this.setParams(n),this._error(r,a),this.setParams({});return}this._error(r,a)}_error(r,n){(r?errors_1.reportExtraError:errors_1.reportError)(this,this.def.error,n)}$dataError(){(0,errors_1.reportError)(this,this.def.$dataError||errors_1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(r){this.allErrors||this.gen.if(r)}setParams(r,n){n?Object.assign(this.params,r):this.params=r}block$data(r,n,a=codegen_1$n.nil){this.gen.block(()=>{this.check$data(r,a),n()})}check$data(r=codegen_1$n.nil,n=codegen_1$n.nil){if(!this.$data)return;const{gen:a,schemaCode:c,schemaType:l,def:u}=this;a.if((0,codegen_1$n.or)((0,codegen_1$n._)`${c} === undefined`,n)),r!==codegen_1$n.nil&&a.assign(r,!0),(l.length||u.validateSchema)&&(a.elseIf(this.invalid$data()),this.$dataError(),r!==codegen_1$n.nil&&a.assign(r,!1)),a.else()}invalid$data(){const{gen:r,schemaCode:n,schemaType:a,def:c,it:l}=this;return(0,codegen_1$n.or)(u(),d());function u(){if(a.length){if(!(n instanceof codegen_1$n.Name))throw new Error("ajv implementation error");const h=Array.isArray(a)?a:[a];return(0,codegen_1$n._)`${(0,dataType_2.checkDataTypes)(h,n,l.opts.strictNumbers,dataType_2.DataType.Wrong)}`}return codegen_1$n.nil}function d(){if(c.validateSchema){const h=r.scopeValue("validate$data",{ref:c.validateSchema});return(0,codegen_1$n._)`!${h}(${n})`}return codegen_1$n.nil}}subschema(r,n){const a=(0,subschema_1.getSubschema)(this.it,r);(0,subschema_1.extendSubschemaData)(a,this.it,r),(0,subschema_1.extendSubschemaMode)(a,r);const c={...this.it,...a,items:void 0,props:void 0};return subschemaCode(c,n),c}mergeEvaluated(r,n){const{it:a,gen:c}=this;a.opts.unevaluated&&(a.props!==!0&&r.props!==void 0&&(a.props=util_1$l.mergeEvaluated.props(c,r.props,a.props,n)),a.items!==!0&&r.items!==void 0&&(a.items=util_1$l.mergeEvaluated.items(c,r.items,a.items,n)))}mergeValidEvaluated(r,n){const{it:a,gen:c}=this;if(a.opts.unevaluated&&(a.props!==!0||a.items!==!0))return c.if(n,()=>this.mergeEvaluated(r,codegen_1$n.Name)),!0}}validate.KeywordCxt=KeywordCxt;function keywordCode(o,r,n,a){const c=new KeywordCxt(o,n,r);"code"in n?n.code(c,a):c.$data&&n.validate?(0,keyword_1.funcKeywordCode)(c,n):"macro"in n?(0,keyword_1.macroKeywordCode)(c,n):(n.compile||n.validate)&&(0,keyword_1.funcKeywordCode)(c,n)}const JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/,RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData(o,{dataLevel:r,dataNames:n,dataPathArr:a}){let c,l;if(o==="")return names_1$3.default.rootData;if(o[0]==="/"){if(!JSON_POINTER.test(o))throw new Error(`Invalid JSON-pointer: ${o}`);c=o,l=names_1$3.default.rootData}else{const f=RELATIVE_JSON_POINTER.exec(o);if(!f)throw new Error(`Invalid JSON-pointer: ${o}`);const y=+f[1];if(c=f[2],c==="#"){if(y>=r)throw new Error(h("property/index",y));return a[r-y]}if(y>r)throw new Error(h("data",y));if(l=n[r-y],!c)return l}let u=l;const d=c.split("/");for(const f of d)f&&(l=(0,codegen_1$n._)`${l}${(0,codegen_1$n.getProperty)((0,util_1$l.unescapeJsonPointer)(f))}`,u=(0,codegen_1$n._)`${u} && ${l}`);return u;function h(f,y){return`Cannot access ${f} ${y} levels up, current level is ${r}`}}validate.getData=getData;var validation_error={};Object.defineProperty(validation_error,"__esModule",{value:!0});class ValidationError extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}validation_error.default=ValidationError;var ref_error={};Object.defineProperty(ref_error,"__esModule",{value:!0});const resolve_1$1=resolve$1;class MissingRefError extends Error{constructor(r,n,a,c){super(c||`can't resolve reference ${a} from id ${n}`),this.missingRef=(0,resolve_1$1.resolveUrl)(r,n,a),this.missingSchema=(0,resolve_1$1.normalizeId)((0,resolve_1$1.getFullPath)(r,this.missingRef))}}ref_error.default=MissingRefError;var compile={};Object.defineProperty(compile,"__esModule",{value:!0});compile.resolveSchema=compile.getCompilingSchema=compile.resolveRef=compile.compileSchema=compile.SchemaEnv=void 0;const codegen_1$m=codegen,validation_error_1=validation_error,names_1$2=names$1,resolve_1=resolve$1,util_1$k=util,validate_1$1=validate;class SchemaEnv{constructor(r){var n;this.refs={},this.dynamicAnchors={};let a;typeof r.schema=="object"&&(a=r.schema),this.schema=r.schema,this.schemaId=r.schemaId,this.root=r.root||this,this.baseId=(n=r.baseId)!==null&&n!==void 0?n:(0,resolve_1.normalizeId)(a==null?void 0:a[r.schemaId||"$id"]),this.schemaPath=r.schemaPath,this.localRefs=r.localRefs,this.meta=r.meta,this.$async=a==null?void 0:a.$async,this.refs={}}}compile.SchemaEnv=SchemaEnv;function compileSchema(o){const r=getCompilingSchema.call(this,o);if(r)return r;const n=(0,resolve_1.getFullPath)(this.opts.uriResolver,o.root.baseId),{es5:a,lines:c}=this.opts.code,{ownProperties:l}=this.opts,u=new codegen_1$m.CodeGen(this.scope,{es5:a,lines:c,ownProperties:l});let d;o.$async&&(d=u.scopeValue("Error",{ref:validation_error_1.default,code:(0,codegen_1$m._)`require("ajv/dist/runtime/validation_error").default`}));const h=u.scopeName("validate");o.validateName=h;const f={gen:u,allErrors:this.opts.allErrors,data:names_1$2.default.data,parentData:names_1$2.default.parentData,parentDataProperty:names_1$2.default.parentDataProperty,dataNames:[names_1$2.default.data],dataPathArr:[codegen_1$m.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:u.scopeValue("schema",this.opts.code.source===!0?{ref:o.schema,code:(0,codegen_1$m.stringify)(o.schema)}:{ref:o.schema}),validateName:h,ValidationError:d,schema:o.schema,schemaEnv:o,rootId:n,baseId:o.baseId||n,schemaPath:codegen_1$m.nil,errSchemaPath:o.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,codegen_1$m._)`""`,opts:this.opts,self:this};let y;try{this._compilations.add(o),(0,validate_1$1.validateFunctionCode)(f),u.optimize(this.opts.code.optimize);const v=u.toString();y=`${u.scopeRefs(names_1$2.default.scope)}return ${v}`,this.opts.code.process&&(y=this.opts.code.process(y,o));const I=new Function(`${names_1$2.default.self}`,`${names_1$2.default.scope}`,y)(this,this.scope.get());if(this.scope.value(h,{ref:I}),I.errors=null,I.schema=o.schema,I.schemaEnv=o,o.$async&&(I.$async=!0),this.opts.code.source===!0&&(I.source={validateName:h,validateCode:v,scopeValues:u._values}),this.opts.unevaluated){const{props:b,items:R}=f;I.evaluated={props:b instanceof codegen_1$m.Name?void 0:b,items:R instanceof codegen_1$m.Name?void 0:R,dynamicProps:b instanceof codegen_1$m.Name,dynamicItems:R instanceof codegen_1$m.Name},I.source&&(I.source.evaluated=(0,codegen_1$m.stringify)(I.evaluated))}return o.validate=I,o}catch(v){throw delete o.validate,delete o.validateName,y&&this.logger.error("Error compiling schema, function code:",y),v}finally{this._compilations.delete(o)}}compile.compileSchema=compileSchema;function resolveRef(o,r,n){var a;n=(0,resolve_1.resolveUrl)(this.opts.uriResolver,r,n);const c=o.refs[n];if(c)return c;let l=resolve.call(this,o,n);if(l===void 0){const u=(a=o.localRefs)===null||a===void 0?void 0:a[n],{schemaId:d}=this.opts;u&&(l=new SchemaEnv({schema:u,schemaId:d,root:o,baseId:r}))}if(l!==void 0)return o.refs[n]=inlineOrCompile.call(this,l)}compile.resolveRef=resolveRef;function inlineOrCompile(o){return(0,resolve_1.inlineRef)(o.schema,this.opts.inlineRefs)?o.schema:o.validate?o:compileSchema.call(this,o)}function getCompilingSchema(o){for(const r of this._compilations)if(sameSchemaEnv(r,o))return r}compile.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(o,r){return o.schema===r.schema&&o.root===r.root&&o.baseId===r.baseId}function resolve(o,r){let n;for(;typeof(n=this.refs[r])=="string";)r=n;return n||this.schemas[r]||resolveSchema.call(this,o,r)}function resolveSchema(o,r){const n=this.opts.uriResolver.parse(r),a=(0,resolve_1._getFullPath)(this.opts.uriResolver,n);let c=(0,resolve_1.getFullPath)(this.opts.uriResolver,o.baseId,void 0);if(Object.keys(o.schema).length>0&&a===c)return getJsonPointer.call(this,n,o);const l=(0,resolve_1.normalizeId)(a),u=this.refs[l]||this.schemas[l];if(typeof u=="string"){const d=resolveSchema.call(this,o,u);return typeof(d==null?void 0:d.schema)!="object"?void 0:getJsonPointer.call(this,n,d)}if(typeof(u==null?void 0:u.schema)=="object"){if(u.validate||compileSchema.call(this,u),l===(0,resolve_1.normalizeId)(r)){const{schema:d}=u,{schemaId:h}=this.opts,f=d[h];return f&&(c=(0,resolve_1.resolveUrl)(this.opts.uriResolver,c,f)),new SchemaEnv({schema:d,schemaId:h,root:o,baseId:c})}return getJsonPointer.call(this,n,u)}}compile.resolveSchema=resolveSchema;const PREVENT_SCOPE_CHANGE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(o,{baseId:r,schema:n,root:a}){var c;if(((c=o.fragment)===null||c===void 0?void 0:c[0])!=="/")return;for(const d of o.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const h=n[(0,util_1$k.unescapeFragment)(d)];if(h===void 0)return;n=h;const f=typeof n=="object"&&n[this.opts.schemaId];!PREVENT_SCOPE_CHANGE.has(d)&&f&&(r=(0,resolve_1.resolveUrl)(this.opts.uriResolver,r,f))}let l;if(typeof n!="boolean"&&n.$ref&&!(0,util_1$k.schemaHasRulesButRef)(n,this.RULES)){const d=(0,resolve_1.resolveUrl)(this.opts.uriResolver,r,n.$ref);l=resolveSchema.call(this,a,d)}const{schemaId:u}=this.opts;if(l=l||new SchemaEnv({schema:n,schemaId:u,root:a,baseId:r}),l.schema!==l.root.schema)return l}const $id$1="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description="Meta-schema for $data reference (JSON AnySchema extension proposal)",type$1="object",required$1=["$data"],properties$2={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties$1=!1,require$$9={$id:$id$1,description,type:type$1,required:required$1,properties:properties$2,additionalProperties:additionalProperties$1};var uri$1={},uri_all={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(o,r){(function(n,a){a(r)})(commonjsGlobal,function(n){function a(){for(var S=arguments.length,_=Array(S),C=0;C<S;C++)_[C]=arguments[C];if(_.length>1){_[0]=_[0].slice(0,-1);for(var L=_.length-1,j=1;j<L;++j)_[j]=_[j].slice(1,-1);return _[L]=_[L].slice(1),_.join("")}else return _[0]}function c(S){return"(?:"+S+")"}function l(S){return S===void 0?"undefined":S===null?"null":Object.prototype.toString.call(S).split(" ").pop().split("]").shift().toLowerCase()}function u(S){return S.toUpperCase()}function d(S){return S!=null?S instanceof Array?S:typeof S.length!="number"||S.split||S.setInterval||S.call?[S]:Array.prototype.slice.call(S):[]}function h(S,_){var C=S;if(_)for(var L in _)C[L]=_[L];return C}function f(S){var _="[A-Za-z]",C="[0-9]",L=a(C,"[A-Fa-f]"),j=c(c("%[EFef]"+L+"%"+L+L+"%"+L+L)+"|"+c("%[89A-Fa-f]"+L+"%"+L+L)+"|"+c("%"+L+L)),H="[\\:\\/\\?\\#\\[\\]\\@]",W="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",re=a(H,W),se=S?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",ce=S?"[\\uE000-\\uF8FF]":"[]",ee=a(_,C,"[\\-\\.\\_\\~]",se);c(_+a(_,C,"[\\+\\-\\.]")+"*"),c(c(j+"|"+a(ee,W,"[\\:]"))+"*");var ne=c(c("25[0-5]")+"|"+c("2[0-4]"+C)+"|"+c("1"+C+C)+"|"+c("0?[1-9]"+C)+"|0?0?"+C),le=c(ne+"\\."+ne+"\\."+ne+"\\."+ne),Q=c(L+"{1,4}"),ie=c(c(Q+"\\:"+Q)+"|"+le),de=c(c(Q+"\\:")+"{6}"+ie),oe=c("\\:\\:"+c(Q+"\\:")+"{5}"+ie),ke=c(c(Q)+"?\\:\\:"+c(Q+"\\:")+"{4}"+ie),we=c(c(c(Q+"\\:")+"{0,1}"+Q)+"?\\:\\:"+c(Q+"\\:")+"{3}"+ie),Se=c(c(c(Q+"\\:")+"{0,2}"+Q)+"?\\:\\:"+c(Q+"\\:")+"{2}"+ie),qe=c(c(c(Q+"\\:")+"{0,3}"+Q)+"?\\:\\:"+Q+"\\:"+ie),Oe=c(c(c(Q+"\\:")+"{0,4}"+Q)+"?\\:\\:"+ie),ge=c(c(c(Q+"\\:")+"{0,5}"+Q)+"?\\:\\:"+Q),Ee=c(c(c(Q+"\\:")+"{0,6}"+Q)+"?\\:\\:"),Te=c([de,oe,ke,we,Se,qe,Oe,ge,Ee].join("|")),Pe=c(c(ee+"|"+j)+"+");c("[vV]"+L+"+\\."+a(ee,W,"[\\:]")+"+"),c(c(j+"|"+a(ee,W))+"*");var Ke=c(j+"|"+a(ee,W,"[\\:\\@]"));return c(c(j+"|"+a(ee,W,"[\\@]"))+"+"),c(c(Ke+"|"+a("[\\/\\?]",ce))+"*"),{NOT_SCHEME:new RegExp(a("[^]",_,C,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",ee,W),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",ee,W),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",ee,W),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",ee,W),"g"),NOT_QUERY:new RegExp(a("[^\\%]",ee,W,"[\\:\\@\\/\\?]",ce),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",ee,W,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",ee,W),"g"),UNRESERVED:new RegExp(ee,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",ee,re),"g"),PCT_ENCODED:new RegExp(j,"g"),IPV4ADDRESS:new RegExp("^("+le+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Te+")"+c(c("\\%25|\\%(?!"+L+"{2})")+"("+Pe+")")+"?\\]?$")}}var y=f(!1),v=f(!0),T=function(){function S(_,C){var L=[],j=!0,H=!1,W=void 0;try{for(var re=_[Symbol.iterator](),se;!(j=(se=re.next()).done)&&(L.push(se.value),!(C&&L.length===C));j=!0);}catch(ce){H=!0,W=ce}finally{try{!j&&re.return&&re.return()}finally{if(H)throw W}}return L}return function(_,C){if(Array.isArray(_))return _;if(Symbol.iterator in Object(_))return S(_,C);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),I=function(S){if(Array.isArray(S)){for(var _=0,C=Array(S.length);_<S.length;_++)C[_]=S[_];return C}else return Array.from(S)},b=2147483647,R=36,$=1,g=26,k=38,O=700,P=72,U=128,m="-",w=/^xn--/,D=/[^\0-\x7E]/,G=/[\x2E\u3002\uFF0E\uFF61]/g,B={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},V=R-$,z=Math.floor,te=String.fromCharCode;function Z(S){throw new RangeError(B[S])}function he(S,_){for(var C=[],L=S.length;L--;)C[L]=_(S[L]);return C}function ue(S,_){var C=S.split("@"),L="";C.length>1&&(L=C[0]+"@",S=C[1]),S=S.replace(G,".");var j=S.split("."),H=he(j,_).join(".");return L+H}function me(S){for(var _=[],C=0,L=S.length;C<L;){var j=S.charCodeAt(C++);if(j>=55296&&j<=56319&&C<L){var H=S.charCodeAt(C++);(H&64512)==56320?_.push(((j&1023)<<10)+(H&1023)+65536):(_.push(j),C--)}else _.push(j)}return _}var ye=function(_){return String.fromCodePoint.apply(String,I(_))},J=function(_){return _-48<10?_-22:_-65<26?_-65:_-97<26?_-97:R},F=function(_,C){return _+22+75*(_<26)-((C!=0)<<5)},A=function(_,C,L){var j=0;for(_=L?z(_/O):_>>1,_+=z(_/C);_>V*g>>1;j+=R)_=z(_/V);return z(j+(V+1)*_/(_+k))},M=function(_){var C=[],L=_.length,j=0,H=U,W=P,re=_.lastIndexOf(m);re<0&&(re=0);for(var se=0;se<re;++se)_.charCodeAt(se)>=128&&Z("not-basic"),C.push(_.charCodeAt(se));for(var ce=re>0?re+1:0;ce<L;){for(var ee=j,ne=1,le=R;;le+=R){ce>=L&&Z("invalid-input");var Q=J(_.charCodeAt(ce++));(Q>=R||Q>z((b-j)/ne))&&Z("overflow"),j+=Q*ne;var ie=le<=W?$:le>=W+g?g:le-W;if(Q<ie)break;var de=R-ie;ne>z(b/de)&&Z("overflow"),ne*=de}var oe=C.length+1;W=A(j-ee,oe,ee==0),z(j/oe)>b-H&&Z("overflow"),H+=z(j/oe),j%=oe,C.splice(j++,0,H)}return String.fromCodePoint.apply(String,C)},N=function(_){var C=[];_=me(_);var L=_.length,j=U,H=0,W=P,re=!0,se=!1,ce=void 0;try{for(var ee=_[Symbol.iterator](),ne;!(re=(ne=ee.next()).done);re=!0){var le=ne.value;le<128&&C.push(te(le))}}catch(ze){se=!0,ce=ze}finally{try{!re&&ee.return&&ee.return()}finally{if(se)throw ce}}var Q=C.length,ie=Q;for(Q&&C.push(m);ie<L;){var de=b,oe=!0,ke=!1,we=void 0;try{for(var Se=_[Symbol.iterator](),qe;!(oe=(qe=Se.next()).done);oe=!0){var Oe=qe.value;Oe>=j&&Oe<de&&(de=Oe)}}catch(ze){ke=!0,we=ze}finally{try{!oe&&Se.return&&Se.return()}finally{if(ke)throw we}}var ge=ie+1;de-j>z((b-H)/ge)&&Z("overflow"),H+=(de-j)*ge,j=de;var Ee=!0,Te=!1,Pe=void 0;try{for(var Ke=_[Symbol.iterator](),ot;!(Ee=(ot=Ke.next()).done);Ee=!0){var at=ot.value;if(at<j&&++H>b&&Z("overflow"),at==j){for(var We=H,Je=R;;Je+=R){var Ye=Je<=W?$:Je>=W+g?g:Je-W;if(We<Ye)break;var ct=We-Ye,lt=R-Ye;C.push(te(F(Ye+ct%lt,0))),We=z(ct/lt)}C.push(te(F(We,0))),W=A(H,ge,ie==Q),H=0,++ie}}}catch(ze){Te=!0,Pe=ze}finally{try{!Ee&&Ke.return&&Ke.return()}finally{if(Te)throw Pe}}++H,++j}return C.join("")},p=function(_){return ue(_,function(C){return w.test(C)?M(C.slice(4).toLowerCase()):C})},E=function(_){return ue(_,function(C){return D.test(C)?"xn--"+N(C):C})},q={version:"2.1.0",ucs2:{decode:me,encode:ye},decode:M,encode:N,toASCII:E,toUnicode:p},x={};function K(S){var _=S.charCodeAt(0),C=void 0;return _<16?C="%0"+_.toString(16).toUpperCase():_<128?C="%"+_.toString(16).toUpperCase():_<2048?C="%"+(_>>6|192).toString(16).toUpperCase()+"%"+(_&63|128).toString(16).toUpperCase():C="%"+(_>>12|224).toString(16).toUpperCase()+"%"+(_>>6&63|128).toString(16).toUpperCase()+"%"+(_&63|128).toString(16).toUpperCase(),C}function Y(S){for(var _="",C=0,L=S.length;C<L;){var j=parseInt(S.substr(C+1,2),16);if(j<128)_+=String.fromCharCode(j),C+=3;else if(j>=194&&j<224){if(L-C>=6){var H=parseInt(S.substr(C+4,2),16);_+=String.fromCharCode((j&31)<<6|H&63)}else _+=S.substr(C,6);C+=6}else if(j>=224){if(L-C>=9){var W=parseInt(S.substr(C+4,2),16),re=parseInt(S.substr(C+7,2),16);_+=String.fromCharCode((j&15)<<12|(W&63)<<6|re&63)}else _+=S.substr(C,9);C+=9}else _+=S.substr(C,3),C+=3}return _}function X(S,_){function C(L){var j=Y(L);return j.match(_.UNRESERVED)?j:L}return S.scheme&&(S.scheme=String(S.scheme).replace(_.PCT_ENCODED,C).toLowerCase().replace(_.NOT_SCHEME,"")),S.userinfo!==void 0&&(S.userinfo=String(S.userinfo).replace(_.PCT_ENCODED,C).replace(_.NOT_USERINFO,K).replace(_.PCT_ENCODED,u)),S.host!==void 0&&(S.host=String(S.host).replace(_.PCT_ENCODED,C).toLowerCase().replace(_.NOT_HOST,K).replace(_.PCT_ENCODED,u)),S.path!==void 0&&(S.path=String(S.path).replace(_.PCT_ENCODED,C).replace(S.scheme?_.NOT_PATH:_.NOT_PATH_NOSCHEME,K).replace(_.PCT_ENCODED,u)),S.query!==void 0&&(S.query=String(S.query).replace(_.PCT_ENCODED,C).replace(_.NOT_QUERY,K).replace(_.PCT_ENCODED,u)),S.fragment!==void 0&&(S.fragment=String(S.fragment).replace(_.PCT_ENCODED,C).replace(_.NOT_FRAGMENT,K).replace(_.PCT_ENCODED,u)),S}function ae(S){return S.replace(/^0*(.*)/,"$1")||"0"}function ve(S,_){var C=S.match(_.IPV4ADDRESS)||[],L=T(C,2),j=L[1];return j?j.split(".").map(ae).join("."):S}function Ie(S,_){var C=S.match(_.IPV6ADDRESS)||[],L=T(C,3),j=L[1],H=L[2];if(j){for(var W=j.toLowerCase().split("::").reverse(),re=T(W,2),se=re[0],ce=re[1],ee=ce?ce.split(":").map(ae):[],ne=se.split(":").map(ae),le=_.IPV4ADDRESS.test(ne[ne.length-1]),Q=le?7:8,ie=ne.length-Q,de=Array(Q),oe=0;oe<Q;++oe)de[oe]=ee[oe]||ne[ie+oe]||"";le&&(de[Q-1]=ve(de[Q-1],_));var ke=de.reduce(function(ge,Ee,Te){if(!Ee||Ee==="0"){var Pe=ge[ge.length-1];Pe&&Pe.index+Pe.length===Te?Pe.length++:ge.push({index:Te,length:1})}return ge},[]),we=ke.sort(function(ge,Ee){return Ee.length-ge.length})[0],Se=void 0;if(we&&we.length>1){var qe=de.slice(0,we.index),Oe=de.slice(we.index+we.length);Se=qe.join(":")+"::"+Oe.join(":")}else Se=de.join(":");return H&&(Se+="%"+H),Se}else return S}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ue="".match(/(){0}/)[1]===void 0;function pe(S){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C={},L=_.iri!==!1?v:y;_.reference==="suffix"&&(S=(_.scheme?_.scheme+":":"")+"//"+S);var j=S.match(Me);if(j){Ue?(C.scheme=j[1],C.userinfo=j[3],C.host=j[4],C.port=parseInt(j[5],10),C.path=j[6]||"",C.query=j[7],C.fragment=j[8],isNaN(C.port)&&(C.port=j[5])):(C.scheme=j[1]||void 0,C.userinfo=S.indexOf("@")!==-1?j[3]:void 0,C.host=S.indexOf("//")!==-1?j[4]:void 0,C.port=parseInt(j[5],10),C.path=j[6]||"",C.query=S.indexOf("?")!==-1?j[7]:void 0,C.fragment=S.indexOf("#")!==-1?j[8]:void 0,isNaN(C.port)&&(C.port=S.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?j[4]:void 0)),C.host&&(C.host=Ie(ve(C.host,L),L)),C.scheme===void 0&&C.userinfo===void 0&&C.host===void 0&&C.port===void 0&&!C.path&&C.query===void 0?C.reference="same-document":C.scheme===void 0?C.reference="relative":C.fragment===void 0?C.reference="absolute":C.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==C.reference&&(C.error=C.error||"URI is not a "+_.reference+" reference.");var H=x[(_.scheme||C.scheme||"").toLowerCase()];if(!_.unicodeSupport&&(!H||!H.unicodeSupport)){if(C.host&&(_.domainHost||H&&H.domainHost))try{C.host=q.toASCII(C.host.replace(L.PCT_ENCODED,Y).toLowerCase())}catch(W){C.error=C.error||"Host's domain name can not be converted to ASCII via punycode: "+W}X(C,y)}else X(C,L);H&&H.parse&&H.parse(C,_)}else C.error=C.error||"URI can not be parsed.";return C}function Fe(S,_){var C=_.iri!==!1?v:y,L=[];return S.userinfo!==void 0&&(L.push(S.userinfo),L.push("@")),S.host!==void 0&&L.push(Ie(ve(String(S.host),C),C).replace(C.IPV6ADDRESS,function(j,H,W){return"["+H+(W?"%25"+W:"")+"]"})),(typeof S.port=="number"||typeof S.port=="string")&&(L.push(":"),L.push(String(S.port))),L.length?L.join(""):void 0}var Ae=/^\.\.?\//,Ne=/^\/\.(\/|$)/,je=/^\/\.\.(\/|$)/,Be=/^\/?(?:.|\n)*?(?=\/|$)/;function $e(S){for(var _=[];S.length;)if(S.match(Ae))S=S.replace(Ae,"");else if(S.match(Ne))S=S.replace(Ne,"/");else if(S.match(je))S=S.replace(je,"/"),_.pop();else if(S==="."||S==="..")S="";else{var C=S.match(Be);if(C){var L=C[0];S=S.slice(L.length),_.push(L)}else throw new Error("Unexpected dot segment condition")}return _.join("")}function fe(S){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C=_.iri?v:y,L=[],j=x[(_.scheme||S.scheme||"").toLowerCase()];if(j&&j.serialize&&j.serialize(S,_),S.host&&!C.IPV6ADDRESS.test(S.host)){if(_.domainHost||j&&j.domainHost)try{S.host=_.iri?q.toUnicode(S.host):q.toASCII(S.host.replace(C.PCT_ENCODED,Y).toLowerCase())}catch(re){S.error=S.error||"Host's domain name can not be converted to "+(_.iri?"Unicode":"ASCII")+" via punycode: "+re}}X(S,C),_.reference!=="suffix"&&S.scheme&&(L.push(S.scheme),L.push(":"));var H=Fe(S,_);if(H!==void 0&&(_.reference!=="suffix"&&L.push("//"),L.push(H),S.path&&S.path.charAt(0)!=="/"&&L.push("/")),S.path!==void 0){var W=S.path;!_.absolutePath&&(!j||!j.absolutePath)&&(W=$e(W)),H===void 0&&(W=W.replace(/^\/\//,"/%2F")),L.push(W)}return S.query!==void 0&&(L.push("?"),L.push(S.query)),S.fragment!==void 0&&(L.push("#"),L.push(S.fragment)),L.join("")}function De(S,_){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},L=arguments[3],j={};return L||(S=pe(fe(S,C),C),_=pe(fe(_,C),C)),C=C||{},!C.tolerant&&_.scheme?(j.scheme=_.scheme,j.userinfo=_.userinfo,j.host=_.host,j.port=_.port,j.path=$e(_.path||""),j.query=_.query):(_.userinfo!==void 0||_.host!==void 0||_.port!==void 0?(j.userinfo=_.userinfo,j.host=_.host,j.port=_.port,j.path=$e(_.path||""),j.query=_.query):(_.path?(_.path.charAt(0)==="/"?j.path=$e(_.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?j.path="/"+_.path:S.path?j.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+_.path:j.path=_.path,j.path=$e(j.path)),j.query=_.query):(j.path=S.path,_.query!==void 0?j.query=_.query:j.query=S.query),j.userinfo=S.userinfo,j.host=S.host,j.port=S.port),j.scheme=S.scheme),j.fragment=_.fragment,j}function Ge(S,_,C){var L=h({scheme:"null"},C);return fe(De(pe(S,L),pe(_,L),L,!0),L)}function Ce(S,_){return typeof S=="string"?S=fe(pe(S,_),_):l(S)==="object"&&(S=pe(fe(S,_),_)),S}function Ve(S,_,C){return typeof S=="string"?S=fe(pe(S,C),C):l(S)==="object"&&(S=fe(S,C)),typeof _=="string"?_=fe(pe(_,C),C):l(_)==="object"&&(_=fe(_,C)),S===_}function He(S,_){return S&&S.toString().replace(!_||!_.iri?y.ESCAPE:v.ESCAPE,K)}function _e(S,_){return S&&S.toString().replace(!_||!_.iri?y.PCT_ENCODED:v.PCT_ENCODED,Y)}var Re={scheme:"http",domainHost:!0,parse:function(_,C){return _.host||(_.error=_.error||"HTTP URIs must have a host."),_},serialize:function(_,C){var L=String(_.scheme).toLowerCase()==="https";return(_.port===(L?443:80)||_.port==="")&&(_.port=void 0),_.path||(_.path="/"),_}},Xe={scheme:"https",domainHost:Re.domainHost,parse:Re.parse,serialize:Re.serialize};function Ze(S){return typeof S.secure=="boolean"?S.secure:String(S.scheme).toLowerCase()==="wss"}var xe={scheme:"ws",domainHost:!0,parse:function(_,C){var L=_;return L.secure=Ze(L),L.resourceName=(L.path||"/")+(L.query?"?"+L.query:""),L.path=void 0,L.query=void 0,L},serialize:function(_,C){if((_.port===(Ze(_)?443:80)||_.port==="")&&(_.port=void 0),typeof _.secure=="boolean"&&(_.scheme=_.secure?"wss":"ws",_.secure=void 0),_.resourceName){var L=_.resourceName.split("?"),j=T(L,2),H=j[0],W=j[1];_.path=H&&H!=="/"?H:void 0,_.query=W,_.resourceName=void 0}return _.fragment=void 0,_}},et={scheme:"wss",domainHost:xe.domainHost,parse:xe.parse,serialize:xe.serialize},ut={},tt="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",be="[0-9A-Fa-f]",dt=c(c("%[EFef]"+be+"%"+be+be+"%"+be+be)+"|"+c("%[89A-Fa-f]"+be+"%"+be+be)+"|"+c("%"+be+be)),ht="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",ft="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",pt=a(ft,'[\\"\\\\]'),mt="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",_t=new RegExp(tt,"g"),Le=new RegExp(dt,"g"),gt=new RegExp(a("[^]",ht,"[\\.]",'[\\"]',pt),"g"),rt=new RegExp(a("[^]",tt,mt),"g"),yt=rt;function Qe(S){var _=Y(S);return _.match(_t)?_:S}var nt={scheme:"mailto",parse:function(_,C){var L=_,j=L.to=L.path?L.path.split(","):[];if(L.path=void 0,L.query){for(var H=!1,W={},re=L.query.split("&"),se=0,ce=re.length;se<ce;++se){var ee=re[se].split("=");switch(ee[0]){case"to":for(var ne=ee[1].split(","),le=0,Q=ne.length;le<Q;++le)j.push(ne[le]);break;case"subject":L.subject=_e(ee[1],C);break;case"body":L.body=_e(ee[1],C);break;default:H=!0,W[_e(ee[0],C)]=_e(ee[1],C);break}}H&&(L.headers=W)}L.query=void 0;for(var ie=0,de=j.length;ie<de;++ie){var oe=j[ie].split("@");if(oe[0]=_e(oe[0]),C.unicodeSupport)oe[1]=_e(oe[1],C).toLowerCase();else try{oe[1]=q.toASCII(_e(oe[1],C).toLowerCase())}catch(ke){L.error=L.error||"Email address's domain name can not be converted to ASCII via punycode: "+ke}j[ie]=oe.join("@")}return L},serialize:function(_,C){var L=_,j=d(_.to);if(j){for(var H=0,W=j.length;H<W;++H){var re=String(j[H]),se=re.lastIndexOf("@"),ce=re.slice(0,se).replace(Le,Qe).replace(Le,u).replace(gt,K),ee=re.slice(se+1);try{ee=C.iri?q.toUnicode(ee):q.toASCII(_e(ee,C).toLowerCase())}catch(ie){L.error=L.error||"Email address's domain name can not be converted to "+(C.iri?"Unicode":"ASCII")+" via punycode: "+ie}j[H]=ce+"@"+ee}L.path=j.join(",")}var ne=_.headers=_.headers||{};_.subject&&(ne.subject=_.subject),_.body&&(ne.body=_.body);var le=[];for(var Q in ne)ne[Q]!==ut[Q]&&le.push(Q.replace(Le,Qe).replace(Le,u).replace(rt,K)+"="+ne[Q].replace(Le,Qe).replace(Le,u).replace(yt,K));return le.length&&(L.query=le.join("&")),L}},vt=/^([^\:]+)\:(.*)/,st={scheme:"urn",parse:function(_,C){var L=_.path&&_.path.match(vt),j=_;if(L){var H=C.scheme||j.scheme||"urn",W=L[1].toLowerCase(),re=L[2],se=H+":"+(C.nid||W),ce=x[se];j.nid=W,j.nss=re,j.path=void 0,ce&&(j=ce.parse(j,C))}else j.error=j.error||"URN can not be parsed.";return j},serialize:function(_,C){var L=C.scheme||_.scheme||"urn",j=_.nid,H=L+":"+(C.nid||j),W=x[H];W&&(_=W.serialize(_,C));var re=_,se=_.nss;return re.path=(j||C.nid)+":"+se,re}},$t=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,it={scheme:"urn:uuid",parse:function(_,C){var L=_;return L.uuid=L.nss,L.nss=void 0,!C.tolerant&&(!L.uuid||!L.uuid.match($t))&&(L.error=L.error||"UUID is not valid."),L},serialize:function(_,C){var L=_;return L.nss=(_.uuid||"").toLowerCase(),L}};x[Re.scheme]=Re,x[Xe.scheme]=Xe,x[xe.scheme]=xe,x[et.scheme]=et,x[nt.scheme]=nt,x[st.scheme]=st,x[it.scheme]=it,n.SCHEMES=x,n.pctEncChar=K,n.pctDecChars=Y,n.parse=pe,n.removeDotSegments=$e,n.serialize=fe,n.resolveComponents=De,n.resolve=Ge,n.normalize=Ce,n.equal=Ve,n.escapeComponent=He,n.unescapeComponent=_e,Object.defineProperty(n,"__esModule",{value:!0})})})(uri_all,uri_all.exports);var uri_allExports=uri_all.exports;Object.defineProperty(uri$1,"__esModule",{value:!0});const uri=uri_allExports;uri.code='require("ajv/dist/runtime/uri").default';uri$1.default=uri;(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.CodeGen=o.Name=o.nil=o.stringify=o.str=o._=o.KeywordCxt=void 0;var r=validate;Object.defineProperty(o,"KeywordCxt",{enumerable:!0,get:function(){return r.KeywordCxt}});var n=codegen;Object.defineProperty(o,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(o,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(o,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(o,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(o,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(o,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const a=validation_error,c=ref_error,l=rules,u=compile,d=codegen,h=resolve$1,f=dataType,y=util,v=require$$9,T=uri$1,I=(F,A)=>new RegExp(F,A);I.code="new RegExp";const b=["removeAdditional","useDefaults","coerceTypes"],R=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),$={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."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},k=200;function O(F){var A,M,N,p,E,q,x,K,Y,X,ae,ve,Ie,Me,Ue,pe,Fe,Ae,Ne,je,Be,$e,fe,De,Ge;const Ce=F.strict,Ve=(A=F.code)===null||A===void 0?void 0:A.optimize,He=Ve===!0||Ve===void 0?1:Ve||0,_e=(N=(M=F.code)===null||M===void 0?void 0:M.regExp)!==null&&N!==void 0?N:I,Re=(p=F.uriResolver)!==null&&p!==void 0?p:T.default;return{strictSchema:(q=(E=F.strictSchema)!==null&&E!==void 0?E:Ce)!==null&&q!==void 0?q:!0,strictNumbers:(K=(x=F.strictNumbers)!==null&&x!==void 0?x:Ce)!==null&&K!==void 0?K:!0,strictTypes:(X=(Y=F.strictTypes)!==null&&Y!==void 0?Y:Ce)!==null&&X!==void 0?X:"log",strictTuples:(ve=(ae=F.strictTuples)!==null&&ae!==void 0?ae:Ce)!==null&&ve!==void 0?ve:"log",strictRequired:(Me=(Ie=F.strictRequired)!==null&&Ie!==void 0?Ie:Ce)!==null&&Me!==void 0?Me:!1,code:F.code?{...F.code,optimize:He,regExp:_e}:{optimize:He,regExp:_e},loopRequired:(Ue=F.loopRequired)!==null&&Ue!==void 0?Ue:k,loopEnum:(pe=F.loopEnum)!==null&&pe!==void 0?pe:k,meta:(Fe=F.meta)!==null&&Fe!==void 0?Fe:!0,messages:(Ae=F.messages)!==null&&Ae!==void 0?Ae:!0,inlineRefs:(Ne=F.inlineRefs)!==null&&Ne!==void 0?Ne:!0,schemaId:(je=F.schemaId)!==null&&je!==void 0?je:"$id",addUsedSchema:(Be=F.addUsedSchema)!==null&&Be!==void 0?Be:!0,validateSchema:($e=F.validateSchema)!==null&&$e!==void 0?$e:!0,validateFormats:(fe=F.validateFormats)!==null&&fe!==void 0?fe:!0,unicodeRegExp:(De=F.unicodeRegExp)!==null&&De!==void 0?De:!0,int32range:(Ge=F.int32range)!==null&&Ge!==void 0?Ge:!0,uriResolver:Re}}class P{constructor(A={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,A=this.opts={...A,...O(A)};const{es5:M,lines:N}=this.opts.code;this.scope=new d.ValueScope({scope:{},prefixes:R,es5:M,lines:N}),this.logger=z(A.logger);const p=A.validateFormats;A.validateFormats=!1,this.RULES=(0,l.getRules)(),U.call(this,$,A,"NOT SUPPORTED"),U.call(this,g,A,"DEPRECATED","warn"),this._metaOpts=B.call(this),A.formats&&D.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),A.keywords&&G.call(this,A.keywords),typeof A.meta=="object"&&this.addMetaSchema(A.meta),w.call(this),A.validateFormats=p}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:A,meta:M,schemaId:N}=this.opts;let p=v;N==="id"&&(p={...v},p.id=p.$id,delete p.$id),M&&A&&this.addMetaSchema(p,p[N],!1)}defaultMeta(){const{meta:A,schemaId:M}=this.opts;return this.opts.defaultMeta=typeof A=="object"?A[M]||A:void 0}validate(A,M){let N;if(typeof A=="string"){if(N=this.getSchema(A),!N)throw new Error(`no schema with key or ref "${A}"`)}else N=this.compile(A);const p=N(M);return"$async"in N||(this.errors=N.errors),p}compile(A,M){const N=this._addSchema(A,M);return N.validate||this._compileSchemaEnv(N)}compileAsync(A,M){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return p.call(this,A,M);async function p(X,ae){await E.call(this,X.$schema);const ve=this._addSchema(X,ae);return ve.validate||q.call(this,ve)}async function E(X){X&&!this.getSchema(X)&&await p.call(this,{$ref:X},!0)}async function q(X){try{return this._compileSchemaEnv(X)}catch(ae){if(!(ae instanceof c.default))throw ae;return x.call(this,ae),await K.call(this,ae.missingSchema),q.call(this,X)}}function x({missingSchema:X,missingRef:ae}){if(this.refs[X])throw new Error(`AnySchema ${X} is loaded but ${ae} cannot be resolved`)}async function K(X){const ae=await Y.call(this,X);this.refs[X]||await E.call(this,ae.$schema),this.refs[X]||this.addSchema(ae,X,M)}async function Y(X){const ae=this._loading[X];if(ae)return ae;try{return await(this._loading[X]=N(X))}finally{delete this._loading[X]}}}addSchema(A,M,N,p=this.opts.validateSchema){if(Array.isArray(A)){for(const q of A)this.addSchema(q,void 0,N,p);return this}let E;if(typeof A=="object"){const{schemaId:q}=this.opts;if(E=A[q],E!==void 0&&typeof E!="string")throw new Error(`schema ${q} must be string`)}return M=(0,h.normalizeId)(M||E),this._checkUnique(M),this.schemas[M]=this._addSchema(A,N,M,p,!0),this}addMetaSchema(A,M,N=this.opts.validateSchema){return this.addSchema(A,M,!0,N),this}validateSchema(A,M){if(typeof A=="boolean")return!0;let N;if(N=A.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const p=this.validate(N,A);if(!p&&M){const E="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(E);else throw new Error(E)}return p}getSchema(A){let M;for(;typeof(M=m.call(this,A))=="string";)A=M;if(M===void 0){const{schemaId:N}=this.opts,p=new u.SchemaEnv({schema:{},schemaId:N});if(M=u.resolveSchema.call(this,p,A),!M)return;this.refs[A]=M}return M.validate||this._compileSchemaEnv(M)}removeSchema(A){if(A instanceof RegExp)return this._removeAllSchemas(this.schemas,A),this._removeAllSchemas(this.refs,A),this;switch(typeof A){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const M=m.call(this,A);return typeof M=="object"&&this._cache.delete(M.schema),delete this.schemas[A],delete this.refs[A],this}case"object":{const M=A;this._cache.delete(M);let N=A[this.opts.schemaId];return N&&(N=(0,h.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(A){for(const M of A)this.addKeyword(M);return this}addKeyword(A,M){let N;if(typeof A=="string")N=A,typeof M=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),M.keyword=N);else if(typeof A=="object"&&M===void 0){if(M=A,N=M.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Z.call(this,N,M),!M)return(0,y.eachItem)(N,E=>he.call(this,E)),this;me.call(this,M);const p={...M,type:(0,f.getJSONTypes)(M.type),schemaType:(0,f.getJSONTypes)(M.schemaType)};return(0,y.eachItem)(N,p.type.length===0?E=>he.call(this,E,p):E=>p.type.forEach(q=>he.call(this,E,p,q))),this}getKeyword(A){const M=this.RULES.all[A];return typeof M=="object"?M.definition:!!M}removeKeyword(A){const{RULES:M}=this;delete M.keywords[A],delete M.all[A];for(const N of M.rules){const p=N.rules.findIndex(E=>E.keyword===A);p>=0&&N.rules.splice(p,1)}return this}addFormat(A,M){return typeof M=="string"&&(M=new RegExp(M)),this.formats[A]=M,this}errorsText(A=this.errors,{separator:M=", ",dataVar:N="data"}={}){return!A||A.length===0?"No errors":A.map(p=>`${N}${p.instancePath} ${p.message}`).reduce((p,E)=>p+M+E)}$dataMetaSchema(A,M){const N=this.RULES.all;A=JSON.parse(JSON.stringify(A));for(const p of M){const E=p.split("/").slice(1);let q=A;for(const x of E)q=q[x];for(const x in N){const K=N[x];if(typeof K!="object")continue;const{$data:Y}=K.definition,X=q[x];Y&&X&&(q[x]=J(X))}}return A}_removeAllSchemas(A,M){for(const N in A){const p=A[N];(!M||M.test(N))&&(typeof p=="string"?delete A[N]:p&&!p.meta&&(this._cache.delete(p.schema),delete A[N]))}}_addSchema(A,M,N,p=this.opts.validateSchema,E=this.opts.addUsedSchema){let q;const{schemaId:x}=this.opts;if(typeof A=="object")q=A[x];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof A!="boolean")throw new Error("schema must be object or boolean")}let K=this._cache.get(A);if(K!==void 0)return K;N=(0,h.normalizeId)(q||N);const Y=h.getSchemaRefs.call(this,A,N);return K=new u.SchemaEnv({schema:A,schemaId:x,meta:M,baseId:N,localRefs:Y}),this._cache.set(K.schema,K),E&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=K),p&&this.validateSchema(A,!0),K}_checkUnique(A){if(this.schemas[A]||this.refs[A])throw new Error(`schema with key or id "${A}" already exists`)}_compileSchemaEnv(A){if(A.meta?this._compileMetaSchema(A):u.compileSchema.call(this,A),!A.validate)throw new Error("ajv implementation error");return A.validate}_compileMetaSchema(A){const M=this.opts;this.opts=this._metaOpts;try{u.compileSchema.call(this,A)}finally{this.opts=M}}}o.default=P,P.ValidationError=a.default,P.MissingRefError=c.default;function U(F,A,M,N="error"){for(const p in F){const E=p;E in A&&this.logger[N](`${M}: option ${p}. ${F[E]}`)}}function m(F){return F=(0,h.normalizeId)(F),this.schemas[F]||this.refs[F]}function w(){const F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(const A in F)this.addSchema(F[A],A)}function D(){for(const F in this.opts.formats){const A=this.opts.formats[F];A&&this.addFormat(F,A)}}function G(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const A in F){const M=F[A];M.keyword||(M.keyword=A),this.addKeyword(M)}}function B(){const F={...this.opts};for(const A of b)delete F[A];return F}const V={log(){},warn(){},error(){}};function z(F){if(F===!1)return V;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}const te=/^[a-z_$][a-z0-9_$:-]*$/i;function Z(F,A){const{RULES:M}=this;if((0,y.eachItem)(F,N=>{if(M.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!te.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!A&&A.$data&&!("code"in A||"validate"in A))throw new Error('$data keyword must have "code" or "validate" function')}function he(F,A,M){var N;const p=A==null?void 0:A.post;if(M&&p)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:E}=this;let q=p?E.post:E.rules.find(({type:K})=>K===M);if(q||(q={type:M,rules:[]},E.rules.push(q)),E.keywords[F]=!0,!A)return;const x={keyword:F,definition:{...A,type:(0,f.getJSONTypes)(A.type),schemaType:(0,f.getJSONTypes)(A.schemaType)}};A.before?ue.call(this,q,x,A.before):q.rules.push(x),E.all[F]=x,(N=A.implements)===null||N===void 0||N.forEach(K=>this.addKeyword(K))}function ue(F,A,M){const N=F.rules.findIndex(p=>p.keyword===M);N>=0?F.rules.splice(N,0,A):(F.rules.push(A),this.logger.warn(`rule ${M} is not defined`))}function me(F){let{metaSchema:A}=F;A!==void 0&&(F.$data&&this.opts.$data&&(A=J(A)),F.validateSchema=this.compile(A,!0))}const ye={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function J(F){return{anyOf:[F,ye]}}})(core$2);var draft7={},core$1={},id={};Object.defineProperty(id,"__esModule",{value:!0});const def$s={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};id.default=def$s;var ref={};Object.defineProperty(ref,"__esModule",{value:!0});ref.callRef=ref.getValidate=void 0;const ref_error_1=ref_error,code_1$8=code,codegen_1$l=codegen,names_1$1=names$1,compile_1$1=compile,util_1$j=util,def$r={keyword:"$ref",schemaType:"string",code(o){const{gen:r,schema:n,it:a}=o,{baseId:c,schemaEnv:l,validateName:u,opts:d,self:h}=a,{root:f}=l;if((n==="#"||n==="#/")&&c===f.baseId)return v();const y=compile_1$1.resolveRef.call(h,f,c,n);if(y===void 0)throw new ref_error_1.default(a.opts.uriResolver,c,n);if(y instanceof compile_1$1.SchemaEnv)return T(y);return I(y);function v(){if(l===f)return callRef(o,u,l,l.$async);const b=r.scopeValue("root",{ref:f});return callRef(o,(0,codegen_1$l._)`${b}.validate`,f,f.$async)}function T(b){const R=getValidate(o,b);callRef(o,R,b,b.$async)}function I(b){const R=r.scopeValue("schema",d.code.source===!0?{ref:b,code:(0,codegen_1$l.stringify)(b)}:{ref:b}),$=r.name("valid"),g=o.subschema({schema:b,dataTypes:[],schemaPath:codegen_1$l.nil,topSchemaRef:R,errSchemaPath:n},$);o.mergeEvaluated(g),o.ok($)}}};function getValidate(o,r){const{gen:n}=o;return r.validate?n.scopeValue("validate",{ref:r.validate}):(0,codegen_1$l._)`${n.scopeValue("wrapper",{ref:r})}.validate`}ref.getValidate=getValidate;function callRef(o,r,n,a){const{gen:c,it:l}=o,{allErrors:u,schemaEnv:d,opts:h}=l,f=h.passContext?names_1$1.default.this:codegen_1$l.nil;a?y():v();function y(){if(!d.$async)throw new Error("async schema referenced by sync schema");const b=c.let("valid");c.try(()=>{c.code((0,codegen_1$l._)`await ${(0,code_1$8.callValidateCode)(o,r,f)}`),I(r),u||c.assign(b,!0)},R=>{c.if((0,codegen_1$l._)`!(${R} instanceof ${l.ValidationError})`,()=>c.throw(R)),T(R),u||c.assign(b,!1)}),o.ok(b)}function v(){o.result((0,code_1$8.callValidateCode)(o,r,f),()=>I(r),()=>T(r))}function T(b){const R=(0,codegen_1$l._)`${b}.errors`;c.assign(names_1$1.default.vErrors,(0,codegen_1$l._)`${names_1$1.default.vErrors} === null ? ${R} : ${names_1$1.default.vErrors}.concat(${R})`),c.assign(names_1$1.default.errors,(0,codegen_1$l._)`${names_1$1.default.vErrors}.length`)}function I(b){var R;if(!l.opts.unevaluated)return;const $=(R=n==null?void 0:n.validate)===null||R===void 0?void 0:R.evaluated;if(l.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(l.props=util_1$j.mergeEvaluated.props(c,$.props,l.props));else{const g=c.var("props",(0,codegen_1$l._)`${b}.evaluated.props`);l.props=util_1$j.mergeEvaluated.props(c,g,l.props,codegen_1$l.Name)}if(l.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(l.items=util_1$j.mergeEvaluated.items(c,$.items,l.items));else{const g=c.var("items",(0,codegen_1$l._)`${b}.evaluated.items`);l.items=util_1$j.mergeEvaluated.items(c,g,l.items,codegen_1$l.Name)}}}ref.callRef=callRef;ref.default=def$r;Object.defineProperty(core$1,"__esModule",{value:!0});const id_1=id,ref_1=ref,core=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];core$1.default=core;var validation$1={},limitNumber={};Object.defineProperty(limitNumber,"__esModule",{value:!0});const codegen_1$k=codegen,ops=codegen_1$k.operators,KWDs={maximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},minimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},exclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},exclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},error$i={message:({keyword:o,schemaCode:r})=>(0,codegen_1$k.str)`must be ${KWDs[o].okStr} ${r}`,params:({keyword:o,schemaCode:r})=>(0,codegen_1$k._)`{comparison: ${KWDs[o].okStr}, limit: ${r}}`},def$q={keyword:Object.keys(KWDs),type:"number",schemaType:"number",$data:!0,error:error$i,code(o){const{keyword:r,data:n,schemaCode:a}=o;o.fail$data((0,codegen_1$k._)`${n} ${KWDs[r].fail} ${a} || isNaN(${n})`)}};limitNumber.default=def$q;var multipleOf={};Object.defineProperty(multipleOf,"__esModule",{value:!0});const codegen_1$j=codegen,error$h={message:({schemaCode:o})=>(0,codegen_1$j.str)`must be multiple of ${o}`,params:({schemaCode:o})=>(0,codegen_1$j._)`{multipleOf: ${o}}`},def$p={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:error$h,code(o){const{gen:r,data:n,schemaCode:a,it:c}=o,l=c.opts.multipleOfPrecision,u=r.let("res"),d=l?(0,codegen_1$j._)`Math.abs(Math.round(${u}) - ${u}) > 1e-${l}`:(0,codegen_1$j._)`${u} !== parseInt(${u})`;o.fail$data((0,codegen_1$j._)`(${a} === 0 || (${u} = ${n}/${a}, ${d}))`)}};multipleOf.default=def$p;var limitLength={},ucs2length$1={};Object.defineProperty(ucs2length$1,"__esModule",{value:!0});function ucs2length(o){const r=o.length;let n=0,a=0,c;for(;a<r;)n++,c=o.charCodeAt(a++),c>=55296&&c<=56319&&a<r&&(c=o.charCodeAt(a),(c&64512)===56320&&a++);return n}ucs2length$1.default=ucs2length;ucs2length.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(limitLength,"__esModule",{value:!0});const codegen_1$i=codegen,util_1$i=util,ucs2length_1=ucs2length$1,error$g={message({keyword:o,schemaCode:r}){const n=o==="maxLength"?"more":"fewer";return(0,codegen_1$i.str)`must NOT have ${n} than ${r} characters`},params:({schemaCode:o})=>(0,codegen_1$i._)`{limit: ${o}}`},def$o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:error$g,code(o){const{keyword:r,data:n,schemaCode:a,it:c}=o,l=r==="maxLength"?codegen_1$i.operators.GT:codegen_1$i.operators.LT,u=c.opts.unicode===!1?(0,codegen_1$i._)`${n}.length`:(0,codegen_1$i._)`${(0,util_1$i.useFunc)(o.gen,ucs2length_1.default)}(${n})`;o.fail$data((0,codegen_1$i._)`${u} ${l} ${a}`)}};limitLength.default=def$o;var pattern={};Object.defineProperty(pattern,"__esModule",{value:!0});const code_1$7=code,codegen_1$h=codegen,error$f={message:({schemaCode:o})=>(0,codegen_1$h.str)`must match pattern "${o}"`,params:({schemaCode:o})=>(0,codegen_1$h._)`{pattern: ${o}}`},def$n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:error$f,code(o){const{data:r,$data:n,schema:a,schemaCode:c,it:l}=o,u=l.opts.unicodeRegExp?"u":"",d=n?(0,codegen_1$h._)`(new RegExp(${c}, ${u}))`:(0,code_1$7.usePattern)(o,a);o.fail$data((0,codegen_1$h._)`!${d}.test(${r})`)}};pattern.default=def$n;var limitProperties={};Object.defineProperty(limitProperties,"__esModule",{value:!0});const codegen_1$g=codegen,error$e={message({keyword:o,schemaCode:r}){const n=o==="maxProperties"?"more":"fewer";return(0,codegen_1$g.str)`must NOT have ${n} than ${r} properties`},params:({schemaCode:o})=>(0,codegen_1$g._)`{limit: ${o}}`},def$m={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:error$e,code(o){const{keyword:r,data:n,schemaCode:a}=o,c=r==="maxProperties"?codegen_1$g.operators.GT:codegen_1$g.operators.LT;o.fail$data((0,codegen_1$g._)`Object.keys(${n}).length ${c} ${a}`)}};limitProperties.default=def$m;var required={};Object.defineProperty(required,"__esModule",{value:!0});const code_1$6=code,codegen_1$f=codegen,util_1$h=util,error$d={message:({params:{missingProperty:o}})=>(0,codegen_1$f.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,codegen_1$f._)`{missingProperty: ${o}}`},def$l={keyword:"required",type:"object",schemaType:"array",$data:!0,error:error$d,code(o){const{gen:r,schema:n,schemaCode:a,data:c,$data:l,it:u}=o,{opts:d}=u;if(!l&&n.length===0)return;const h=n.length>=d.loopRequired;if(u.allErrors?f():y(),d.strictRequired){const I=o.parentSchema.properties,{definedProperties:b}=o.it;for(const R of n)if((I==null?void 0:I[R])===void 0&&!b.has(R)){const $=u.schemaEnv.baseId+u.errSchemaPath,g=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,util_1$h.checkStrictMode)(u,g,u.opts.strictRequired)}}function f(){if(h||l)o.block$data(codegen_1$f.nil,v);else for(const I of n)(0,code_1$6.checkReportMissingProp)(o,I)}function y(){const I=r.let("missing");if(h||l){const b=r.let("valid",!0);o.block$data(b,()=>T(I,b)),o.ok(b)}else r.if((0,code_1$6.checkMissingProp)(o,n,I)),(0,code_1$6.reportMissingProp)(o,I),r.else()}function v(){r.forOf("prop",a,I=>{o.setParams({missingProperty:I}),r.if((0,code_1$6.noPropertyInData)(r,c,I,d.ownProperties),()=>o.error())})}function T(I,b){o.setParams({missingProperty:I}),r.forOf(I,a,()=>{r.assign(b,(0,code_1$6.propertyInData)(r,c,I,d.ownProperties)),r.if((0,codegen_1$f.not)(b),()=>{o.error(),r.break()})},codegen_1$f.nil)}}};required.default=def$l;var limitItems={};Object.defineProperty(limitItems,"__esModule",{value:!0});const codegen_1$e=codegen,error$c={message({keyword:o,schemaCode:r}){const n=o==="maxItems"?"more":"fewer";return(0,codegen_1$e.str)`must NOT have ${n} than ${r} items`},params:({schemaCode:o})=>(0,codegen_1$e._)`{limit: ${o}}`},def$k={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:error$c,code(o){const{keyword:r,data:n,schemaCode:a}=o,c=r==="maxItems"?codegen_1$e.operators.GT:codegen_1$e.operators.LT;o.fail$data((0,codegen_1$e._)`${n}.length ${c} ${a}`)}};limitItems.default=def$k;var uniqueItems={},equal$1={};Object.defineProperty(equal$1,"__esModule",{value:!0});const equal=fastDeepEqual;equal.code='require("ajv/dist/runtime/equal").default';equal$1.default=equal;Object.defineProperty(uniqueItems,"__esModule",{value:!0});const dataType_1=dataType,codegen_1$d=codegen,util_1$g=util,equal_1$2=equal$1,error$b={message:({params:{i:o,j:r}})=>(0,codegen_1$d.str)`must NOT have duplicate items (items ## ${r} and ${o} are identical)`,params:({params:{i:o,j:r}})=>(0,codegen_1$d._)`{i: ${o}, j: ${r}}`},def$j={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:error$b,code(o){const{gen:r,data:n,$data:a,schema:c,parentSchema:l,schemaCode:u,it:d}=o;if(!a&&!c)return;const h=r.let("valid"),f=l.items?(0,dataType_1.getSchemaTypes)(l.items):[];o.block$data(h,y,(0,codegen_1$d._)`${u} === false`),o.ok(h);function y(){const b=r.let("i",(0,codegen_1$d._)`${n}.length`),R=r.let("j");o.setParams({i:b,j:R}),r.assign(h,!0),r.if((0,codegen_1$d._)`${b} > 1`,()=>(v()?T:I)(b,R))}function v(){return f.length>0&&!f.some(b=>b==="object"||b==="array")}function T(b,R){const $=r.name("item"),g=(0,dataType_1.checkDataTypes)(f,$,d.opts.strictNumbers,dataType_1.DataType.Wrong),k=r.const("indices",(0,codegen_1$d._)`{}`);r.for((0,codegen_1$d._)`;${b}--;`,()=>{r.let($,(0,codegen_1$d._)`${n}[${b}]`),r.if(g,(0,codegen_1$d._)`continue`),f.length>1&&r.if((0,codegen_1$d._)`typeof ${$} == "string"`,(0,codegen_1$d._)`${$} += "_"`),r.if((0,codegen_1$d._)`typeof ${k}[${$}] == "number"`,()=>{r.assign(R,(0,codegen_1$d._)`${k}[${$}]`),o.error(),r.assign(h,!1).break()}).code((0,codegen_1$d._)`${k}[${$}] = ${b}`)})}function I(b,R){const $=(0,util_1$g.useFunc)(r,equal_1$2.default),g=r.name("outer");r.label(g).for((0,codegen_1$d._)`;${b}--;`,()=>r.for((0,codegen_1$d._)`${R} = ${b}; ${R}--;`,()=>r.if((0,codegen_1$d._)`${$}(${n}[${b}], ${n}[${R}])`,()=>{o.error(),r.assign(h,!1).break(g)})))}}};uniqueItems.default=def$j;var _const={};Object.defineProperty(_const,"__esModule",{value:!0});const codegen_1$c=codegen,util_1$f=util,equal_1$1=equal$1,error$a={message:"must be equal to constant",params:({schemaCode:o})=>(0,codegen_1$c._)`{allowedValue: ${o}}`},def$i={keyword:"const",$data:!0,error:error$a,code(o){const{gen:r,data:n,$data:a,schemaCode:c,schema:l}=o;a||l&&typeof l=="object"?o.fail$data((0,codegen_1$c._)`!${(0,util_1$f.useFunc)(r,equal_1$1.default)}(${n}, ${c})`):o.fail((0,codegen_1$c._)`${l} !== ${n}`)}};_const.default=def$i;var _enum={};Object.defineProperty(_enum,"__esModule",{value:!0});const codegen_1$b=codegen,util_1$e=util,equal_1=equal$1,error$9={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,codegen_1$b._)`{allowedValues: ${o}}`},def$h={keyword:"enum",schemaType:"array",$data:!0,error:error$9,code(o){const{gen:r,data:n,$data:a,schema:c,schemaCode:l,it:u}=o;if(!a&&c.length===0)throw new Error("enum must have non-empty array");const d=c.length>=u.opts.loopEnum;let h;const f=()=>h??(h=(0,util_1$e.useFunc)(r,equal_1.default));let y;if(d||a)y=r.let("valid"),o.block$data(y,v);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const I=r.const("vSchema",l);y=(0,codegen_1$b.or)(...c.map((b,R)=>T(I,R)))}o.pass(y);function v(){r.assign(y,!1),r.forOf("v",l,I=>r.if((0,codegen_1$b._)`${f()}(${n}, ${I})`,()=>r.assign(y,!0).break()))}function T(I,b){const R=c[b];return typeof R=="object"&&R!==null?(0,codegen_1$b._)`${f()}(${n}, ${I}[${b}])`:(0,codegen_1$b._)`${n} === ${R}`}}};_enum.default=def$h;Object.defineProperty(validation$1,"__esModule",{value:!0});const limitNumber_1=limitNumber,multipleOf_1=multipleOf,limitLength_1=limitLength,pattern_1=pattern,limitProperties_1=limitProperties,required_1=required,limitItems_1=limitItems,uniqueItems_1=uniqueItems,const_1=_const,enum_1=_enum,validation=[limitNumber_1.default,multipleOf_1.default,limitLength_1.default,pattern_1.default,limitProperties_1.default,required_1.default,limitItems_1.default,uniqueItems_1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},const_1.default,enum_1.default];validation$1.default=validation;var applicator={},additionalItems={};Object.defineProperty(additionalItems,"__esModule",{value:!0});additionalItems.validateAdditionalItems=void 0;const codegen_1$a=codegen,util_1$d=util,error$8={message:({params:{len:o}})=>(0,codegen_1$a.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,codegen_1$a._)`{limit: ${o}}`},def$g={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:error$8,code(o){const{parentSchema:r,it:n}=o,{items:a}=r;if(!Array.isArray(a)){(0,util_1$d.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}validateAdditionalItems(o,a)}};function validateAdditionalItems(o,r){const{gen:n,schema:a,data:c,keyword:l,it:u}=o;u.items=!0;const d=n.const("len",(0,codegen_1$a._)`${c}.length`);if(a===!1)o.setParams({len:r.length}),o.pass((0,codegen_1$a._)`${d} <= ${r.length}`);else if(typeof a=="object"&&!(0,util_1$d.alwaysValidSchema)(u,a)){const f=n.var("valid",(0,codegen_1$a._)`${d} <= ${r.length}`);n.if((0,codegen_1$a.not)(f),()=>h(f)),o.ok(f)}function h(f){n.forRange("i",r.length,d,y=>{o.subschema({keyword:l,dataProp:y,dataPropType:util_1$d.Type.Num},f),u.allErrors||n.if((0,codegen_1$a.not)(f),()=>n.break())})}}additionalItems.validateAdditionalItems=validateAdditionalItems;additionalItems.default=def$g;var prefixItems={},items={};Object.defineProperty(items,"__esModule",{value:!0});items.validateTuple=void 0;const codegen_1$9=codegen,util_1$c=util,code_1$5=code,def$f={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:r,it:n}=o;if(Array.isArray(r))return validateTuple(o,"additionalItems",r);n.items=!0,!(0,util_1$c.alwaysValidSchema)(n,r)&&o.ok((0,code_1$5.validateArray)(o))}};function validateTuple(o,r,n=o.schema){const{gen:a,parentSchema:c,data:l,keyword:u,it:d}=o;y(c),d.opts.unevaluated&&n.length&&d.items!==!0&&(d.items=util_1$c.mergeEvaluated.items(a,n.length,d.items));const h=a.name("valid"),f=a.const("len",(0,codegen_1$9._)`${l}.length`);n.forEach((v,T)=>{(0,util_1$c.alwaysValidSchema)(d,v)||(a.if((0,codegen_1$9._)`${f} > ${T}`,()=>o.subschema({keyword:u,schemaProp:T,dataProp:T},h)),o.ok(h))});function y(v){const{opts:T,errSchemaPath:I}=d,b=n.length,R=b===v.minItems&&(b===v.maxItems||v[r]===!1);if(T.strictTuples&&!R){const $=`"${u}" is ${b}-tuple, but minItems or maxItems/${r} are not specified or different at path "${I}"`;(0,util_1$c.checkStrictMode)(d,$,T.strictTuples)}}}items.validateTuple=validateTuple;items.default=def$f;Object.defineProperty(prefixItems,"__esModule",{value:!0});const items_1$1=items,def$e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o=>(0,items_1$1.validateTuple)(o,"items")};prefixItems.default=def$e;var items2020={};Object.defineProperty(items2020,"__esModule",{value:!0});const codegen_1$8=codegen,util_1$b=util,code_1$4=code,additionalItems_1$1=additionalItems,error$7={message:({params:{len:o}})=>(0,codegen_1$8.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,codegen_1$8._)`{limit: ${o}}`},def$d={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:error$7,code(o){const{schema:r,parentSchema:n,it:a}=o,{prefixItems:c}=n;a.items=!0,!(0,util_1$b.alwaysValidSchema)(a,r)&&(c?(0,additionalItems_1$1.validateAdditionalItems)(o,c):o.ok((0,code_1$4.validateArray)(o)))}};items2020.default=def$d;var contains={};Object.defineProperty(contains,"__esModule",{value:!0});const codegen_1$7=codegen,util_1$a=util,error$6={message:({params:{min:o,max:r}})=>r===void 0?(0,codegen_1$7.str)`must contain at least ${o} valid item(s)`:(0,codegen_1$7.str)`must contain at least ${o} and no more than ${r} valid item(s)`,params:({params:{min:o,max:r}})=>r===void 0?(0,codegen_1$7._)`{minContains: ${o}}`:(0,codegen_1$7._)`{minContains: ${o}, maxContains: ${r}}`},def$c={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:error$6,code(o){const{gen:r,schema:n,parentSchema:a,data:c,it:l}=o;let u,d;const{minContains:h,maxContains:f}=a;l.opts.next?(u=h===void 0?1:h,d=f):u=1;const y=r.const("len",(0,codegen_1$7._)`${c}.length`);if(o.setParams({min:u,max:d}),d===void 0&&u===0){(0,util_1$a.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(d!==void 0&&u>d){(0,util_1$a.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,util_1$a.alwaysValidSchema)(l,n)){let R=(0,codegen_1$7._)`${y} >= ${u}`;d!==void 0&&(R=(0,codegen_1$7._)`${R} && ${y} <= ${d}`),o.pass(R);return}l.items=!0;const v=r.name("valid");d===void 0&&u===1?I(v,()=>r.if(v,()=>r.break())):u===0?(r.let(v,!0),d!==void 0&&r.if((0,codegen_1$7._)`${c}.length > 0`,T)):(r.let(v,!1),T()),o.result(v,()=>o.reset());function T(){const R=r.name("_valid"),$=r.let("count",0);I(R,()=>r.if(R,()=>b($)))}function I(R,$){r.forRange("i",0,y,g=>{o.subschema({keyword:"contains",dataProp:g,dataPropType:util_1$a.Type.Num,compositeRule:!0},R),$()})}function b(R){r.code((0,codegen_1$7._)`${R}++`),d===void 0?r.if((0,codegen_1$7._)`${R} >= ${u}`,()=>r.assign(v,!0).break()):(r.if((0,codegen_1$7._)`${R} > ${d}`,()=>r.assign(v,!1).break()),u===1?r.assign(v,!0):r.if((0,codegen_1$7._)`${R} >= ${u}`,()=>r.assign(v,!0)))}}};contains.default=def$c;var dependencies={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.validateSchemaDeps=o.validatePropertyDeps=o.error=void 0;const r=codegen,n=util,a=code;o.error={message:({params:{property:h,depsCount:f,deps:y}})=>{const v=f===1?"property":"properties";return(0,r.str)`must have ${v} ${y} when property ${h} is present`},params:({params:{property:h,depsCount:f,deps:y,missingProperty:v}})=>(0,r._)`{property: ${h},
missingProperty: ${v},
depsCount: ${f},
deps: ${y}}`};const c={keyword:"dependencies",type:"object",schemaType:"object",error:o.error,code(h){const[f,y]=l(h);u(h,f),d(h,y)}};function l({schema:h}){const f={},y={};for(const v in h){if(v==="__proto__")continue;const T=Array.isArray(h[v])?f:y;T[v]=h[v]}return[f,y]}function u(h,f=h.schema){const{gen:y,data:v,it:T}=h;if(Object.keys(f).length===0)return;const I=y.let("missing");for(const b in f){const R=f[b];if(R.length===0)continue;const $=(0,a.propertyInData)(y,v,b,T.opts.ownProperties);h.setParams({property:b,depsCount:R.length,deps:R.join(", ")}),T.allErrors?y.if($,()=>{for(const g of R)(0,a.checkReportMissingProp)(h,g)}):(y.if((0,r._)`${$} && (${(0,a.checkMissingProp)(h,R,I)})`),(0,a.reportMissingProp)(h,I),y.else())}}o.validatePropertyDeps=u;function d(h,f=h.schema){const{gen:y,data:v,keyword:T,it:I}=h,b=y.name("valid");for(const R in f)(0,n.alwaysValidSchema)(I,f[R])||(y.if((0,a.propertyInData)(y,v,R,I.opts.ownProperties),()=>{const $=h.subschema({keyword:T,schemaProp:R},b);h.mergeValidEvaluated($,b)},()=>y.var(b,!0)),h.ok(b))}o.validateSchemaDeps=d,o.default=c})(dependencies);var propertyNames={};Object.defineProperty(propertyNames,"__esModule",{value:!0});const codegen_1$6=codegen,util_1$9=util,error$5={message:"property name must be valid",params:({params:o})=>(0,codegen_1$6._)`{propertyName: ${o.propertyName}}`},def$b={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error$5,code(o){const{gen:r,schema:n,data:a,it:c}=o;if((0,util_1$9.alwaysValidSchema)(c,n))return;const l=r.name("valid");r.forIn("key",a,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},l),r.if((0,codegen_1$6.not)(l),()=>{o.error(!0),c.allErrors||r.break()})}),o.ok(l)}};propertyNames.default=def$b;var additionalProperties={};Object.defineProperty(additionalProperties,"__esModule",{value:!0});const code_1$3=code,codegen_1$5=codegen,names_1=names$1,util_1$8=util,error$4={message:"must NOT have additional properties",params:({params:o})=>(0,codegen_1$5._)`{additionalProperty: ${o.additionalProperty}}`},def$a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:error$4,code(o){const{gen:r,schema:n,parentSchema:a,data:c,errsCount:l,it:u}=o;if(!l)throw new Error("ajv implementation error");const{allErrors:d,opts:h}=u;if(u.props=!0,h.removeAdditional!=="all"&&(0,util_1$8.alwaysValidSchema)(u,n))return;const f=(0,code_1$3.allSchemaProperties)(a.properties),y=(0,code_1$3.allSchemaProperties)(a.patternProperties);v(),o.ok((0,codegen_1$5._)`${l} === ${names_1.default.errors}`);function v(){r.forIn("key",c,$=>{!f.length&&!y.length?b($):r.if(T($),()=>b($))})}function T($){let g;if(f.length>8){const k=(0,util_1$8.schemaRefOrVal)(u,a.properties,"properties");g=(0,code_1$3.isOwnProperty)(r,k,$)}else f.length?g=(0,codegen_1$5.or)(...f.map(k=>(0,codegen_1$5._)`${$} === ${k}`)):g=codegen_1$5.nil;return y.length&&(g=(0,codegen_1$5.or)(g,...y.map(k=>(0,codegen_1$5._)`${(0,code_1$3.usePattern)(o,k)}.test(${$})`))),(0,codegen_1$5.not)(g)}function I($){r.code((0,codegen_1$5._)`delete ${c}[${$}]`)}function b($){if(h.removeAdditional==="all"||h.removeAdditional&&n===!1){I($);return}if(n===!1){o.setParams({additionalProperty:$}),o.error(),d||r.break();return}if(typeof n=="object"&&!(0,util_1$8.alwaysValidSchema)(u,n)){const g=r.name("valid");h.removeAdditional==="failing"?(R($,g,!1),r.if((0,codegen_1$5.not)(g),()=>{o.reset(),I($)})):(R($,g),d||r.if((0,codegen_1$5.not)(g),()=>r.break()))}}function R($,g,k){const O={keyword:"additionalProperties",dataProp:$,dataPropType:util_1$8.Type.Str};k===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),o.subschema(O,g)}}};additionalProperties.default=def$a;var properties$1={};Object.defineProperty(properties$1,"__esModule",{value:!0});const validate_1=validate,code_1$2=code,util_1$7=util,additionalProperties_1$1=additionalProperties,def$9={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:r,schema:n,parentSchema:a,data:c,it:l}=o;l.opts.removeAdditional==="all"&&a.additionalProperties===void 0&&additionalProperties_1$1.default.code(new validate_1.KeywordCxt(l,additionalProperties_1$1.default,"additionalProperties"));const u=(0,code_1$2.allSchemaProperties)(n);for(const v of u)l.definedProperties.add(v);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=util_1$7.mergeEvaluated.props(r,(0,util_1$7.toHash)(u),l.props));const d=u.filter(v=>!(0,util_1$7.alwaysValidSchema)(l,n[v]));if(d.length===0)return;const h=r.name("valid");for(const v of d)f(v)?y(v):(r.if((0,code_1$2.propertyInData)(r,c,v,l.opts.ownProperties)),y(v),l.allErrors||r.else().var(h,!0),r.endIf()),o.it.definedProperties.add(v),o.ok(h);function f(v){return l.opts.useDefaults&&!l.compositeRule&&n[v].default!==void 0}function y(v){o.subschema({keyword:"properties",schemaProp:v,dataProp:v},h)}}};properties$1.default=def$9;var patternProperties={};Object.defineProperty(patternProperties,"__esModule",{value:!0});const code_1$1=code,codegen_1$4=codegen,util_1$6=util,util_2=util,def$8={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:r,schema:n,data:a,parentSchema:c,it:l}=o,{opts:u}=l,d=(0,code_1$1.allSchemaProperties)(n),h=d.filter(R=>(0,util_1$6.alwaysValidSchema)(l,n[R]));if(d.length===0||h.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;const f=u.strictSchema&&!u.allowMatchingProperties&&c.properties,y=r.name("valid");l.props!==!0&&!(l.props instanceof codegen_1$4.Name)&&(l.props=(0,util_2.evaluatedPropsToName)(r,l.props));const{props:v}=l;T();function T(){for(const R of d)f&&I(R),l.allErrors?b(R):(r.var(y,!0),b(R),r.if(y))}function I(R){for(const $ in f)new RegExp(R).test($)&&(0,util_1$6.checkStrictMode)(l,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function b(R){r.forIn("key",a,$=>{r.if((0,codegen_1$4._)`${(0,code_1$1.usePattern)(o,R)}.test(${$})`,()=>{const g=h.includes(R);g||o.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:util_2.Type.Str},y),l.opts.unevaluated&&v!==!0?r.assign((0,codegen_1$4._)`${v}[${$}]`,!0):!g&&!l.allErrors&&r.if((0,codegen_1$4.not)(y),()=>r.break())})})}}};patternProperties.default=def$8;var not={};Object.defineProperty(not,"__esModule",{value:!0});const util_1$5=util,def$7={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(o){const{gen:r,schema:n,it:a}=o;if((0,util_1$5.alwaysValidSchema)(a,n)){o.fail();return}const c=r.name("valid");o.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},c),o.failResult(c,()=>o.reset(),()=>o.error())},error:{message:"must NOT be valid"}};not.default=def$7;var anyOf={};Object.defineProperty(anyOf,"__esModule",{value:!0});const code_1=code,def$6={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};anyOf.default=def$6;var oneOf={};Object.defineProperty(oneOf,"__esModule",{value:!0});const codegen_1$3=codegen,util_1$4=util,error$3={message:"must match exactly one schema in oneOf",params:({params:o})=>(0,codegen_1$3._)`{passingSchemas: ${o.passing}}`},def$5={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:error$3,code(o){const{gen:r,schema:n,parentSchema:a,it:c}=o;if(!Array.isArray(n))throw new Error("ajv implementation error");if(c.opts.discriminator&&a.discriminator)return;const l=n,u=r.let("valid",!1),d=r.let("passing",null),h=r.name("_valid");o.setParams({passing:d}),r.block(f),o.result(u,()=>o.reset(),()=>o.error(!0));function f(){l.forEach((y,v)=>{let T;(0,util_1$4.alwaysValidSchema)(c,y)?r.var(h,!0):T=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},h),v>0&&r.if((0,codegen_1$3._)`${h} && ${u}`).assign(u,!1).assign(d,(0,codegen_1$3._)`[${d}, ${v}]`).else(),r.if(h,()=>{r.assign(u,!0),r.assign(d,v),T&&o.mergeEvaluated(T,codegen_1$3.Name)})})}}};oneOf.default=def$5;var allOf={};Object.defineProperty(allOf,"__esModule",{value:!0});const util_1$3=util,def$4={keyword:"allOf",schemaType:"array",code(o){const{gen:r,schema:n,it:a}=o;if(!Array.isArray(n))throw new Error("ajv implementation error");const c=r.name("valid");n.forEach((l,u)=>{if((0,util_1$3.alwaysValidSchema)(a,l))return;const d=o.subschema({keyword:"allOf",schemaProp:u},c);o.ok(c),o.mergeEvaluated(d)})}};allOf.default=def$4;var _if={};Object.defineProperty(_if,"__esModule",{value:!0});const codegen_1$2=codegen,util_1$2=util,error$2={message:({params:o})=>(0,codegen_1$2.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,codegen_1$2._)`{failingKeyword: ${o.ifClause}}`},def$3={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:error$2,code(o){const{gen:r,parentSchema:n,it:a}=o;n.then===void 0&&n.else===void 0&&(0,util_1$2.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const c=hasSchema(a,"then"),l=hasSchema(a,"else");if(!c&&!l)return;const u=r.let("valid",!0),d=r.name("_valid");if(h(),o.reset(),c&&l){const y=r.let("ifClause");o.setParams({ifClause:y}),r.if(d,f("then",y),f("else",y))}else c?r.if(d,f("then")):r.if((0,codegen_1$2.not)(d),f("else"));o.pass(u,()=>o.error(!0));function h(){const y=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);o.mergeEvaluated(y)}function f(y,v){return()=>{const T=o.subschema({keyword:y},d);r.assign(u,d),o.mergeValidEvaluated(T,u),v?r.assign(v,(0,codegen_1$2._)`${y}`):o.setParams({ifClause:y})}}}};function hasSchema(o,r){const n=o.schema[r];return n!==void 0&&!(0,util_1$2.alwaysValidSchema)(o,n)}_if.default=def$3;var thenElse={};Object.defineProperty(thenElse,"__esModule",{value:!0});const util_1$1=util,def$2={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:o,parentSchema:r,it:n}){r.if===void 0&&(0,util_1$1.checkStrictMode)(n,`"${o}" without "if" is ignored`)}};thenElse.default=def$2;Object.defineProperty(applicator,"__esModule",{value:!0});const additionalItems_1=additionalItems,prefixItems_1=prefixItems,items_1=items,items2020_1=items2020,contains_1=contains,dependencies_1=dependencies,propertyNames_1=propertyNames,additionalProperties_1=additionalProperties,properties_1=properties$1,patternProperties_1=patternProperties,not_1=not,anyOf_1=anyOf,oneOf_1=oneOf,allOf_1=allOf,if_1=_if,thenElse_1=thenElse;function getApplicator(o=!1){const r=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];return o?r.push(prefixItems_1.default,items2020_1.default):r.push(additionalItems_1.default,items_1.default),r.push(contains_1.default),r}applicator.default=getApplicator;var format$2={},format$1={};Object.defineProperty(format$1,"__esModule",{value:!0});const codegen_1$1=codegen,error$1={message:({schemaCode:o})=>(0,codegen_1$1.str)`must match format "${o}"`,params:({schemaCode:o})=>(0,codegen_1$1._)`{format: ${o}}`},def$1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:error$1,code(o,r){const{gen:n,data:a,$data:c,schema:l,schemaCode:u,it:d}=o,{opts:h,errSchemaPath:f,schemaEnv:y,self:v}=d;if(!h.validateFormats)return;c?T():I();function T(){const b=n.scopeValue("formats",{ref:v.formats,code:h.code.formats}),R=n.const("fDef",(0,codegen_1$1._)`${b}[${u}]`),$=n.let("fType"),g=n.let("format");n.if((0,codegen_1$1._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>n.assign($,(0,codegen_1$1._)`${R}.type || "string"`).assign(g,(0,codegen_1$1._)`${R}.validate`),()=>n.assign($,(0,codegen_1$1._)`"string"`).assign(g,R)),o.fail$data((0,codegen_1$1.or)(k(),O()));function k(){return h.strictSchema===!1?codegen_1$1.nil:(0,codegen_1$1._)`${u} && !${g}`}function O(){const P=y.$async?(0,codegen_1$1._)`(${R}.async ? await ${g}(${a}) : ${g}(${a}))`:(0,codegen_1$1._)`${g}(${a})`,U=(0,codegen_1$1._)`(typeof ${g} == "function" ? ${P} : ${g}.test(${a}))`;return(0,codegen_1$1._)`${g} && ${g} !== true && ${$} === ${r} && !${U}`}}function I(){const b=v.formats[l];if(!b){k();return}if(b===!0)return;const[R,$,g]=O(b);R===r&&o.pass(P());function k(){if(h.strictSchema===!1){v.logger.warn(U());return}throw new Error(U());function U(){return`unknown format "${l}" ignored in schema at path "${f}"`}}function O(U){const m=U instanceof RegExp?(0,codegen_1$1.regexpCode)(U):h.code.formats?(0,codegen_1$1._)`${h.code.formats}${(0,codegen_1$1.getProperty)(l)}`:void 0,w=n.scopeValue("formats",{key:l,ref:U,code:m});return typeof U=="object"&&!(U instanceof RegExp)?[U.type||"string",U.validate,(0,codegen_1$1._)`${w}.validate`]:["string",U,w]}function P(){if(typeof b=="object"&&!(b instanceof RegExp)&&b.async){if(!y.$async)throw new Error("async format in sync schema");return(0,codegen_1$1._)`await ${g}(${a})`}return typeof $=="function"?(0,codegen_1$1._)`${g}(${a})`:(0,codegen_1$1._)`${g}.test(${a})`}}}};format$1.default=def$1;Object.defineProperty(format$2,"__esModule",{value:!0});const format_1$1=format$1,format=[format_1$1.default];format$2.default=format;var metadata={};Object.defineProperty(metadata,"__esModule",{value:!0});metadata.contentVocabulary=metadata.metadataVocabulary=void 0;metadata.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];metadata.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(draft7,"__esModule",{value:!0});const core_1=core$1,validation_1=validation$1,applicator_1=applicator,format_1=format$2,metadata_1=metadata,draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];draft7.default=draft7Vocabularies;var discriminator={},types={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.DiscrError=void 0,function(r){r.Tag="tag",r.Mapping="mapping"}(o.DiscrError||(o.DiscrError={}))})(types);Object.defineProperty(discriminator,"__esModule",{value:!0});const codegen_1=codegen,types_1=types,compile_1=compile,util_1=util,error={message:({params:{discrError:o,tagName:r}})=>o===types_1.DiscrError.Tag?`tag "${r}" must be string`:`value of tag "${r}" must be in oneOf`,params:({params:{discrError:o,tag:r,tagName:n}})=>(0,codegen_1._)`{error: ${o}, tag: ${n}, tagValue: ${r}}`},def={keyword:"discriminator",type:"object",schemaType:"object",error,code(o){const{gen:r,data:n,schema:a,parentSchema:c,it:l}=o,{oneOf:u}=c;if(!l.opts.discriminator)throw new Error("discriminator: requires discriminator option");const d=a.propertyName;if(typeof d!="string")throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const h=r.let("valid",!1),f=r.const("tag",(0,codegen_1._)`${n}${(0,codegen_1.getProperty)(d)}`);r.if((0,codegen_1._)`typeof ${f} == "string"`,()=>y(),()=>o.error(!1,{discrError:types_1.DiscrError.Tag,tag:f,tagName:d})),o.ok(h);function y(){const I=T();r.if(!1);for(const b in I)r.elseIf((0,codegen_1._)`${f} === ${b}`),r.assign(h,v(I[b]));r.else(),o.error(!1,{discrError:types_1.DiscrError.Mapping,tag:f,tagName:d}),r.endIf()}function v(I){const b=r.name("valid"),R=o.subschema({keyword:"oneOf",schemaProp:I},b);return o.mergeEvaluated(R,codegen_1.Name),b}function T(){var I;const b={},R=g(c);let $=!0;for(let P=0;P<u.length;P++){let U=u[P];U!=null&&U.$ref&&!(0,util_1.schemaHasRulesButRef)(U,l.self.RULES)&&(U=compile_1.resolveRef.call(l.self,l.schemaEnv.root,l.baseId,U==null?void 0:U.$ref),U instanceof compile_1.SchemaEnv&&(U=U.schema));const m=(I=U==null?void 0:U.properties)===null||I===void 0?void 0:I[d];if(typeof m!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${d}"`);$=$&&(R||g(U)),k(m,P)}if(!$)throw new Error(`discriminator: "${d}" must be required`);return b;function g({required:P}){return Array.isArray(P)&&P.includes(d)}function k(P,U){if(P.const)O(P.const,U);else if(P.enum)for(const m of P.enum)O(m,U);else throw new Error(`discriminator: "properties/${d}" must have "const" or "enum"`)}function O(P,U){if(typeof P!="string"||P in b)throw new Error(`discriminator: "${d}" values must be unique strings`);b[P]=U}}}};discriminator.default=def;const $schema="http://json-schema.org/draft-07/schema#",$id="http://json-schema.org/draft-07/schema#",title="Core schema meta-schema",definitions={schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type=["object","boolean"],properties={$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},require$$3={$schema,$id,title,definitions,type,properties,default:!0};(function(o,r){Object.defineProperty(r,"__esModule",{value:!0}),r.MissingRefError=r.ValidationError=r.CodeGen=r.Name=r.nil=r.stringify=r.str=r._=r.KeywordCxt=void 0;const n=core$2,a=draft7,c=discriminator,l=require$$3,u=["/properties"],d="http://json-schema.org/draft-07/schema";class h extends n.default{_addVocabularies(){super._addVocabularies(),a.default.forEach(b=>this.addVocabulary(b)),this.opts.discriminator&&this.addKeyword(c.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const b=this.opts.$data?this.$dataMetaSchema(l,u):l;this.addMetaSchema(b,d,!1),this.refs["http://json-schema.org/schema"]=d}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(d)?d:void 0)}}o.exports=r=h,Object.defineProperty(r,"__esModule",{value:!0}),r.default=h;var f=validate;Object.defineProperty(r,"KeywordCxt",{enumerable:!0,get:function(){return f.KeywordCxt}});var y=codegen;Object.defineProperty(r,"_",{enumerable:!0,get:function(){return y._}}),Object.defineProperty(r,"str",{enumerable:!0,get:function(){return y.str}}),Object.defineProperty(r,"stringify",{enumerable:!0,get:function(){return y.stringify}}),Object.defineProperty(r,"nil",{enumerable:!0,get:function(){return y.nil}}),Object.defineProperty(r,"Name",{enumerable:!0,get:function(){return y.Name}}),Object.defineProperty(r,"CodeGen",{enumerable:!0,get:function(){return y.CodeGen}});var v=validation_error;Object.defineProperty(r,"ValidationError",{enumerable:!0,get:function(){return v.default}});var T=ref_error;Object.defineProperty(r,"MissingRefError",{enumerable:!0,get:function(){return T.default}})})(ajv,ajv.exports);var ajvExports=ajv.exports;const Ajv=getDefaultExportFromCjs(ajvExports);function __awaiter(o,r,n,a){return new(n||(n=Promise))(function(c,l){function u(f){try{h(a.next(f))}catch(y){l(y)}}function d(f){try{h(a.throw(f))}catch(y){l(y)}}function h(f){f.done?c(f.value):function(v){return v instanceof n?v:new n(function(T){T(v)})}(f.value).then(u,d)}h((a=a.apply(o,r||[])).next())})}class ClientResponseError extends Error{constructor(r){var n,a,c,l;super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),r!==null&&typeof r=="object"&&(this.url=typeof r.url=="string"?r.url:"",this.status=typeof r.status=="number"?r.status:0,this.isAbort=!!r.isAbort,this.originalError=r.originalError,r.response!==null&&typeof r.response=="object"?this.response=r.response:r.data!==null&&typeof r.data=="object"?this.response=r.data:this.response={}),this.originalError||r instanceof ClientResponseError||(this.originalError=r),typeof DOMException<"u"&&r instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=(n=this.response)===null||n===void 0?void 0:n.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":!((l=(c=(a=this.originalError)===null||a===void 0?void 0:a.cause)===null||c===void 0?void 0:c.message)===null||l===void 0)&&l.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return Object.assign({},this)}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(o,r){const n={};if(typeof o!="string")return n;const a=Object.assign({},r||{}).decode||defaultDecode;let c=0;for(;c<o.length;){const l=o.indexOf("=",c);if(l===-1)break;let u=o.indexOf(";",c);if(u===-1)u=o.length;else if(u<l){c=o.lastIndexOf(";",l-1)+1;continue}const d=o.slice(c,l).trim();if(n[d]===void 0){let h=o.slice(l+1,u).trim();h.charCodeAt(0)===34&&(h=h.slice(1,-1));try{n[d]=a(h)}catch{n[d]=h}}c=u+1}return n}function cookieSerialize(o,r,n){const a=Object.assign({},n||{}),c=a.encode||defaultEncode;if(!e.test(o))throw new TypeError("argument name is invalid");const l=c(r);if(l&&!e.test(l))throw new TypeError("argument val is invalid");let u=o+"="+l;if(a.maxAge!=null){const d=a.maxAge-0;if(isNaN(d)||!isFinite(d))throw new TypeError("option maxAge is invalid");u+="; Max-Age="+Math.floor(d)}if(a.domain){if(!e.test(a.domain))throw new TypeError("option domain is invalid");u+="; Domain="+a.domain}if(a.path){if(!e.test(a.path))throw new TypeError("option path is invalid");u+="; Path="+a.path}if(a.expires){if(!function(h){return Object.prototype.toString.call(h)==="[object Date]"||h instanceof Date}(a.expires)||isNaN(a.expires.valueOf()))throw new TypeError("option expires is invalid");u+="; Expires="+a.expires.toUTCString()}if(a.httpOnly&&(u+="; HttpOnly"),a.secure&&(u+="; Secure"),a.priority)switch(typeof a.priority=="string"?a.priority.toLowerCase():a.priority){case"low":u+="; Priority=Low";break;case"medium":u+="; Priority=Medium";break;case"high":u+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(a.sameSite)switch(typeof a.sameSite=="string"?a.sameSite.toLowerCase():a.sameSite){case!0:u+="; SameSite=Strict";break;case"lax":u+="; SameSite=Lax";break;case"strict":u+="; SameSite=Strict";break;case"none":u+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return u}function defaultDecode(o){return o.indexOf("%")!==-1?decodeURIComponent(o):o}function defaultEncode(o){return encodeURIComponent(o)}let t;function getTokenPayload(o){if(o)try{const r=decodeURIComponent(t(o.split(".")[1]).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(r)||{}}catch{}return{}}function isTokenExpired(o,r=0){let n=getTokenPayload(o);return!(Object.keys(n).length>0&&(!n.exp||n.exp-r>Date.now()/1e3))}t=typeof atob=="function"?atob:o=>{let r=String(o).replace(/=+$/,"");if(r.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,a,c=0,l=0,u="";a=r.charAt(l++);~a&&(n=c%4?64*n+a:a,c++%4)?u+=String.fromCharCode(255&n>>(-2*c&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return u};const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return getTokenPayload(this.token).type==="admin"}get isAuthRecord(){return getTokenPayload(this.token).type==="authRecord"}save(r,n){this.baseToken=r||"",this.baseModel=n||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(r,n=i){const a=cookieParse(r||"")[n]||"";let c={};try{c=JSON.parse(a),(typeof c===null||typeof c!="object"||Array.isArray(c))&&(c={})}catch{}this.save(c.token||"",c.model||null)}exportToCookie(r,n=i){var a,c;const l={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},u=getTokenPayload(this.token);u!=null&&u.exp?l.expires=new Date(1e3*u.exp):l.expires=new Date("1970-01-01"),r=Object.assign({},l,r);const d={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let h=cookieSerialize(n,JSON.stringify(d),r);const f=typeof Blob<"u"?new Blob([h]).size:h.length;if(d.model&&f>4096){d.model={id:(a=d==null?void 0:d.model)===null||a===void 0?void 0:a.id,email:(c=d==null?void 0:d.model)===null||c===void 0?void 0:c.email};const y=["collectionId","username","verified"];for(const v in this.model)y.includes(v)&&(d.model[v]=this.model[v]);h=cookieSerialize(n,JSON.stringify(d),r)}return h}onChange(r,n=!1){return this._onChangeCallbacks.push(r),n&&r(this.token,this.model),()=>{for(let a=this._onChangeCallbacks.length-1;a>=0;a--)if(this._onChangeCallbacks[a]==r)return delete this._onChangeCallbacks[a],void this._onChangeCallbacks.splice(a,1)}}triggerChange(){for(const r of this._onChangeCallbacks)r&&r(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(r="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=r,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(r,n){this._storageSet(this.storageKey,{token:r,model:n}),super.save(r,n)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(r){if(typeof window<"u"&&(window!=null&&window.localStorage)){const n=window.localStorage.getItem(r)||"";try{return JSON.parse(n)}catch{return n}}return this.storageFallback[r]}_storageSet(r,n){if(typeof window<"u"&&(window!=null&&window.localStorage)){let a=n;typeof n!="string"&&(a=JSON.stringify(n)),window.localStorage.setItem(r,a)}else this.storageFallback[r]=n}_storageRemove(r){var n;typeof window<"u"&&(window!=null&&window.localStorage)&&((n=window.localStorage)===null||n===void 0||n.removeItem(r)),delete this.storageFallback[r]}_bindStorageEvent(){typeof window<"u"&&(window!=null&&window.localStorage)&&window.addEventListener&&window.addEventListener("storage",r=>{if(r.key!=this.storageKey)return;const n=this._storageGet(this.storageKey)||{};super.save(n.token||"",n.model||null)})}}class BaseService{constructor(r){this.client=r}}class SettingsService extends BaseService{getAll(r){return r=Object.assign({method:"GET"},r),this.client.send("/api/settings",r)}update(r,n){return n=Object.assign({method:"PATCH",body:r},n),this.client.send("/api/settings",n)}testS3(r="storage",n){return n=Object.assign({method:"POST",body:{filesystem:r}},n),this.client.send("/api/settings/test/s3",n).then(()=>!0)}testEmail(r,n,a){return a=Object.assign({method:"POST",body:{email:r,template:n}},a),this.client.send("/api/settings/test/email",a).then(()=>!0)}generateAppleClientSecret(r,n,a,c,l,u){return u=Object.assign({method:"POST",body:{clientId:r,teamId:n,keyId:a,privateKey:c,duration:l}},u),this.client.send("/api/settings/apple/generate-client-secret",u)}}class CrudService extends BaseService{decode(r){return r}getFullList(r,n){if(typeof r=="number")return this._getFullList(r,n);let a=500;return(n=Object.assign({},r,n)).batch&&(a=n.batch,delete n.batch),this._getFullList(a,n)}getList(r=1,n=30,a){return(a=Object.assign({method:"GET"},a)).query=Object.assign({page:r,perPage:n},a.query),this.client.send(this.baseCrudPath,a).then(c=>{var l;return c.items=((l=c.items)===null||l===void 0?void 0:l.map(u=>this.decode(u)))||[],c})}getFirstListItem(r,n){return(n=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+r},n)).query=Object.assign({filter:r,skipTotal:1},n.query),this.getList(1,1,n).then(a=>{var c;if(!(!((c=a==null?void 0:a.items)===null||c===void 0)&&c.length))throw new ClientResponseError({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return a.items[0]})}getOne(r,n){return n=Object.assign({method:"GET"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(r),n).then(a=>this.decode(a))}create(r,n){return n=Object.assign({method:"POST",body:r},n),this.client.send(this.baseCrudPath,n).then(a=>this.decode(a))}update(r,n,a){return a=Object.assign({method:"PATCH",body:n},a),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(r),a).then(c=>this.decode(c))}delete(r,n){return n=Object.assign({method:"DELETE"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(r),n).then(()=>!0)}_getFullList(r=500,n){(n=n||{}).query=Object.assign({skipTotal:1},n.query);let a=[],c=l=>__awaiter(this,void 0,void 0,function*(){return this.getList(l,r||500,n).then(u=>{const d=u.items;return a=a.concat(d),d.length==u.perPage?c(l+1):a})});return c(1)}}function normalizeLegacyOptionsArgs(o,r,n,a){const c=a!==void 0;return c||n!==void 0?c?(console.warn(o),r.body=Object.assign({},r.body,n),r.query=Object.assign({},r.query,a),r):Object.assign(r,n):r}function resetAutoRefresh(o){var r,n;(n=(r=o)._resetAutoRefresh)===null||n===void 0||n.call(r)}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}update(r,n,a){return super.update(r,n,a).then(c=>{var l,u;return((l=this.client.authStore.model)===null||l===void 0?void 0:l.id)===c.id&&((u=this.client.authStore.model)===null||u===void 0?void 0:u.collectionId)===void 0&&this.client.authStore.save(this.client.authStore.token,c),c})}delete(r,n){return super.delete(r,n).then(a=>{var c,l;return a&&((c=this.client.authStore.model)===null||c===void 0?void 0:c.id)===r&&((l=this.client.authStore.model)===null||l===void 0?void 0:l.collectionId)===void 0&&this.client.authStore.clear(),a})}authResponse(r){const n=this.decode((r==null?void 0:r.admin)||{});return r!=null&&r.token&&(r!=null&&r.admin)&&this.client.authStore.save(r.token,n),Object.assign({},r,{token:(r==null?void 0:r.token)||"",admin:n})}authWithPassword(r,n,a,c){return __awaiter(this,void 0,void 0,function*(){let l={method:"POST",body:{identity:r,password:n}};l=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",l,a,c);const u=l.autoRefreshThreshold;delete l.autoRefreshThreshold,l.autoRefresh||resetAutoRefresh(this.client);let d=yield this.client.send(this.baseCrudPath+"/auth-with-password",l);return d=this.authResponse(d),u&&function(f,y,v,T){resetAutoRefresh(f);const I=f.beforeSend,b=f.authStore.model,R=f.authStore.onChange(($,g)=>{(!$||(g==null?void 0:g.id)!=(b==null?void 0:b.id)||(g!=null&&g.collectionId||b!=null&&b.collectionId)&&(g==null?void 0:g.collectionId)!=(b==null?void 0:b.collectionId))&&resetAutoRefresh(f)});f._resetAutoRefresh=function(){R(),f.beforeSend=I,delete f._resetAutoRefresh},f.beforeSend=($,g)=>__awaiter(this,void 0,void 0,function*(){var k;const O=f.authStore.token;if(!((k=g.query)===null||k===void 0)&&k.autoRefresh)return I?I($,g):{url:$,sendOptions:g};let P=f.authStore.isValid;if(P&&isTokenExpired(f.authStore.token,y))try{yield v()}catch{P=!1}P||(yield T());const U=g.headers||{};for(let m in U)if(m.toLowerCase()=="authorization"&&O==U[m]&&f.authStore.token){U[m]=f.authStore.token;break}return g.headers=U,I?I($,g):{url:$,sendOptions:g}})}(this.client,u,()=>this.authRefresh({autoRefresh:!0}),()=>this.authWithPassword(r,n,Object.assign({autoRefresh:!0},l))),d})}authRefresh(r,n){let a={method:"POST"};return a=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",a,r,n),this.client.send(this.baseCrudPath+"/auth-refresh",a).then(this.authResponse.bind(this))}requestPasswordReset(r,n,a){let c={method:"POST",body:{email:r}};return c=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",c,n,a),this.client.send(this.baseCrudPath+"/request-password-reset",c).then(()=>!0)}confirmPasswordReset(r,n,a,c,l){let u={method:"POST",body:{token:r,password:n,passwordConfirm:a}};return u=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",u,c,l),this.client.send(this.baseCrudPath+"/confirm-password-reset",u).then(()=>!0)}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentTopics=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}subscribe(r,n){var a;return __awaiter(this,void 0,void 0,function*(){if(!r)throw new Error("topic must be set.");const c=function(l){const u=l;let d;try{d=JSON.parse(u==null?void 0:u.data)}catch{}n(d||{})};return this.subscriptions[r]||(this.subscriptions[r]=[]),this.subscriptions[r].push(c),this.isConnected?this.subscriptions[r].length===1?yield this.submitSubscriptions():(a=this.eventSource)===null||a===void 0||a.addEventListener(r,c):yield this.connect(),()=>__awaiter(this,void 0,void 0,function*(){return this.unsubscribeByTopicAndListener(r,c)})})}unsubscribe(r){var n;return __awaiter(this,void 0,void 0,function*(){if(this.hasSubscriptionListeners(r)){if(r){for(let a of this.subscriptions[r])(n=this.eventSource)===null||n===void 0||n.removeEventListener(r,a);delete this.subscriptions[r]}else this.subscriptions={};this.hasSubscriptionListeners()?this.hasSubscriptionListeners(r)||(yield this.submitSubscriptions()):this.disconnect()}})}unsubscribeByPrefix(r){var n;return __awaiter(this,void 0,void 0,function*(){let a=!1;for(let c in this.subscriptions)if(c.startsWith(r)){a=!0;for(let l of this.subscriptions[c])(n=this.eventSource)===null||n===void 0||n.removeEventListener(c,l);delete this.subscriptions[c]}a&&(this.hasSubscriptionListeners()?yield this.submitSubscriptions():this.disconnect())})}unsubscribeByTopicAndListener(r,n){var a;return __awaiter(this,void 0,void 0,function*(){if(!Array.isArray(this.subscriptions[r])||!this.subscriptions[r].length)return;let c=!1;for(let l=this.subscriptions[r].length-1;l>=0;l--)this.subscriptions[r][l]===n&&(c=!0,delete this.subscriptions[r][l],this.subscriptions[r].splice(l,1),(a=this.eventSource)===null||a===void 0||a.removeEventListener(r,n));c&&(this.subscriptions[r].length||delete this.subscriptions[r],this.hasSubscriptionListeners()?this.hasSubscriptionListeners(r)||(yield this.submitSubscriptions()):this.disconnect())})}hasSubscriptionListeners(r){var n,a;if(this.subscriptions=this.subscriptions||{},r)return!!(!((n=this.subscriptions[r])===null||n===void 0)&&n.length);for(let c in this.subscriptions)if(!((a=this.subscriptions[c])===null||a===void 0)&&a.length)return!0;return!1}submitSubscriptions(){return __awaiter(this,void 0,void 0,function*(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},query:{requestKey:this.getSubscriptionsCancelKey()}}).catch(r=>{if(!(r!=null&&r.isAbort))throw r})})}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getNonEmptySubscriptionTopics(){const r=[];for(let n in this.subscriptions)this.subscriptions[n].length&&r.push(n);return r}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let r in this.subscriptions)for(let n of this.subscriptions[r])this.eventSource.addEventListener(r,n)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let r in this.subscriptions)for(let n of this.subscriptions[r])this.eventSource.removeEventListener(r,n)}connect(){return __awaiter(this,void 0,void 0,function*(){if(!(this.reconnectAttempts>0))return new Promise((r,n)=>{this.pendingConnects.push({resolve:r,reject:n}),this.pendingConnects.length>1||this.initConnect()})})}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout(()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))},this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=r=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",r=>{const n=r;this.clientId=n==null?void 0:n.lastEventId,this.submitSubscriptions().then(()=>__awaiter(this,void 0,void 0,function*(){let a=3;for(;this.hasUnsentSubscriptions()&&a>0;)a--,yield this.submitSubscriptions()})).then(()=>{for(let a of this.pendingConnects)a.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId)}).catch(a=>{this.clientId="",this.connectErrorHandler(a)})})}hasUnsentSubscriptions(){const r=this.getNonEmptySubscriptionTopics();if(r.length!=this.lastSentTopics.length)return!0;for(const n of r)if(!this.lastSentTopics.includes(n))return!0;return!1}connectErrorHandler(r){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let a of this.pendingConnects)a.reject(new ClientResponseError(r));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const n=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout(()=>{this.initConnect()},n)}disconnect(r=!1){var n;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),(n=this.eventSource)===null||n===void 0||n.close(),this.eventSource=null,this.clientId="",!r){this.reconnectAttempts=0;for(let a of this.pendingConnects)a.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(r,n){super(r),this.collectionIdOrName=n}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}subscribeOne(r,n){return __awaiter(this,void 0,void 0,function*(){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),this.client.realtime.subscribe(this.collectionIdOrName+"/"+r,n)})}subscribe(r,n){return __awaiter(this,void 0,void 0,function*(){if(typeof r=="function")return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),this.client.realtime.subscribe(this.collectionIdOrName,r);if(!n)throw new Error("Missing subscription callback.");if(r==="")throw new Error("Missing topic.");let a=this.collectionIdOrName;return r!=="*"&&(a+="/"+r),this.client.realtime.subscribe(a,n)})}unsubscribe(r){return __awaiter(this,void 0,void 0,function*(){return r==="*"?this.client.realtime.unsubscribe(this.collectionIdOrName):r?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+r):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)})}getFullList(r,n){if(typeof r=="number")return super.getFullList(r,n);const a=Object.assign({},r,n);return super.getFullList(a)}getList(r=1,n=30,a){return super.getList(r,n,a)}getFirstListItem(r,n){return super.getFirstListItem(r,n)}getOne(r,n){return super.getOne(r,n)}create(r,n){return super.create(r,n)}update(r,n,a){return super.update(r,n,a).then(c=>{var l,u,d;return((l=this.client.authStore.model)===null||l===void 0?void 0:l.id)!==(c==null?void 0:c.id)||((u=this.client.authStore.model)===null||u===void 0?void 0:u.collectionId)!==this.collectionIdOrName&&((d=this.client.authStore.model)===null||d===void 0?void 0:d.collectionName)!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,c),c})}delete(r,n){return super.delete(r,n).then(a=>{var c,l,u;return!a||((c=this.client.authStore.model)===null||c===void 0?void 0:c.id)!==r||((l=this.client.authStore.model)===null||l===void 0?void 0:l.collectionId)!==this.collectionIdOrName&&((u=this.client.authStore.model)===null||u===void 0?void 0:u.collectionName)!==this.collectionIdOrName||this.client.authStore.clear(),a})}authResponse(r){const n=this.decode((r==null?void 0:r.record)||{});return this.client.authStore.save(r==null?void 0:r.token,n),Object.assign({},r,{token:(r==null?void 0:r.token)||"",record:n})}listAuthMethods(r){return r=Object.assign({method:"GET"},r),this.client.send(this.baseCollectionPath+"/auth-methods",r).then(n=>Object.assign({},n,{usernamePassword:!!(n!=null&&n.usernamePassword),emailPassword:!!(n!=null&&n.emailPassword),authProviders:Array.isArray(n==null?void 0:n.authProviders)?n==null?void 0:n.authProviders:[]}))}authWithPassword(r,n,a,c){let l={method:"POST",body:{identity:r,password:n}};return l=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",l,a,c),this.client.send(this.baseCollectionPath+"/auth-with-password",l).then(u=>this.authResponse(u))}authWithOAuth2Code(r,n,a,c,l,u,d){let h={method:"POST",body:{provider:r,code:n,codeVerifier:a,redirectUrl:c,createData:l}};return h=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",h,u,d),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",h).then(f=>this.authResponse(f))}authWithOAuth2(...r){return __awaiter(this,void 0,void 0,function*(){if(r.length>1||typeof(r==null?void 0:r[0])=="string")return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code((r==null?void 0:r[0])||"",(r==null?void 0:r[1])||"",(r==null?void 0:r[2])||"",(r==null?void 0:r[3])||"",(r==null?void 0:r[4])||{},(r==null?void 0:r[5])||{},(r==null?void 0:r[6])||{});const n=(r==null?void 0:r[0])||{},a=(yield this.listAuthMethods()).authProviders.find(h=>h.name===n.provider);if(!a)throw new ClientResponseError(new Error(`Missing or invalid provider "${n.provider}".`));const c=this.client.buildUrl("/api/oauth2-redirect"),l=new RealtimeService(this.client);let u=null;function d(){u==null||u.close(),l.unsubscribe()}return n.urlCallback||(u=openBrowserPopup(void 0)),new Promise((h,f)=>__awaiter(this,void 0,void 0,function*(){var y;try{yield l.subscribe("@oauth2",b=>__awaiter(this,void 0,void 0,function*(){const R=l.clientId;try{if(!b.state||R!==b.state)throw new Error("State parameters don't match.");const $=Object.assign({},n);delete $.provider,delete $.scopes,delete $.createData,delete $.urlCallback;const g=yield this.authWithOAuth2Code(a.name,b.code,a.codeVerifier,c,n.createData,$);h(g)}catch($){f(new ClientResponseError($))}d()}));const v={state:l.clientId};!((y=n.scopes)===null||y===void 0)&&y.length&&(v.scope=n.scopes.join(" "));const T=this._replaceQueryParams(a.authUrl+c,v);yield(n.urlCallback||function(b){u?u.location.href=b:u=openBrowserPopup(b)})(T)}catch(v){d(),f(new ClientResponseError(v))}}))})}authRefresh(r,n){let a={method:"POST"};return a=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",a,r,n),this.client.send(this.baseCollectionPath+"/auth-refresh",a).then(c=>this.authResponse(c))}requestPasswordReset(r,n,a){let c={method:"POST",body:{email:r}};return c=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",c,n,a),this.client.send(this.baseCollectionPath+"/request-password-reset",c).then(()=>!0)}confirmPasswordReset(r,n,a,c,l){let u={method:"POST",body:{token:r,password:n,passwordConfirm:a}};return u=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",u,c,l),this.client.send(this.baseCollectionPath+"/confirm-password-reset",u).then(()=>!0)}requestVerification(r,n,a){let c={method:"POST",body:{email:r}};return c=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",c,n,a),this.client.send(this.baseCollectionPath+"/request-verification",c).then(()=>!0)}confirmVerification(r,n,a){let c={method:"POST",body:{token:r}};return c=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",c,n,a),this.client.send(this.baseCollectionPath+"/confirm-verification",c).then(()=>!0)}requestEmailChange(r,n,a){let c={method:"POST",body:{newEmail:r}};return c=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",c,n,a),this.client.send(this.baseCollectionPath+"/request-email-change",c).then(()=>!0)}confirmEmailChange(r,n,a,c){let l={method:"POST",body:{token:r,password:n}};return l=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",l,a,c),this.client.send(this.baseCollectionPath+"/confirm-email-change",l).then(()=>!0)}listExternalAuths(r,n){return n=Object.assign({method:"GET"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(r)+"/external-auths",n)}unlinkExternalAuth(r,n,a){return a=Object.assign({method:"DELETE"},a),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(r)+"/external-auths/"+encodeURIComponent(n),a).then(()=>!0)}_replaceQueryParams(r,n={}){let a=r,c="";r.indexOf("?")>=0&&(a=r.substring(0,r.indexOf("?")),c=r.substring(r.indexOf("?")+1));const l={},u=c.split("&");for(const d of u){if(d=="")continue;const h=d.split("=");l[decodeURIComponent(h[0].replace(/\+/g," "))]=decodeURIComponent((h[1]||"").replace(/\+/g," "))}for(let d in n)n.hasOwnProperty(d)&&(n[d]==null?delete l[d]:l[d]=n[d]);c="";for(let d in l)l.hasOwnProperty(d)&&(c!=""&&(c+="&"),c+=encodeURIComponent(d.replace(/%20/g,"+"))+"="+encodeURIComponent(l[d].replace(/%20/g,"+")));return c!=""?a+"?"+c:a}}function openBrowserPopup(o){if(typeof window>"u"||!(window!=null&&window.open))throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let r=1024,n=768,a=window.innerWidth,c=window.innerHeight;r=r>a?a:r,n=n>c?c:n;let l=a/2-r/2,u=c/2-n/2;return window.open(o,"popup_window","width="+r+",height="+n+",top="+u+",left="+l+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}import(r,n=!1,a){return __awaiter(this,void 0,void 0,function*(){return a=Object.assign({method:"PUT",body:{collections:r,deleteMissing:n}},a),this.client.send(this.baseCrudPath+"/import",a).then(()=>!0)})}}class LogService extends BaseService{getRequestsList(r=1,n=30,a){return(a=Object.assign({method:"GET"},a)).query=Object.assign({page:r,perPage:n},a.query),this.client.send("/api/logs/requests",a)}getRequest(r,n){return n=Object.assign({method:"GET"},n),this.client.send("/api/logs/requests/"+encodeURIComponent(r),n)}getRequestsStats(r){return r=Object.assign({method:"GET"},r),this.client.send("/api/logs/requests/stats",r)}}class HealthService extends BaseService{check(r){return r=Object.assign({method:"GET"},r),this.client.send("/api/health",r)}}class FileService extends BaseService{getUrl(r,n,a={}){if(!n||!(r!=null&&r.id)||!(r!=null&&r.collectionId)&&!(r!=null&&r.collectionName))return"";const c=[];c.push("api"),c.push("files"),c.push(encodeURIComponent(r.collectionId||r.collectionName)),c.push(encodeURIComponent(r.id)),c.push(encodeURIComponent(n));let l=this.client.buildUrl(c.join("/"));if(Object.keys(a).length){a.download===!1&&delete a.download;const u=new URLSearchParams(a);l+=(l.includes("?")?"&":"?")+u}return l}getToken(r){return r=Object.assign({method:"POST"},r),this.client.send("/api/files/token",r).then(n=>(n==null?void 0:n.token)||"")}}class BackupService extends BaseService{getFullList(r){return r=Object.assign({method:"GET"},r),this.client.send("/api/backups",r)}create(r,n){return n=Object.assign({method:"POST",body:{name:r}},n),this.client.send("/api/backups",n).then(()=>!0)}upload(r,n){return n=Object.assign({method:"POST",body:r},n),this.client.send("/api/backups/upload",n).then(()=>!0)}delete(r,n){return n=Object.assign({method:"DELETE"},n),this.client.send(`/api/backups/${encodeURIComponent(r)}`,n).then(()=>!0)}restore(r,n){return n=Object.assign({method:"POST"},n),this.client.send(`/api/backups/${encodeURIComponent(r)}/restore`,n).then(()=>!0)}getDownloadUrl(r,n){return this.client.buildUrl(`/api/backups/${encodeURIComponent(n)}?token=${encodeURIComponent(r)}`)}}const s=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];class Client{constructor(r="/",n,a="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=r,this.lang=a,this.authStore=n||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(r){return this.recordServices[r]||(this.recordServices[r]=new RecordService(this,r)),this.recordServices[r]}autoCancellation(r){return this.enableAutoCancellation=!!r,this}cancelRequest(r){return this.cancelControllers[r]&&(this.cancelControllers[r].abort(),delete this.cancelControllers[r]),this}cancelAllRequests(){for(let r in this.cancelControllers)this.cancelControllers[r].abort();return this.cancelControllers={},this}getFileUrl(r,n,a={}){return this.files.getUrl(r,n,a)}buildUrl(r){var n;let a=this.baseUrl;return typeof window>"u"||!window.location||a.startsWith("https://")||a.startsWith("http://")||(a=!((n=window.location.origin)===null||n===void 0)&&n.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(a+=window.location.pathname||"/",a+=a.endsWith("/")?"":"/"),a+=this.baseUrl),r&&(a+=a.endsWith("/")?"":"/",a+=r.startsWith("/")?r.substring(1):r),a}send(r,n){return __awaiter(this,void 0,void 0,function*(){n=this.initSendOptions(r,n);let a=this.buildUrl(r);if(this.beforeSend){const c=Object.assign({},yield this.beforeSend(a,n));c.url!==void 0||c.options!==void 0?(a=c.url||a,n=c.options||n):Object.keys(c).length&&(n=c,console!=null&&console.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(n.query!==void 0){const c=this.serializeQueryParams(n.query);c&&(a+=(a.includes("?")?"&":"?")+c),delete n.query}return this.getHeader(n.headers,"Content-Type")=="application/json"&&n.body&&typeof n.body!="string"&&(n.body=JSON.stringify(n.body)),(n.fetch||fetch)(a,n).then(c=>__awaiter(this,void 0,void 0,function*(){let l={};try{l=yield c.json()}catch{}if(this.afterSend&&(l=yield this.afterSend(c,l)),c.status>=400)throw new ClientResponseError({url:c.url,status:c.status,data:l});return l})).catch(c=>{throw new ClientResponseError(c)})})}initSendOptions(r,n){(n=Object.assign({method:"GET"},n)).query=n.query||{},n.body=this.convertToFormDataIfNeeded(n.body);for(let a in n)s.includes(a)||(n.query[a]=n[a],delete n[a]);if(n.query=Object.assign({},n.params,n.query),n.requestKey===void 0&&(n.$autoCancel===!1||n.query.$autoCancel===!1?n.requestKey=null:(n.$cancelKey||n.query.$cancelKey)&&(n.requestKey=n.$cancelKey||n.query.$cancelKey)),delete n.$autoCancel,delete n.query.$autoCancel,delete n.$cancelKey,delete n.query.$cancelKey,this.getHeader(n.headers,"Content-Type")!==null||this.isFormData(n.body)||(n.headers=Object.assign({},n.headers,{"Content-Type":"application/json"})),this.getHeader(n.headers,"Accept-Language")===null&&(n.headers=Object.assign({},n.headers,{"Accept-Language":this.lang})),this.authStore.token&&this.getHeader(n.headers,"Authorization")===null&&(n.headers=Object.assign({},n.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&n.requestKey!==null){const a=n.requestKey||(n.method||"GET")+r;delete n.requestKey,this.cancelRequest(a);const c=new AbortController;this.cancelControllers[a]=c,n.signal=c.signal}return n}convertToFormDataIfNeeded(r){if(typeof FormData>"u"||r===void 0||typeof r!="object"||r===null||this.isFormData(r)||!this.hasBlobField(r))return r;const n=new FormData;for(let a in r){const c=Array.isArray(r[a])?r[a]:[r[a]];for(let l of c)n.append(a,l)}return n}hasBlobField(r){for(let n in r){const a=Array.isArray(r[n])?r[n]:[r[n]];for(let c of a)if(typeof Blob<"u"&&c instanceof Blob||typeof File<"u"&&c instanceof File)return!0}return!1}getHeader(r,n){r=r||{},n=n.toLowerCase();for(let a in r)if(a.toLowerCase()==n)return r[a];return null}isFormData(r){return r&&(r.constructor.name==="FormData"||typeof FormData<"u"&&r instanceof FormData)}serializeQueryParams(r){const n=[];for(const a in r){if(r[a]===null)continue;const c=r[a],l=encodeURIComponent(a);if(Array.isArray(c))for(const u of c)n.push(l+"="+encodeURIComponent(u));else c instanceof Date?n.push(l+"="+encodeURIComponent(c.toISOString())):typeof c!==null&&typeof c=="object"?n.push(l+"="+encodeURIComponent(JSON.stringify(c))):n.push(l+"="+encodeURIComponent(c))}return n.join("&")}}const SAFECATCH_TTL_MS=5e3,safeCatch=(o,r,n,a=SAFECATCH_TTL_MS)=>async(...c)=>{const l=`${o}:${nanoid$1()}`,u=chalk$1.red(`safeCatch:${l}`),{raw:d,error:h,warn:f,dbg:y}=r.create(u);d("args",c);const v=setTimeout(()=>{f(`timeout ${a}ms waiting for ${u}`)},a);try{const T=await n(...c);return d("finished"),T}catch(T){const I=JSON.stringify(c);throw T instanceof ClientResponseError?T.status===400?y(`PocketBase API error: It looks like you don't have permission to make this request. Raw error: ${T}. Payload: ${I}`):T.status===0?y(`Client request aborted (possible duplicate request or real error). Raw error: ${T}. Payload: ${I}`):T.status===404?y(`Record not found. Raw error: ${T}. Payload: ${I}`):y(`Unknown PocketBase API error. Raw error: ${T}. Payload: ${I}`):y(`Caught an unknown error. Raw error: ${T}. Payload: ${I}`),T}finally{clearTimeout(v)}},CreateInstancePayloadSchema={type:"object",properties:{subdomain:{type:"string"}},required:["subdomain"],additionalProperties:!1},RenameInstancePayloadSchema={type:"object",properties:{instanceId:{type:"string"},subdomain:{type:"string"}},required:["instanceId","subdomain"],additionalProperties:!1},SECRET_KEY_REGEX=/^[A-Z][A-Z0-9_]*$/,SaveSecretsPayloadSchema={type:"object",properties:{instanceId:{type:"string"},secrets:{type:"object",patternProperties:{[SECRET_KEY_REGEX.source]:{anyOf:[{type:"string"}]}},required:[]}},required:["instanceId","secrets"],additionalProperties:!1},SaveVersionPayloadSchema={type:"object",properties:{instanceId:{type:"string"},version:{type:"string"}},required:["instanceId","version"],additionalProperties:!1},SetInstanceMaintenancePayloadSchema={type:"object",properties:{instanceId:{type:"string"},maintenance:{type:"boolean"}},required:["instanceId","maintenance"],additionalProperties:!1},RPC_COLLECTION="rpc";var RpcCommands=(o=>(o.CreateInstance="create-instance",o.SaveSecrets="save-secrets",o.SaveVersion="save-version",o.SetInstanceMaintenance="set-instance-maintenance",o.RenameInstance="rename-instance",o))(RpcCommands||{}),RpcStatus=(o=>(o.New="new",o.Queued="queued",o.Running="running",o.Starting="starting",o.FinishedSuccess="finished-success",o.FinishedError="finished-error",o))(RpcStatus||{});new Ajv;const createRpcHelper=o=>{const r=LoggerService().create("RpcHelper"),{client:n,watchHelper:{watchById:a}}=o;return{mkRpc:(l,u)=>{const d=new Ajv().compile(u);return safeCatch(l,LoggerService(),async(h,f)=>{const y=r.create(l),{dbg:v,error:T}=y;v("Executing RPC");const I=n.authStore.model;if(!I)throw new Error("Expected authenticated user here.");if(!d(h))throw new Error(`Invalid RPC payload: ${d.errors}`);const{id:b}=I,R={id:newId(),cmd:l,userId:b,payload:h};return y.breadcrumb(R.id),v({rpcIn:R}),new Promise(($,g)=>{(async()=>{v(`Watching ${R.id}`),await a(RPC_COLLECTION,R.id,(O,P)=>{v("Got an RPC change",O),f==null||f(O),O.record.status===RpcStatus.FinishedSuccess&&(v("RPC finished successfully",O),P(),$(O.record.result)),O.record.status===RpcStatus.FinishedError&&(v("RPC finished unsuccessfully",O),P(),g(new ClientResponseError(O.record.result)))},{initialFetch:!1,pollIntervalMs:100}),v(`Creating ${R.id}`);const k=await n.collection(RPC_COLLECTION).create(R);v(`Created ${k.id}`)})().catch(k=>{T(k),g(k)})})})}}},createWatchHelper=o=>{const{client:r}=o;return{watchById:async(c,l,u,d)=>{const{dbg:h}=LoggerService().create(`watchById:${c}:${l}`),f={initialFetch:!0,pollIntervalMs:0,...d},{initialFetch:y,pollIntervalMs:v}=f,T=createTimerManager();h(`watching ${c}:${l}`);let I=!1,b=!1;v&&(h(`Configuring polling for ${v}ms`),T.repeat(async()=>{h(`Checking ${l} by polling`);try{const g=await r.collection(c).getOne(l);I=!0,h(`Got an update polling ${c}:${l}`),u({action:"poll",record:g},R)}catch(g){h("Failed to poll at interval",g)}return!0},v));const R=async()=>{h(`Unsubbing ${c}:${l}`),T.shutdown(),b=!0,await $()},$=await r.collection(c).subscribe(l,g=>{h(`Got an update watching ${c}:${l}`,g),u(g,R)});if(y)try{const g=await r.collection(c).getOne(l);!I&&!b&&(h(`Sending initial update for ${c}:${l}`,g),u({action:"initial",record:g},R))}catch{throw new Error(`Expected ${c}.${l} to exist.`)}return R},watchAllById:async(c,l,u,d,h=!0)=>{let f={};const y=r.collection(c).subscribe("*",v=>{v.record[l]===u&&(f[v.record.id]=!0,d(v))});return h&&(await r.collection(c).getFullList(100,{filter:`${l.toString()} = '${u}'`})).forEach(T=>{f[T.id]||d({action:"initial",record:T})}),y}}},createGenericSyncEvent=()=>{let o=0;const r={};return[c=>{const l=o++;return r[l]=c,()=>{delete r[l]}},c=>{forEach(r,l=>l(c))}]};async function getBytes(o,r){const n=o.getReader();let a;for(;!(a=await n.read()).done;)r(a.value)}function getLines(o){let r,n,a,c=!1;return function(u){r===void 0?(r=u,n=0,a=-1):r=concat(r,u);const d=r.length;let h=0;for(;n<d;){c&&(r[n]===10&&(h=++n),c=!1);let f=-1;for(;n<d&&f===-1;++n)switch(r[n]){case 58:a===-1&&(a=n-h);break;case 13:c=!0;case 10:f=n;break}if(f===-1)break;o(r.subarray(h,f),a),h=n,a=-1}h===d?r=void 0:h!==0&&(r=r.subarray(h),n-=h)}}function getMessages(o,r,n){let a=newMessage();const c=new TextDecoder;return function(u,d){if(u.length===0)n==null||n(a),a=newMessage();else if(d>0){const h=c.decode(u.subarray(0,d)),f=d+(u[d+1]===32?2:1),y=c.decode(u.subarray(f));switch(h){case"data":a.data=a.data?a.data+`
`+y:y;break;case"event":a.event=y;break;case"id":o(a.id=y);break;case"retry":const v=parseInt(y,10);isNaN(v)||r(a.retry=v);break}}}}function concat(o,r){const n=new Uint8Array(o.length+r.length);return n.set(o),n.set(r,o.length),n}function newMessage(){return{data:"",event:"",id:"",retry:void 0}}const EventStreamContentType="text/event-stream",DefaultRetryInterval=1e3,LastEventId="last-event-id";function fetchEventSource(o,{signal:r,headers:n,onopen:a,onmessage:c,onclose:l,onerror:u,openWhenHidden:d,fetch:h,...f}){return new Promise((y,v)=>{var U;const T={...n};T.accept||(T.accept=EventStreamContentType);let I;function b(){var m;I.abort(),(m=globalThis.document)!=null&&m.hidden||P()}globalThis.document&&!d&&((U=globalThis.document)==null||U.addEventListener("visibilitychange",b));let R=DefaultRetryInterval,$;function g(){var m;(m=globalThis.document)==null||m.removeEventListener("visibilitychange",b),globalThis.clearTimeout($),I.abort()}r==null||r.addEventListener("abort",()=>{g(),y()});const k=h??globalThis.fetch,O=a??defaultOnOpen;async function P(){I&&I.abort(),I=new AbortController;try{const m=await k(o,{...f,headers:T,signal:I.signal});await O(m),await getBytes(m.body,getLines(getMessages(w=>{w?T[LastEventId]=w:delete T[LastEventId]},w=>{R=w},c))),l==null||l(),g(),y()}catch(m){if(!I.signal.aborted)try{const w=(u==null?void 0:u(m))??R;globalThis.clearTimeout($),$=globalThis.setTimeout(P,w)}catch(w){g(),v(w)}}}P()})}function defaultOnOpen(o){const r=o.headers.get("content-type");if(!(r!=null&&r.startsWith(EventStreamContentType)))throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${r}`)}const createPocketbaseClient=o=>{const{url:r}=o,n=LoggerService(),{dbg:a,error:c}=n,l=new Client(r),{authStore:u}=l,d=()=>u.model,h=()=>u.isValid,f=()=>u.clear(),y=(J,F)=>l.collection("users").create({email:J,password:F,passwordConfirm:F}).then(()=>l.collection("users").requestVerification(J)),v=J=>l.collection("users").confirmVerification(J).then(F=>F),T=J=>l.collection("users").requestPasswordReset(J).then(()=>!0),I=(J,F)=>l.collection("users").confirmPasswordReset(J,F,F).then(A=>A),b=(J,F)=>l.collection("users").authWithPassword(J,F),R=()=>l.collection("users").authRefresh(),$=createWatchHelper({client:l}),{watchById:g,watchAllById:k}=$,O=createRpcHelper({client:l,watchHelper:$}),{mkRpc:P}=O,U=P(RpcCommands.CreateInstance,CreateInstancePayloadSchema),m=P(RpcCommands.SaveSecrets,SaveSecretsPayloadSchema),w=P(RpcCommands.SaveVersion,SaveVersionPayloadSchema),D=P(RpcCommands.RenameInstance,RenameInstancePayloadSchema),G=P(RpcCommands.SetInstanceMaintenance,SetInstanceMaintenancePayloadSchema),B=J=>l.collection("instances").getOne(J),V=async(J,F)=>g("instances",J,F),z=async()=>(await l.collection("instances").getFullList()).reduce((J,F)=>(J[F.id]=F,J),{}),te=J=>J instanceof ClientResponseError?J.data.message&&keys(J.data.data).length===0?[J.data.message]:map(J.data.data,(F,A)=>F?F.message:void 0).filter(F=>!!F):[J.message],Z=async()=>{const J=l.authStore.model;assertExists(J,"Login required"),await l.collection("users").requestVerification(J.email)},he=()=>{const{isAdmin:J,model:F,token:A,isValid:M}=l.authStore;if(J)throw new Error("Admin models not supported");if(F&&!F.email)throw new Error("Expected model to be a user here");return{token:A,model:F,isValid:M}},[ue,me]=createGenericSyncEvent();{l.authStore.onChange(()=>{me(l.authStore)}),R().catch(F=>{a(`Clearing auth store: ${F}`),l.authStore.clear()}).finally(()=>{me(l.authStore)});const J=ue(F=>{const{model:A,isAdmin:M}=F;if(A&&!M){if(A.verified){J();return}setTimeout(R,1e3)}})}return{client:l,saveSecrets:m,watchInstanceLog:(J,F,A=100)=>{const{dbg:M,trace:N}=n.create("watchInstanceLog"),p=l.authStore.exportToCookie(),E=new AbortController,q=E.signal,x=()=>{const K=INSTANCE_URL(J,"logs");M(`Subscribing to ${K}`),fetchEventSource(K,{method:"POST",headers:{"Content-Type":"application/json",Authorization:l.authStore.token},body:JSON.stringify({instanceId:J,n:A,auth:p}),onmessage:Y=>{M("Got stream event",Y);const{}=Y,X=JSON.parse(Y.data);M("Log is",X),F(X)},onopen:async Y=>{M("Stream is open",Y)},onerror:Y=>{M("Stream error",Y)},onclose:()=>{setTimeout(x,100),M("Stream closed")},signal:q})};return x(),()=>{E.abort()}},getAuthStoreProps:he,parseError:te,getInstanceById:B,createInstance:U,authViaEmail:b,createUser:y,requestPasswordReset:T,requestPasswordResetConfirm:I,confirmVerification:v,logOut:f,onAuthChange:ue,isLoggedIn:h,user:d,watchInstanceById:V,getAllInstancesById:z,resendVerificationEmail:Z,renameInstance:D,setInstanceMaintenance:G,saveVersion:w}},client=(()=>{let o;return()=>{if(o)return o;const{info:r}=LoggerService();return r("Initializing pocketbase client"),o=createPocketbaseClient({url:PUBLIC_MOTHERSHIP_URL}),o}})();export{APP_URL as A,DOCS_URL as D,FTP_URL as F,INSTANCE_ADMIN_URL as I,LoggerService as L,PUBLIC_DEBUG as P,SECRET_KEY_REGEX as S,assert as a,LogLevelName as b,client as c,INSTANCE_URL as d,assertExists as e,forEach as f,getDefaultExportFromCjs as g,commonjsGlobal as h,nanoid$1 as n,reduce as r,values as v};