wabe 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -85,6 +85,10 @@ export interface SessionConfig {
85
85
  * Set to true to automatically store the session tokens in cookies
86
86
  */
87
87
  cookieSession?: boolean;
88
+ /**
89
+ * The JWT secret used to sign the session tokens
90
+ */
91
+ jwtSecret: string;
88
92
  }
89
93
  export interface AuthenticationConfig<T extends WabeTypes> {
90
94
  session?: SessionConfig;
package/dist/index.js CHANGED
@@ -202,7 +202,7 @@ ${$.toString("base64")}
202
202
  `))}else B.enqueue(m9.Buffer.from(`\r
203
203
  --${A}--\r
204
204
  `)),B.close()}})}function m01($,A,F){return Object.defineProperty(A,"name",{configurable:!0,enumerable:!0,value:F||A.name||$}),A}function v01($){return $?.arrayBuffer!=null}});var gY=C((x01)=>{Object.defineProperty(x01,"__esModule",{value:!0});x01.PonyfillBody=void 0;var ls1=dY(),A7=p("node:buffer"),x8=p("node:stream"),cs1=ls1.__importDefault(o11()),IB=fY(),as1=mV(),p01=xV(),v9=JA(),J4=D9(),y2;(function($){$.ReadableStream="ReadableStream",$.Blob="Blob",$.FormData="FormData",$.String="String",$.Readable="Readable",$.Buffer="Buffer",$.AsyncIterable="AsyncIterable"})(y2||(y2={}));class g01{bodyInit;options;bodyUsed=!1;contentType=null;contentLength=null;constructor($,A={}){this.bodyInit=$,this.options=A;let{bodyFactory:F,contentType:D,contentLength:B,bodyType:E,buffer:w}=is1($);this._bodyFactory=F,this.contentType=D,this.contentLength=B,this.bodyType=E,this._buffer=w}bodyType;_bodyFactory=()=>null;_generatedBody=null;_buffer;generateBody(){if(this._generatedBody?.readable?.destroyed&&this._buffer)this._generatedBody.readable=x8.Readable.from(this._buffer);if(this._generatedBody)return this._generatedBody;let $=this._bodyFactory();return this._generatedBody=$,$}handleContentLengthHeader($=!1){let A=this.headers.get("content-type");if(!A){if(this.contentType)this.headers.set("content-type",this.contentType)}else this.contentType=A;let F=this.headers.get("content-length");if($&&this.bodyInit==null&&!F)this.contentLength=0,this.headers.set("content-length","0");if(!F){if(this.contentLength)this.headers.set("content-length",this.contentLength.toString())}else this.contentLength=parseInt(F,10)}get body(){let $=this.generateBody();if($!=null){let A=$,F=$.readable;return new Proxy($.readable,{get(D,B){if(B in A){let E=A[B];if(typeof E==="function")return E.bind(A);return E}if(B in F){let E=F[B];if(typeof E==="function")return E.bind(F);return E}}})}return null}_chunks=null;_collectChunksFromReadable(){if(this._chunks)return J4.fakePromise(this._chunks);if(this.bodyType===y2.AsyncIterable){let A=this.bodyInit[Symbol.asyncIterator](),F=()=>{return A.next().then(({value:D,done:B})=>{if(this._chunks||=[],D)this._chunks.push(D);if(!B)return F();return this._chunks})};return F()}let $=this.generateBody();if(!$)return J4.fakePromise([]);return this._chunks=[],$.readable.on("data",(A)=>{this._chunks.push(A)}),new Promise((A,F)=>{$.readable.once("end",()=>{A(this._chunks)}),$.readable.once("error",(D)=>{F(D)})})}_blob=null;blob(){if(this._blob)return J4.fakePromise(this._blob);if(this.bodyType===y2.Blob)return this._blob=this.bodyInit,J4.fakePromise(this._blob);if(this._buffer)return this._blob=new IB.PonyfillBlob([this._buffer],{type:this.contentType||"",size:this.contentLength}),J4.fakePromise(this._blob);return this._collectChunksFromReadable().then(($)=>{return this._blob=new IB.PonyfillBlob($,{type:this.contentType||"",size:this.contentLength}),this._blob})}_formData=null;formData($){if(this._formData)return J4.fakePromise(this._formData);if(this.bodyType===y2.FormData)return this._formData=this.bodyInit,J4.fakePromise(this._formData);this._formData=new p01.PonyfillFormData;let A=this.generateBody();if(A==null)return J4.fakePromise(this._formData);let F={...this.options.formDataLimits,...$?.formDataLimits};return new Promise((D,B)=>{let E=cs1.default({headers:{"content-type":this.contentType||""},limits:F,defParamCharset:"utf-8"});E.on("field",(w,Z,{nameTruncated:J,valueTruncated:Y})=>{if(J)B(new Error(`Field name size exceeded: ${F?.fieldNameSize} bytes`));if(Y)B(new Error(`Field value size exceeded: ${F?.fieldSize} bytes`));this._formData.set(w,Z)}),E.on("fieldsLimit",()=>{B(new Error(`Fields limit exceeded: ${F?.fields}`))}),E.on("file",(w,Z,{filename:J,mimeType:Y})=>{let W=[];Z.on("limit",()=>{B(new Error(`File size limit exceeded: ${F?.fileSize} bytes`))}),Z.on("data",(X)=>{W.push(X)}),Z.on("close",()=>{if(Z.truncated)B(new Error(`File size limit exceeded: ${F?.fileSize} bytes`));let X=new as1.PonyfillFile(W,J,{type:Y});this._formData.set(w,X)})}),E.on("filesLimit",()=>{B(new Error(`Files limit exceeded: ${F?.files}`))}),E.on("partsLimit",()=>{B(new Error(`Parts limit exceeded: ${F?.parts}`))}),E.on("close",()=>{D(this._formData)}),E.on("error",(w="An error occurred while parsing the form data")=>{let Z=w.message||w.toString();B(new TypeError(Z,w.cause))}),A?.readable.pipe(E)})}buffer(){if(this._buffer)return J4.fakePromise(this._buffer);if(this.bodyType===y2.Blob){if(IB.hasBufferMethod(this.bodyInit))return this.bodyInit.buffer().then(($)=>{return this._buffer=$,this._buffer});if(IB.hasBytesMethod(this.bodyInit))return this.bodyInit.bytes().then(($)=>{return this._buffer=A7.Buffer.from($),this._buffer});if(IB.hasArrayBufferMethod(this.bodyInit))return this.bodyInit.arrayBuffer().then(($)=>{return this._buffer=A7.Buffer.from($,void 0,$.byteLength),this._buffer})}return this._collectChunksFromReadable().then(($)=>{if($.length===1)return this._buffer=$[0],this._buffer;return this._buffer=A7.Buffer.concat($),this._buffer})}bytes(){return this.buffer()}arrayBuffer(){return this.buffer()}_json=null;json(){if(this._json)return J4.fakePromise(this._json);return this.text().then(($)=>{try{this._json=JSON.parse($)}catch(A){if(A instanceof SyntaxError)A.message+=`, "${$}" is not valid JSON`;throw A}return this._json})}_text=null;text(){if(this._text)return J4.fakePromise(this._text);if(this.bodyType===y2.String)return this._text=this.bodyInit,J4.fakePromise(this._text);return this.buffer().then(($)=>{return this._text=$.toString("utf-8"),this._text})}}x01.PonyfillBody=g01;function is1($){if($==null)return{bodyFactory:()=>null,contentType:null,contentLength:null};if(typeof $==="string"){let A=A7.Buffer.from($),F=A.byteLength;return{bodyType:y2.String,contentType:"text/plain;charset=UTF-8",contentLength:F,buffer:A,bodyFactory(){let D=x8.Readable.from(A);return new v9.PonyfillReadableStream(D)}}}if(A7.Buffer.isBuffer($))return{bodyType:y2.Buffer,contentType:null,contentLength:$.length,buffer:$,bodyFactory(){let A=x8.Readable.from($);return new v9.PonyfillReadableStream(A)}};if(J4.isArrayBufferView($)){let A=A7.Buffer.from($.buffer,$.byteOffset,$.byteLength);return{bodyType:y2.Buffer,contentLength:$.byteLength,contentType:null,buffer:A,bodyFactory(){let F=x8.Readable.from(A);return new v9.PonyfillReadableStream(F)}}}if($ instanceof v9.PonyfillReadableStream&&$.readable!=null)return{bodyType:y2.ReadableStream,bodyFactory:()=>$,contentType:null,contentLength:null};if(ns1($))return{bodyType:y2.Blob,contentType:$.type,contentLength:$.size,bodyFactory(){return $.stream()}};if($ instanceof ArrayBuffer){let A=$.byteLength,F=A7.Buffer.from($,void 0,$.byteLength);return{bodyType:y2.Buffer,contentType:null,contentLength:A,buffer:F,bodyFactory(){let D=x8.Readable.from(F);return new v9.PonyfillReadableStream(D)}}}if($ instanceof x8.Readable)return{bodyType:y2.Readable,contentType:null,contentLength:null,bodyFactory(){return new v9.PonyfillReadableStream($)}};if(rs1($))return{bodyType:y2.String,contentType:"application/x-www-form-urlencoded;charset=UTF-8",contentLength:null,bodyFactory(){return new v9.PonyfillReadableStream(x8.Readable.from($.toString()))}};if(ss1($)){let A=Math.random().toString(36).substr(2),F=`multipart/form-data; boundary=${A}`;return{bodyType:y2.FormData,contentType:F,contentLength:null,bodyFactory(){return p01.getStreamFromFormData($,A)}}}if(ts1($))return{contentType:null,contentLength:null,bodyFactory(){return new v9.PonyfillReadableStream($)}};if($[Symbol.iterator]||$[Symbol.asyncIterator])return{contentType:null,contentLength:null,bodyType:y2.AsyncIterable,bodyFactory(){let A=x8.Readable.from($);return new v9.PonyfillReadableStream(A)}};throw new Error("Unknown body type")}function ss1($){return $?.forEach!=null}function ns1($){return $?.stream!=null&&typeof $.stream==="function"}function rs1($){return $?.sort!=null}function ts1($){return $?.getReader!=null}});var xY=C((c01)=>{Object.defineProperty(c01,"__esModule",{value:!0});c01.PonyfillHeaders=void 0;c01.isHeadersLike=F7;var os1=p("node:util"),yV=pY();function F7($){return $?.get&&$?.forEach}class l01{headersInit;_map;objectNormalizedKeysOfHeadersInit=[];objectOriginalKeysOfHeadersInit=[];_setCookies;constructor($){this.headersInit=$}_get($){let A=$.toLowerCase();if(A==="set-cookie"&&this._setCookies?.length)return this._setCookies.join(", ");if(this._map)return this._map.get(A)||null;if(this.headersInit==null)return null;if(Array.isArray(this.headersInit)){let F=this.headersInit.filter(([D])=>D.toLowerCase()===A);if(F.length===0)return null;if(F.length===1)return F[0][1];return F.map(([,D])=>D).join(", ")}else if(F7(this.headersInit))return this.headersInit.get(A);else{let F=this.headersInit[$]||this.headersInit[A];if(F!=null)return F;if(!this.objectNormalizedKeysOfHeadersInit.length)Object.keys(this.headersInit).forEach((E)=>{this.objectOriginalKeysOfHeadersInit.push(E),this.objectNormalizedKeysOfHeadersInit.push(E.toLowerCase())});let D=this.objectNormalizedKeysOfHeadersInit.indexOf(A);if(D===-1)return null;let B=this.objectOriginalKeysOfHeadersInit[D];return this.headersInit[B]}}getMap(){if(!this._map)if(this._setCookies=[],this.headersInit!=null)if(Array.isArray(this.headersInit)){this._map=new Map;for(let[$,A]of this.headersInit){let F=$.toLowerCase();if(F==="set-cookie"){this._setCookies.push(A);continue}this._map.set(F,A)}}else if(F7(this.headersInit))this._map=new Map,this.headersInit.forEach(($,A)=>{if(A==="set-cookie"){this._setCookies||=[],this._setCookies.push($);return}this._map.set(A,$)});else{this._map=new Map;for(let $ in this.headersInit){let A=this.headersInit[$];if(A!=null){let F=$.toLowerCase();if(F==="set-cookie"){this._setCookies||=[],this._setCookies.push(A);continue}this._map.set(F,A)}}}else this._map=new Map;return this._map}append($,A){let F=$.toLowerCase();if(F==="set-cookie"){this._setCookies||=[],this._setCookies.push(A);return}let D=this.getMap().get(F),B=D?`${D}, ${A}`:A;this.getMap().set(F,B)}get($){let A=this._get($);if(A==null)return null;return A.toString()}has($){if($==="set-cookie")return!!this._setCookies?.length;return!!this._get($)}set($,A){let F=$.toLowerCase();if(F==="set-cookie"){this._setCookies=[A];return}this.getMap().set(F,A)}delete($){let A=$.toLowerCase();if(A==="set-cookie"){this._setCookies=[];return}this.getMap().delete(A)}forEach($){if(this._setCookies?.forEach((A)=>{$(A,"set-cookie",this)}),!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){this.headersInit.forEach(([A,F])=>{$(F,A,this)});return}if(F7(this.headersInit)){this.headersInit.forEach($);return}Object.entries(this.headersInit).forEach(([A,F])=>{if(F!=null)$(F,A,this)})}return}this.getMap().forEach((A,F)=>{$(A,F,this)})}*_keys(){if(this._setCookies?.length)yield"set-cookie";if(!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([$])=>$)[Symbol.iterator]();return}if(F7(this.headersInit)){yield*this.headersInit.keys();return}yield*Object.keys(this.headersInit)[Symbol.iterator]();return}}yield*this.getMap().keys()}keys(){return new yV.PonyfillIteratorObject(this._keys(),"HeadersIterator")}*_values(){if(this._setCookies?.length)yield*this._setCookies;if(!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([,$])=>$)[Symbol.iterator]();return}if(F7(this.headersInit)){yield*this.headersInit.values();return}yield*Object.values(this.headersInit)[Symbol.iterator]();return}}yield*this.getMap().values()}values(){return new yV.PonyfillIteratorObject(this._values(),"HeadersIterator")}*_entries(){if(this._setCookies?.length)yield*this._setCookies.map(($)=>["set-cookie",$]);if(!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit;return}if(F7(this.headersInit)){yield*this.headersInit.entries();return}yield*Object.entries(this.headersInit);return}}yield*this.getMap().entries()}entries(){return new yV.PonyfillIteratorObject(this._entries(),"HeadersIterator")}getSetCookie(){if(!this._setCookies)this.getMap();return this._setCookies}[Symbol.iterator](){return this.entries()}[Symbol.for("nodejs.util.inspect.custom")](){let $={};return this.forEach((A,F)=>{if(F==="set-cookie")$["set-cookie"]=this._setCookies||[];else $[F]=A?.includes(",")?A.split(",").map((D)=>D.trim()):A}),`Headers ${os1.inspect($)}`}}c01.PonyfillHeaders=l01});var RB=C((i01)=>{Object.defineProperty(i01,"__esModule",{value:!0});i01.PonyfillResponse=void 0;var $n1=p("node:http"),An1=gY(),yY=xY(),Fn1="application/json; charset=utf-8";class jB extends An1.PonyfillBody{headers;constructor($,A){super($||null,A);this.headers=A?.headers&&yY.isHeadersLike(A.headers)?A.headers:new yY.PonyfillHeaders(A?.headers),this.status=A?.status||200,this.statusText=A?.statusText||$n1.STATUS_CODES[this.status]||"OK",this.url=A?.url||"",this.redirected=A?.redirected||!1,this.type=A?.type||"default",this.handleContentLengthHeader()}get ok(){return this.status>=200&&this.status<300}status;statusText;url;redirected;type;clone(){return this}static error(){return new jB(null,{status:500,statusText:"Internal Server Error"})}static redirect($,A=302){if(A<300||A>399)throw new RangeError("Invalid status code");return new jB(null,{headers:{location:$},status:A})}static json($,A={}){if(A.headers=A?.headers&&yY.isHeadersLike(A.headers)?A.headers:new yY.PonyfillHeaders(A?.headers),!A.headers.has("content-type"))A.headers.set("content-type",Fn1);return new jB(JSON.stringify($),A)}}i01.PonyfillResponse=jB});var t01=C((r01)=>{Object.defineProperty(r01,"__esModule",{value:!0});r01.fetchCurl=Zn1;var n01=p("node:stream"),Dn1=p("node:stream/promises"),Bn1=p("node:tls"),En1=SY(),wn1=RB(),lV=D9();function Zn1($){let{Curl:A,CurlFeature:F,CurlPause:D,CurlProgressFunc:B}=globalThis.libcurl,E=new A;if(E.enable(F.NoDataParsing),E.setOpt("URL",$.url),process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")E.setOpt("SSL_VERIFYPEER",!1);if(process.env.NODE_EXTRA_CA_CERTS)E.setOpt("CAINFO",process.env.NODE_EXTRA_CA_CERTS);else E.setOpt("CAINFO_BLOB",Bn1.rootCertificates.join(`
205
- `));if(E.enable(F.StreamResponse),E.setStreamProgressCallback(function(){return $.signal.aborted?process.env.DEBUG?B.Continue:1:0}),$.bodyType==="String")E.setOpt("POSTFIELDS",$.bodyInit);else{let U=$.body!=null?lV.isNodeReadable($.body)?$.body:n01.Readable.from($.body):null;if(U)E.setOpt("UPLOAD",!0),E.setUploadStream(U)}if(process.env.DEBUG)E.setOpt("VERBOSE",!0);E.setOpt("TRANSFER_ENCODING",!1),E.setOpt("HTTP_TRANSFER_DECODING",!0),E.setOpt("FOLLOWLOCATION",$.redirect==="follow"),E.setOpt("MAXREDIRS",20),E.setOpt("ACCEPT_ENCODING",""),E.setOpt("CUSTOMREQUEST",$.method);let w=$.headersSerializer||lV.defaultHeadersSerializer,Z,J=w($.headers,(U)=>{Z=Number(U)});if(Z!=null)E.setOpt("INFILESIZE",Z);E.setOpt("HTTPHEADER",J),E.enable(F.NoHeaderParsing);let Y=En1.createDeferredPromise(),W;function X(){if(E.isOpen)try{E.pause(D.Recv)}catch(U){Y.reject(U)}}if($.signal)$.signal.addEventListener("abort",X,{once:!0});return E.once("end",function U(){try{E.close()}catch(H){Y.reject(H)}if($.signal)$.signal.removeEventListener("abort",X)}),E.once("error",function U(H){if(W&&!W.closed&&!W.destroyed)W.destroy(H);else{if(H.message==="Operation was aborted by an application callback")H.message="The operation was aborted.";Y.reject(H)}try{E.close()}catch(Q){Y.reject(Q)}}),E.once("stream",function U(H,Q,q){let V=new n01.PassThrough;Dn1.pipeline(H,V,{end:!0,signal:$.signal}).then(()=>{if(!H.destroyed)H.resume()}).catch(Y.reject);let h=q.toString("utf8").split(/\r?\n|\r/g).filter((T)=>{if(T&&!T.startsWith("HTTP/")){if($.redirect==="error"&&T.toLowerCase().includes("location")&&lV.shouldRedirect(Q)){if(!H.destroyed)H.resume();V.destroy(),Y.reject(new Error("redirect is not allowed"))}return!0}return!1}).map((T)=>T.split(/:\s(.+)/).slice(0,2)),P=new wn1.PonyfillResponse(V,{status:Q,headers:h,url:E.getInfo(A.info.REDIRECT_URL)?.toString()||$.url,redirected:Number(E.getInfo(A.info.REDIRECT_COUNT))>0});Y.resolve(P),W=V}),setImmediate(()=>{E.perform()}),Y.promise}});var LB=C((e01)=>{Object.defineProperty(e01,"__esModule",{value:!0});e01.PonyfillURL=void 0;var Yn1=dY(),Wn1=Yn1.__importDefault(p("node:buffer")),Xn1=p("node:crypto");class o01 extends URL{static blobRegistry=new Map;static createObjectURL($){let A=`blob:whatwgnode:${Xn1.randomUUID()}`;return this.blobRegistry.set(A,$),A}static revokeObjectURL($){if(!this.blobRegistry.has($))URL.revokeObjectURL($);else this.blobRegistry.delete($)}static getBlobFromURL($){return this.blobRegistry.get($)||Wn1.default?.resolveObjectURL?.($)}}e01.PonyfillURL=o01});var lY=C((D21)=>{Object.defineProperty(D21,"__esModule",{value:!0});D21.PonyfillRequest=void 0;var Un1=p("node:http"),Hn1=p("node:https"),Qn1=gY(),A21=xY(),Cn1=LB();function Gn1($){return $[Symbol.toStringTag]==="Request"}function Kn1($){return $?.href!=null}class F21 extends Qn1.PonyfillBody{constructor($,A){let F,D,B=null,E;if(typeof $==="string")F=$;else if(Kn1($))D=$;else if(Gn1($)){if($._parsedUrl)D=$._parsedUrl;else if($._url)F=$._url;else F=$.url;B=$.body,E=$}if(A!=null)B=A.body||null,E=A;super(B,A);if(this._url=F,this._parsedUrl=D,this.cache=E?.cache||"default",this.credentials=E?.credentials||"same-origin",this.headers=E?.headers&&A21.isHeadersLike(E.headers)?E.headers:new A21.PonyfillHeaders(E?.headers),this.integrity=E?.integrity||"",this.keepalive=E?.keepalive!=null?E?.keepalive:!1,this.method=E?.method?.toUpperCase()||"GET",this.mode=E?.mode||"cors",this.redirect=E?.redirect||"follow",this.referrer=E?.referrer||"about:client",this.referrerPolicy=E?.referrerPolicy||"no-referrer",this.signal=E?.signal||new AbortController().signal,this.headersSerializer=E?.headersSerializer,this.duplex=E?.duplex||"half",this.destination="document",this.priority="auto",this.method!=="GET"&&this.method!=="HEAD")this.handleContentLengthHeader(!0);if(E?.agent!=null){let w=D?.protocol||F||this.url;if(E.agent===!1)this.agent=!1;else if(w.startsWith("http:")&&E.agent instanceof Un1.Agent)this.agent=E.agent;else if(w.startsWith("https:")&&E.agent instanceof Hn1.Agent)this.agent=E.agent}}headersSerializer;cache;credentials;destination;headers;integrity;keepalive;method;mode;priority;redirect;referrer;referrerPolicy;_url;get url(){if(this._url==null)if(this._parsedUrl)this._url=this._parsedUrl.toString();else throw new TypeError("Invalid URL");return this._url}_parsedUrl;get parsedUrl(){if(this._parsedUrl==null)if(this._url!=null)this._parsedUrl=new Cn1.PonyfillURL(this._url,"http://localhost");else throw new TypeError("Invalid URL");return this._parsedUrl}duplex;agent;signal;clone(){return this}[Symbol.toStringTag]="Request"}D21.PonyfillRequest=F21});var Y21=C((J21)=>{Object.defineProperty(J21,"__esModule",{value:!0});J21.fetchNodeHttp=Z21;var w21=p("node:http"),qn1=p("node:https"),E21=p("node:stream"),zn1=p("node:stream/promises"),cY=p("node:zlib"),Vn1=lY(),un1=RB(),Pn1=LB(),cV=D9();function Mn1($){if($.startsWith("http:"))return w21.request;else if($.startsWith("https:"))return qn1.request;throw new Error(`Unsupported protocol: ${$.split(":")[0]||$}`)}function Z21($){return new Promise((A,F)=>{try{let D=Mn1($.parsedUrl?.protocol||$.url),B=$.body!=null?cV.isNodeReadable($.body)?$.body:E21.Readable.from($.body):null,w=($.headersSerializer||cV.getHeadersObj)($.headers);if(w["accept-encoding"]==null)w["accept-encoding"]="gzip, deflate, br";let Z;if($.parsedUrl)Z=D($.parsedUrl,{method:$.method,headers:w,signal:$.signal,agent:$.agent});else Z=D($.url,{method:$.method,headers:w,signal:$.signal,agent:$.agent});if(Z.once("response",(J)=>{let Y;switch(J.headers["content-encoding"]){case"x-gzip":case"gzip":Y=cY.createGunzip();break;case"x-deflate":case"deflate":Y=cY.createInflate();break;case"x-deflate-raw":case"deflate-raw":Y=cY.createInflateRaw();break;case"br":Y=cY.createBrotliDecompress();break;default:Y=new E21.PassThrough}if(J.headers.location&&cV.shouldRedirect(J.statusCode)){if($.redirect==="error"){let Q=new Error("Redirects are not allowed");F(Q),J.resume();return}if($.redirect==="follow"){let Q=new Pn1.PonyfillURL(J.headers.location,$.parsedUrl||$.url),q=Z21(new Vn1.PonyfillRequest(Q,$));A(q.then((V)=>{return V.redirected=!0,V})),J.resume();return}}zn1.pipeline(J,Y,{signal:$.signal,end:!0}).then(()=>{if(!J.destroyed)J.resume()}).catch(F);let X=J.statusCode||200,U=J.statusMessage||w21.STATUS_CODES[X];if(U==null)U="";let H=new un1.PonyfillResponse(Y,{status:X,statusText:U,headers:J.headers,url:$.url});A(H)}),Z.once("error",F),B)B.pipe(Z);else Z.end()}catch(D){F(D)}})}});var Q21=C((H21)=>{Object.defineProperty(H21,"__esModule",{value:!0});H21.fetchPonyfill=U21;var jn1=p("node:buffer"),aY=p("node:fs"),Rn1=p("node:url"),Ln1=t01(),Tn1=Y21(),Sn1=lY(),YA=RB(),On1=LB(),W21=D9(),X21=";base64";async function hn1($){let A=Rn1.fileURLToPath($);try{await aY.promises.access(A,aY.promises.constants.R_OK);let F=await aY.promises.stat(A,{bigint:!0}),D=aY.createReadStream(A);return new YA.PonyfillResponse(D,{status:200,statusText:"OK",headers:{"content-type":"application/octet-stream","last-modified":F.mtime.toUTCString()}})}catch(F){if(F.code==="ENOENT")return new YA.PonyfillResponse(null,{status:404,statusText:"Not Found"});else if(F.code==="EACCES")return new YA.PonyfillResponse(null,{status:403,statusText:"Forbidden"});throw F}}function Nn1($){let[A="text/plain",...F]=$.substring(5).split(","),D=decodeURIComponent(F.join(","));if(A.endsWith(X21)){let B=jn1.Buffer.from(D,"base64url"),E=A.slice(0,-X21.length);return new YA.PonyfillResponse(B,{status:200,statusText:"OK",headers:{"content-type":E}})}return new YA.PonyfillResponse(D,{status:200,statusText:"OK",headers:{"content-type":A}})}function dn1($){let A=On1.PonyfillURL.getBlobFromURL($);if(!A)throw new TypeError("Invalid Blob URL");return new YA.PonyfillResponse(A,{status:200,headers:{"content-type":A.type,"content-length":A.size.toString()}})}function kn1($){return $!=null&&$.href!=null}function U21($,A){if(typeof $==="string"||kn1($)){let D=new Sn1.PonyfillRequest($,A);return U21(D)}let F=$;if(F.url.startsWith("data:")){let D=Nn1(F.url);return W21.fakePromise(D)}if(F.url.startsWith("file:"))return hn1(F.url);if(F.url.startsWith("blob:")){let D=dn1(F.url);return W21.fakePromise(D)}if(globalThis.libcurl&&!F.agent)return Ln1.fetchCurl(F);return Tn1.fetchNodeHttp(F)}});var aV=C((K21)=>{Object.defineProperty(K21,"__esModule",{value:!0});K21.PonyfillTextDecoder=K21.PonyfillTextEncoder=void 0;K21.PonyfillBtoa=fn1;var TB=p("node:buffer"),vn1=D9();class C21{encoding;constructor($="utf-8"){this.encoding=$}encode($){return TB.Buffer.from($,this.encoding)}encodeInto($,A){let D=this.encode($).copy(A);return{read:D,written:D}}}K21.PonyfillTextEncoder=C21;class G21{encoding;fatal=!1;ignoreBOM=!1;constructor($="utf-8",A){if(this.encoding=$,A)this.fatal=A.fatal||!1,this.ignoreBOM=A.ignoreBOM||!1}decode($){if(TB.Buffer.isBuffer($))return $.toString(this.encoding);if(vn1.isArrayBufferView($))return TB.Buffer.from($.buffer,$.byteOffset,$.byteLength).toString(this.encoding);return TB.Buffer.from($).toString(this.encoding)}}K21.PonyfillTextDecoder=G21;function fn1($){return TB.Buffer.from($,"binary").toString("base64")}});var u21=C((z21)=>{Object.defineProperty(z21,"__esModule",{value:!0});z21.PonyfillURLSearchParams=void 0;z21.PonyfillURLSearchParams=globalThis.URLSearchParams});var nV=C((M21)=>{Object.defineProperty(M21,"__esModule",{value:!0});M21.PonyfillWritableStream=void 0;var iV=p("node:stream"),sV=D9();class P21{writable;constructor($){if($ instanceof iV.Writable)this.writable=$;else if($){let A=new iV.Writable({write(B,E,w){try{let Z=$.write?.(B,D);if(Z instanceof Promise)Z.then(()=>{w()},(J)=>{w(J)});else w()}catch(Z){w(Z)}},final(B){let E=$.close?.();if(E instanceof Promise)E.then(()=>{B()},(w)=>{B(w)});else B()}});this.writable=A;let F=new AbortController,D={signal:F.signal,error(B){A.destroy(B)}};A.once("error",(B)=>F.abort(B)),A.once("close",()=>F.abort())}else this.writable=new iV.Writable}getWriter(){let $=this.writable;return{closed:new Promise((A)=>{$.once("close",()=>{A(void 0)})}),get desiredSize(){return $.writableLength},ready:new Promise((A)=>{$.once("drain",()=>{A(void 0)})}),releaseLock(){},write(A){if(A==null)return sV.fakePromise();return new Promise((F,D)=>{$.write(A,(B)=>{if(B)D(B);else F()})})},close(){if(!$.errored&&$.closed)return sV.fakePromise();return new Promise((A,F)=>{if($.errored)F($.errored);else $.end((D)=>{if(D)F(D);else A()})})},abort(A){return new Promise((F)=>{$.destroy(A),$.once("close",F)})}}}close(){if(!this.writable.errored&&this.writable.closed)return sV.fakePromise();return new Promise(($,A)=>{if(this.writable.errored)A(this.writable.errored);else this.writable.end((F)=>{if(F)A(F);else $()})})}abort($){return new Promise((A)=>{this.writable.destroy($),this.writable.once("close",A)})}locked=!1}M21.PonyfillWritableStream=P21});var SB=C((R21)=>{Object.defineProperty(R21,"__esModule",{value:!0});R21.PonyfillTransformStream=void 0;var rV=p("node:stream"),pn1=JA(),gn1=nV();class j21{transform;writable;readable;constructor($){if($ instanceof rV.Transform)this.transform=$;else if($){let A={enqueue(D){F.push(D)},error(D){F.destroy(D)},terminate(){F.end()},get desiredSize(){return F.writableLength}},F=new rV.Transform({read(){},write(D,B,E){try{let w=$.transform?.(D,A);if(w instanceof Promise)w.then(()=>{E()},(Z)=>{E(Z)});else E()}catch(w){E(w)}},final(D){try{let B=$.flush?.(A);if(B instanceof Promise)B.then(()=>{D()},(E)=>{D(E)});else D()}catch(B){D(B)}}});this.transform=F}else this.transform=new rV.Transform;this.writable=new gn1.PonyfillWritableStream(this.transform),this.readable=new pn1.PonyfillReadableStream(this.transform)}}R21.PonyfillTransformStream=j21});var h21=C((S21)=>{Object.defineProperty(S21,"__esModule",{value:!0});S21.PonyfillCompressionStream=void 0;var iY=p("node:zlib"),xn1=SB();class T21 extends xn1.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith("v2")?["gzip","deflate","br"]:["gzip","deflate","deflate-raw","br"];constructor($){switch($){case"x-gzip":case"gzip":super(iY.createGzip());break;case"x-deflate":case"deflate":super(iY.createDeflate());break;case"deflate-raw":super(iY.createDeflateRaw());break;case"br":super(iY.createBrotliCompress());break;default:throw new Error(`Unsupported compression format: ${$}`)}}}S21.PonyfillCompressionStream=T21});var m21=C((d21)=>{Object.defineProperty(d21,"__esModule",{value:!0});d21.PonyfillDecompressionStream=void 0;var sY=p("node:zlib"),yn1=SB();class N21 extends yn1.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith("v2")?["gzip","deflate","br"]:["gzip","deflate","deflate-raw","br"];constructor($){switch($){case"x-gzip":case"gzip":super(sY.createGunzip());break;case"x-deflate":case"deflate":super(sY.createInflate());break;case"deflate-raw":super(sY.createInflateRaw());break;case"br":super(sY.createBrotliDecompress());break;default:throw new TypeError(`Unsupported compression format: '${$}'`)}}}d21.PonyfillDecompressionStream=N21});var x21=C((p21)=>{Object.defineProperty(p21,"__esModule",{value:!0});p21.PonyfillTextEncoderStream=p21.PonyfillTextDecoderStream=void 0;var v21=aV(),f21=SB();class b21 extends f21.PonyfillTransformStream{textDecoder;constructor($,A){super({transform:(F,D)=>{D.enqueue(this.textDecoder.decode(F,{stream:!0}))}});this.textDecoder=new v21.PonyfillTextDecoder($,A)}get encoding(){return this.textDecoder.encoding}get fatal(){return this.textDecoder.fatal}get ignoreBOM(){return this.textDecoder.ignoreBOM}}p21.PonyfillTextDecoderStream=b21;class _21 extends f21.PonyfillTransformStream{textEncoder;constructor($){super({transform:(A,F)=>{F.enqueue(this.textEncoder.encode(A))}});this.textEncoder=new v21.PonyfillTextEncoder($)}get encoding(){return this.textEncoder.encoding}encode($){return this.textEncoder.encode($)}}p21.PonyfillTextEncoderStream=_21});var l21=C((_0)=>{Object.defineProperty(_0,"__esModule",{value:!0});_0.TextEncoderStream=_0.TextDecoderStream=_0.IteratorObject=_0.DecompressionStream=_0.CompressionStream=_0.TransformStream=_0.WritableStream=_0.URLSearchParams=_0.URL=_0.btoa=_0.TextDecoder=_0.TextEncoder=_0.Blob=_0.FormData=_0.File=_0.ReadableStream=_0.Response=_0.Request=_0.Body=_0.Headers=_0.fetch=void 0;var cn1=Q21();Object.defineProperty(_0,"fetch",{enumerable:!0,get:function(){return cn1.fetchPonyfill}});var an1=xY();Object.defineProperty(_0,"Headers",{enumerable:!0,get:function(){return an1.PonyfillHeaders}});var in1=gY();Object.defineProperty(_0,"Body",{enumerable:!0,get:function(){return in1.PonyfillBody}});var sn1=lY();Object.defineProperty(_0,"Request",{enumerable:!0,get:function(){return sn1.PonyfillRequest}});var nn1=RB();Object.defineProperty(_0,"Response",{enumerable:!0,get:function(){return nn1.PonyfillResponse}});var rn1=JA();Object.defineProperty(_0,"ReadableStream",{enumerable:!0,get:function(){return rn1.PonyfillReadableStream}});var tn1=mV();Object.defineProperty(_0,"File",{enumerable:!0,get:function(){return tn1.PonyfillFile}});var on1=xV();Object.defineProperty(_0,"FormData",{enumerable:!0,get:function(){return on1.PonyfillFormData}});var en1=fY();Object.defineProperty(_0,"Blob",{enumerable:!0,get:function(){return en1.PonyfillBlob}});var tV=aV();Object.defineProperty(_0,"TextEncoder",{enumerable:!0,get:function(){return tV.PonyfillTextEncoder}});Object.defineProperty(_0,"TextDecoder",{enumerable:!0,get:function(){return tV.PonyfillTextDecoder}});Object.defineProperty(_0,"btoa",{enumerable:!0,get:function(){return tV.PonyfillBtoa}});var $r1=LB();Object.defineProperty(_0,"URL",{enumerable:!0,get:function(){return $r1.PonyfillURL}});var Ar1=u21();Object.defineProperty(_0,"URLSearchParams",{enumerable:!0,get:function(){return Ar1.PonyfillURLSearchParams}});var Fr1=nV();Object.defineProperty(_0,"WritableStream",{enumerable:!0,get:function(){return Fr1.PonyfillWritableStream}});var Dr1=SB();Object.defineProperty(_0,"TransformStream",{enumerable:!0,get:function(){return Dr1.PonyfillTransformStream}});var Br1=h21();Object.defineProperty(_0,"CompressionStream",{enumerable:!0,get:function(){return Br1.PonyfillCompressionStream}});var Er1=m21();Object.defineProperty(_0,"DecompressionStream",{enumerable:!0,get:function(){return Er1.PonyfillDecompressionStream}});var wr1=pY();Object.defineProperty(_0,"IteratorObject",{enumerable:!0,get:function(){return wr1.PonyfillIteratorObject}});var y21=x21();Object.defineProperty(_0,"TextDecoderStream",{enumerable:!0,get:function(){return y21.PonyfillTextDecoderStream}});Object.defineProperty(_0,"TextEncoderStream",{enumerable:!0,get:function(){return y21.PonyfillTextEncoderStream}})});var a21=C((HY0,c21)=>{var Jr1=uV(),p0;c21.exports=function $(A={}){let F={};if(F.URLPattern=globalThis.URLPattern,!F.URLPattern){let D=ae();F.URLPattern=D.URLPattern}if(A.skipPonyfill||Jr1())return{fetch:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response,FormData:globalThis.FormData,ReadableStream:globalThis.ReadableStream,WritableStream:globalThis.WritableStream,TransformStream:globalThis.TransformStream,CompressionStream:globalThis.CompressionStream,DecompressionStream:globalThis.DecompressionStream,TextDecoderStream:globalThis.TextDecoderStream,TextEncoderStream:globalThis.TextEncoderStream,Blob:globalThis.Blob,File:globalThis.File,crypto:globalThis.crypto,btoa:globalThis.btoa,TextEncoder:globalThis.TextEncoder,TextDecoder:globalThis.TextDecoder,URLPattern:F.URLPattern,URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams};if(p0||=l21(),F.fetch=p0.fetch,F.Request=p0.Request,F.Response=p0.Response,F.Headers=p0.Headers,F.FormData=p0.FormData,F.ReadableStream=p0.ReadableStream,F.URL=p0.URL,F.URLSearchParams=p0.URLSearchParams,F.WritableStream=p0.WritableStream,F.TransformStream=p0.TransformStream,F.CompressionStream=p0.CompressionStream,F.DecompressionStream=p0.DecompressionStream,F.TextDecoderStream=p0.TextDecoderStream,F.TextEncoderStream=p0.TextEncoderStream,F.Blob=p0.Blob,F.File=p0.File,F.crypto=globalThis.crypto,F.btoa=p0.btoa,F.TextEncoder=p0.TextEncoder,F.TextDecoder=p0.TextDecoder,A.formDataLimits)F.Body=class D extends p0.Body{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}},F.Request=class D extends p0.Request{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}},F.Response=class D extends p0.Response{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}};if(!F.crypto){let D=p("crypto");F.crypto=D.webcrypto}return F}});var n31=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((F)=>F.name===$.className);if(!A)return;Object.entries(A.fields).filter(([F,D])=>D.type==="File").map(async([F])=>{let D=$.originalObject?.[F]?.name;if(!D)return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");await $.context.wabe.controllers.file?.deleteFile(D)})},zu=($)=>n31($);var r31=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className);if(!A)return;let F=$.context.wabe.config.file?.urlCacheInSeconds||86400;await Promise.all(Object.entries(A.fields).filter(([D,B])=>B.type==="File").map(async([D])=>{let B=$.object?.[D];if(!B)return;let E=B.name;if(!E&&B.url)return B.url;let w=B.urlGeneratedAt;if(w&&w.getTime()+F*1000>new Date().getTime())return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");let Z=await $.context.wabe.controllers.file?.readFile(E);return $.context.wabe.controllers.database.updateObject({className:$.className,context:$.context,id:$.object?.id||"",data:{[D]:{...B,urlGeneratedAt:new Date,url:Z||B.url}},skipHooks:!0})}))},Vu=($)=>r31($);var uu=async($)=>{let A=$.getNewData(),F=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className);if(!F)return;await Promise.all(Object.keys(A).map(async(D)=>{let B=A[D]?.file,E=A[D]?.url;if(!B&&!E)return;if(E){$.upsertNewData(D,{url:E,isPresignedUrl:!1});return}if(F.fields[D].type!=="File"||!(B instanceof File))return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");await $.context.wabe.controllers.file?.uploadFile(B),$.upsertNewData(D,{name:B.name,isPresignedUrl:!0})}))},Pu=($)=>uu($),Mu=($)=>uu($);var R1=($)=>({...$,isRoot:!0});class pB{className;newData;operationType;context;object;originalObject;select;constructor({newData:$,className:A,operationType:F,context:D,object:B,originalObject:E,select:w}){this.newData=$,this.className=A,this.operationType=F,this.context=D,this.object=B,this.originalObject=E,this.select=w||{}}getUser(){return this.context.user}isFieldUpdated($){return this.newData&&!!this.newData[$]}upsertNewData($,A){if(!this.newData)return;if(!this.operationType.includes("before"))throw new Error("Cannot set data in a hook that is not a before hook");this.newData[$]=A}getNewData(){return this.newData||{}}fetch(){let $=this.context.wabe.controllers.database;if(!this.object?.id)return Promise.resolve(null);return $.getObject({className:this.className,id:this.object.id,context:R1(this.context)})}async addACL($,A){let F=async(Y)=>{if(this.className==="User"){let W=this.object?.id;if(W)await this.context.wabe.controllers.database.updateObject({className:this.className,context:R1(this.context),id:W,data:{acl:Y},select:{}});return}this.upsertNewData("acl",Y)},B=(this.className==="User"?await this.context.wabe.controllers.database.getObject({className:"User",select:{acl:!0},id:this.object?.id,context:R1(this.context)}):{acl:this.getNewData().acl})?.acl||{};if(A===null){await F({...B,[$]:[]});return}let{userId:E,role:w,read:Z,write:J}=A;if(E&&w)throw new Error("Cannot specify both userId and role");if(w){let W=(await this.context.wabe.controllers.database.getObjects({className:"Role",select:{id:!0},where:{name:{equalTo:w}},context:R1(this.context)}))[0]?.id;await F({...B,[$]:[...B?.[$]||[],{roleId:W,read:Z,write:J}]});return}await F({...B,[$]:[...B?.[$]||[],{userId:E,read:Z,write:J}]})}}import{Algorithm as t31,hash as o31}from"@node-rs/argon2";var g9=($,A)=>{let F=A.wabe.config?.authentication?.customAuthenticationMethods;if(!F)throw new Error("No custom authentication methods found");let D=$.filter((w)=>w!=="secondaryFactor");if(D.length>1||D.length===0)throw new Error("One authentication method is required at the time");let B=D[0],E=F.find((w)=>w.name.toLowerCase()===B.toLowerCase());if(!E)throw new Error("No available custom authentication methods found");return E},D7=($)=>o31($,{algorithm:t31.Argon2id});var Iu=async($)=>{if(!$.isFieldUpdated("authentication")||$.getNewData().isOauth)return;let A=$.context,F=$.getNewData().authentication;if(F.emailPasswordSRP)return;let{provider:D,name:B}=g9(Object.keys(F),A),E=F[B],{authenticationDataToSave:w}=await D.onSignUp({input:E,context:A});$.upsertNewData("authentication",{[B]:w})},ju=async($)=>{if(!$.isFieldUpdated("authentication")||$.getNewData().isOauth)return;let A=$.context,F=$.getNewData().authentication;if(F.emailPasswordSRP)return;let{provider:D,name:B}=g9(Object.keys(F),A);if(!D.onUpdateAuthenticationData)return;let E=F[B];if(!$.object?.id)return;let{authenticationDataToSave:w}=await D.onUpdateAuthenticationData({context:A,input:E,userId:$.object.id});$.upsertNewData("authentication",{[B]:w})};var PA=($)=>{let A=$.search(/[a-z]/i);return $.slice(0,A)+$[A].toUpperCase()+$.slice(A+1)},x9=($)=>{let A=$.search(/[a-z]/i);return $.slice(0,A)+$[A].toLowerCase()+$.slice(A+1)},B7=($,A)=>{let F=A.schema?.classes?.find((D)=>D.name===$);if(!F)throw new Error("Class not found in schema");return F},Ru=($,A)=>{let F=A.get("Cookie");if(!F)return;let D=F.split(";").find((B)=>B.includes($));if(!D)return;return D.split("=")[1]},gB=($)=>{return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s\s+/g," ").replace(/[\W_]+/g," ").trim()};var Lu=($)=>{if(!$.isFieldUpdated("createdAt"))$.upsertNewData("createdAt",new Date);if(!$.isFieldUpdated("updatedAt"))$.upsertNewData("updatedAt",new Date)},Tu=($)=>{$.upsertNewData("updatedAt",new Date)},Su=async($)=>{let A=B7($.className,$.context.wabe.config);Object.keys(A.fields).map((D)=>{let B=A.fields[D];if(!$.isFieldUpdated(D)&&B.type!=="Pointer"&&B.type!=="Relation"&&B.type!=="File"&&B.defaultValue!==void 0)$.upsertNewData(D,B.defaultValue)})};var Ou=async($)=>{let A=$.object?.id;await $.context.wabe.controllers.database.deleteObjects({className:"_Session",context:R1($.context),where:{user:{id:{equalTo:A}}},select:{}})};var e31=($)=>{return{beforeCreate:"create",afterCreate:"create",beforeRead:"read",afterRead:"read",beforeDelete:"delete",afterDelete:"delete",beforeUpdate:"update",afterUpdate:"update"}[$]},$91=async({className:$,operation:A,context:F})=>{let D=F.wabe.config.schema?.classes?.find((E)=>E.name===$);if(!D)throw new Error(`Class ${$} not found in schema`);return D.permissions?.[A]},xB=async($,A)=>{if($.context.isRoot)return;let F=e31(A);if(!F)throw new Error("Bad operation type provided");let D=await $91({className:$.className,operation:F,context:$.context});if(!D)throw new Error(`Permission denied to ${F} class ${$.className}`);let B=$.context.sessionId;if(!D.requireAuthentication)return;if(!B||!$.getUser())throw new Error(`Permission denied to ${F} class ${$.className}`);if(D.authorizedRoles?.includes("everyone"))return;if(D.authorizedRoles?.length===0||!D)throw new Error(`Permission denied to ${F} class ${$.className}`);let E=$.context.user?.role?.name;if(!E)throw new Error(`Permission denied to ${F} class ${$.className}`);if(!D.authorizedRoles?.includes(E))throw new Error(`Permission denied to ${F} class ${$.className}`)},hu=($)=>xB($,"beforeRead"),Nu=($)=>xB($,"beforeCreate"),du=($)=>xB($,"beforeUpdate"),ku=($)=>xB($,"beforeDelete");var WW=($,A)=>{let F=$.context.wabe.config.schema?.classes?.find((Z)=>Z.name===$.className);if(!F)return;let D=$.getUser()?.role?.name||"",B=$.context.isRoot;if(A==="beforeRead"){Object.keys($.select).map((Z)=>{let J=F.fields[Z]?.protected;if(J?.protectedOperations.includes("read")){if(B&&J.authorizedRoles.includes("rootOnly"))return;if(!J.authorizedRoles.includes(D))throw new Error("You are not authorized to read this field")}});return}let E=$.getNewData(),w=A==="beforeUpdate"?"update":"create";Object.keys(E).map((Z)=>{let J=F.fields[Z]?.protected;if(J?.protectedOperations.includes(w)){if(B&&J.authorizedRoles.includes("rootOnly"))return;if(!J.authorizedRoles.includes(D))throw new Error(`You are not authorized to ${w} this field`)}})},mu=($)=>WW($,"beforeRead"),vu=($)=>WW($,"beforeUpdate"),fu=($)=>WW($,"beforeCreate");var lB=JSON;var bu=($)=>$.toUpperCase(),_u=($)=>{let A={};return $.forEach((F,D)=>{A[D]=F}),A};var pu=($,A,F)=>{return $.document?$:{document:$,variables:A,requestHeaders:F,signal:void 0}},gu=($,A,F)=>{return $.query?$:{query:$,variables:A,requestHeaders:F,signal:void 0}},xu=($,A)=>{return $.documents?$:{documents:$,requestHeaders:A,signal:void 0}};var gE=H1(K1(),1),mT=($)=>{let A=void 0,F=$.definitions.filter((D)=>D.kind==="OperationDefinition");if(F.length===1)A=F[0]?.name?.value;return A},Y5=($)=>{if(typeof $==="string"){let F=void 0;try{let D=gE.parse($);F=mT(D)}catch(D){}return{query:$,operationName:F}}let A=mT($);return{query:gE.print($),operationName:A}};class X9 extends Error{constructor($,A){let F=`${X9.extractMessage($)}: ${JSON.stringify({response:$,request:A})}`;super(F);if(Object.setPrototypeOf(this,X9.prototype),this.response=$,this.request=A,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,X9)}static extractMessage($){return $.errors?.[0]?.message??`GraphQL Error (Code: ${$.status})`}}var C9=H1(jS(),1);var dX1="connection_init",kX1="connection_ack",LS="ping",TS="pong",mX1="subscribe",vX1="next",fX1="error",SS="complete";class A8{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor($,A,F){this._type=$,this._payload=A,this._id=F}get text(){let $={type:this.type};if(this.id!=null&&this.id!=null)$.id=this.id;if(this.payload!=null&&this.payload!=null)$.payload=this.payload;return JSON.stringify($)}static parse($,A){let{type:F,payload:D,id:B}=JSON.parse($);return new A8(F,A(D),B)}}class sU{constructor($,{onInit:A,onAcknowledged:F,onPing:D,onPong:B}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=$,$.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},$.send(_X1(A?await A():null).text)}),$.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),$.addEventListener("error",(E)=>{console.error(E)}),$.addEventListener("message",(E)=>{try{let w=bX1(E.data);switch(w.type){case kX1:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,F)F(w.payload);return}case LS:{if(D)D(w.payload).then((W)=>$.send(RS(W).text));else $.send(RS(null).text);return}case TS:{if(B)B(w.payload);return}}if(!this.socketState.acknowledged)return;if(w.id===void 0||w.id===null||!this.socketState.subscriptions[w.id])return;let{query:Z,variables:J,subscriber:Y}=this.socketState.subscriptions[w.id];switch(w.type){case vX1:{if(!w.payload.errors&&w.payload.data)Y.next&&Y.next(w.payload.data);if(w.payload.errors)Y.error&&Y.error(new X9({...w.payload,status:200},{query:Z,variables:J}));return}case fX1:{Y.error&&Y.error(new X9({errors:w.payload,status:200},{query:Z,variables:J}));return}case SS:{Y.complete&&Y.complete(),delete this.socketState.subscriptions[w.id];return}}}catch(w){console.error(w),$.close(1006)}$.close(4400,"Unknown graphql-ws message.")})}makeSubscribe($,A,F,D){let B=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[B]={query:$,variables:D,subscriber:F},this.socket.send(gX1(B,{query:$,operationName:A,variables:D}).text),()=>{this.socket.send(xX1(B).text),delete this.socketState.subscriptions[B]}}rawRequest($,A){return new Promise((F,D)=>{let B;this.rawSubscribe($,{next:(E,w)=>B={data:E,extensions:w},error:D,complete:()=>F(B)},A)})}request($,A){return new Promise((F,D)=>{let B;this.subscribe($,{next:(E)=>B=E,error:D,complete:()=>F(B)},A)})}subscribe($,A,F){let{query:D,operationName:B}=Y5($);return this.makeSubscribe(D,B,A,F)}rawSubscribe($,A,F){return this.makeSubscribe($,void 0,A,F)}ping($){this.socket.send(pX1($).text)}close(){this.socket.close(1000)}}sU.PROTOCOL="graphql-transport-ws";function bX1($,A=(F)=>F){return A8.parse($,A)}function _X1($){return new A8(dX1,$)}function pX1($){return new A8(LS,$,void 0)}function RS($){return new A8(TS,$,void 0)}function gX1($,A){return new A8(mX1,A,$)}function xX1($){return new A8(SS,void 0,$)}var L7=($)=>{let A={};if($)if(typeof Headers!=="undefined"&&$ instanceof Headers||C9&&C9.Headers&&$ instanceof C9.Headers)A=_u($);else if(Array.isArray($))$.forEach(([F,D])=>{if(F&&D!==void 0)A[F]=D});else A=$;return A},OS=($)=>$.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),yX1=($)=>{if(!Array.isArray($.query)){let D=$,B=[`query=${encodeURIComponent(OS(D.query))}`];if($.variables)B.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)B.push(`operationName=${encodeURIComponent(D.operationName)}`);return B.join("&")}if(typeof $.variables!=="undefined"&&!Array.isArray($.variables))throw new Error("Cannot create query with given variable type, array expected");let A=$,F=$.query.reduce((D,B,E)=>{return D.push({query:OS(B),variables:A.variables?A.jsonSerializer.stringify(A.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(A.jsonSerializer.stringify(F))}`},lX1=($)=>async(A)=>{let{url:F,query:D,variables:B,operationName:E,fetch:w,fetchOptions:Z,middleware:J}=A,Y={...A.headers},W="",X=void 0;if($==="POST"){if(X=cX1(D,B,E,Z.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else W=yX1({query:D,variables:B,operationName:E,jsonSerializer:Z.jsonSerializer??lB});let U={method:$,headers:Y,body:X,...Z},H=F,Q=U;if(J){let q=await Promise.resolve(J({...U,url:F,operationName:E,variables:B})),{url:V,...L}=q;H=V,Q=L}if(W)H=`${H}?${W}`;return await w(H,Q)};class tU{constructor($,A={}){this.url=$,this.requestConfig=A,this.rawRequest=async(...F)=>{let[D,B,E]=F,w=gu(D,B,E),{headers:Z,fetch:J=C9.default,method:Y="POST",requestMiddleware:W,responseMiddleware:X,...U}=this.requestConfig,{url:H}=this;if(w.signal!==void 0)U.signal=w.signal;let{operationName:Q}=Y5(w.query);return nU({url:H,query:w.query,variables:w.variables,headers:{...L7(rU(Z)),...L7(w.requestHeaders)},operationName:Q,fetch:J,method:Y,fetchOptions:U,middleware:W}).then((q)=>{if(X)X(q);return q}).catch((q)=>{if(X)X(q);throw q})}}async request($,...A){let[F,D]=A,B=pu($,F,D),{headers:E,fetch:w=C9.default,method:Z="POST",requestMiddleware:J,responseMiddleware:Y,...W}=this.requestConfig,{url:X}=this;if(B.signal!==void 0)W.signal=B.signal;let{query:U,operationName:H}=Y5(B.document);return nU({url:X,query:U,variables:B.variables,headers:{...L7(rU(E)),...L7(B.requestHeaders)},operationName:H,fetch:w,method:Z,fetchOptions:W,middleware:J}).then((Q)=>{if(Y)Y(Q);return Q.data}).catch((Q)=>{if(Y)Y(Q);throw Q})}batchRequests($,A){let F=xu($,A),{headers:D,...B}=this.requestConfig;if(F.signal!==void 0)B.signal=F.signal;let E=F.documents.map(({document:Z})=>Y5(Z).query),w=F.documents.map(({variables:Z})=>Z);return nU({url:this.url,query:E,variables:w,headers:{...L7(rU(D)),...L7(F.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??C9.default,method:this.requestConfig.method||"POST",fetchOptions:B,middleware:this.requestConfig.requestMiddleware}).then((Z)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(Z);return Z.data}).catch((Z)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(Z);throw Z})}setHeaders($){return this.requestConfig.headers=$,this}setHeader($,A){let{headers:F}=this.requestConfig;if(F)F[$]=A;else this.requestConfig.headers={[$]:A};return this}setEndpoint($){return this.url=$,this}}var nU=async($)=>{let{query:A,variables:F,fetchOptions:D}=$,B=lX1(bu($.method??"post")),E=Array.isArray($.query),w=await B($),Z=await aX1(w,D.jsonSerializer??lB),J=Array.isArray(Z)?!Z.some(({data:W})=>!W):Boolean(Z.data),Y=Array.isArray(Z)||!Z.errors||Array.isArray(Z.errors)&&!Z.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(w.ok&&Y&&J){let{errors:W,...X}=Array.isArray(Z)?Z:Z,U=D.errorPolicy==="ignore"?X:Z;return{...E?{data:U}:U,headers:w.headers,status:w.status}}else throw new X9({...typeof Z==="string"?{error:Z}:Z,status:w.status,headers:w.headers},{query:A,variables:F})};var cX1=($,A,F,D)=>{let B=D??lB;if(!Array.isArray($))return B.stringify({query:$,variables:A,operationName:F});if(typeof A!=="undefined"&&!Array.isArray(A))throw new Error("Cannot create request body with given variable type, array expected");let E=$.reduce((w,Z,J)=>{return w.push({query:Z,variables:A?A[J]:void 0}),w},[]);return B.stringify(E)},aX1=async($,A)=>{let F;if($.headers.forEach((D,B)=>{if(B.toLowerCase()==="content-type")F=D}),F&&(F.toLowerCase().startsWith("application/json")||F.toLowerCase().startsWith("application/graphql+json")||F.toLowerCase().startsWith("application/graphql-response+json")))return A.parse(await $.text());else return $.text()},rU=($)=>{return typeof $==="function"?$():$},oU=($,...A)=>{return $.reduce((F,D,B)=>`${F}${D}${B in A?String(A[B]):""}`,"")};var s3=H1(dZ(),1);var fl=H1(ml(),1);var vk1=Object.prototype.toString,fk1=($)=>vk1.call($)==="[object Error]",bk1=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function wq($){if(!($&&fk1($)&&$.name==="TypeError"&&typeof $.message==="string"))return!1;if($.message==="Load failed")return $.stack===void 0;return bk1.has($.message)}class bl extends Error{constructor($){super();if($ instanceof Error)this.originalError=$,{message:$}=$;else this.originalError=new Error($),this.originalError.stack=this.stack;this.name="AbortError",this.message=$}}var vl=($,A,F)=>{let D=F.retries-(A-1);return $.attemptNumber=A,$.retriesLeft=D,$};async function Zq($,A){return new Promise((F,D)=>{A={...A},A.onFailedAttempt??=()=>{},A.shouldRetry??=()=>!0,A.retries??=10;let B=fl.default.operation(A),E=()=>{B.stop(),D(A.signal?.reason)};if(A.signal&&!A.signal.aborted)A.signal.addEventListener("abort",E,{once:!0});let w=()=>{A.signal?.removeEventListener("abort",E),B.stop()};B.attempt(async(Z)=>{try{let J=await $(Z);w(),F(J)}catch(J){try{if(!(J instanceof Error))throw new TypeError(`Non-error was thrown: "${J}". You should only throw errors.`);if(J instanceof bl)throw J.originalError;if(J instanceof TypeError&&!wq(J))throw J;if(vl(J,Z,A),!await A.shouldRetry(J))B.stop(),D(J);if(await A.onFailedAttempt(J),!B.retry(J))throw B.mainError()}catch(Y){vl(Y,Z,A),w(),D(Y)}}})})}var _k1=($)=>{if(!$)return{};return Object.keys($).reduce((F,D)=>{let B=$[D];if(B==="ASC")F[D]=1;if(B==="DESC")F[D]=-1;return F},{})},i3=($)=>{if(!$)return{};return Object.keys($).reduce((F,D)=>{let B=$[D],E=D==="id"?"_id":D;if(B?.contains||B?.contains===null)F[E]={$all:B.contains};if(B?.notContains||B?.notContains===null)F[E]={$ne:B.notContains};if(B?.equalTo||B?.equalTo===null)F[E]=E==="_id"&&typeof B.equalTo==="string"?s3.ObjectId.createFromHexString(B.equalTo):B.equalTo;if(B?.notEqualTo||B?.notEqualTo===null)F[E]={$ne:E==="_id"&&typeof B.notEqualTo==="string"?s3.ObjectId.createFromHexString(B.notEqualTo):B.notEqualTo};if(B?.greaterThan||B?.greaterThan===null)F[E]={$gt:B.greaterThan};if(B?.greaterThanOrEqualTo||B?.greaterThanOrEqualTo===null)F[E]={$gte:B.greaterThanOrEqualTo};if(B?.lessThan||B?.lessThan===null)F[E]={$lt:B.lessThan};if(B?.lessThanOrEqualTo||B?.lessThanOrEqualTo===null)F[E]={$lte:B.lessThanOrEqualTo};if(B?.in||B?.in===null)F[E]={$in:E==="_id"?B.in.filter((w)=>typeof w==="string").map((w)=>s3.ObjectId.createFromHexString(w)):B.in};if(B?.notIn||B?.notIn===null)F[E]={$nin:E==="_id"?B.notIn.filter((w)=>typeof w==="string").map((w)=>s3.ObjectId.createFromHexString(w)):B.notIn};if(B&&E==="OR")return F.$or=$.OR?.map((w)=>i3(w)),F;if(B&&E==="AND")return F.$and=$.AND?.map((w)=>i3(w)),F;if(typeof B==="object"){let w=i3(B),Z=Object.entries(w);if(Z.length>0)return{[`${E.toString()}.${Z[0][0]}`]:Z[0][1]}}return F},{})};class Jq{options;database;client;constructor($){this.options=$,this.client=new s3.MongoClient($.databaseUrl)}async connect(){let $=await Zq(()=>this.client.connect(),{retries:5,minTimeout:100,factor:2});return this.database=$.db(this.options.databaseName),$}close(){return this.client.close()}async createClassIfNotExist($,A){if(!this.database)throw new Error("Connection to database is not established");let F=A.wabe.config.schema?.classes?.find((E)=>E.name===$);if(!F)throw new Error(`${$} is not defined in schema`);let D=this.database.collection($);return(F.indexes||[]).map((E)=>D.createIndex({[E.field]:E.order==="ASC"?1:-1},{unique:!!E.unique})),D}async count($){let{className:A,where:F,context:D}=$,B=await this.createClassIfNotExist(A,D),E=i3(F);return B.countDocuments(E)}async clearDatabase(){if(!this.database)throw new Error("Connection to database is not established");let $=await this.database.collections();await Promise.all($.filter((A)=>A.collectionName!=="Role").map((A)=>A.deleteMany({})))}async getObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,select:D,where:B,context:E}=$,w=i3(B),J=await(await this.createClassIfNotExist(A,E)).findOne({_id:new s3.ObjectId(F),...w},{projection:D?{...D,_id:1}:void 0});if(!J)throw new Error("Object not found");let{_id:Y,...W}=J;return{...W,...{id:Y.toString()}}}async getObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,select:F,where:D,offset:B,first:E,context:w,order:Z}=$,J=i3(D),Y=_k1(Z);return(await(await this.createClassIfNotExist(A,w)).find(J,{projection:F?{...F,_id:1}:void 0}).limit(E||0).skip(B||0).sort(Y).toArray()).map((U)=>{let{_id:H,...Q}=U;return{...Q,...{id:H.toString()}}})}async createObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,data:F,context:D}=$;return{id:(await(await this.createClassIfNotExist(A,D)).insertOne(F,{})).insertedId.toString()}}async createObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,data:F,context:D}=$,E=await(await this.createClassIfNotExist(A,D)).insertMany(F,{});return Object.values(E.insertedIds).map((w)=>({id:w.toString()}))}async updateObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,data:D,context:B,where:E}=$,w=E?i3(E):{};if((await(await this.createClassIfNotExist(A,B)).updateOne({_id:new s3.ObjectId(F),...w},{$set:D})).matchedCount===0)throw new Error("Object not found");return{id:F}}async updateObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,where:F,data:D,offset:B,first:E,context:w,order:Z}=$,J=i3(F),Y=await this.createClassIfNotExist(A,w),W=await w.wabe.controllers.database.getObjects({className:A,where:F,select:{id:!0},offset:B,first:E,context:R1(w),order:Z});if(W.length===0)return[];return await Y.updateMany(J,{$set:D}),Object.values(W).filter(x2).map((X)=>({id:X?.id||""}))}async deleteObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,context:D}=$,B=i3($.where);if((await(await this.createClassIfNotExist(A,D)).deleteOne({_id:new s3.ObjectId(F),...B})).deletedCount===0)throw new Error("Object not found")}async deleteObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,where:F,context:D}=$,B=i3(F);await(await this.createClassIfNotExist(A,D)).deleteMany(B)}}var _l;((A)=>A.Mongo="mongo")(_l||={});class pl{adapter={};async getCustomerById(){return{email:"customer@test.com"}}async deleteCoupon(){}async updatePromotionCode(){}async createCoupon(){return{code:"",id:""}}async createPromotionCode(){return{code:"",id:""}}async validateWebhook(){return{isValid:!0,payload:{},type:""}}async createCustomer(){return""}async createPayment(){return""}async cancelSubscription(){}async getInvoices(){return[]}async getTotalRevenue(){return 0}async getAllTransactions(){return[]}async getHypotheticalSubscriptionRevenue(){return 0}}class gl{async send(){return"123456"}}var xl;((F)=>{F.EUR="eur";F.USD="usd"})(xl||={});var pk1;((F)=>{F.payment="payment";F.subscription="subscription"})(pk1||={});var gk1;((F)=>{F.Month="month";F.Year="year"})(gk1||={});import{writeFile as xk1,mkdir as yk1,rm as lk1,access as yl,constants as ll}from"node:fs/promises";import cZ from"node:path";class cl{basePath="bucket";rootPath=process.cwd();async uploadFile($){let A=cZ.join(this.rootPath,this.basePath);await yk1(A,{recursive:!0});let F=$.type,D;if(F.startsWith("text")||F.includes("json")){let B=await $.text();D=Buffer.from(B,"utf-8")}else{let B=await $.arrayBuffer();D=Buffer.from(B)}await xk1(cZ.join(A,$.name),D)}async readFile($,A){let F=cZ.join(this.rootPath,this.basePath,$);try{return await yl(F,ll.F_OK),`http://127.0.0.1:${A?.port||3000}/${this.basePath}/${$}`}catch{return null}}async deleteFile($){let A=cZ.join(this.rootPath,this.basePath,$);try{await yl(A,ll.F_OK),await lk1(A)}catch{}}}var S$=($)=>$.charAt(0).toUpperCase()+$.slice(1),x2=($)=>$!==null&&$!==void 0,al=($)=>{let A=new tU(`http://127.0.0.1:${$}/graphql`,{headers:{"Wabe-Root-Key":"0uwFvUxM$ceFuF1aEtTtZMa7DUN2NZudqgY5ve5W*QCyb58cwMj9JeoaV@d#%29v&aJzswuudVU1%nAT+rxS0Bh&OkgBYc0PH18*"}});return{...A,request:A.request}};var aZ=($)=>{if($===void 0||$===null)return[];if(typeof $==="object")return Object.values($).flatMap((A)=>aZ(A));if(typeof $==="string")return gB($).trim().split(" ").map((A)=>A.trim()).flatMap((A)=>{let F=[];for(let D=1;D<=A.length;D+=1)F.push(A.substring(0,D).toLowerCase());return F});if(typeof $==="number")return[String($)];return[]},sl=($)=>{let A=$.context.wabe.config.schema?.classes?.find((B)=>B.name===$.className)?.searchableFields;if(!A||A.length===0)return;let F=$.getNewData(),D=Object.entries(F).flatMap(([B,E])=>{if(!A.includes(B))return;return aZ(E)}).filter(x2);$.upsertNewData("search",D)},nl=($)=>{let A=$.context.wabe.config.schema?.classes?.find((Z)=>Z.name===$.className)?.searchableFields;if(!A||A.length===0)return;let F=$.getNewData(),D=Object.entries(F).flatMap(([Z,J])=>{if(!A.includes(Z))return;return aZ(J)}).filter(x2),B=Object.entries($.object||{}).flatMap(([Z,J])=>{if(!A.includes(Z)||!Object.keys(F).includes(Z))return;return aZ(J)}).filter(x2),w=[...($.object?.search||[]).filter((Z)=>!B.includes(Z)),...D];$.upsertNewData("search",w)};var rl=async($)=>{let A=$.object,F=A?.user;if(!F)return;let D=$.context.wabe.controllers.database,E=(await D.getObject({className:"User",id:F,select:{sessions:!0},context:$.context}))?.sessions?.map((w)=>w.id)||[];await D.updateObject({className:"User",id:F,context:$.context,data:{sessions:[...E,A?.id].filter(x2)}})},tl=async($)=>{let A=$.object,F=A?.user;if(!F)return;let D=$.context.wabe.controllers.database,E=(await D.getObject({className:"User",id:F,select:{sessions:!0},context:$.context}))?.sessions?.filter((w)=>w.id!==A?.id).map((w)=>w.id);await D.updateObject({className:"User",id:F,context:$.context,data:{sessions:E}})},ol=($)=>{if($.context.isRoot)return;if($.isFieldUpdated("sessions"))throw new Error("Not authorized to update user sessions")};var el=($)=>{let A=$.getNewData().authentication;if(!A)return;let F=Object.keys(A)[0],D=A[F].email;if(!D)return;if($.upsertNewData("email",D),F)$.upsertNewData("provider",F)},$c=($)=>{if($.isFieldUpdated("email"))return;el($)},Ac=($)=>{if($.isFieldUpdated("email"))return;el($)};var Fc=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className)?.permissions;if(!A)return;let{acl:F}=A;if($.isFieldUpdated("acl")||!F)return;if(F)await F($)},Dc=async($)=>{if($.className==="User")return;await Fc($)},Bc=async($)=>Fc($);var yB;((J)=>{J.AfterCreate="afterCreate";J.AfterUpdate="afterUpdate";J.AfterDelete="afterDelete";J.AfterRead="afterRead";J.BeforeCreate="beforeCreate";J.BeforeUpdate="beforeUpdate";J.BeforeDelete="beforeDelete";J.BeforeRead="beforeRead"})(yB||={});var Ec=async({className:$,operationType:A,priority:F,config:D})=>D.hooks?.filter((B)=>B.operationType===A&&B.priority===F&&($===B.className||!B.className))||[],ck1=($)=>$.hooks?.reduce((A,F)=>{if(!A.includes(F.priority))A.push(F.priority);return A},[]).sort((A,F)=>A-F)||[],n3=({className:$,newData:A,context:F,select:D})=>{let B=({id:Z})=>{if(!Z)return{};return F.wabe.controllers.database.getObject({className:$,context:R1(F),id:Z,skipHooks:!0})},E=async({where:Z,ids:J})=>{if(!Z&&J.length===0)return[{}];let Y=await F.wabe.controllers.database.getObjects({className:$,context:R1(F),where:Z?Z:{id:{in:J}},skipHooks:!0});if(Y.length===0)return[{}];return Y},w=ck1(F.wabe.config);return{runOnSingleObject:async(Z)=>{if(w.length===0)return{object:void 0,newData:{}};let J=await B({id:Z.id}),Y=new pB({className:$,newData:A,operationType:Z.operationType,context:F,object:J,originalObject:Z.originalObject,select:D});return await w.reduce(async(W,X)=>{await W;let U=await Ec({className:$,operationType:Z.operationType,priority:X,config:F.wabe.config});await Promise.all(U.map((H)=>H.callback(Y)))},Promise.resolve()),{object:J,newData:Y.getNewData()}},runOnMultipleObjects:async(Z)=>{if(w.length===0)return{objects:[],newData:[A||{}]};let J=await E({where:Z.where,ids:Z.ids||[]}),Y=(Z.operationType==="afterDelete"?Z.originalObjects:J)||[],W=await Promise.all(Y.map(async(X)=>{let U=(Z.originalObjects||[]).find((Q)=>Q?.id===X?.id),H=new pB({className:$,newData:A,operationType:Z.operationType,context:F,object:X,originalObject:U,select:D});return await w.reduce(async(Q,q)=>{await Q;let V=await Ec({className:$,operationType:Z.operationType,priority:q,config:F.wabe.config});await Promise.all(V.map((L)=>L.callback(H)))},Promise.resolve()),H.getNewData()}));return{objects:J,newData:W}}}},wc=()=>[{operationType:"beforeRead",priority:0,callback:hu},{operationType:"beforeUpdate",priority:0,callback:du},{operationType:"beforeCreate",priority:0,callback:Nu},{operationType:"beforeDelete",priority:0,callback:ku},{operationType:"beforeRead",priority:0,callback:mu},{operationType:"beforeUpdate",priority:0,callback:vu},{operationType:"beforeCreate",priority:0,callback:fu},{operationType:"beforeCreate",priority:1,callback:Lu},{operationType:"beforeCreate",priority:1,callback:Su},{operationType:"beforeUpdate",priority:1,callback:Tu},{operationType:"beforeCreate",priority:1,callback:Pu},{operationType:"beforeUpdate",priority:1,callback:Mu},{operationType:"afterRead",priority:1,callback:Vu},{operationType:"afterDelete",priority:1,callback:zu},{className:"User",operationType:"beforeCreate",priority:1,callback:Iu},{className:"User",operationType:"beforeUpdate",priority:1,callback:ju},{operationType:"beforeCreate",priority:3,callback:sl},{operationType:"beforeUpdate",priority:3,callback:nl},{operationType:"beforeCreate",priority:0,callback:Dc},{className:"User",operationType:"afterCreate",priority:0,callback:Bc},{className:"User",operationType:"beforeCreate",priority:2,callback:$c},{className:"User",operationType:"beforeUpdate",priority:2,callback:Ac},{className:"User",operationType:"beforeDelete",priority:1,callback:Ou},{className:"_Session",operationType:"afterCreate",priority:1,callback:rl},{className:"_Session",operationType:"afterDelete",priority:1,callback:tl},{className:"User",operationType:"beforeUpdate",priority:1,callback:ol}];class Yq{adapter;constructor($){this.adapter=$}_getSelectMinusPointersAndRelations({className:$,context:A,select:F}){let D=A.wabe.config.schema?.classes?.find((E)=>E.name.toLowerCase()===$.toLowerCase());if(!D)throw new Error("Class not found in schema");if(!F)return{pointers:{},selectWithoutPointers:{}};let B=Object.keys(D.fields).filter((E)=>D.fields[E].type==="Pointer"||D.fields[E].type==="Relation");return Object.entries(F).reduce((E,[w,Z])=>{if(!B.includes(w))return{...E,selectWithoutPointers:{...E.selectWithoutPointers,[w]:!0}};let J=D.fields[w].class;return{...E,pointers:{...E.pointers,[w]:{className:J,select:Z===!0?void 0:Z}}}},{pointers:{},selectWithoutPointers:{}})}_isRelationField({pointerField:$,currentClassName:A,context:F,originClassName:D}){if(!A)return!1;return F.wabe.config.schema?.classes?.some((B)=>B.name.toLowerCase()===D.toLowerCase()&&Object.entries(B.fields).find(([E,w])=>E===$&&w.type==="Relation"&&w.class.toLowerCase()===A.toLowerCase()))}_isPointerField({pointerField:$,currentClassName:A,context:F,originClassName:D}){if(!A)return!1;return F.wabe.config.schema?.classes?.some((B)=>B.name.toLowerCase()===D.toLowerCase()&&Object.entries(B.fields).find(([E,w])=>E===$&&w.type==="Pointer"&&w.class.toLowerCase()===A.toLowerCase()))}async _getWhereObjectWithPointerOrRelation($,A,F){let D=Object.keys(A),B=F.wabe.config.schema?.classes?.find((w)=>w.name.toLowerCase()===$.toLowerCase()),E=await D.reduce(async(w,Z)=>{let J=await w,Y=Z,W=B?.fields[Y];if(Y==="AND"||Y==="OR"){let Q=await Promise.all(A[Y].map((q)=>this._getWhereObjectWithPointerOrRelation($,q,F)));return{...J,[Y]:Q}}if(W?.type!=="Pointer"&&W?.type!=="Relation")return w;let X=W.class,U=A[Y],H=await this.getObjects({className:X,select:{id:!0},where:U,context:F});return{...w,[Y]:{in:H.map((Q)=>Q?.id).filter(x2)}}},Promise.resolve({}));return{...A,...E}}_buildWhereWithACL($,A,F){if(A.isRoot)return $;let D=A.user?.role?.id,B=A.user?.id;return{AND:[{...$},!B?{acl:{equalTo:null}}:void 0,B||D?{OR:[{acl:{equalTo:null}},B?{AND:[{acl:{users:{userId:{in:[B]}}}},{acl:{users:{[F]:{in:[!0]}}}}]}:void 0,D?{AND:[{acl:{users:{userId:{notIn:[B]}}}},{acl:{roles:{roleId:{in:[D]}}}},{acl:{roles:{[F]:{in:[!0]}}}}]}:void 0].filter(x2)}:void 0].filter(x2)}}_getFinalObjectWithPointerAndRelation({pointers:$,context:A,originClassName:F,object:D,isGraphQLCall:B}){return Object.entries($).reduce(async(E,[w,{className:Z,select:J}])=>{let Y=await E;if(this._isPointerField({originClassName:F,context:A,currentClassName:Z,pointerField:w})){if(!D[w])return{...Y,[w]:null};let U=await this.getObject({className:Z,id:D[w],context:A,select:J});return{...Y,[w]:U}}if(this._isRelationField({originClassName:F,context:A,currentClassName:Z,pointerField:w})&&D[w]){let U=await this.getObjects({className:Z,select:J,where:{id:{in:D[w]}},context:A});return{...E,[w]:B?{totalCount:U.length,edges:U.map((H)=>({node:H}))}:U}}return Y},Promise.resolve({}))}connect(){return this.adapter.connect()}close(){return this.adapter.close()}createClassIfNotExist($,A){return this.adapter.createClassIfNotExist($,A)}async count({className:$,context:A,where:F}){let D=n3({className:$,context:A,select:{}});await D?.runOnSingleObject({operationType:"beforeRead"});let B=await this.adapter.count({className:$,context:A,where:F});return await D?.runOnSingleObject({operationType:"afterRead"}),B}async clearDatabase(){await this.adapter.clearDatabase()}async getObject({select:$,className:A,context:F,skipHooks:D,id:B,where:E,isGraphQLCall:w=!1}){let{pointers:Z,selectWithoutPointers:J}=this._getSelectMinusPointersAndRelations({className:A,context:F,select:$}),Y=!D?n3({className:A,context:F,select:J}):void 0;await Y?.runOnSingleObject({operationType:"beforeRead",id:B});let W=this._buildWhereWithACL(E||{},F,"read"),X=Object.keys(Z).reduce((H,Q)=>{return H[Q]=!0,H},J);await Y?.runOnSingleObject({operationType:"afterRead",id:B});let U=await this.adapter.getObject({className:A,id:B,context:R1(F),select:!$?void 0:X,where:W});return{...U,...await this._getFinalObjectWithPointerAndRelation({context:F,originClassName:A,pointers:Z,object:U,isGraphQLCall:w})}}async getObjects({className:$,select:A,context:F,where:D,skipHooks:B,first:E,offset:w,order:Z,isGraphQLCall:J=!1}){let{pointers:Y,selectWithoutPointers:W}=this._getSelectMinusPointersAndRelations({className:$,context:F,select:A}),X=await this._getWhereObjectWithPointerOrRelation($,D||{},F),U=this._buildWhereWithACL(X||{},F,"read"),H=Object.keys(Y).reduce((V,L)=>{return V[L]=!0,V},W),Q=!B?n3({className:$,select:W,context:F}):void 0;await Q?.runOnMultipleObjects({operationType:"beforeRead",where:U}),await Q?.runOnMultipleObjects({operationType:"afterRead",where:U});let q=await this.adapter.getObjects({className:$,context:R1(F),first:E,offset:w,where:U,select:!A?void 0:H,order:Z});return Promise.all(q.map(async(V)=>({...V,...await this._getFinalObjectWithPointerAndRelation({object:V,context:F,originClassName:$,pointers:Y,isGraphQLCall:J})})))}async createObject({className:$,context:A,data:F,select:D,isGraphQLCall:B=!1}){let E=n3({className:$,context:A,newData:F,select:D}),{newData:w}=await E.runOnSingleObject({operationType:"beforeCreate"}),{id:Z}=await this.adapter.createObject({className:$,context:A,select:D,data:w});if(await E.runOnSingleObject({operationType:"afterCreate",id:Z}),D&&Object.keys(D).length===0)return null;return this.getObject({className:$,context:R1(A),select:D,id:Z,skipHooks:!0,isGraphQLCall:B})}async createObjects({data:$,select:A,className:F,context:D,first:B,offset:E,order:w,isGraphQLCall:Z=!1}){if($.length===0)return[];let J=await Promise.all($.map((U)=>n3({className:F,context:D,newData:U,select:A}))),Y=await Promise.all(J.map(async(U)=>(await U.runOnMultipleObjects({operationType:"beforeCreate"}))?.newData[0])),X=(await this.adapter.createObjects({className:F,select:A,context:D,data:Y,first:B,offset:E,order:w})).map(({id:U})=>U);if(await Promise.all(J.map((U)=>U.runOnMultipleObjects({operationType:"afterCreate",ids:X}))),A&&Object.keys(A).length===0)return[];return this.getObjects({className:F,context:D,select:A,where:{id:{in:X}},skipHooks:!0,first:B,offset:E,order:w,isGraphQLCall:Z})}async updateObject({id:$,className:A,context:F,data:D,select:B,skipHooks:E,isGraphQLCall:w=!1}){let Z=!E?n3({className:A,context:F,newData:D,select:B}):void 0,J=await Z?.runOnSingleObject({operationType:"beforeUpdate",id:$}),Y=this._buildWhereWithACL({},F,"write");if(await this.adapter.updateObject({className:A,select:B,id:$,context:F,data:J?.newData||D,where:Y}),await Z?.runOnSingleObject({operationType:"afterUpdate",id:$,originalObject:J?.object}),B&&Object.keys(B).length===0)return null;return this.getObject({className:A,context:F,select:B,id:$,isGraphQLCall:w})}async updateObjects({className:$,where:A,context:F,select:D,data:B,first:E,offset:w,order:Z,skipHooks:J,isGraphQLCall:Y=!1}){let W=await this._getWhereObjectWithPointerOrRelation($,A||{},F),X=!J?n3({className:$,context:F,newData:B,select:D}):void 0,U=this._buildWhereWithACL(W,F,"write"),H=await X?.runOnMultipleObjects({operationType:"beforeUpdate",where:U}),q=(await this.adapter.updateObjects({className:$,context:F,select:D,data:H?.newData[0]||B,where:U,first:E,offset:w,order:Z})).map((V)=>V?.id).filter(x2);if(await X?.runOnMultipleObjects({operationType:"afterUpdate",ids:q,originalObjects:H?.objects||[]}),D&&Object.keys(D).length===0)return[];return this.getObjects({className:$,context:F,select:D,where:{id:{in:q}},first:E,offset:w,order:Z,isGraphQLCall:Y})}async deleteObject({context:$,className:A,id:F,select:D,isGraphQLCall:B=!1}){let E=n3({className:A,context:$,select:D}),w=this._buildWhereWithACL({},$,"write"),Z=null;if(D&&Object.keys(D).length>0)Z=await this.getObject({className:A,select:D,id:F,context:$,isGraphQLCall:B});let J=await E.runOnSingleObject({operationType:"beforeDelete",id:F});return await this.adapter.deleteObject({className:A,context:$,select:D,id:F,where:w}),await E.runOnSingleObject({operationType:"afterDelete",originalObject:J.object}),Z}async deleteObjects({className:$,context:A,select:F,where:D,first:B,offset:E,order:w,isGraphQLCall:Z=!1}){let J=await this._getWhereObjectWithPointerOrRelation($,D||{},A),Y=n3({className:$,context:A,select:F}),W=this._buildWhereWithACL(J,A,"write"),X=[];if(F&&Object.keys(F).length>0)X=await this.getObjects({className:$,where:D,select:F,context:A,first:B,offset:E,order:w,isGraphQLCall:Z});let U=await Y.runOnMultipleObjects({operationType:"beforeDelete",where:W});return await this.adapter.deleteObjects({className:$,context:A,select:F,first:B,offset:E,where:W,order:w}),await Y.runOnMultipleObjects({operationType:"afterDelete",originalObjects:U.objects}),X}}var Zc;((F)=>{F.google="google";F.github="github"})(Zc||={});var O$;((B)=>{B.GitHub="github";B.Google="google";B.EmailPassword="emailPassword";B.PhonePassword="phonePassword"})(O$||={});var Wq;((A)=>A.EmailOTP="emailOTP")(Wq||={});import Jc from"node:crypto";var Yc=($)=>{return Jc.createHash("sha256").update($).digest("base64").split("=")[0].replaceAll("+","-").replaceAll("/","_")},vD=()=>Jc.randomBytes(60).toString("base64url");class fD{clientId;authorizeEndpoint;tokenEndpoint;redirectURI;constructor($,A,F,D){this.clientId=$,this.authorizeEndpoint=A,this.tokenEndpoint=F,this.redirectURI=D}createAuthorizationURL($){let A=Array.from(new Set($?.scopes||[])),F=new URL(this.authorizeEndpoint);if(F.searchParams.set("response_type","code"),F.searchParams.set("client_id",this.clientId),$?.state!==void 0)F.searchParams.set("state",$.state);if(A.length>0)F.searchParams.set("scope",A.join(" "));if(this.redirectURI!==null)F.searchParams.set("redirect_uri",this.redirectURI);if($?.codeVerifier!==void 0){let D=Yc($.codeVerifier);F.searchParams.set("code_challenge_method","S256"),F.searchParams.set("code_challenge",D)}return F}validateAuthorizationCode($,A){let F=new URLSearchParams;if(F.set("code",$),F.set("client_id",this.clientId),F.set("grant_type","authorization_code"),this.redirectURI!==null)F.set("redirect_uri",this.redirectURI);if(A?.codeVerifier!==void 0)F.set("code_verifier",A.codeVerifier);return this._sendTokenRequest(F,A)}async refreshAccessToken($,A){let F=new URLSearchParams;F.set("refresh_token",$),F.set("client_id",this.clientId),F.set("grant_type","refresh_token");let D=Array.from(new Set(A?.scopes??[]));if(D.length>0)F.set("scope",D.join(" "));return await this._sendTokenRequest(F,A)}async _sendTokenRequest($,A){let F=new Headers;if(F.set("Content-Type","application/x-www-form-urlencoded"),F.set("Accept","application/json"),F.set("User-Agent","wabe"),A?.credentials!==void 0)if((A?.authenticateWith||"http_basic_auth")==="http_basic_auth"){let Z=btoa(`${this.clientId}:${A.credentials}`);F.set("Authorization",`Basic ${Z}`)}else $.set("client_secret",A.credentials);let D=new Request(this.tokenEndpoint,{method:"POST",headers:F,body:$}),B=await fetch(D),E=await B.json();if(!("access_token"in E)||B.status!==200||!B.ok)throw new Error("Error in token request");return E}}var ak1="https://accounts.google.com/o/oauth2/v2/auth",ik1="https://oauth2.googleapis.com/token";class bD{client;clientSecret;constructor($){let A=$.authentication?.providers?.google;if(!A)throw new Error("Google config not found");let D=`${`http${$.isProduction?"s":""}://${$.authentication?.backDomain||"127.0.0.1:"+$.port||3000}`}/auth/oauth/callback`;this.client=new fD(A.clientId,ak1,ik1,D),this.clientSecret=A.clientSecret}createAuthorizationURL($,A,F){let D=F?.scopes??[],B=this.client.createAuthorizationURL({state:$,codeVerifier:A,scopes:[...D,"openid"]});return B.searchParams.set("access_type","offline"),B.searchParams.set("prompt","select_account"),B}async validateAuthorizationCode($,A){let{access_token:F,expires_in:D,refresh_token:B,id_token:E}=await this.client.validateAuthorizationCode($,{authenticateWith:"request_body",credentials:this.clientSecret,codeVerifier:A});return{accessToken:F,refreshToken:B,accessTokenExpiresAt:new Date(Date.now()+D*1000),idToken:E}}async refreshAccessToken($){let{access_token:A,expires_in:F}=await this.client.refreshAccessToken($,{authenticateWith:"request_body",credentials:this.clientSecret});return{accessToken:A,accessTokenExpiresAt:new Date(Date.now()+F*1000)}}async getUserInfo($){let A=await fetch(`https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${$}`),{email:F,verified_email:D}=await A.json();return{email:F,verifiedEmail:D}}}var tD=H1(xs(),1);class D4{accessToken=void 0;refreshToken=void 0;getAccessTokenExpireAt($){let A=$?.authentication?.session?.accessTokenExpiresInMs;if(!A)return new Date(Date.now()+900000);return new Date(Date.now()+A)}_getRefreshTokenExpiresInMs($){let A=$?.authentication?.session?.refreshTokenExpiresInMs;if(!A)return 2592000000;return A}getRefreshTokenExpireAt($){let A=this._getRefreshTokenExpiresInMs($);return new Date(Date.now()+A)}async meFromAccessToken($,A){let F=await A.wabe.controllers.database.getObjects({className:"_Session",where:{accessToken:{equalTo:$},OR:[{accessTokenExpiresAt:{greaterThanOrEqualTo:new Date}},{refreshTokenExpiresAt:{greaterThanOrEqualTo:new Date}}]},select:{id:!0,user:!0,accessTokenExpiresAt:!0,refreshTokenExpiresAt:!0,refreshToken:!0},first:1,context:A});if(F.length===0)return{sessionId:null,user:null,accessToken:null,refreshToken:null};let D=F[0];if(!D||!D?.user)return{sessionId:null,user:null,accessToken:null,refreshToken:null};let B=D.user,E=await A.wabe.controllers.database.getObject({className:"User",select:{role:!0},context:A,id:B.id});if(new Date(D.accessTokenExpiresAt)<new Date&&new Date(D.refreshTokenExpiresAt)>=new Date&&D.refreshToken){let{accessToken:w,refreshToken:Z}=await this.refresh($,D.refreshToken,A);return{sessionId:D.id,user:{...B,role:E?.role},accessToken:w,refreshToken:Z}}return{sessionId:D.id,user:{...B,role:E?.role},accessToken:$,refreshToken:D.refreshToken}}async create($,A){this.accessToken=tD.default.sign({userId:$,iat:Date.now(),exp:this.getAccessTokenExpireAt(A.wabe.config).getTime()},import.meta.env.JWT_SECRET||"dev"),this.refreshToken=tD.default.sign({userId:$,iat:Date.now(),exp:this.getRefreshTokenExpireAt(A.wabe.config).getTime()},import.meta.env.JWT_SECRET||"dev");let F=await A.wabe.controllers.database.createObject({className:"_Session",context:R1(A),data:{accessToken:this.accessToken,accessTokenExpiresAt:this.getAccessTokenExpireAt(A.wabe.config),refreshToken:this.refreshToken,refreshTokenExpiresAt:this.getRefreshTokenExpireAt(A.wabe.config),user:$},select:{id:!0}});if(!F)throw new Error("Session not created");return{accessToken:this.accessToken,refreshToken:this.refreshToken,sessionId:F.id}}async delete($){if(!$.sessionId)return;await $.wabe.controllers.database.deleteObject({className:"_Session",context:R1($),id:$.sessionId,select:{}})}_isRefreshTokenExpired($,A){let F=$.getTime()-A;return Date.now()-F>=0.75*A}async refresh($,A,F){let D=await F.wabe.controllers.database.getObjects({className:"_Session",where:{accessToken:{equalTo:$}},select:{id:!0,user:{id:!0,role:{id:!0,name:!0}},refreshToken:!0,refreshTokenExpiresAt:!0},context:R1(F)});if(!D.length)return{accessToken:null,refreshToken:null};if(!D[0])throw new Error("Session not found");let{refreshTokenExpiresAt:B,user:E,refreshToken:w,id:Z}=D[0];if(new Date(B)<new Date(Date.now()))throw new Error("Refresh token expired");let J=this._getRefreshTokenExpiresInMs(F.wabe.config);if(!this._isRefreshTokenExpired(new Date(B),J))return{accessToken:$,refreshToken:A};if(A!==w)throw new Error("Invalid refresh token");let Y=E?.id;if(!Y)return{accessToken:null,refreshToken:null};let W=tD.default.sign({userId:Y,iat:Date.now(),exp:this.getAccessTokenExpireAt(F.wabe.config).getTime()},import.meta.env.JWT_SECRET||"dev"),X=tD.default.sign({userId:Y,iat:Date.now(),exp:this.getRefreshTokenExpireAt(F.wabe.config).getTime()},import.meta.env.JWT_SECRET||"dev");return await F.wabe.controllers.database.updateObject({className:"_Session",context:R1(F),id:Z,data:{accessToken:W,accessTokenExpiresAt:this.getAccessTokenExpireAt(F.wabe.config),refreshToken:X,refreshTokenExpiresAt:this.getRefreshTokenExpireAt(F.wabe.config)},select:{}}),{accessToken:W,refreshToken:X}}}var ys=async($,A,F)=>{let{input:{refreshToken:D,accessToken:B}}=A,E=new D4,{accessToken:w,refreshToken:Z}=await E.refresh(B,D,F);return{accessToken:w,refreshToken:Z}};var ls=async($,A,F)=>{if(await new D4().delete(F),F.wabe.config.authentication?.session?.cookieSession)F.response?.deleteCookie("accessToken"),F.response?.deleteCookie("refreshToken");return!0};var cs=async($,{input:A},F)=>{if(!A.secondFA)throw new Error("One factor is required");let D=Object.keys(A.secondFA);if(D.length>1)throw new Error("Only one factor is allowed");let{provider:B,name:E}=g9(D,F),w=await B.onVerifyChallenge({context:F,input:A.secondFA[E]});if(!w?.userId)throw new Error("Invalid challenge");let Z=new D4,{accessToken:J,refreshToken:Y}=await Z.create(w.userId,F);if(F.wabe.config.authentication?.session?.cookieSession){let W=Z.getAccessTokenExpireAt(F.wabe.config),X=Z.getRefreshTokenExpireAt(F.wabe.config);F.response?.setCookie("refreshToken",Y,{httpOnly:!0,path:"/",sameSite:"None",secure:!0,expires:X}),F.response?.setCookie("accessToken",J,{httpOnly:!0,path:"/",sameSite:"None",secure:!0,expires:W})}return{accessToken:J}};var as=($,A,F)=>{if(!F.user?.id)return{user:void 0};return{user:F.user}};var is=($,{input:A},F)=>{if(!F.user&&!F.isRoot)throw new Error("Permission denied");let D=F.wabe.controllers.email;if(!D)throw new Error("Email adapter not defined");return D.send({...A,text:A.text??void 0,html:A.html??void 0})};var dn=H1(hn(),1);import{createHash as Nn}from"node:crypto";var Kx1=5;class T8{secret;internalTotp;constructor($){this.secret=$,this.internalTotp=dn.totp.clone({window:[Kx1,0]})}generate($){let A=Nn("sha256").update(`${this.secret}:${$}`).digest("hex");return this.internalTotp.generate(A)}verify($,A){let F=Nn("sha256").update(`${this.secret}:${A}`).digest("hex");return this.internalTotp.verify({secret:F,token:$})}}var kn=async($,{input:{email:A,phone:F,password:D,otp:B}},E)=>{if(!A&&!F)throw new Error("Email or phone is required");let w=await E.wabe.controllers.database.getObjects({className:"User",where:{...A&&{email:{equalTo:A}},...F&&{authentication:{phonePassword:{phone:{equalTo:F}}}}},select:{id:!0,authentication:!0},first:1,context:R1(E)});if(w.length===0)return!0;let Z=w[0];if(!Z)return!0;let Y=new T8(E.wabe.config.rootKey).verify(B,Z.id);if(B!=="000000"&&!Y)throw new Error("Invalid OTP code");let W=F?"phonePassword":"emailPassword";return await E.wabe.controllers.database.updateObject({className:"User",id:Z.id,data:{authentication:{[W]:{...F&&{phone:Z.authentication?.phonePassword?.phone},...A&&{email:A},password:D}}},select:{},context:R1(E)}),!0};var mJ=($)=>`
205
+ `));if(E.enable(F.StreamResponse),E.setStreamProgressCallback(function(){return $.signal.aborted?process.env.DEBUG?B.Continue:1:0}),$.bodyType==="String")E.setOpt("POSTFIELDS",$.bodyInit);else{let U=$.body!=null?lV.isNodeReadable($.body)?$.body:n01.Readable.from($.body):null;if(U)E.setOpt("UPLOAD",!0),E.setUploadStream(U)}if(process.env.DEBUG)E.setOpt("VERBOSE",!0);E.setOpt("TRANSFER_ENCODING",!1),E.setOpt("HTTP_TRANSFER_DECODING",!0),E.setOpt("FOLLOWLOCATION",$.redirect==="follow"),E.setOpt("MAXREDIRS",20),E.setOpt("ACCEPT_ENCODING",""),E.setOpt("CUSTOMREQUEST",$.method);let w=$.headersSerializer||lV.defaultHeadersSerializer,Z,J=w($.headers,(U)=>{Z=Number(U)});if(Z!=null)E.setOpt("INFILESIZE",Z);E.setOpt("HTTPHEADER",J),E.enable(F.NoHeaderParsing);let Y=En1.createDeferredPromise(),W;function X(){if(E.isOpen)try{E.pause(D.Recv)}catch(U){Y.reject(U)}}if($.signal)$.signal.addEventListener("abort",X,{once:!0});return E.once("end",function U(){try{E.close()}catch(H){Y.reject(H)}if($.signal)$.signal.removeEventListener("abort",X)}),E.once("error",function U(H){if(W&&!W.closed&&!W.destroyed)W.destroy(H);else{if(H.message==="Operation was aborted by an application callback")H.message="The operation was aborted.";Y.reject(H)}try{E.close()}catch(Q){Y.reject(Q)}}),E.once("stream",function U(H,Q,q){let V=new n01.PassThrough;Dn1.pipeline(H,V,{end:!0,signal:$.signal}).then(()=>{if(!H.destroyed)H.resume()}).catch(Y.reject);let h=q.toString("utf8").split(/\r?\n|\r/g).filter((T)=>{if(T&&!T.startsWith("HTTP/")){if($.redirect==="error"&&T.toLowerCase().includes("location")&&lV.shouldRedirect(Q)){if(!H.destroyed)H.resume();V.destroy(),Y.reject(new Error("redirect is not allowed"))}return!0}return!1}).map((T)=>T.split(/:\s(.+)/).slice(0,2)),P=new wn1.PonyfillResponse(V,{status:Q,headers:h,url:E.getInfo(A.info.REDIRECT_URL)?.toString()||$.url,redirected:Number(E.getInfo(A.info.REDIRECT_COUNT))>0});Y.resolve(P),W=V}),setImmediate(()=>{E.perform()}),Y.promise}});var LB=C((e01)=>{Object.defineProperty(e01,"__esModule",{value:!0});e01.PonyfillURL=void 0;var Yn1=dY(),Wn1=Yn1.__importDefault(p("node:buffer")),Xn1=p("node:crypto");class o01 extends URL{static blobRegistry=new Map;static createObjectURL($){let A=`blob:whatwgnode:${Xn1.randomUUID()}`;return this.blobRegistry.set(A,$),A}static revokeObjectURL($){if(!this.blobRegistry.has($))URL.revokeObjectURL($);else this.blobRegistry.delete($)}static getBlobFromURL($){return this.blobRegistry.get($)||Wn1.default?.resolveObjectURL?.($)}}e01.PonyfillURL=o01});var lY=C((D21)=>{Object.defineProperty(D21,"__esModule",{value:!0});D21.PonyfillRequest=void 0;var Un1=p("node:http"),Hn1=p("node:https"),Qn1=gY(),A21=xY(),Cn1=LB();function Gn1($){return $[Symbol.toStringTag]==="Request"}function Kn1($){return $?.href!=null}class F21 extends Qn1.PonyfillBody{constructor($,A){let F,D,B=null,E;if(typeof $==="string")F=$;else if(Kn1($))D=$;else if(Gn1($)){if($._parsedUrl)D=$._parsedUrl;else if($._url)F=$._url;else F=$.url;B=$.body,E=$}if(A!=null)B=A.body||null,E=A;super(B,A);if(this._url=F,this._parsedUrl=D,this.cache=E?.cache||"default",this.credentials=E?.credentials||"same-origin",this.headers=E?.headers&&A21.isHeadersLike(E.headers)?E.headers:new A21.PonyfillHeaders(E?.headers),this.integrity=E?.integrity||"",this.keepalive=E?.keepalive!=null?E?.keepalive:!1,this.method=E?.method?.toUpperCase()||"GET",this.mode=E?.mode||"cors",this.redirect=E?.redirect||"follow",this.referrer=E?.referrer||"about:client",this.referrerPolicy=E?.referrerPolicy||"no-referrer",this.signal=E?.signal||new AbortController().signal,this.headersSerializer=E?.headersSerializer,this.duplex=E?.duplex||"half",this.destination="document",this.priority="auto",this.method!=="GET"&&this.method!=="HEAD")this.handleContentLengthHeader(!0);if(E?.agent!=null){let w=D?.protocol||F||this.url;if(E.agent===!1)this.agent=!1;else if(w.startsWith("http:")&&E.agent instanceof Un1.Agent)this.agent=E.agent;else if(w.startsWith("https:")&&E.agent instanceof Hn1.Agent)this.agent=E.agent}}headersSerializer;cache;credentials;destination;headers;integrity;keepalive;method;mode;priority;redirect;referrer;referrerPolicy;_url;get url(){if(this._url==null)if(this._parsedUrl)this._url=this._parsedUrl.toString();else throw new TypeError("Invalid URL");return this._url}_parsedUrl;get parsedUrl(){if(this._parsedUrl==null)if(this._url!=null)this._parsedUrl=new Cn1.PonyfillURL(this._url,"http://localhost");else throw new TypeError("Invalid URL");return this._parsedUrl}duplex;agent;signal;clone(){return this}[Symbol.toStringTag]="Request"}D21.PonyfillRequest=F21});var Y21=C((J21)=>{Object.defineProperty(J21,"__esModule",{value:!0});J21.fetchNodeHttp=Z21;var w21=p("node:http"),qn1=p("node:https"),E21=p("node:stream"),zn1=p("node:stream/promises"),cY=p("node:zlib"),Vn1=lY(),un1=RB(),Pn1=LB(),cV=D9();function Mn1($){if($.startsWith("http:"))return w21.request;else if($.startsWith("https:"))return qn1.request;throw new Error(`Unsupported protocol: ${$.split(":")[0]||$}`)}function Z21($){return new Promise((A,F)=>{try{let D=Mn1($.parsedUrl?.protocol||$.url),B=$.body!=null?cV.isNodeReadable($.body)?$.body:E21.Readable.from($.body):null,w=($.headersSerializer||cV.getHeadersObj)($.headers);if(w["accept-encoding"]==null)w["accept-encoding"]="gzip, deflate, br";let Z;if($.parsedUrl)Z=D($.parsedUrl,{method:$.method,headers:w,signal:$.signal,agent:$.agent});else Z=D($.url,{method:$.method,headers:w,signal:$.signal,agent:$.agent});if(Z.once("response",(J)=>{let Y;switch(J.headers["content-encoding"]){case"x-gzip":case"gzip":Y=cY.createGunzip();break;case"x-deflate":case"deflate":Y=cY.createInflate();break;case"x-deflate-raw":case"deflate-raw":Y=cY.createInflateRaw();break;case"br":Y=cY.createBrotliDecompress();break;default:Y=new E21.PassThrough}if(J.headers.location&&cV.shouldRedirect(J.statusCode)){if($.redirect==="error"){let Q=new Error("Redirects are not allowed");F(Q),J.resume();return}if($.redirect==="follow"){let Q=new Pn1.PonyfillURL(J.headers.location,$.parsedUrl||$.url),q=Z21(new Vn1.PonyfillRequest(Q,$));A(q.then((V)=>{return V.redirected=!0,V})),J.resume();return}}zn1.pipeline(J,Y,{signal:$.signal,end:!0}).then(()=>{if(!J.destroyed)J.resume()}).catch(F);let X=J.statusCode||200,U=J.statusMessage||w21.STATUS_CODES[X];if(U==null)U="";let H=new un1.PonyfillResponse(Y,{status:X,statusText:U,headers:J.headers,url:$.url});A(H)}),Z.once("error",F),B)B.pipe(Z);else Z.end()}catch(D){F(D)}})}});var Q21=C((H21)=>{Object.defineProperty(H21,"__esModule",{value:!0});H21.fetchPonyfill=U21;var jn1=p("node:buffer"),aY=p("node:fs"),Rn1=p("node:url"),Ln1=t01(),Tn1=Y21(),Sn1=lY(),YA=RB(),On1=LB(),W21=D9(),X21=";base64";async function hn1($){let A=Rn1.fileURLToPath($);try{await aY.promises.access(A,aY.promises.constants.R_OK);let F=await aY.promises.stat(A,{bigint:!0}),D=aY.createReadStream(A);return new YA.PonyfillResponse(D,{status:200,statusText:"OK",headers:{"content-type":"application/octet-stream","last-modified":F.mtime.toUTCString()}})}catch(F){if(F.code==="ENOENT")return new YA.PonyfillResponse(null,{status:404,statusText:"Not Found"});else if(F.code==="EACCES")return new YA.PonyfillResponse(null,{status:403,statusText:"Forbidden"});throw F}}function Nn1($){let[A="text/plain",...F]=$.substring(5).split(","),D=decodeURIComponent(F.join(","));if(A.endsWith(X21)){let B=jn1.Buffer.from(D,"base64url"),E=A.slice(0,-X21.length);return new YA.PonyfillResponse(B,{status:200,statusText:"OK",headers:{"content-type":E}})}return new YA.PonyfillResponse(D,{status:200,statusText:"OK",headers:{"content-type":A}})}function dn1($){let A=On1.PonyfillURL.getBlobFromURL($);if(!A)throw new TypeError("Invalid Blob URL");return new YA.PonyfillResponse(A,{status:200,headers:{"content-type":A.type,"content-length":A.size.toString()}})}function kn1($){return $!=null&&$.href!=null}function U21($,A){if(typeof $==="string"||kn1($)){let D=new Sn1.PonyfillRequest($,A);return U21(D)}let F=$;if(F.url.startsWith("data:")){let D=Nn1(F.url);return W21.fakePromise(D)}if(F.url.startsWith("file:"))return hn1(F.url);if(F.url.startsWith("blob:")){let D=dn1(F.url);return W21.fakePromise(D)}if(globalThis.libcurl&&!F.agent)return Ln1.fetchCurl(F);return Tn1.fetchNodeHttp(F)}});var aV=C((K21)=>{Object.defineProperty(K21,"__esModule",{value:!0});K21.PonyfillTextDecoder=K21.PonyfillTextEncoder=void 0;K21.PonyfillBtoa=fn1;var TB=p("node:buffer"),vn1=D9();class C21{encoding;constructor($="utf-8"){this.encoding=$}encode($){return TB.Buffer.from($,this.encoding)}encodeInto($,A){let D=this.encode($).copy(A);return{read:D,written:D}}}K21.PonyfillTextEncoder=C21;class G21{encoding;fatal=!1;ignoreBOM=!1;constructor($="utf-8",A){if(this.encoding=$,A)this.fatal=A.fatal||!1,this.ignoreBOM=A.ignoreBOM||!1}decode($){if(TB.Buffer.isBuffer($))return $.toString(this.encoding);if(vn1.isArrayBufferView($))return TB.Buffer.from($.buffer,$.byteOffset,$.byteLength).toString(this.encoding);return TB.Buffer.from($).toString(this.encoding)}}K21.PonyfillTextDecoder=G21;function fn1($){return TB.Buffer.from($,"binary").toString("base64")}});var u21=C((z21)=>{Object.defineProperty(z21,"__esModule",{value:!0});z21.PonyfillURLSearchParams=void 0;z21.PonyfillURLSearchParams=globalThis.URLSearchParams});var nV=C((M21)=>{Object.defineProperty(M21,"__esModule",{value:!0});M21.PonyfillWritableStream=void 0;var iV=p("node:stream"),sV=D9();class P21{writable;constructor($){if($ instanceof iV.Writable)this.writable=$;else if($){let A=new iV.Writable({write(B,E,w){try{let Z=$.write?.(B,D);if(Z instanceof Promise)Z.then(()=>{w()},(J)=>{w(J)});else w()}catch(Z){w(Z)}},final(B){let E=$.close?.();if(E instanceof Promise)E.then(()=>{B()},(w)=>{B(w)});else B()}});this.writable=A;let F=new AbortController,D={signal:F.signal,error(B){A.destroy(B)}};A.once("error",(B)=>F.abort(B)),A.once("close",()=>F.abort())}else this.writable=new iV.Writable}getWriter(){let $=this.writable;return{closed:new Promise((A)=>{$.once("close",()=>{A(void 0)})}),get desiredSize(){return $.writableLength},ready:new Promise((A)=>{$.once("drain",()=>{A(void 0)})}),releaseLock(){},write(A){if(A==null)return sV.fakePromise();return new Promise((F,D)=>{$.write(A,(B)=>{if(B)D(B);else F()})})},close(){if(!$.errored&&$.closed)return sV.fakePromise();return new Promise((A,F)=>{if($.errored)F($.errored);else $.end((D)=>{if(D)F(D);else A()})})},abort(A){return new Promise((F)=>{$.destroy(A),$.once("close",F)})}}}close(){if(!this.writable.errored&&this.writable.closed)return sV.fakePromise();return new Promise(($,A)=>{if(this.writable.errored)A(this.writable.errored);else this.writable.end((F)=>{if(F)A(F);else $()})})}abort($){return new Promise((A)=>{this.writable.destroy($),this.writable.once("close",A)})}locked=!1}M21.PonyfillWritableStream=P21});var SB=C((R21)=>{Object.defineProperty(R21,"__esModule",{value:!0});R21.PonyfillTransformStream=void 0;var rV=p("node:stream"),pn1=JA(),gn1=nV();class j21{transform;writable;readable;constructor($){if($ instanceof rV.Transform)this.transform=$;else if($){let A={enqueue(D){F.push(D)},error(D){F.destroy(D)},terminate(){F.end()},get desiredSize(){return F.writableLength}},F=new rV.Transform({read(){},write(D,B,E){try{let w=$.transform?.(D,A);if(w instanceof Promise)w.then(()=>{E()},(Z)=>{E(Z)});else E()}catch(w){E(w)}},final(D){try{let B=$.flush?.(A);if(B instanceof Promise)B.then(()=>{D()},(E)=>{D(E)});else D()}catch(B){D(B)}}});this.transform=F}else this.transform=new rV.Transform;this.writable=new gn1.PonyfillWritableStream(this.transform),this.readable=new pn1.PonyfillReadableStream(this.transform)}}R21.PonyfillTransformStream=j21});var h21=C((S21)=>{Object.defineProperty(S21,"__esModule",{value:!0});S21.PonyfillCompressionStream=void 0;var iY=p("node:zlib"),xn1=SB();class T21 extends xn1.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith("v2")?["gzip","deflate","br"]:["gzip","deflate","deflate-raw","br"];constructor($){switch($){case"x-gzip":case"gzip":super(iY.createGzip());break;case"x-deflate":case"deflate":super(iY.createDeflate());break;case"deflate-raw":super(iY.createDeflateRaw());break;case"br":super(iY.createBrotliCompress());break;default:throw new Error(`Unsupported compression format: ${$}`)}}}S21.PonyfillCompressionStream=T21});var m21=C((d21)=>{Object.defineProperty(d21,"__esModule",{value:!0});d21.PonyfillDecompressionStream=void 0;var sY=p("node:zlib"),yn1=SB();class N21 extends yn1.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith("v2")?["gzip","deflate","br"]:["gzip","deflate","deflate-raw","br"];constructor($){switch($){case"x-gzip":case"gzip":super(sY.createGunzip());break;case"x-deflate":case"deflate":super(sY.createInflate());break;case"deflate-raw":super(sY.createInflateRaw());break;case"br":super(sY.createBrotliDecompress());break;default:throw new TypeError(`Unsupported compression format: '${$}'`)}}}d21.PonyfillDecompressionStream=N21});var x21=C((p21)=>{Object.defineProperty(p21,"__esModule",{value:!0});p21.PonyfillTextEncoderStream=p21.PonyfillTextDecoderStream=void 0;var v21=aV(),f21=SB();class b21 extends f21.PonyfillTransformStream{textDecoder;constructor($,A){super({transform:(F,D)=>{D.enqueue(this.textDecoder.decode(F,{stream:!0}))}});this.textDecoder=new v21.PonyfillTextDecoder($,A)}get encoding(){return this.textDecoder.encoding}get fatal(){return this.textDecoder.fatal}get ignoreBOM(){return this.textDecoder.ignoreBOM}}p21.PonyfillTextDecoderStream=b21;class _21 extends f21.PonyfillTransformStream{textEncoder;constructor($){super({transform:(A,F)=>{F.enqueue(this.textEncoder.encode(A))}});this.textEncoder=new v21.PonyfillTextEncoder($)}get encoding(){return this.textEncoder.encoding}encode($){return this.textEncoder.encode($)}}p21.PonyfillTextEncoderStream=_21});var l21=C((_0)=>{Object.defineProperty(_0,"__esModule",{value:!0});_0.TextEncoderStream=_0.TextDecoderStream=_0.IteratorObject=_0.DecompressionStream=_0.CompressionStream=_0.TransformStream=_0.WritableStream=_0.URLSearchParams=_0.URL=_0.btoa=_0.TextDecoder=_0.TextEncoder=_0.Blob=_0.FormData=_0.File=_0.ReadableStream=_0.Response=_0.Request=_0.Body=_0.Headers=_0.fetch=void 0;var cn1=Q21();Object.defineProperty(_0,"fetch",{enumerable:!0,get:function(){return cn1.fetchPonyfill}});var an1=xY();Object.defineProperty(_0,"Headers",{enumerable:!0,get:function(){return an1.PonyfillHeaders}});var in1=gY();Object.defineProperty(_0,"Body",{enumerable:!0,get:function(){return in1.PonyfillBody}});var sn1=lY();Object.defineProperty(_0,"Request",{enumerable:!0,get:function(){return sn1.PonyfillRequest}});var nn1=RB();Object.defineProperty(_0,"Response",{enumerable:!0,get:function(){return nn1.PonyfillResponse}});var rn1=JA();Object.defineProperty(_0,"ReadableStream",{enumerable:!0,get:function(){return rn1.PonyfillReadableStream}});var tn1=mV();Object.defineProperty(_0,"File",{enumerable:!0,get:function(){return tn1.PonyfillFile}});var on1=xV();Object.defineProperty(_0,"FormData",{enumerable:!0,get:function(){return on1.PonyfillFormData}});var en1=fY();Object.defineProperty(_0,"Blob",{enumerable:!0,get:function(){return en1.PonyfillBlob}});var tV=aV();Object.defineProperty(_0,"TextEncoder",{enumerable:!0,get:function(){return tV.PonyfillTextEncoder}});Object.defineProperty(_0,"TextDecoder",{enumerable:!0,get:function(){return tV.PonyfillTextDecoder}});Object.defineProperty(_0,"btoa",{enumerable:!0,get:function(){return tV.PonyfillBtoa}});var $r1=LB();Object.defineProperty(_0,"URL",{enumerable:!0,get:function(){return $r1.PonyfillURL}});var Ar1=u21();Object.defineProperty(_0,"URLSearchParams",{enumerable:!0,get:function(){return Ar1.PonyfillURLSearchParams}});var Fr1=nV();Object.defineProperty(_0,"WritableStream",{enumerable:!0,get:function(){return Fr1.PonyfillWritableStream}});var Dr1=SB();Object.defineProperty(_0,"TransformStream",{enumerable:!0,get:function(){return Dr1.PonyfillTransformStream}});var Br1=h21();Object.defineProperty(_0,"CompressionStream",{enumerable:!0,get:function(){return Br1.PonyfillCompressionStream}});var Er1=m21();Object.defineProperty(_0,"DecompressionStream",{enumerable:!0,get:function(){return Er1.PonyfillDecompressionStream}});var wr1=pY();Object.defineProperty(_0,"IteratorObject",{enumerable:!0,get:function(){return wr1.PonyfillIteratorObject}});var y21=x21();Object.defineProperty(_0,"TextDecoderStream",{enumerable:!0,get:function(){return y21.PonyfillTextDecoderStream}});Object.defineProperty(_0,"TextEncoderStream",{enumerable:!0,get:function(){return y21.PonyfillTextEncoderStream}})});var a21=C((HY0,c21)=>{var Jr1=uV(),p0;c21.exports=function $(A={}){let F={};if(F.URLPattern=globalThis.URLPattern,!F.URLPattern){let D=ae();F.URLPattern=D.URLPattern}if(A.skipPonyfill||Jr1())return{fetch:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response,FormData:globalThis.FormData,ReadableStream:globalThis.ReadableStream,WritableStream:globalThis.WritableStream,TransformStream:globalThis.TransformStream,CompressionStream:globalThis.CompressionStream,DecompressionStream:globalThis.DecompressionStream,TextDecoderStream:globalThis.TextDecoderStream,TextEncoderStream:globalThis.TextEncoderStream,Blob:globalThis.Blob,File:globalThis.File,crypto:globalThis.crypto,btoa:globalThis.btoa,TextEncoder:globalThis.TextEncoder,TextDecoder:globalThis.TextDecoder,URLPattern:F.URLPattern,URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams};if(p0||=l21(),F.fetch=p0.fetch,F.Request=p0.Request,F.Response=p0.Response,F.Headers=p0.Headers,F.FormData=p0.FormData,F.ReadableStream=p0.ReadableStream,F.URL=p0.URL,F.URLSearchParams=p0.URLSearchParams,F.WritableStream=p0.WritableStream,F.TransformStream=p0.TransformStream,F.CompressionStream=p0.CompressionStream,F.DecompressionStream=p0.DecompressionStream,F.TextDecoderStream=p0.TextDecoderStream,F.TextEncoderStream=p0.TextEncoderStream,F.Blob=p0.Blob,F.File=p0.File,F.crypto=globalThis.crypto,F.btoa=p0.btoa,F.TextEncoder=p0.TextEncoder,F.TextDecoder=p0.TextDecoder,A.formDataLimits)F.Body=class D extends p0.Body{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}},F.Request=class D extends p0.Request{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}},F.Response=class D extends p0.Response{constructor(B,E){super(B,{formDataLimits:A.formDataLimits,...E})}};if(!F.crypto){let D=p("crypto");F.crypto=D.webcrypto}return F}});var n31=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((F)=>F.name===$.className);if(!A)return;Object.entries(A.fields).filter(([F,D])=>D.type==="File").map(async([F])=>{let D=$.originalObject?.[F]?.name;if(!D)return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");await $.context.wabe.controllers.file?.deleteFile(D)})},zu=($)=>n31($);var r31=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className);if(!A)return;let F=$.context.wabe.config.file?.urlCacheInSeconds||86400;await Promise.all(Object.entries(A.fields).filter(([D,B])=>B.type==="File").map(async([D])=>{let B=$.object?.[D];if(!B)return;let E=B.name;if(!E&&B.url)return B.url;let w=B.urlGeneratedAt;if(w&&w.getTime()+F*1000>new Date().getTime())return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");let Z=await $.context.wabe.controllers.file?.readFile(E);return $.context.wabe.controllers.database.updateObject({className:$.className,context:$.context,id:$.object?.id||"",data:{[D]:{...B,urlGeneratedAt:new Date,url:Z||B.url}},skipHooks:!0})}))},Vu=($)=>r31($);var uu=async($)=>{let A=$.getNewData(),F=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className);if(!F)return;await Promise.all(Object.keys(A).map(async(D)=>{let B=A[D]?.file,E=A[D]?.url;if(!B&&!E)return;if(E){$.upsertNewData(D,{url:E,isPresignedUrl:!1});return}if(F.fields[D].type!=="File"||!(B instanceof File))return;if(!$.context.wabe.controllers.file)throw new Error("No file adapter found");await $.context.wabe.controllers.file?.uploadFile(B),$.upsertNewData(D,{name:B.name,isPresignedUrl:!0})}))},Pu=($)=>uu($),Mu=($)=>uu($);var R1=($)=>({...$,isRoot:!0});class pB{className;newData;operationType;context;object;originalObject;select;constructor({newData:$,className:A,operationType:F,context:D,object:B,originalObject:E,select:w}){this.newData=$,this.className=A,this.operationType=F,this.context=D,this.object=B,this.originalObject=E,this.select=w||{}}getUser(){return this.context.user}isFieldUpdated($){return this.newData&&!!this.newData[$]}upsertNewData($,A){if(!this.newData)return;if(!this.operationType.includes("before"))throw new Error("Cannot set data in a hook that is not a before hook");this.newData[$]=A}getNewData(){return this.newData||{}}fetch(){let $=this.context.wabe.controllers.database;if(!this.object?.id)return Promise.resolve(null);return $.getObject({className:this.className,id:this.object.id,context:R1(this.context)})}async addACL($,A){let F=async(Y)=>{if(this.className==="User"){let W=this.object?.id;if(W)await this.context.wabe.controllers.database.updateObject({className:this.className,context:R1(this.context),id:W,data:{acl:Y},select:{}});return}this.upsertNewData("acl",Y)},B=(this.className==="User"?await this.context.wabe.controllers.database.getObject({className:"User",select:{acl:!0},id:this.object?.id,context:R1(this.context)}):{acl:this.getNewData().acl})?.acl||{};if(A===null){await F({...B,[$]:[]});return}let{userId:E,role:w,read:Z,write:J}=A;if(E&&w)throw new Error("Cannot specify both userId and role");if(w){let W=(await this.context.wabe.controllers.database.getObjects({className:"Role",select:{id:!0},where:{name:{equalTo:w}},context:R1(this.context)}))[0]?.id;await F({...B,[$]:[...B?.[$]||[],{roleId:W,read:Z,write:J}]});return}await F({...B,[$]:[...B?.[$]||[],{userId:E,read:Z,write:J}]})}}import{Algorithm as t31,hash as o31}from"@node-rs/argon2";var g9=($,A)=>{let F=A.wabe.config?.authentication?.customAuthenticationMethods;if(!F)throw new Error("No custom authentication methods found");let D=$.filter((w)=>w!=="secondaryFactor");if(D.length>1||D.length===0)throw new Error("One authentication method is required at the time");let B=D[0],E=F.find((w)=>w.name.toLowerCase()===B.toLowerCase());if(!E)throw new Error("No available custom authentication methods found");return E},D7=($)=>o31($,{algorithm:t31.Argon2id});var Iu=async($)=>{if(!$.isFieldUpdated("authentication")||$.getNewData().isOauth)return;let A=$.context,F=$.getNewData().authentication;if(F.emailPasswordSRP)return;let{provider:D,name:B}=g9(Object.keys(F),A),E=F[B],{authenticationDataToSave:w}=await D.onSignUp({input:E,context:A});$.upsertNewData("authentication",{[B]:w})},ju=async($)=>{if(!$.isFieldUpdated("authentication")||$.getNewData().isOauth)return;let A=$.context,F=$.getNewData().authentication;if(F.emailPasswordSRP)return;let{provider:D,name:B}=g9(Object.keys(F),A);if(!D.onUpdateAuthenticationData)return;let E=F[B];if(!$.object?.id)return;let{authenticationDataToSave:w}=await D.onUpdateAuthenticationData({context:A,input:E,userId:$.object.id});$.upsertNewData("authentication",{[B]:w})};var PA=($)=>{let A=$.search(/[a-z]/i);return $.slice(0,A)+$[A].toUpperCase()+$.slice(A+1)},x9=($)=>{let A=$.search(/[a-z]/i);return $.slice(0,A)+$[A].toLowerCase()+$.slice(A+1)},B7=($,A)=>{let F=A.schema?.classes?.find((D)=>D.name===$);if(!F)throw new Error("Class not found in schema");return F},Ru=($,A)=>{let F=A.get("Cookie");if(!F)return;let D=F.split(";").find((B)=>B.includes($));if(!D)return;return D.split("=")[1]},gB=($)=>{return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s\s+/g," ").replace(/[\W_]+/g," ").trim()};var Lu=($)=>{if(!$.isFieldUpdated("createdAt"))$.upsertNewData("createdAt",new Date);if(!$.isFieldUpdated("updatedAt"))$.upsertNewData("updatedAt",new Date)},Tu=($)=>{$.upsertNewData("updatedAt",new Date)},Su=async($)=>{let A=B7($.className,$.context.wabe.config);Object.keys(A.fields).map((D)=>{let B=A.fields[D];if(!$.isFieldUpdated(D)&&B.type!=="Pointer"&&B.type!=="Relation"&&B.type!=="File"&&B.defaultValue!==void 0)$.upsertNewData(D,B.defaultValue)})};var Ou=async($)=>{let A=$.object?.id;await $.context.wabe.controllers.database.deleteObjects({className:"_Session",context:R1($.context),where:{user:{id:{equalTo:A}}},select:{}})};var e31=($)=>{return{beforeCreate:"create",afterCreate:"create",beforeRead:"read",afterRead:"read",beforeDelete:"delete",afterDelete:"delete",beforeUpdate:"update",afterUpdate:"update"}[$]},$91=async({className:$,operation:A,context:F})=>{let D=F.wabe.config.schema?.classes?.find((E)=>E.name===$);if(!D)throw new Error(`Class ${$} not found in schema`);return D.permissions?.[A]},xB=async($,A)=>{if($.context.isRoot)return;let F=e31(A);if(!F)throw new Error("Bad operation type provided");let D=await $91({className:$.className,operation:F,context:$.context});if(!D)throw new Error(`Permission denied to ${F} class ${$.className}`);let B=$.context.sessionId;if(!D.requireAuthentication)return;if(!B||!$.getUser())throw new Error(`Permission denied to ${F} class ${$.className}`);if(D.authorizedRoles?.includes("everyone"))return;if(D.authorizedRoles?.length===0||!D)throw new Error(`Permission denied to ${F} class ${$.className}`);let E=$.context.user?.role?.name;if(!E)throw new Error(`Permission denied to ${F} class ${$.className}`);if(!D.authorizedRoles?.includes(E))throw new Error(`Permission denied to ${F} class ${$.className}`)},hu=($)=>xB($,"beforeRead"),Nu=($)=>xB($,"beforeCreate"),du=($)=>xB($,"beforeUpdate"),ku=($)=>xB($,"beforeDelete");var WW=($,A)=>{let F=$.context.wabe.config.schema?.classes?.find((Z)=>Z.name===$.className);if(!F)return;let D=$.getUser()?.role?.name||"",B=$.context.isRoot;if(A==="beforeRead"){Object.keys($.select).map((Z)=>{let J=F.fields[Z]?.protected;if(J?.protectedOperations.includes("read")){if(B&&J.authorizedRoles.includes("rootOnly"))return;if(!J.authorizedRoles.includes(D))throw new Error("You are not authorized to read this field")}});return}let E=$.getNewData(),w=A==="beforeUpdate"?"update":"create";Object.keys(E).map((Z)=>{let J=F.fields[Z]?.protected;if(J?.protectedOperations.includes(w)){if(B&&J.authorizedRoles.includes("rootOnly"))return;if(!J.authorizedRoles.includes(D))throw new Error(`You are not authorized to ${w} this field`)}})},mu=($)=>WW($,"beforeRead"),vu=($)=>WW($,"beforeUpdate"),fu=($)=>WW($,"beforeCreate");var lB=JSON;var bu=($)=>$.toUpperCase(),_u=($)=>{let A={};return $.forEach((F,D)=>{A[D]=F}),A};var pu=($,A,F)=>{return $.document?$:{document:$,variables:A,requestHeaders:F,signal:void 0}},gu=($,A,F)=>{return $.query?$:{query:$,variables:A,requestHeaders:F,signal:void 0}},xu=($,A)=>{return $.documents?$:{documents:$,requestHeaders:A,signal:void 0}};var gE=H1(K1(),1),mT=($)=>{let A=void 0,F=$.definitions.filter((D)=>D.kind==="OperationDefinition");if(F.length===1)A=F[0]?.name?.value;return A},Y5=($)=>{if(typeof $==="string"){let F=void 0;try{let D=gE.parse($);F=mT(D)}catch(D){}return{query:$,operationName:F}}let A=mT($);return{query:gE.print($),operationName:A}};class X9 extends Error{constructor($,A){let F=`${X9.extractMessage($)}: ${JSON.stringify({response:$,request:A})}`;super(F);if(Object.setPrototypeOf(this,X9.prototype),this.response=$,this.request=A,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,X9)}static extractMessage($){return $.errors?.[0]?.message??`GraphQL Error (Code: ${$.status})`}}var C9=H1(jS(),1);var dX1="connection_init",kX1="connection_ack",LS="ping",TS="pong",mX1="subscribe",vX1="next",fX1="error",SS="complete";class A8{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor($,A,F){this._type=$,this._payload=A,this._id=F}get text(){let $={type:this.type};if(this.id!=null&&this.id!=null)$.id=this.id;if(this.payload!=null&&this.payload!=null)$.payload=this.payload;return JSON.stringify($)}static parse($,A){let{type:F,payload:D,id:B}=JSON.parse($);return new A8(F,A(D),B)}}class sU{constructor($,{onInit:A,onAcknowledged:F,onPing:D,onPong:B}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=$,$.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},$.send(_X1(A?await A():null).text)}),$.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),$.addEventListener("error",(E)=>{console.error(E)}),$.addEventListener("message",(E)=>{try{let w=bX1(E.data);switch(w.type){case kX1:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,F)F(w.payload);return}case LS:{if(D)D(w.payload).then((W)=>$.send(RS(W).text));else $.send(RS(null).text);return}case TS:{if(B)B(w.payload);return}}if(!this.socketState.acknowledged)return;if(w.id===void 0||w.id===null||!this.socketState.subscriptions[w.id])return;let{query:Z,variables:J,subscriber:Y}=this.socketState.subscriptions[w.id];switch(w.type){case vX1:{if(!w.payload.errors&&w.payload.data)Y.next&&Y.next(w.payload.data);if(w.payload.errors)Y.error&&Y.error(new X9({...w.payload,status:200},{query:Z,variables:J}));return}case fX1:{Y.error&&Y.error(new X9({errors:w.payload,status:200},{query:Z,variables:J}));return}case SS:{Y.complete&&Y.complete(),delete this.socketState.subscriptions[w.id];return}}}catch(w){console.error(w),$.close(1006)}$.close(4400,"Unknown graphql-ws message.")})}makeSubscribe($,A,F,D){let B=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[B]={query:$,variables:D,subscriber:F},this.socket.send(gX1(B,{query:$,operationName:A,variables:D}).text),()=>{this.socket.send(xX1(B).text),delete this.socketState.subscriptions[B]}}rawRequest($,A){return new Promise((F,D)=>{let B;this.rawSubscribe($,{next:(E,w)=>B={data:E,extensions:w},error:D,complete:()=>F(B)},A)})}request($,A){return new Promise((F,D)=>{let B;this.subscribe($,{next:(E)=>B=E,error:D,complete:()=>F(B)},A)})}subscribe($,A,F){let{query:D,operationName:B}=Y5($);return this.makeSubscribe(D,B,A,F)}rawSubscribe($,A,F){return this.makeSubscribe($,void 0,A,F)}ping($){this.socket.send(pX1($).text)}close(){this.socket.close(1000)}}sU.PROTOCOL="graphql-transport-ws";function bX1($,A=(F)=>F){return A8.parse($,A)}function _X1($){return new A8(dX1,$)}function pX1($){return new A8(LS,$,void 0)}function RS($){return new A8(TS,$,void 0)}function gX1($,A){return new A8(mX1,A,$)}function xX1($){return new A8(SS,void 0,$)}var L7=($)=>{let A={};if($)if(typeof Headers!=="undefined"&&$ instanceof Headers||C9&&C9.Headers&&$ instanceof C9.Headers)A=_u($);else if(Array.isArray($))$.forEach(([F,D])=>{if(F&&D!==void 0)A[F]=D});else A=$;return A},OS=($)=>$.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),yX1=($)=>{if(!Array.isArray($.query)){let D=$,B=[`query=${encodeURIComponent(OS(D.query))}`];if($.variables)B.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)B.push(`operationName=${encodeURIComponent(D.operationName)}`);return B.join("&")}if(typeof $.variables!=="undefined"&&!Array.isArray($.variables))throw new Error("Cannot create query with given variable type, array expected");let A=$,F=$.query.reduce((D,B,E)=>{return D.push({query:OS(B),variables:A.variables?A.jsonSerializer.stringify(A.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(A.jsonSerializer.stringify(F))}`},lX1=($)=>async(A)=>{let{url:F,query:D,variables:B,operationName:E,fetch:w,fetchOptions:Z,middleware:J}=A,Y={...A.headers},W="",X=void 0;if($==="POST"){if(X=cX1(D,B,E,Z.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else W=yX1({query:D,variables:B,operationName:E,jsonSerializer:Z.jsonSerializer??lB});let U={method:$,headers:Y,body:X,...Z},H=F,Q=U;if(J){let q=await Promise.resolve(J({...U,url:F,operationName:E,variables:B})),{url:V,...L}=q;H=V,Q=L}if(W)H=`${H}?${W}`;return await w(H,Q)};class tU{constructor($,A={}){this.url=$,this.requestConfig=A,this.rawRequest=async(...F)=>{let[D,B,E]=F,w=gu(D,B,E),{headers:Z,fetch:J=C9.default,method:Y="POST",requestMiddleware:W,responseMiddleware:X,...U}=this.requestConfig,{url:H}=this;if(w.signal!==void 0)U.signal=w.signal;let{operationName:Q}=Y5(w.query);return nU({url:H,query:w.query,variables:w.variables,headers:{...L7(rU(Z)),...L7(w.requestHeaders)},operationName:Q,fetch:J,method:Y,fetchOptions:U,middleware:W}).then((q)=>{if(X)X(q);return q}).catch((q)=>{if(X)X(q);throw q})}}async request($,...A){let[F,D]=A,B=pu($,F,D),{headers:E,fetch:w=C9.default,method:Z="POST",requestMiddleware:J,responseMiddleware:Y,...W}=this.requestConfig,{url:X}=this;if(B.signal!==void 0)W.signal=B.signal;let{query:U,operationName:H}=Y5(B.document);return nU({url:X,query:U,variables:B.variables,headers:{...L7(rU(E)),...L7(B.requestHeaders)},operationName:H,fetch:w,method:Z,fetchOptions:W,middleware:J}).then((Q)=>{if(Y)Y(Q);return Q.data}).catch((Q)=>{if(Y)Y(Q);throw Q})}batchRequests($,A){let F=xu($,A),{headers:D,...B}=this.requestConfig;if(F.signal!==void 0)B.signal=F.signal;let E=F.documents.map(({document:Z})=>Y5(Z).query),w=F.documents.map(({variables:Z})=>Z);return nU({url:this.url,query:E,variables:w,headers:{...L7(rU(D)),...L7(F.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??C9.default,method:this.requestConfig.method||"POST",fetchOptions:B,middleware:this.requestConfig.requestMiddleware}).then((Z)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(Z);return Z.data}).catch((Z)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(Z);throw Z})}setHeaders($){return this.requestConfig.headers=$,this}setHeader($,A){let{headers:F}=this.requestConfig;if(F)F[$]=A;else this.requestConfig.headers={[$]:A};return this}setEndpoint($){return this.url=$,this}}var nU=async($)=>{let{query:A,variables:F,fetchOptions:D}=$,B=lX1(bu($.method??"post")),E=Array.isArray($.query),w=await B($),Z=await aX1(w,D.jsonSerializer??lB),J=Array.isArray(Z)?!Z.some(({data:W})=>!W):Boolean(Z.data),Y=Array.isArray(Z)||!Z.errors||Array.isArray(Z.errors)&&!Z.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(w.ok&&Y&&J){let{errors:W,...X}=Array.isArray(Z)?Z:Z,U=D.errorPolicy==="ignore"?X:Z;return{...E?{data:U}:U,headers:w.headers,status:w.status}}else throw new X9({...typeof Z==="string"?{error:Z}:Z,status:w.status,headers:w.headers},{query:A,variables:F})};var cX1=($,A,F,D)=>{let B=D??lB;if(!Array.isArray($))return B.stringify({query:$,variables:A,operationName:F});if(typeof A!=="undefined"&&!Array.isArray(A))throw new Error("Cannot create request body with given variable type, array expected");let E=$.reduce((w,Z,J)=>{return w.push({query:Z,variables:A?A[J]:void 0}),w},[]);return B.stringify(E)},aX1=async($,A)=>{let F;if($.headers.forEach((D,B)=>{if(B.toLowerCase()==="content-type")F=D}),F&&(F.toLowerCase().startsWith("application/json")||F.toLowerCase().startsWith("application/graphql+json")||F.toLowerCase().startsWith("application/graphql-response+json")))return A.parse(await $.text());else return $.text()},rU=($)=>{return typeof $==="function"?$():$},oU=($,...A)=>{return $.reduce((F,D,B)=>`${F}${D}${B in A?String(A[B]):""}`,"")};var s3=H1(dZ(),1);var fl=H1(ml(),1);var vk1=Object.prototype.toString,fk1=($)=>vk1.call($)==="[object Error]",bk1=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function wq($){if(!($&&fk1($)&&$.name==="TypeError"&&typeof $.message==="string"))return!1;if($.message==="Load failed")return $.stack===void 0;return bk1.has($.message)}class bl extends Error{constructor($){super();if($ instanceof Error)this.originalError=$,{message:$}=$;else this.originalError=new Error($),this.originalError.stack=this.stack;this.name="AbortError",this.message=$}}var vl=($,A,F)=>{let D=F.retries-(A-1);return $.attemptNumber=A,$.retriesLeft=D,$};async function Zq($,A){return new Promise((F,D)=>{A={...A},A.onFailedAttempt??=()=>{},A.shouldRetry??=()=>!0,A.retries??=10;let B=fl.default.operation(A),E=()=>{B.stop(),D(A.signal?.reason)};if(A.signal&&!A.signal.aborted)A.signal.addEventListener("abort",E,{once:!0});let w=()=>{A.signal?.removeEventListener("abort",E),B.stop()};B.attempt(async(Z)=>{try{let J=await $(Z);w(),F(J)}catch(J){try{if(!(J instanceof Error))throw new TypeError(`Non-error was thrown: "${J}". You should only throw errors.`);if(J instanceof bl)throw J.originalError;if(J instanceof TypeError&&!wq(J))throw J;if(vl(J,Z,A),!await A.shouldRetry(J))B.stop(),D(J);if(await A.onFailedAttempt(J),!B.retry(J))throw B.mainError()}catch(Y){vl(Y,Z,A),w(),D(Y)}}})})}var _k1=($)=>{if(!$)return{};return Object.keys($).reduce((F,D)=>{let B=$[D];if(B==="ASC")F[D]=1;if(B==="DESC")F[D]=-1;return F},{})},i3=($)=>{if(!$)return{};return Object.keys($).reduce((F,D)=>{let B=$[D],E=D==="id"?"_id":D;if(B?.contains||B?.contains===null)F[E]={$all:B.contains};if(B?.notContains||B?.notContains===null)F[E]={$ne:B.notContains};if(B?.equalTo||B?.equalTo===null)F[E]=E==="_id"&&typeof B.equalTo==="string"?s3.ObjectId.createFromHexString(B.equalTo):B.equalTo;if(B?.notEqualTo||B?.notEqualTo===null)F[E]={$ne:E==="_id"&&typeof B.notEqualTo==="string"?s3.ObjectId.createFromHexString(B.notEqualTo):B.notEqualTo};if(B?.greaterThan||B?.greaterThan===null)F[E]={$gt:B.greaterThan};if(B?.greaterThanOrEqualTo||B?.greaterThanOrEqualTo===null)F[E]={$gte:B.greaterThanOrEqualTo};if(B?.lessThan||B?.lessThan===null)F[E]={$lt:B.lessThan};if(B?.lessThanOrEqualTo||B?.lessThanOrEqualTo===null)F[E]={$lte:B.lessThanOrEqualTo};if(B?.in||B?.in===null)F[E]={$in:E==="_id"?B.in.filter((w)=>typeof w==="string").map((w)=>s3.ObjectId.createFromHexString(w)):B.in};if(B?.notIn||B?.notIn===null)F[E]={$nin:E==="_id"?B.notIn.filter((w)=>typeof w==="string").map((w)=>s3.ObjectId.createFromHexString(w)):B.notIn};if(B&&E==="OR")return F.$or=$.OR?.map((w)=>i3(w)),F;if(B&&E==="AND")return F.$and=$.AND?.map((w)=>i3(w)),F;if(typeof B==="object"){let w=i3(B),Z=Object.entries(w);if(Z.length>0)return{[`${E.toString()}.${Z[0][0]}`]:Z[0][1]}}return F},{})};class Jq{options;database;client;constructor($){this.options=$,this.client=new s3.MongoClient($.databaseUrl)}async connect(){let $=await Zq(()=>this.client.connect(),{retries:5,minTimeout:100,factor:2});return this.database=$.db(this.options.databaseName),$}close(){return this.client.close()}async createClassIfNotExist($,A){if(!this.database)throw new Error("Connection to database is not established");let F=A.wabe.config.schema?.classes?.find((E)=>E.name===$);if(!F)throw new Error(`${$} is not defined in schema`);let D=this.database.collection($);return(F.indexes||[]).map((E)=>D.createIndex({[E.field]:E.order==="ASC"?1:-1},{unique:!!E.unique})),D}async count($){let{className:A,where:F,context:D}=$,B=await this.createClassIfNotExist(A,D),E=i3(F);return B.countDocuments(E)}async clearDatabase(){if(!this.database)throw new Error("Connection to database is not established");let $=await this.database.collections();await Promise.all($.filter((A)=>A.collectionName!=="Role").map((A)=>A.deleteMany({})))}async getObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,select:D,where:B,context:E}=$,w=i3(B),J=await(await this.createClassIfNotExist(A,E)).findOne({_id:new s3.ObjectId(F),...w},{projection:D?{...D,_id:1}:void 0});if(!J)throw new Error("Object not found");let{_id:Y,...W}=J;return{...W,...{id:Y.toString()}}}async getObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,select:F,where:D,offset:B,first:E,context:w,order:Z}=$,J=i3(D),Y=_k1(Z);return(await(await this.createClassIfNotExist(A,w)).find(J,{projection:F?{...F,_id:1}:void 0}).limit(E||0).skip(B||0).sort(Y).toArray()).map((U)=>{let{_id:H,...Q}=U;return{...Q,...{id:H.toString()}}})}async createObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,data:F,context:D}=$;return{id:(await(await this.createClassIfNotExist(A,D)).insertOne(F,{})).insertedId.toString()}}async createObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,data:F,context:D}=$,E=await(await this.createClassIfNotExist(A,D)).insertMany(F,{});return Object.values(E.insertedIds).map((w)=>({id:w.toString()}))}async updateObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,data:D,context:B,where:E}=$,w=E?i3(E):{};if((await(await this.createClassIfNotExist(A,B)).updateOne({_id:new s3.ObjectId(F),...w},{$set:D})).matchedCount===0)throw new Error("Object not found");return{id:F}}async updateObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,where:F,data:D,offset:B,first:E,context:w,order:Z}=$,J=i3(F),Y=await this.createClassIfNotExist(A,w),W=await w.wabe.controllers.database.getObjects({className:A,where:F,select:{id:!0},offset:B,first:E,context:R1(w),order:Z});if(W.length===0)return[];return await Y.updateMany(J,{$set:D}),Object.values(W).filter(x2).map((X)=>({id:X?.id||""}))}async deleteObject($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,id:F,context:D}=$,B=i3($.where);if((await(await this.createClassIfNotExist(A,D)).deleteOne({_id:new s3.ObjectId(F),...B})).deletedCount===0)throw new Error("Object not found")}async deleteObjects($){if(!this.database)throw new Error("Connection to database is not established");let{className:A,where:F,context:D}=$,B=i3(F);await(await this.createClassIfNotExist(A,D)).deleteMany(B)}}var _l;((A)=>A.Mongo="mongo")(_l||={});class pl{adapter={};async getCustomerById(){return{email:"customer@test.com"}}async deleteCoupon(){}async updatePromotionCode(){}async createCoupon(){return{code:"",id:""}}async createPromotionCode(){return{code:"",id:""}}async validateWebhook(){return{isValid:!0,payload:{},type:""}}async createCustomer(){return""}async createPayment(){return""}async cancelSubscription(){}async getInvoices(){return[]}async getTotalRevenue(){return 0}async getAllTransactions(){return[]}async getHypotheticalSubscriptionRevenue(){return 0}}class gl{async send(){return"123456"}}var xl;((F)=>{F.EUR="eur";F.USD="usd"})(xl||={});var pk1;((F)=>{F.payment="payment";F.subscription="subscription"})(pk1||={});var gk1;((F)=>{F.Month="month";F.Year="year"})(gk1||={});import{writeFile as xk1,mkdir as yk1,rm as lk1,access as yl,constants as ll}from"node:fs/promises";import cZ from"node:path";class cl{basePath="bucket";rootPath=process.cwd();async uploadFile($){let A=cZ.join(this.rootPath,this.basePath);await yk1(A,{recursive:!0});let F=$.type,D;if(F.startsWith("text")||F.includes("json")){let B=await $.text();D=Buffer.from(B,"utf-8")}else{let B=await $.arrayBuffer();D=Buffer.from(B)}await xk1(cZ.join(A,$.name),D)}async readFile($,A){let F=cZ.join(this.rootPath,this.basePath,$);try{return await yl(F,ll.F_OK),`http://127.0.0.1:${A?.port||3000}/${this.basePath}/${$}`}catch{return null}}async deleteFile($){let A=cZ.join(this.rootPath,this.basePath,$);try{await yl(A,ll.F_OK),await lk1(A)}catch{}}}var S$=($)=>$.charAt(0).toUpperCase()+$.slice(1),x2=($)=>$!==null&&$!==void 0,al=($)=>{let A=new tU(`http://127.0.0.1:${$}/graphql`,{headers:{"Wabe-Root-Key":"0uwFvUxM$ceFuF1aEtTtZMa7DUN2NZudqgY5ve5W*QCyb58cwMj9JeoaV@d#%29v&aJzswuudVU1%nAT+rxS0Bh&OkgBYc0PH18*"}});return{...A,request:A.request}};var aZ=($)=>{if($===void 0||$===null)return[];if(typeof $==="object")return Object.values($).flatMap((A)=>aZ(A));if(typeof $==="string")return gB($).trim().split(" ").map((A)=>A.trim()).flatMap((A)=>{let F=[];for(let D=1;D<=A.length;D+=1)F.push(A.substring(0,D).toLowerCase());return F});if(typeof $==="number")return[String($)];return[]},sl=($)=>{let A=$.context.wabe.config.schema?.classes?.find((B)=>B.name===$.className)?.searchableFields;if(!A||A.length===0)return;let F=$.getNewData(),D=Object.entries(F).flatMap(([B,E])=>{if(!A.includes(B))return;return aZ(E)}).filter(x2);$.upsertNewData("search",D)},nl=($)=>{let A=$.context.wabe.config.schema?.classes?.find((Z)=>Z.name===$.className)?.searchableFields;if(!A||A.length===0)return;let F=$.getNewData(),D=Object.entries(F).flatMap(([Z,J])=>{if(!A.includes(Z))return;return aZ(J)}).filter(x2),B=Object.entries($.object||{}).flatMap(([Z,J])=>{if(!A.includes(Z)||!Object.keys(F).includes(Z))return;return aZ(J)}).filter(x2),w=[...($.object?.search||[]).filter((Z)=>!B.includes(Z)),...D];$.upsertNewData("search",w)};var rl=async($)=>{let A=$.object,F=A?.user;if(!F)return;let D=$.context.wabe.controllers.database,E=(await D.getObject({className:"User",id:F,select:{sessions:!0},context:$.context}))?.sessions?.map((w)=>w.id)||[];await D.updateObject({className:"User",id:F,context:$.context,data:{sessions:[...E,A?.id].filter(x2)}})},tl=async($)=>{let A=$.object,F=A?.user;if(!F)return;let D=$.context.wabe.controllers.database,E=(await D.getObject({className:"User",id:F,select:{sessions:!0},context:$.context}))?.sessions?.filter((w)=>w.id!==A?.id).map((w)=>w.id);await D.updateObject({className:"User",id:F,context:$.context,data:{sessions:E}})},ol=($)=>{if($.context.isRoot)return;if($.isFieldUpdated("sessions"))throw new Error("Not authorized to update user sessions")};var el=($)=>{let A=$.getNewData().authentication;if(!A)return;let F=Object.keys(A)[0],D=A[F].email;if(!D)return;if($.upsertNewData("email",D),F)$.upsertNewData("provider",F)},$c=($)=>{if($.isFieldUpdated("email"))return;el($)},Ac=($)=>{if($.isFieldUpdated("email"))return;el($)};var Fc=async($)=>{let A=$.context.wabe.config.schema?.classes?.find((D)=>D.name===$.className)?.permissions;if(!A)return;let{acl:F}=A;if($.isFieldUpdated("acl")||!F)return;if(F)await F($)},Dc=async($)=>{if($.className==="User")return;await Fc($)},Bc=async($)=>Fc($);var yB;((J)=>{J.AfterCreate="afterCreate";J.AfterUpdate="afterUpdate";J.AfterDelete="afterDelete";J.AfterRead="afterRead";J.BeforeCreate="beforeCreate";J.BeforeUpdate="beforeUpdate";J.BeforeDelete="beforeDelete";J.BeforeRead="beforeRead"})(yB||={});var Ec=async({className:$,operationType:A,priority:F,config:D})=>D.hooks?.filter((B)=>B.operationType===A&&B.priority===F&&($===B.className||!B.className))||[],ck1=($)=>$.hooks?.reduce((A,F)=>{if(!A.includes(F.priority))A.push(F.priority);return A},[]).sort((A,F)=>A-F)||[],n3=({className:$,newData:A,context:F,select:D})=>{let B=({id:Z})=>{if(!Z)return{};return F.wabe.controllers.database.getObject({className:$,context:R1(F),id:Z,skipHooks:!0})},E=async({where:Z,ids:J})=>{if(!Z&&J.length===0)return[{}];let Y=await F.wabe.controllers.database.getObjects({className:$,context:R1(F),where:Z?Z:{id:{in:J}},skipHooks:!0});if(Y.length===0)return[{}];return Y},w=ck1(F.wabe.config);return{runOnSingleObject:async(Z)=>{if(w.length===0)return{object:void 0,newData:{}};let J=await B({id:Z.id}),Y=new pB({className:$,newData:A,operationType:Z.operationType,context:F,object:J,originalObject:Z.originalObject,select:D});return await w.reduce(async(W,X)=>{await W;let U=await Ec({className:$,operationType:Z.operationType,priority:X,config:F.wabe.config});await Promise.all(U.map((H)=>H.callback(Y)))},Promise.resolve()),{object:J,newData:Y.getNewData()}},runOnMultipleObjects:async(Z)=>{if(w.length===0)return{objects:[],newData:[A||{}]};let J=await E({where:Z.where,ids:Z.ids||[]}),Y=(Z.operationType==="afterDelete"?Z.originalObjects:J)||[],W=await Promise.all(Y.map(async(X)=>{let U=(Z.originalObjects||[]).find((Q)=>Q?.id===X?.id),H=new pB({className:$,newData:A,operationType:Z.operationType,context:F,object:X,originalObject:U,select:D});return await w.reduce(async(Q,q)=>{await Q;let V=await Ec({className:$,operationType:Z.operationType,priority:q,config:F.wabe.config});await Promise.all(V.map((L)=>L.callback(H)))},Promise.resolve()),H.getNewData()}));return{objects:J,newData:W}}}},wc=()=>[{operationType:"beforeRead",priority:0,callback:hu},{operationType:"beforeUpdate",priority:0,callback:du},{operationType:"beforeCreate",priority:0,callback:Nu},{operationType:"beforeDelete",priority:0,callback:ku},{operationType:"beforeRead",priority:0,callback:mu},{operationType:"beforeUpdate",priority:0,callback:vu},{operationType:"beforeCreate",priority:0,callback:fu},{operationType:"beforeCreate",priority:1,callback:Lu},{operationType:"beforeCreate",priority:1,callback:Su},{operationType:"beforeUpdate",priority:1,callback:Tu},{operationType:"beforeCreate",priority:1,callback:Pu},{operationType:"beforeUpdate",priority:1,callback:Mu},{operationType:"afterRead",priority:1,callback:Vu},{operationType:"afterDelete",priority:1,callback:zu},{className:"User",operationType:"beforeCreate",priority:1,callback:Iu},{className:"User",operationType:"beforeUpdate",priority:1,callback:ju},{operationType:"beforeCreate",priority:3,callback:sl},{operationType:"beforeUpdate",priority:3,callback:nl},{operationType:"beforeCreate",priority:0,callback:Dc},{className:"User",operationType:"afterCreate",priority:0,callback:Bc},{className:"User",operationType:"beforeCreate",priority:2,callback:$c},{className:"User",operationType:"beforeUpdate",priority:2,callback:Ac},{className:"User",operationType:"beforeDelete",priority:1,callback:Ou},{className:"_Session",operationType:"afterCreate",priority:1,callback:rl},{className:"_Session",operationType:"afterDelete",priority:1,callback:tl},{className:"User",operationType:"beforeUpdate",priority:1,callback:ol}];class Yq{adapter;constructor($){this.adapter=$}_getSelectMinusPointersAndRelations({className:$,context:A,select:F}){let D=A.wabe.config.schema?.classes?.find((E)=>E.name.toLowerCase()===$.toLowerCase());if(!D)throw new Error("Class not found in schema");if(!F)return{pointers:{},selectWithoutPointers:{}};let B=Object.keys(D.fields).filter((E)=>D.fields[E].type==="Pointer"||D.fields[E].type==="Relation");return Object.entries(F).reduce((E,[w,Z])=>{if(!B.includes(w))return{...E,selectWithoutPointers:{...E.selectWithoutPointers,[w]:!0}};let J=D.fields[w].class;return{...E,pointers:{...E.pointers,[w]:{className:J,select:Z===!0?void 0:Z}}}},{pointers:{},selectWithoutPointers:{}})}_isRelationField({pointerField:$,currentClassName:A,context:F,originClassName:D}){if(!A)return!1;return F.wabe.config.schema?.classes?.some((B)=>B.name.toLowerCase()===D.toLowerCase()&&Object.entries(B.fields).find(([E,w])=>E===$&&w.type==="Relation"&&w.class.toLowerCase()===A.toLowerCase()))}_isPointerField({pointerField:$,currentClassName:A,context:F,originClassName:D}){if(!A)return!1;return F.wabe.config.schema?.classes?.some((B)=>B.name.toLowerCase()===D.toLowerCase()&&Object.entries(B.fields).find(([E,w])=>E===$&&w.type==="Pointer"&&w.class.toLowerCase()===A.toLowerCase()))}async _getWhereObjectWithPointerOrRelation($,A,F){let D=Object.keys(A),B=F.wabe.config.schema?.classes?.find((w)=>w.name.toLowerCase()===$.toLowerCase()),E=await D.reduce(async(w,Z)=>{let J=await w,Y=Z,W=B?.fields[Y];if(Y==="AND"||Y==="OR"){let Q=await Promise.all(A[Y].map((q)=>this._getWhereObjectWithPointerOrRelation($,q,F)));return{...J,[Y]:Q}}if(W?.type!=="Pointer"&&W?.type!=="Relation")return w;let X=W.class,U=A[Y],H=await this.getObjects({className:X,select:{id:!0},where:U,context:F});return{...w,[Y]:{in:H.map((Q)=>Q?.id).filter(x2)}}},Promise.resolve({}));return{...A,...E}}_buildWhereWithACL($,A,F){if(A.isRoot)return $;let D=A.user?.role?.id,B=A.user?.id;return{AND:[{...$},!B?{acl:{equalTo:null}}:void 0,B||D?{OR:[{acl:{equalTo:null}},B?{AND:[{acl:{users:{userId:{in:[B]}}}},{acl:{users:{[F]:{in:[!0]}}}}]}:void 0,D?{AND:[{acl:{users:{userId:{notIn:[B]}}}},{acl:{roles:{roleId:{in:[D]}}}},{acl:{roles:{[F]:{in:[!0]}}}}]}:void 0].filter(x2)}:void 0].filter(x2)}}_getFinalObjectWithPointerAndRelation({pointers:$,context:A,originClassName:F,object:D,isGraphQLCall:B}){return Object.entries($).reduce(async(E,[w,{className:Z,select:J}])=>{let Y=await E;if(this._isPointerField({originClassName:F,context:A,currentClassName:Z,pointerField:w})){if(!D[w])return{...Y,[w]:null};let U=await this.getObject({className:Z,id:D[w],context:A,select:J});return{...Y,[w]:U}}if(this._isRelationField({originClassName:F,context:A,currentClassName:Z,pointerField:w})&&D[w]){let U=await this.getObjects({className:Z,select:J,where:{id:{in:D[w]}},context:A});return{...E,[w]:B?{totalCount:U.length,edges:U.map((H)=>({node:H}))}:U}}return Y},Promise.resolve({}))}connect(){return this.adapter.connect()}close(){return this.adapter.close()}createClassIfNotExist($,A){return this.adapter.createClassIfNotExist($,A)}async count({className:$,context:A,where:F}){let D=n3({className:$,context:A,select:{}});await D?.runOnSingleObject({operationType:"beforeRead"});let B=await this.adapter.count({className:$,context:A,where:F});return await D?.runOnSingleObject({operationType:"afterRead"}),B}async clearDatabase(){await this.adapter.clearDatabase()}async getObject({select:$,className:A,context:F,skipHooks:D,id:B,where:E,isGraphQLCall:w=!1}){let{pointers:Z,selectWithoutPointers:J}=this._getSelectMinusPointersAndRelations({className:A,context:F,select:$}),Y=!D?n3({className:A,context:F,select:J}):void 0;await Y?.runOnSingleObject({operationType:"beforeRead",id:B});let W=this._buildWhereWithACL(E||{},F,"read"),X=Object.keys(Z).reduce((H,Q)=>{return H[Q]=!0,H},J);await Y?.runOnSingleObject({operationType:"afterRead",id:B});let U=await this.adapter.getObject({className:A,id:B,context:R1(F),select:!$?void 0:X,where:W});return{...U,...await this._getFinalObjectWithPointerAndRelation({context:F,originClassName:A,pointers:Z,object:U,isGraphQLCall:w})}}async getObjects({className:$,select:A,context:F,where:D,skipHooks:B,first:E,offset:w,order:Z,isGraphQLCall:J=!1}){let{pointers:Y,selectWithoutPointers:W}=this._getSelectMinusPointersAndRelations({className:$,context:F,select:A}),X=await this._getWhereObjectWithPointerOrRelation($,D||{},F),U=this._buildWhereWithACL(X||{},F,"read"),H=Object.keys(Y).reduce((V,L)=>{return V[L]=!0,V},W),Q=!B?n3({className:$,select:W,context:F}):void 0;await Q?.runOnMultipleObjects({operationType:"beforeRead",where:U}),await Q?.runOnMultipleObjects({operationType:"afterRead",where:U});let q=await this.adapter.getObjects({className:$,context:R1(F),first:E,offset:w,where:U,select:!A?void 0:H,order:Z});return Promise.all(q.map(async(V)=>({...V,...await this._getFinalObjectWithPointerAndRelation({object:V,context:F,originClassName:$,pointers:Y,isGraphQLCall:J})})))}async createObject({className:$,context:A,data:F,select:D,isGraphQLCall:B=!1}){let E=n3({className:$,context:A,newData:F,select:D}),{newData:w}=await E.runOnSingleObject({operationType:"beforeCreate"}),{id:Z}=await this.adapter.createObject({className:$,context:A,select:D,data:w});if(await E.runOnSingleObject({operationType:"afterCreate",id:Z}),D&&Object.keys(D).length===0)return null;return this.getObject({className:$,context:R1(A),select:D,id:Z,skipHooks:!0,isGraphQLCall:B})}async createObjects({data:$,select:A,className:F,context:D,first:B,offset:E,order:w,isGraphQLCall:Z=!1}){if($.length===0)return[];let J=await Promise.all($.map((U)=>n3({className:F,context:D,newData:U,select:A}))),Y=await Promise.all(J.map(async(U)=>(await U.runOnMultipleObjects({operationType:"beforeCreate"}))?.newData[0])),X=(await this.adapter.createObjects({className:F,select:A,context:D,data:Y,first:B,offset:E,order:w})).map(({id:U})=>U);if(await Promise.all(J.map((U)=>U.runOnMultipleObjects({operationType:"afterCreate",ids:X}))),A&&Object.keys(A).length===0)return[];return this.getObjects({className:F,context:D,select:A,where:{id:{in:X}},skipHooks:!0,first:B,offset:E,order:w,isGraphQLCall:Z})}async updateObject({id:$,className:A,context:F,data:D,select:B,skipHooks:E,isGraphQLCall:w=!1}){let Z=!E?n3({className:A,context:F,newData:D,select:B}):void 0,J=await Z?.runOnSingleObject({operationType:"beforeUpdate",id:$}),Y=this._buildWhereWithACL({},F,"write");if(await this.adapter.updateObject({className:A,select:B,id:$,context:F,data:J?.newData||D,where:Y}),await Z?.runOnSingleObject({operationType:"afterUpdate",id:$,originalObject:J?.object}),B&&Object.keys(B).length===0)return null;return this.getObject({className:A,context:F,select:B,id:$,isGraphQLCall:w})}async updateObjects({className:$,where:A,context:F,select:D,data:B,first:E,offset:w,order:Z,skipHooks:J,isGraphQLCall:Y=!1}){let W=await this._getWhereObjectWithPointerOrRelation($,A||{},F),X=!J?n3({className:$,context:F,newData:B,select:D}):void 0,U=this._buildWhereWithACL(W,F,"write"),H=await X?.runOnMultipleObjects({operationType:"beforeUpdate",where:U}),q=(await this.adapter.updateObjects({className:$,context:F,select:D,data:H?.newData[0]||B,where:U,first:E,offset:w,order:Z})).map((V)=>V?.id).filter(x2);if(await X?.runOnMultipleObjects({operationType:"afterUpdate",ids:q,originalObjects:H?.objects||[]}),D&&Object.keys(D).length===0)return[];return this.getObjects({className:$,context:F,select:D,where:{id:{in:q}},first:E,offset:w,order:Z,isGraphQLCall:Y})}async deleteObject({context:$,className:A,id:F,select:D,isGraphQLCall:B=!1}){let E=n3({className:A,context:$,select:D}),w=this._buildWhereWithACL({},$,"write"),Z=null;if(D&&Object.keys(D).length>0)Z=await this.getObject({className:A,select:D,id:F,context:$,isGraphQLCall:B});let J=await E.runOnSingleObject({operationType:"beforeDelete",id:F});return await this.adapter.deleteObject({className:A,context:$,select:D,id:F,where:w}),await E.runOnSingleObject({operationType:"afterDelete",originalObject:J.object}),Z}async deleteObjects({className:$,context:A,select:F,where:D,first:B,offset:E,order:w,isGraphQLCall:Z=!1}){let J=await this._getWhereObjectWithPointerOrRelation($,D||{},A),Y=n3({className:$,context:A,select:F}),W=this._buildWhereWithACL(J,A,"write"),X=[];if(F&&Object.keys(F).length>0)X=await this.getObjects({className:$,where:D,select:F,context:A,first:B,offset:E,order:w,isGraphQLCall:Z});let U=await Y.runOnMultipleObjects({operationType:"beforeDelete",where:W});return await this.adapter.deleteObjects({className:$,context:A,select:F,first:B,offset:E,where:W,order:w}),await Y.runOnMultipleObjects({operationType:"afterDelete",originalObjects:U.objects}),X}}var Zc;((F)=>{F.google="google";F.github="github"})(Zc||={});var O$;((B)=>{B.GitHub="github";B.Google="google";B.EmailPassword="emailPassword";B.PhonePassword="phonePassword"})(O$||={});var Wq;((A)=>A.EmailOTP="emailOTP")(Wq||={});import Jc from"node:crypto";var Yc=($)=>{return Jc.createHash("sha256").update($).digest("base64").split("=")[0].replaceAll("+","-").replaceAll("/","_")},vD=()=>Jc.randomBytes(60).toString("base64url");class fD{clientId;authorizeEndpoint;tokenEndpoint;redirectURI;constructor($,A,F,D){this.clientId=$,this.authorizeEndpoint=A,this.tokenEndpoint=F,this.redirectURI=D}createAuthorizationURL($){let A=Array.from(new Set($?.scopes||[])),F=new URL(this.authorizeEndpoint);if(F.searchParams.set("response_type","code"),F.searchParams.set("client_id",this.clientId),$?.state!==void 0)F.searchParams.set("state",$.state);if(A.length>0)F.searchParams.set("scope",A.join(" "));if(this.redirectURI!==null)F.searchParams.set("redirect_uri",this.redirectURI);if($?.codeVerifier!==void 0){let D=Yc($.codeVerifier);F.searchParams.set("code_challenge_method","S256"),F.searchParams.set("code_challenge",D)}return F}validateAuthorizationCode($,A){let F=new URLSearchParams;if(F.set("code",$),F.set("client_id",this.clientId),F.set("grant_type","authorization_code"),this.redirectURI!==null)F.set("redirect_uri",this.redirectURI);if(A?.codeVerifier!==void 0)F.set("code_verifier",A.codeVerifier);return this._sendTokenRequest(F,A)}async refreshAccessToken($,A){let F=new URLSearchParams;F.set("refresh_token",$),F.set("client_id",this.clientId),F.set("grant_type","refresh_token");let D=Array.from(new Set(A?.scopes??[]));if(D.length>0)F.set("scope",D.join(" "));return await this._sendTokenRequest(F,A)}async _sendTokenRequest($,A){let F=new Headers;if(F.set("Content-Type","application/x-www-form-urlencoded"),F.set("Accept","application/json"),F.set("User-Agent","wabe"),A?.credentials!==void 0)if((A?.authenticateWith||"http_basic_auth")==="http_basic_auth"){let Z=btoa(`${this.clientId}:${A.credentials}`);F.set("Authorization",`Basic ${Z}`)}else $.set("client_secret",A.credentials);let D=new Request(this.tokenEndpoint,{method:"POST",headers:F,body:$}),B=await fetch(D),E=await B.json();if(!("access_token"in E)||B.status!==200||!B.ok)throw new Error("Error in token request");return E}}var ak1="https://accounts.google.com/o/oauth2/v2/auth",ik1="https://oauth2.googleapis.com/token";class bD{client;clientSecret;constructor($){let A=$.authentication?.providers?.google;if(!A)throw new Error("Google config not found");let D=`${`http${$.isProduction?"s":""}://${$.authentication?.backDomain||"127.0.0.1:"+$.port||3000}`}/auth/oauth/callback`;this.client=new fD(A.clientId,ak1,ik1,D),this.clientSecret=A.clientSecret}createAuthorizationURL($,A,F){let D=F?.scopes??[],B=this.client.createAuthorizationURL({state:$,codeVerifier:A,scopes:[...D,"openid"]});return B.searchParams.set("access_type","offline"),B.searchParams.set("prompt","select_account"),B}async validateAuthorizationCode($,A){let{access_token:F,expires_in:D,refresh_token:B,id_token:E}=await this.client.validateAuthorizationCode($,{authenticateWith:"request_body",credentials:this.clientSecret,codeVerifier:A});return{accessToken:F,refreshToken:B,accessTokenExpiresAt:new Date(Date.now()+D*1000),idToken:E}}async refreshAccessToken($){let{access_token:A,expires_in:F}=await this.client.refreshAccessToken($,{authenticateWith:"request_body",credentials:this.clientSecret});return{accessToken:A,accessTokenExpiresAt:new Date(Date.now()+F*1000)}}async getUserInfo($){let A=await fetch(`https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${$}`),{email:F,verified_email:D}=await A.json();return{email:F,verifiedEmail:D}}}var tD=H1(xs(),1);class D4{accessToken=void 0;refreshToken=void 0;getAccessTokenExpireAt($){let A=$?.authentication?.session?.accessTokenExpiresInMs;if(!A)return new Date(Date.now()+900000);return new Date(Date.now()+A)}_getRefreshTokenExpiresInMs($){let A=$?.authentication?.session?.refreshTokenExpiresInMs;if(!A)return 2592000000;return A}getRefreshTokenExpireAt($){let A=this._getRefreshTokenExpiresInMs($);return new Date(Date.now()+A)}async meFromAccessToken($,A){let F=await A.wabe.controllers.database.getObjects({className:"_Session",where:{accessToken:{equalTo:$},OR:[{accessTokenExpiresAt:{greaterThanOrEqualTo:new Date}},{refreshTokenExpiresAt:{greaterThanOrEqualTo:new Date}}]},select:{id:!0,user:!0,accessTokenExpiresAt:!0,refreshTokenExpiresAt:!0,refreshToken:!0},first:1,context:A});if(F.length===0)return{sessionId:null,user:null,accessToken:null,refreshToken:null};let D=F[0];if(!D||!D?.user)return{sessionId:null,user:null,accessToken:null,refreshToken:null};let B=D.user,E=await A.wabe.controllers.database.getObject({className:"User",select:{role:!0},context:A,id:B.id});if(new Date(D.accessTokenExpiresAt)<new Date&&new Date(D.refreshTokenExpiresAt)>=new Date&&D.refreshToken){let{accessToken:w,refreshToken:Z}=await this.refresh($,D.refreshToken,A);return{sessionId:D.id,user:{...B,role:E?.role},accessToken:w,refreshToken:Z}}return{sessionId:D.id,user:{...B,role:E?.role},accessToken:$,refreshToken:D.refreshToken}}async create($,A){this.accessToken=tD.default.sign({userId:$,iat:Date.now(),exp:this.getAccessTokenExpireAt(A.wabe.config).getTime()},A.wabe.config.authentication?.session?.jwtSecret||"dev"),this.refreshToken=tD.default.sign({userId:$,iat:Date.now(),exp:this.getRefreshTokenExpireAt(A.wabe.config).getTime()},A.wabe.config.authentication?.session?.jwtSecret||"dev");let F=await A.wabe.controllers.database.createObject({className:"_Session",context:R1(A),data:{accessToken:this.accessToken,accessTokenExpiresAt:this.getAccessTokenExpireAt(A.wabe.config),refreshToken:this.refreshToken,refreshTokenExpiresAt:this.getRefreshTokenExpireAt(A.wabe.config),user:$},select:{id:!0}});if(!F)throw new Error("Session not created");return{accessToken:this.accessToken,refreshToken:this.refreshToken,sessionId:F.id}}async delete($){if(!$.sessionId)return;await $.wabe.controllers.database.deleteObject({className:"_Session",context:R1($),id:$.sessionId,select:{}})}_isRefreshTokenExpired($,A){let F=$.getTime()-A;return Date.now()-F>=0.75*A}async refresh($,A,F){let D=await F.wabe.controllers.database.getObjects({className:"_Session",where:{accessToken:{equalTo:$}},select:{id:!0,user:{id:!0,role:{id:!0,name:!0}},refreshToken:!0,refreshTokenExpiresAt:!0},context:R1(F)});if(!D.length)return{accessToken:null,refreshToken:null};if(!D[0])throw new Error("Session not found");let{refreshTokenExpiresAt:B,user:E,refreshToken:w,id:Z}=D[0];if(new Date(B)<new Date(Date.now()))throw new Error("Refresh token expired");let J=this._getRefreshTokenExpiresInMs(F.wabe.config);if(!this._isRefreshTokenExpired(new Date(B),J))return{accessToken:$,refreshToken:A};if(A!==w)throw new Error("Invalid refresh token");let Y=E?.id;if(!Y)return{accessToken:null,refreshToken:null};let W=tD.default.sign({userId:Y,iat:Date.now(),exp:this.getAccessTokenExpireAt(F.wabe.config).getTime()},F.wabe.config.authentication?.session?.jwtSecret||"dev"),X=tD.default.sign({userId:Y,iat:Date.now(),exp:this.getRefreshTokenExpireAt(F.wabe.config).getTime()},F.wabe.config.authentication?.session?.jwtSecret||"dev");return await F.wabe.controllers.database.updateObject({className:"_Session",context:R1(F),id:Z,data:{accessToken:W,accessTokenExpiresAt:this.getAccessTokenExpireAt(F.wabe.config),refreshToken:X,refreshTokenExpiresAt:this.getRefreshTokenExpireAt(F.wabe.config)},select:{}}),{accessToken:W,refreshToken:X}}}var ys=async($,A,F)=>{let{input:{refreshToken:D,accessToken:B}}=A,E=new D4,{accessToken:w,refreshToken:Z}=await E.refresh(B,D,F);return{accessToken:w,refreshToken:Z}};var ls=async($,A,F)=>{if(await new D4().delete(F),F.wabe.config.authentication?.session?.cookieSession)F.response?.deleteCookie("accessToken"),F.response?.deleteCookie("refreshToken");return!0};var cs=async($,{input:A},F)=>{if(!A.secondFA)throw new Error("One factor is required");let D=Object.keys(A.secondFA);if(D.length>1)throw new Error("Only one factor is allowed");let{provider:B,name:E}=g9(D,F),w=await B.onVerifyChallenge({context:F,input:A.secondFA[E]});if(!w?.userId)throw new Error("Invalid challenge");let Z=new D4,{accessToken:J,refreshToken:Y}=await Z.create(w.userId,F);if(F.wabe.config.authentication?.session?.cookieSession){let W=Z.getAccessTokenExpireAt(F.wabe.config),X=Z.getRefreshTokenExpireAt(F.wabe.config);F.response?.setCookie("refreshToken",Y,{httpOnly:!0,path:"/",sameSite:"None",secure:!0,expires:X}),F.response?.setCookie("accessToken",J,{httpOnly:!0,path:"/",sameSite:"None",secure:!0,expires:W})}return{accessToken:J}};var as=($,A,F)=>{if(!F.user?.id)return{user:void 0};return{user:F.user}};var is=($,{input:A},F)=>{if(!F.user&&!F.isRoot)throw new Error("Permission denied");let D=F.wabe.controllers.email;if(!D)throw new Error("Email adapter not defined");return D.send({...A,text:A.text??void 0,html:A.html??void 0})};var dn=H1(hn(),1);import{createHash as Nn}from"node:crypto";var Kx1=5;class T8{secret;internalTotp;constructor($){this.secret=$,this.internalTotp=dn.totp.clone({window:[Kx1,0]})}generate($){let A=Nn("sha256").update(`${this.secret}:${$}`).digest("hex");return this.internalTotp.generate(A)}verify($,A){let F=Nn("sha256").update(`${this.secret}:${A}`).digest("hex");return this.internalTotp.verify({secret:F,token:$})}}var kn=async($,{input:{email:A,phone:F,password:D,otp:B}},E)=>{if(!A&&!F)throw new Error("Email or phone is required");let w=await E.wabe.controllers.database.getObjects({className:"User",where:{...A&&{email:{equalTo:A}},...F&&{authentication:{phonePassword:{phone:{equalTo:F}}}}},select:{id:!0,authentication:!0},first:1,context:R1(E)});if(w.length===0)return!0;let Z=w[0];if(!Z)return!0;let Y=new T8(E.wabe.config.rootKey).verify(B,Z.id);if(B!=="000000"&&!Y)throw new Error("Invalid OTP code");let W=F?"phonePassword":"emailPassword";return await E.wabe.controllers.database.updateObject({className:"User",id:Z.id,data:{authentication:{[W]:{...F&&{phone:Z.authentication?.phonePassword?.phone},...A&&{email:A},password:D}}},select:{},context:R1(E)}),!0};var mJ=($)=>`
206
206
  <!DOCTYPE html>
207
207
  <html lang="en">
208
208
 
@@ -543,4 +543,4 @@ It will affect your performance. Please check our Bun integration recipe, and av
543
543
  `))}if(X.done)W.enqueue(J.encode(`event: complete
544
544
  `)),W.enqueue(J.encode(`data:
545
545
 
546
- `)),clearInterval(Z),W.close()}catch(X){W.error(X)}},async cancel(W){clearInterval(Z),await w.return?.(W)}});return new F.Response(Y,E)}}var br1={mediaTypes:["multipart/mixed"],asyncIterables:!0,processResult:E41};function _r1(){return{mediaTypes:["text/event-stream"],asyncIterables:!0,processResult:Z41()}}var J41={mediaTypes:["application/graphql-response+json","application/json"],asyncIterables:!1,processResult:w41};function Y41(){let $=new WeakMap,A=_r1(),F=[A,br1,J41],D=[A,J41];return{onSubscribe({args:{contextValue:B}}){if(B.request)$.set(B.request,!0)},onResultProcess({request:B,result:E,acceptableMediaTypes:w,setResultProcessor:Z}){let Y=$.get(B)?D:F,W=A41(B),X=I6(E);for(let U of Y)for(let H of W){if(X&&!U.asyncIterables)continue;for(let Q of U.mediaTypes)if(w.push(Q),F41(Q,H))Z(U.processResult,Q)}}}}var W41="<!doctype html><html lang=en><head><meta charset=utf-8><title>Welcome to GraphQL Yoga</title><link rel=icon href=https://raw.githubusercontent.com/dotansimha/graphql-yoga/main/website/public/favicon.ico><style>body,html{padding:0;margin:0;height:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#fff;background-color:#000}main>section.hero{display:flex;height:90vh;justify-content:center;align-items:center;flex-direction:column}.logo{display:flex;align-items:center}.buttons{margin-top:24px}h1{font-size:80px}h2{color:#888;max-width:50%;margin-top:0;text-align:center}a{color:#fff;text-decoration:none;margin-left:10px;margin-right:10px;font-weight:700;transition:color .3s ease;padding:4px;overflow:visible}a.graphiql:hover{color:rgba(255,0,255,.7)}a.docs:hover{color:rgba(28,200,238,.7)}a.tutorial:hover{color:rgba(125,85,245,.7)}svg{margin-right:24px}.not-what-your-looking-for{margin-top:5vh}.not-what-your-looking-for>*{margin-left:auto;margin-right:auto}.not-what-your-looking-for>p{text-align:center}.not-what-your-looking-for>h2{color:#464646}.not-what-your-looking-for>p{max-width:600px;line-height:1.3em}.not-what-your-looking-for>pre{max-width:300px}</style></head><body id=body><main><section class=hero><div class=logo><div><svg xmlns=http://www.w3.org/2000/svg viewBox=\"-0.41 0.445 472.812 499.811\" height=150><defs><linearGradient id=paint0_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint1_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint2_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint3_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint4_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint5_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><filter id=filter0_f_1677_11483 x=23 y=-25 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><filter id=filter1_f_1677_11483 x=-24 y=19 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><linearGradient id=paint6_linear_1677_11483 x1=30 y1=28 x2=66.1645 y2=44.4363 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><filter id=filter2_f_1677_11483 x=-12 y=-44 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><filter id=filter3_f_1677_11483 x=13 y=19 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter></defs><mask id=mask0_1677_11483 style=mask-type:alpha maskUnits=userSpaceOnUse x=16 y=14 width=58 height=62><path d=\"M21 25.3501C21.7279 25.3501 22.4195 25.5056 23.0433 25.7853L42.1439 14.8C43.0439 14.3 44.1439 14 45.1439 14C46.2439 14 47.2439 14.3 48.1439 14.8L64.5439 24.3C63.3439 25.1 62.4439 26.3 61.8439 27.7L45.9438 18.5C45.6439 18.3 45.344 18.3 45.0441 18.3C44.7441 18.3 44.4439 18.4 44.1439 18.5L25.8225 29.0251C25.9382 29.4471 26 29.8914 26 30.3501C26 33.1115 23.7614 35.3501 21 35.3501C18.2386 35.3501 16 33.1115 16 30.3501C16 27.5887 18.2386 25.3501 21 25.3501Z\" fill=url(#paint3_linear_1677_11483) /><path d=\"M67.2438 35.0329C65.3487 34.3219 64 32.4934 64 30.35C64 27.5886 66.2386 25.35 69 25.35C71.7614 25.35 74 27.5886 74 30.35C74 32.1825 73.0142 33.7848 71.5439 34.6554V55.2C71.5439 57.4 70.3439 59.4 68.5439 60.5L52.1439 69.9C52.1439 68.4 51.6438 66.9 50.7438 65.8L66.3439 56.8C66.9439 56.5 67.2438 55.9 67.2438 55.2V35.0329Z\" fill=url(#paint4_linear_1677_11483) /><path d=\"M49.8439 69.1055C49.9458 69.5034 50 69.9204 50 70.3501C50 73.1115 47.7614 75.3501 45 75.3501C42.5102 75.3501 40.4454 73.5302 40.0633 71.1481L21.8439 60.6C19.9439 59.5 18.8439 57.5 18.8439 55.3V36.8C19.5439 37 20.3439 37.2 21.0439 37.2C21.7439 37.2 22.4439 37.1 23.0439 36.9V55.3C23.0439 56 23.4438 56.6 23.9438 56.9L41.3263 66.9583C42.2398 65.9694 43.5476 65.3501 45 65.3501C47.3291 65.3501 49.2862 66.9426 49.8419 69.0981L49.8436 69.0997L49.8439 69.1055Z\" fill=url(#paint5_linear_1677_11483) /></mask><mask id=mask1_1677_11483 style=mask-type:alpha maskUnits=userSpaceOnUse x=30 y=28 width=30 height=30><path fill-rule=evenodd clip-rule=evenodd d=\"M49.3945 32.3945C49.3945 34.7088 47.5796 38.5469 45 38.5469C42.4271 38.5469 40.6055 34.7112 40.6055 32.3945C40.6055 29.9714 42.5769 28 45 28C47.4231 28 49.3945 29.9714 49.3945 32.3945ZM35.332 49.0433V48.2148C35.332 42.8117 37.8535 41.0004 39.8796 39.545L39.8801 39.5447C40.3928 39.1767 40.8604 38.8404 41.2488 38.4742C42.3293 39.6642 43.626 40.3047 45 40.3047C46.3752 40.3047 47.6725 39.6642 48.7529 38.4754C49.1408 38.841 49.6078 39.1773 50.1199 39.5447L50.1204 39.545C52.1465 41.0004 54.668 42.8117 54.668 48.2148V49.0433L53.8406 49.092C49.9848 49.3185 46.8646 46.9002 45 43.5777C43.1159 46.935 39.9847 49.318 36.1594 49.092L35.332 49.0433ZM58.1463 51.0747L58.1463 51.0746C57.0179 50.891 50.0128 49.7507 45.0007 55.693C40.0116 49.7553 33.1965 50.8592 31.9095 51.0677L31.9095 51.0677C31.7906 51.087 31.7189 51.0986 31.7002 51.0963C31.7005 51.0969 31.7011 51.1045 31.7023 51.1187C31.726 51.4003 31.9682 54.2745 34.0566 56.2422L30 58H60L55.8956 56.2422C57.8537 54.4764 58.1396 52.2685 58.2508 51.4092V51.4091C58.2697 51.2628 58.2836 51.1556 58.2998 51.0963C58.2881 51.0977 58.2356 51.0892 58.1463 51.0747ZM40.4836 50.104C42.3956 49.3212 43.6746 48.1737 45 46.61C46.332 48.1841 47.6159 49.3259 49.5164 50.104C49.5356 50.1425 49.5557 50.1805 49.5756 50.2182C49.5793 50.2253 49.583 50.2323 49.5867 50.2393C48.0911 50.8127 46.4264 51.825 45.0047 53.1444C43.5906 51.8221 41.9673 50.8196 40.4256 50.2153C40.4455 50.1784 40.4648 50.1415 40.4836 50.104Z\" fill=black /></mask><path d=\"M 40.59 93.095 C 46.517 93.095 52.14 94.365 57.22 96.635 L 212.7 7.22 C 220.025 3.149 228.978 0.706 237.12 0.706 C 246.073 0.706 254.213 3.149 261.54 7.22 L 395.032 84.547 C 385.264 91.059 377.939 100.827 373.055 112.224 L 243.631 37.338 C 241.19 35.71 238.747 35.71 236.305 35.71 C 233.863 35.71 231.42 36.523 228.978 37.338 L 79.84 123.009 C 80.786 126.443 81.29 130.058 81.29 133.793 C 81.29 156.269 63.065 174.493 40.59 174.493 C 18.116 174.493 -0.109 156.269 -0.109 133.793 C -0.109 111.32 18.116 93.095 40.59 93.095 Z\" fill=url(#paint0_linear_1677_11483) /><path d=\"M 417.01 171.913 C 401.585 166.126 390.603 151.238 390.603 133.793 C 390.603 111.32 408.83 93.095 431.303 93.095 C 453.777 93.095 472.001 111.32 472.001 133.793 C 472.001 148.706 463.976 161.755 452.011 168.835 L 452.011 336.07 C 452.011 353.977 442.243 370.258 427.591 379.21 L 294.098 455.726 C 294.098 443.516 290.029 431.306 282.703 422.353 L 409.683 349.093 C 414.568 346.651 417.01 341.767 417.01 336.07 L 417.01 171.913 Z\" fill=url(#paint1_linear_1677_11483) /><path d=\"M 275.376 449.253 C 276.206 452.495 276.646 455.889 276.646 459.389 C 276.646 481.863 258.422 500.087 235.947 500.087 C 215.679 500.087 198.87 485.272 195.761 465.883 L 47.46 380.025 C 31.995 371.071 23.041 354.792 23.041 336.884 L 23.041 186.296 C 28.738 187.923 35.25 189.553 40.948 189.553 C 46.646 189.553 52.345 188.738 57.228 187.111 L 57.228 336.884 C 57.228 342.582 60.485 347.465 64.554 349.908 L 206.042 431.777 C 213.481 423.728 224.127 418.689 235.947 418.689 C 254.905 418.689 270.833 431.656 275.36 449.196 L 275.376 449.214 L 275.376 449.253 Z\" fill=url(#paint2_linear_1677_11483) /><g mask=url(#mask0_1677_11483) transform=\"matrix(8.139854, 0, 0, 8.139854, -130.346375, -113.251038)\"><g filter=url(#filter0_f_1677_11483)><circle cx=73 cy=25 r=26 fill=#ED2E7E /></g><g filter=url(#filter1_f_1677_11483)><circle cx=26 cy=69 r=26 fill=#1CC8EE /></g></g><path fill-rule=evenodd clip-rule=evenodd d=\"M 271.713 150.431 C 271.713 169.275 256.948 200.517 235.947 200.517 C 215.003 200.517 200.172 169.292 200.172 150.431 C 200.172 130.708 216.225 114.666 235.947 114.666 C 255.67 114.666 271.713 130.708 271.713 150.431 Z M 157.251 285.952 L 157.251 279.212 C 157.251 235.233 177.771 220.485 194.27 208.641 C 198.447 205.644 202.247 202.901 205.414 199.923 C 214.204 209.608 224.763 214.826 235.947 214.826 C 247.138 214.826 257.697 209.608 266.496 199.931 C 269.653 202.911 273.456 205.644 277.622 208.641 C 294.114 220.485 314.642 235.233 314.642 279.212 L 314.642 285.952 L 307.912 286.351 C 276.525 288.191 251.128 268.509 235.947 241.468 C 220.611 268.795 195.126 288.191 163.981 286.351 L 157.251 285.952 Z M 342.953 302.492 C 333.771 300.994 276.751 291.715 235.955 340.082 C 195.345 291.749 139.865 300.734 129.389 302.436 C 128.428 302.59 127.841 302.688 127.687 302.665 C 127.687 302.673 127.695 302.729 127.702 302.85 C 127.897 305.138 129.867 328.532 146.872 344.55 L 113.849 358.862 L 358.044 358.862 L 324.639 344.55 C 340.576 330.177 342.905 312.202 343.807 305.212 C 343.962 304.022 344.077 303.153 344.206 302.665 C 344.108 302.68 343.686 302.606 342.953 302.492 Z M 199.188 294.59 C 214.751 288.215 225.161 278.879 235.947 266.15 C 246.788 278.96 257.241 288.255 272.707 294.59 C 272.869 294.898 273.031 295.207 273.196 295.518 C 273.219 295.574 273.252 295.631 273.285 295.688 C 261.107 300.361 247.555 308.598 235.989 319.334 C 224.477 308.573 211.258 300.417 198.715 295.493 C 198.87 295.191 199.033 294.891 199.188 294.59 Z\" fill=url(#paint6_linear_1677_11483) /><g mask=url(#mask1_1677_11483) transform=\"matrix(8.139854, 0, 0, 8.139854, -130.346375, -113.251038)\"><g filter=url(#filter2_f_1677_11483)><circle cx=38 cy=6 r=26 fill=#ED2E7E /></g><g filter=url(#filter3_f_1677_11483)><circle cx=63 cy=69 r=26 fill=#1CC8EE /></g></g></svg></div><h1>GraphQL Yoga</h1><p>Version: 5.11.0</p></div><h2>The batteries-included cross-platform GraphQL Server.</h2><div class=buttons><a href=https://www.the-guild.dev/graphql/yoga-server/docs class=docs>Read the Docs</a> <a href=https://www.the-guild.dev/graphql/yoga-server/tutorial/basic class=tutorial>Start the Tutorial </a><a href=__GRAPHIQL_LINK__ class=graphiql>Visit GraphiQL</a></div></section><section class=not-what-your-looking-for><h2>Not the page you are looking for? \uD83D\uDC40</h2><p>This page is shown be default whenever a 404 is hit.<br>You can disable this by behavior via the <code>landingPage</code> option.</p><pre>\n <code>\nimport { createYoga } from 'graphql-yoga';\n\nconst yoga = createYoga({\n landingPage: false\n})\n </code>\n </pre><p>If you expected this page to be the GraphQL route, you need to configure Yoga. Currently, the GraphQL route is configured to be on <code>__GRAPHIQL_LINK__</code>.</p><pre>\n <code>\nimport { createYoga } from 'graphql-yoga';\n\nconst yoga = createYoga({\n graphqlEndpoint: '__REQUEST_PATH__',\n})\n </code>\n </pre></section></main></body></html>";var pr1=function $(A){return new A.fetchAPI.Response(W41.replace(/__GRAPHIQL_LINK__/g,A.graphqlEndpoint).replace(/__REQUEST_PATH__/g,A.url.pathname),{status:200,statusText:"OK",headers:{"Content-Type":"text/html"}})};function X41($){let A;function F({URLPattern:B}){return A||=new B({pathname:$.graphqlEndpoint}),A}let D=$.landingPageRenderer||pr1;return{onRequest({request:B,fetchAPI:E,endResponse:w,url:Z}){if(!B.url.endsWith($.graphqlEndpoint)&&!B.url.endsWith(`${$.graphqlEndpoint}/`)&&Z.pathname!==$.graphqlEndpoint&&Z.pathname!==`${$.graphqlEndpoint}/`&&!F(E).test(Z)){if($.showLandingPage===!0&&B.method==="GET"&&!!B.headers?.get("accept")?.includes("text/html")){let J=D({request:B,fetchAPI:E,url:Z,graphqlEndpoint:$.graphqlEndpoint,get urlPattern(){return F(E)}});if(n1(J))return J.then(w);w(J);return}w(new E.Response("",{status:404,statusText:"Not Found"}))}}}}var U41=H1(K1(),1);async function Zu({request:$,result:A,fetchAPI:F,onResultProcessHooks:D,serverContext:B}){let E,w=[],Z="*/*";for(let J of D)await J({request:$,acceptableMediaTypes:w,result:A,setResult(Y){A=Y},resultProcessor:E,setResultProcessor(Y,W){E=Y,Z=W},serverContext:B});if(!E)return new F.Response(null,{status:406,statusText:"Not Acceptable",headers:{accept:w.join("; charset=utf-8, ")}});return E(A,F,Z)}async function H41({params:$,enveloped:A}){let F=A.parse($.query),D=A.validate(A.schema,F);if(D.length>0)return{errors:D};let B=await A.contextFactory(),E={schema:A.schema,document:F,contextValue:B,variableValues:$.variables,operationName:$.operationName};return(U41.getOperationAST(F,$.operationName)?.operation==="subscription"?A.subscribe:A.execute)(E)}var Q41=($,A,F=globalThis.process?.env?.NODE_ENV==="development")=>{if(f9($)){if($.originalError){if($.originalError.name==="GraphQLError")return $;let D={...$.extensions,unexpected:!0};if(F)D.originalError={message:$.originalError.message,stack:$.originalError.stack};return o(A,{nodes:$.nodes,source:$.source,positions:$.positions,path:$.path,extensions:D})}return $}return o(A,{extensions:{unexpected:!0,originalError:F?$ instanceof Error?{message:$.message,stack:$.stack}:$:void 0}})};class C41{getEnveloped;logger;graphqlEndpoint;fetchAPI;plugins;onRequestParseHooks;onParamsHooks;onExecutionResultHooks;onResultProcessHooks;maskedErrorsOpts;id;version="5.11.0";constructor($){if(this.id=$?.id??"yoga",this.fetchAPI={...OB},$?.fetchAPI){for(let Z in $.fetchAPI)if($.fetchAPI[Z])this.fetchAPI[Z]=$.fetchAPI[Z]}let A=$?.logging==null?!0:$.logging;this.logger=typeof A==="boolean"?A===!0?FY():FY("silent"):typeof A==="string"?FY(A):A;let F=typeof $?.maskedErrors==="object"&&$.maskedErrors.maskError||Q41,D=new WeakSet;this.maskedErrorsOpts=$?.maskedErrors===!1?null:{errorMessage:"Unexpected error.",...typeof $?.maskedErrors==="object"?$.maskedErrors:{},maskError:(Z,J)=>{if(D.has(Z))return Z;let Y=F(Z,J,this.maskedErrorsOpts?.isDev);if(Y!==Z)this.logger.error(Z);return D.add(Y),Y}};let B=this.maskedErrorsOpts==null?null:this.maskedErrorsOpts,E=0;if($?.batching)if(typeof $.batching==="boolean")E=10;else E=$.batching.limit??10;this.graphqlEndpoint=$?.graphqlEndpoint||"/graphql";let w=this.graphqlEndpoint;this.plugins=[Ae({parse:qA.parse,validate:qA.validate,execute:TY,subscribe:TY,specifiedRules:qA.specifiedRules}),!!$?.schema&&ht($.schema),$?.context!=null&&$e((Z)=>{if($?.context){if(typeof $.context==="function")return $.context(Z);return $.context}return{}}),n61({id:this.id,logger:this.logger,endpoint:$?.healthCheckEndpoint}),$?.cors!==!1&&L61($?.cors),$?.graphiql!==!1&&St({graphqlEndpoint:w,options:$?.graphiql,render:$?.renderGraphiQL,logger:this.logger}),GA({match:d61,parse:k61}),GA({match:_61,parse:p61}),$?.multipart!==!1&&GA({match:x61,parse:y61}),GA({match:f61,parse:b61}),GA({match:m61,parse:v61}),Y41(),S61((Z,J,Y)=>{let X={errors:hB(Z,this.maskedErrorsOpts,this.logger)};return Zu({request:J,result:X,fetchAPI:this.fetchAPI,onResultProcessHooks:this.onResultProcessHooks,serverContext:Y})}),...$?.plugins??[],{onPluginInit({addPlugin:Z}){if($?.parserAndValidationCache!==!1)Z($41(!$?.parserAndValidationCache||$?.parserAndValidationCache===!0?{}:$?.parserAndValidationCache));Z(i61(E)),Z(l61($?.extraParamNames));let J=!!($?.landingPage??!0);if(Z(X41({graphqlEndpoint:w,showLandingPage:J,landingPageRenderer:typeof $?.landingPage==="function"?$.landingPage:void 0})),Z(c61()),Z(s61()),B)Z({onSubscribe(){return{onSubscribeError({error:Y}){if(Bu(Y))throw Y}}}}),Z(eo(B));Z(a61())}}],this.getEnveloped=to({plugins:this.plugins}),this.plugins=this.getEnveloped._plugins,this.onRequestParseHooks=[],this.onParamsHooks=[],this.onExecutionResultHooks=[],this.onResultProcessHooks=[];for(let Z of this.plugins)if(Z){if(Z.onYogaInit)Z.onYogaInit({yoga:this});if(Z.onRequestParse)this.onRequestParseHooks.push(Z.onRequestParse);if(Z.onParams)this.onParamsHooks.push(Z.onParams);if(Z.onExecutionResult)this.onExecutionResultHooks.push(Z.onExecutionResult);if(Z.onResultProcess)this.onResultProcessHooks.push(Z.onResultProcess)}}handleParams=async({request:$,context:A,params:F})=>{let D;try{let B=A.request===$?{params:F}:{request:$,params:F};Object.assign(A,B);let E=this.getEnveloped(A);this.logger.debug("Processing GraphQL Parameters"),D=await H41({params:F,enveloped:E}),this.logger.debug("Processing GraphQL Parameters done.")}catch(B){D={errors:hB(B,this.maskedErrorsOpts,this.logger)}}if(I6(D))D=d9(D,(B)=>B,(B)=>{if(B.name==="AbortError")throw this.logger.debug("Request aborted"),B;return{errors:hB(B,this.maskedErrorsOpts,this.logger)}});return D};async getResultForParams({params:$,request:A},F){let D,B=this.handleParams;for(let E of this.onParamsHooks)await E({params:$,request:A,setParams(w){$=w},paramsHandler:B,setParamsHandler(w){B=w},setResult(w){D=w},fetchAPI:this.fetchAPI,context:F});D??=await B({request:A,params:$,context:F});for(let E of this.onExecutionResultHooks)await E({result:D,setResult(w){D=w},request:A,context:F});return D}handle=async($,A)=>{let F=new Proxy({},{get:(Z,J,Y)=>{return F=new this.fetchAPI.URL($.url,"http://localhost"),Reflect.get(F,J,F)}}),D,B=[];for(let Z of this.onRequestParseHooks){let J=await Z({request:$,url:F,requestParser:D,serverContext:A,setRequestParser(Y){D=Y}});if(J?.onRequestParseDone!=null)B.push(J.onRequestParseDone)}if(this.logger.debug("Parsing request to extract GraphQL parameters"),!D)return new this.fetchAPI.Response(null,{status:415,statusText:"Unsupported Media Type"});let E=await D($);for(let Z of B)await Z({requestParserResult:E,setRequestParserResult(J){E=J}});let w=await(Array.isArray(E)?Promise.all(E.map((Z)=>this.getResultForParams({params:Z,request:$},Object.create(A)))):this.getResultForParams({params:E,request:$},A));return Zu({request:$,result:w,fetchAPI:this.fetchAPI,onResultProcessHooks:this.onResultProcessHooks,serverContext:A})}}function G41($){let A=new C41($);return R61(A,{fetchAPI:A.fetchAPI,plugins:A.plugins})}var K41=({graphqlMiddleware:$,...A})=>{let F=G41({...A,schema:A.schema||co({typeDefs:A.typeDefs||"",resolvers:A.resolvers||{}})}),D=async(B)=>{let E=await(async()=>{if(!$)return F.handle(B.request,B);return $(async()=>F.handle(B.request,B),B.res)})();for(let[w,Z]of B.res.headers.entries()){if(w==="set-cookie"){E.headers.append("set-cookie",Z);continue}E.headers.set(w,Z)}return E};return(B)=>{B.get(A?.graphqlEndpoint||"/graphql",async(E)=>D(E)),B.post(A?.graphqlEndpoint||"/graphql",async(E)=>D(E))}};var q41=async($)=>{let A=$.config?.authentication?.roles||[];if(A.length===0)return;let D=(await $.controllers.database.getObjects({className:"Role",context:{isRoot:!0,wabe:$},select:{name:!0},where:{name:{in:A}}})).map((E)=>E?.name).filter(x2),B=A.filter((E)=>!D.includes(E)).map((E)=>({name:E}));if(B.length===0)return;await $.controllers.database.createObjects({className:"Role",context:{isRoot:!0,wabe:$},data:B,select:{}})};class Ju{adapter;constructor($){this.adapter=$}send($){return this.adapter.send($)}}class Yu{adapter;config;constructor($){this.adapter=$.adapter,this.config=$}deleteCoupon($){return this.adapter.deleteCoupon($)}updatePromotionCode($){return this.adapter.updatePromotionCode($)}createCoupon($){return this.adapter.createCoupon($)}createPromotionCode($){return this.adapter.createPromotionCode($)}getCustomerById($){return this.adapter.getCustomerById($)}validateWebhook($){return this.adapter.validateWebhook($)}createCustomer($){return this.adapter.createCustomer($)}createPayment($){return this.adapter.createPayment({...$,currency:this.config.currency,paymentMethod:this.config.supportedPaymentMethods})}cancelSubscription($){return this.adapter.cancelSubscription($)}getInvoices($){return this.adapter.getInvoices($)}getTotalRevenue($){return this.adapter.getTotalRevenue($)}getAllTransactions($){return this.adapter.getAllTransactions($)}getHypotheticalSubscriptionRevenue(){return this.adapter.getHypotheticalSubscriptionRevenue()}}var V41=H1(K1(),1),z41=new WeakMap,u41=($)=>{return{async onRequest({request:A}){let F=$?.isDisabled?await $.isDisabled(A):!0;z41.set(A,F)},onValidate({addValidationRule:A,context:F}){if(z41.get(F.request)??!0)A(V41.NoSchemaIntrospectionCustomRule)}}};class Wu{adapter;wabe;constructor($,A){this.adapter=$,this.wabe=A}uploadFile($){return this.adapter.uploadFile($)}readFile($,A){return this.adapter.readFile($,{...A,port:this.wabe.config.port})}deleteFile($){return this.adapter.deleteFile($)}}var P41=($)=>async(A)=>{let F=A.request.headers;if(F.get("Wabe-Root-Key")===$.config.rootKey){A.wabe={isRoot:!0,wabe:$,response:A.res};return}let D=()=>{if(F.get("Wabe-Access-Token"))return{accessToken:F.get("Wabe-Access-Token")};if(!!$.config.authentication?.session?.cookieSession)return{accessToken:Ru("accessToken",A.request.headers)};return{accessToken:null}},{accessToken:B}=D();if(!B){A.wabe={isRoot:!1,wabe:$,response:A.res};return}let E=new D4,{user:w,sessionId:Z,accessToken:J,refreshToken:Y}=await E.meFromAccessToken(B,{wabe:$,isRoot:!0});if(A.wabe={isRoot:!1,sessionId:Z,user:w,wabe:$,response:A.res},$.config.authentication?.session?.cookieSession&&J&&Y&&J!==B)A.res.setCookie("accessToken",J,{httpOnly:!0,path:"/",expires:E.getAccessTokenExpireAt($.config),sameSite:"None",secure:!0}),A.res.setCookie("refreshToken",Y,{httpOnly:!0,path:"/",expires:E.getAccessTokenExpireAt($.config),sameSite:"None",secure:!0})};var __dirname="/home/runner/work/wabe/wabe/packages/wabe/src/server";class il{server;config;controllers;constructor({isProduction:$,port:A,hostname:F,security:D,schema:B,database:E,authentication:w,rootKey:Z,codegen:J,hooks:Y,file:W,email:X,payment:U,routes:H,crons:Q}){this.config={isProduction:$,port:A,hostname:F,security:D,schema:B,database:E,codegen:J,authentication:w,rootKey:Z,hooks:Y,email:X,payment:U,routes:H,file:W,crons:Q},this.server=new az({hostname:F}).get("/health",(V)=>{V.res.status=200,V.res.send("OK")});let q=new Jq({databaseName:E.name,databaseUrl:E.url});this.controllers={database:new Yq(q),email:X?.adapter?new Ju(X.adapter):void 0,payment:U?.adapter?new Yu(U):void 0,file:W?.adapter?new Wu(W.adapter,this):void 0},this.loadCrons(),this.loadAuthenticationMethods(),this.loadRoleEnum(),this.loadRoutes(),this.loadHooks()}loadCrons(){if(!this.config.crons)return;let $=this.config.crons.map((A)=>({...A,job:A.cron(this)}));this.config.crons=$}loadRoleEnum(){let $=this.config.authentication?.roles||[];if($.length===0)return;let A={name:"RoleEnum",values:$.reduce((F,D)=>{return F[D]=D,F},{})};this.config.schema={...this.config.schema,enums:[...this.config.schema?.enums||[],A]}}loadAuthenticationMethods(){this.config.authentication={...this.config.authentication,customAuthenticationMethods:[...Mt(),...this.config.authentication?.customAuthenticationMethods||[]]}}loadHooks(){if(this.config.hooks?.find(($)=>$.priority<=0))throw new Error("Hook priority <= 0 is reserved for internal uses");this.config.hooks=[...wc(),...this.config.hooks||[]]}loadRoutes(){[...Ct(this.config.file?.devDirectory||`${__dirname}/../../bucket`),...this.config.routes||[]].map((A)=>{let{method:F}=A;switch(F){case"GET":this.server.get(A.path,A.handler);break;case"POST":this.server.post(A.path,A.handler);break;case"PUT":this.server.put(A.path,A.handler);break;case"DELETE":this.server.delete(A.path,A.handler);break;default:throw new Error("Invalid method for default route")}})}async start(){await this.controllers.database.connect();let $=new Yz(this.config);this.config.schema=$.schema;let F=new yz($).createSchema();if(this.config.graphqlSchema=new kB.GraphQLSchema({query:new kB.GraphQLObjectType({name:"Query",fields:F.queries}),mutation:new kB.GraphQLObjectType({name:"Mutation",fields:F.mutations}),types:[...F.scalars,...F.enums,...F.objects]}),!this.config.isProduction&&!0&&this.config.codegen&&this.config.codegen.enabled&&this.config.codegen.path.length>0){if(await Vt({path:this.config.codegen.path,schema:$.schema,graphqlSchema:this.config.graphqlSchema}),process.env.CODEGEN)process.exit(0)}this.server.options("/*",(B)=>{return B.res.send("OK")},iz(this.config.security?.corsOptions));let D=this.config.security?.rateLimit;if(D)this.server.beforeHandler(Xt(D));this.server.beforeHandler(iz(this.config.security?.corsOptions)),this.server.beforeHandler(this.config.authentication.sessionHandler||P41(this)),this.server.usePlugin(K41({schema:this.config.graphqlSchema,maskedErrors:this.config.security?.maskErrorMessage||this.config.isProduction,graphqlEndpoint:"/graphql",plugins:this.config.isProduction?[u41()]:[],context:async(B)=>B.wabe})),await Promise.all([q41(this)]),this.server.listen(this.config.port,({port:B})=>{if(!process.env.TEST)console.log(`Server is running on port ${B}`)})}async close(){await this.controllers.database.close(),this.server.stop()}}function J6($,A,F,D,B,E,w,Z){return J6.fromTZ(J6.tp($,A,F,D,B,E,w),Z)}J6.fromTZISO=($,A,F)=>J6.fromTZ(gr1($,A),F);J6.fromTZ=function($,A){let F=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),D=Xu($.tz,F),B=new Date(F.getTime()-D),E=Xu($.tz,B);if(E-D===0)return B;{let w=new Date(F.getTime()-E),Z=Xu($.tz,w);if(Z-E===0)return w;if(!A&&Z-E>0)return w;if(A)throw new Error("Invalid date passed to fromTZ()");return B}};J6.toTZ=function($,A){let F=$.toLocaleString("en-US",{timeZone:A}).replace(/[\u202f]/," "),D=new Date(F);return{y:D.getFullYear(),m:D.getMonth()+1,d:D.getDate(),h:D.getHours(),i:D.getMinutes(),s:D.getSeconds(),tz:A}};J6.tp=($,A,F,D,B,E,w)=>({y:$,m:A,d:F,h:D,i:B,s:E,tz:w});function Xu($,A=new Date){let F=A.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],D=A.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${D} GMT`)-Date.parse(`${D} ${F}`)}function gr1($,A){let F=new Date(Date.parse($));if(isNaN(F))throw new Error("minitz: Invalid ISO8601 passed to parser.");let D=$.substring(9);return $.includes("Z")||D.includes("-")||D.includes("+")?J6.tp(F.getUTCFullYear(),F.getUTCMonth()+1,F.getUTCDate(),F.getUTCHours(),F.getUTCMinutes(),F.getUTCSeconds(),"Etc/UTC"):J6.tp(F.getFullYear(),F.getMonth()+1,F.getDate(),F.getHours(),F.getMinutes(),F.getSeconds(),A)}J6.minitz=J6;var Uu=32,vB=31|Uu,R41=[1,2,4,8,16],M41=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,A){this.pattern=$,this.timezone=A,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw new TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw new TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let A=new x4(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",A.getSeconds().toString()),$[1]=$[1].replace("?",A.getMinutes().toString()),$[2]=$[2].replace("?",A.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",A.getDate().toString())),$[4]=$[4].replace("?",(A.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",A.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,vB),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,A,F,D){let B=this[$],E=$==="day"&&this.lastDayOfMonth;if(A===""&&!E)throw new TypeError("CronPattern: configuration entry "+$+" ("+A+") is empty, check for trailing spaces.");if(A==="*")return B.fill(D);let w=A.split(",");if(w.length>1)for(let Z=0;Z<w.length;Z++)this.partToArray($,w[Z],F,D);else A.indexOf("-")!==-1&&A.indexOf("/")!==-1?this.handleRangeWithStepping(A,$,F,D):A.indexOf("-")!==-1?this.handleRange(A,$,F,D):A.indexOf("/")!==-1?this.handleStepping(A,$,F,D):A!==""&&this.handleNumber(A,$,F,D)}throwAtIllegalCharacters($){for(let A=0;A<$.length;A++)if((A===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[A]))throw new TypeError("CronPattern: configuration entry "+A+" ("+$[A]+") contains illegal characters.")}handleNumber($,A,F,D){let B=this.extractNth($,A),E=parseInt(B[0],10)+F;if(isNaN(E))throw new TypeError("CronPattern: "+A+" is not a number: '"+$+"'");this.setPart(A,E,B[1]||D)}setPart($,A,F){if(!Object.prototype.hasOwnProperty.call(this,$))throw new TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(A===7&&(A=0),A<0||A>6)throw new RangeError("CronPattern: Invalid value for dayOfWeek: "+A);this.setNthWeekdayOfMonth(A,F);return}if($==="second"||$==="minute"){if(A<0||A>=60)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="hour"){if(A<0||A>=24)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="day"){if(A<0||A>=31)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="month"&&(A<0||A>=12))throw new RangeError("CronPattern: Invalid value for "+$+": "+A);this[$][A]=F}handleRangeWithStepping($,A,F,D){let B=this.extractNth($,A),E=B[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(E===null)throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,w,Z,J]=E,Y=parseInt(w,10)+F,W=parseInt(Z,10)+F,X=parseInt(J,10);if(isNaN(Y))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(W))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(X))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(X===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(X>this[A].length)throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[A].length+")");if(Y>W)throw new TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let U=Y;U<=W;U+=X)this.setPart(A,U,B[1]||D)}extractNth($,A){let F=$,D;if(F.includes("#")){if(A!=="dayOfWeek")throw new Error("CronPattern: nth (#) only allowed in day-of-week field");D=F.split("#")[1],F=F.split("#")[0]}return[F,D]}handleRange($,A,F,D){let B=this.extractNth($,A),E=B[0].split("-");if(E.length!==2)throw new TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let w=parseInt(E[0],10)+F,Z=parseInt(E[1],10)+F;if(isNaN(w))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(w>Z)throw new TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let J=w;J<=Z;J++)this.setPart(A,J,B[1]||D)}handleStepping($,A,F,D){let B=this.extractNth($,A),E=B[0].split("/");if(E.length!==2)throw new TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");E[0]===""&&(E[0]="*");let w=0;E[0]!=="*"&&(w=parseInt(E[0],10)+F);let Z=parseInt(E[1],10);if(isNaN(Z))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[A].length)throw new TypeError("CronPattern: Syntax error, max steps for part is ("+this[A].length+")");for(let J=w;J<this[A].length;J+=Z)this.setPart(A,J,B[1]||D)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let A=$.trim().toLowerCase();return A==="@yearly"||A==="@annually"?"0 0 1 1 *":A==="@monthly"?"0 0 1 * *":A==="@weekly"?"0 0 * * 0":A==="@daily"?"0 0 * * *":A==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,A){if(typeof A!="number"&&A==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|Uu;else if(A===vB)this.dayOfWeek[$]=vB;else if(A<6&&A>0)this.dayOfWeek[$]=this.dayOfWeek[$]|R41[A-1];else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${A}, Type: ${typeof A}`)}},I41=[31,28,31,30,31,30,31,31,30,31,30,31],_9=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],x4=class ${tz;ms;second;minute;hour;day;month;year;constructor(A,F){if(this.tz=F,A&&A instanceof Date)if(!isNaN(A))this.fromDate(A);else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");else if(A===void 0)this.fromDate(new Date);else if(A&&typeof A=="string")this.fromString(A);else if(A instanceof $)this.fromCronDate(A);else throw new TypeError("CronDate: Invalid type ("+typeof A+") passed to CronDate constructor")}isNthWeekdayOfMonth(A,F,D,B){let E=new Date(Date.UTC(A,F,D)).getUTCDay(),w=0;for(let Z=1;Z<=D;Z++)new Date(Date.UTC(A,F,Z)).getUTCDay()===E&&w++;if(B&vB&&R41[w-1]&B)return!0;if(B&Uu){let Z=new Date(Date.UTC(A,F+1,0)).getUTCDate();for(let J=D+1;J<=Z;J++)if(new Date(Date.UTC(A,F,J)).getUTCDay()===E)return!1;return!0}return!1}fromDate(A){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=A.getUTCMilliseconds(),this.second=A.getUTCSeconds(),this.minute=A.getUTCMinutes()+this.tz,this.hour=A.getUTCHours(),this.day=A.getUTCDate(),this.month=A.getUTCMonth(),this.year=A.getUTCFullYear(),this.apply();else{let F=J6.toTZ(A,this.tz);this.ms=A.getMilliseconds(),this.second=F.s,this.minute=F.i,this.hour=F.h,this.day=F.d,this.month=F.m-1,this.year=F.y}else this.ms=A.getMilliseconds(),this.second=A.getSeconds(),this.minute=A.getMinutes(),this.hour=A.getHours(),this.day=A.getDate(),this.month=A.getMonth(),this.year=A.getFullYear()}fromCronDate(A){this.tz=A.tz,this.year=A.year,this.month=A.month,this.day=A.day,this.hour=A.hour,this.minute=A.minute,this.second=A.second,this.ms=A.ms}apply(){if(this.month>11||this.day>I41[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let A=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=A.getUTCMilliseconds(),this.second=A.getUTCSeconds(),this.minute=A.getUTCMinutes(),this.hour=A.getUTCHours(),this.day=A.getUTCDate(),this.month=A.getUTCMonth(),this.year=A.getUTCFullYear(),!0}else return!1}fromString(A){if(typeof this.tz=="number"){let F=J6.fromTZISO(A);this.ms=F.getUTCMilliseconds(),this.second=F.getUTCSeconds(),this.minute=F.getUTCMinutes(),this.hour=F.getUTCHours(),this.day=F.getUTCDate(),this.month=F.getUTCMonth(),this.year=F.getUTCFullYear(),this.apply()}else return this.fromDate(J6.fromTZISO(A,this.tz))}findNext(A,F,D,B){let E=this[F],w;D.lastDayOfMonth&&(this.month!==1?w=I41[this.month]:w=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!D.starDOW&&F=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let J=this[F]+B;J<D[F].length;J++){let Y=D[F][J];if(F==="day"&&D.lastDayOfMonth&&J-B==w&&(Y=1),F==="day"&&!D.starDOW){let W=D.dayOfWeek[(Z+(J-B-1))%7];if(W&&W&vB)W=this.isNthWeekdayOfMonth(this.year,this.month,J-B,W)?1:0;else if(W)throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${W}`);A.legacyMode&&!D.starDOM?Y=Y||W:Y=Y&&W}if(Y)return this[F]=J-B,E!==this[F]?2:1}return 3}recurse(A,F,D){let B=this.findNext(F,_9[D][0],A,_9[D][2]);if(B>1){let E=D+1;for(;E<_9.length;)this[_9[E][0]]=-_9[E][2],E++;if(B===3)return this[_9[D][1]]++,this[_9[D][0]]=-_9[D][2],this.apply(),this.recurse(A,F,0);if(this.apply())return this.recurse(A,F,D-1)}return D+=1,D>=_9.length?this:this.year>=3000?null:this.recurse(A,F,D)}increment(A,F,D){return this.second+=F.interval!==void 0&&F.interval>1&&D?F.interval:1,this.ms=0,this.apply(),this.recurse(A,F,0)}getDate(A){return A||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):J6.fromTZ(J6.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xr1($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new x4($.startAt,$.timezone)),$.stopAt&&($.stopAt=new x4($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw new Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw new Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw new Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw new Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function mB($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function yr1($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var j41=30000,FW=[],L41=class{name;options;_states;fn;constructor($,A,F){let D,B;if(mB(A))B=A;else if(typeof A=="object")D=A;else if(A!==void 0)throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(mB(F))B=F;else if(typeof F=="object")D=F;else if(F!==void 0)throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=D?.name,this.options=xr1(D),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:D?D.maxRuns:void 0,paused:D?D.paused:!1,pattern:new M41("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new x4($,this.options.timezone||this.options.utcOffset):this._states.pattern=new M41($,this.options.timezone),this.name){if(FW.find((E)=>E.name===this.name))throw new Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");FW.push(this)}return B!==void 0&&mB(B)&&(this.fn=B,this.schedule()),this}nextRun($){let A=this._next($);return A?A.getDate(!1):null}nextRuns($,A){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let F=[],D=A||this._states.currentRun||void 0;for(;$--&&(D=this.nextRun(D));)F.push(D);return F}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),A=!this._states.paused,F=this.fn!==void 0,D=!this._states.kill;return A&&F&&D&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){$=$||new Date;let A=this._next($);return A?$ instanceof x4||$ instanceof Date?A.getTime()-$.getTime():A.getTime()-new x4($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=FW.indexOf(this);$>=0&&FW.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let A=this.msToNext(),F=this.nextRun(this._states.currentRun);return A==null||isNaN(A)||F===null?this:(A>j41&&(A=j41),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(F),A),this._states.currentTimeout&&this.options.unref&&yr1(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new x4(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(A){mB(this.options.catch)&&this.options.catch(A,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new x4($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let A=new Date,F=!this._states.paused&&A.getTime()>=$.getTime(),D=this._states.blocking&&this.options.protect;F&&!D?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):F&&D&&mB(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let A=!!($||this._states.currentRun),F=!1;!$&&this.options.startAt&&this.options.interval&&([$,A]=this._calculatePreviousRun($,A),F=!$),$=new x4($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let D=this._states.once||new x4($,this.options.timezone||this.options.utcOffset);return!F&&D!==this._states.once&&(D=D.increment(this._states.pattern,this.options,A)),this._states.once&&this._states.once.getTime()<=$.getTime()||D===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&D.getTime()>=this.options.stopAt.getTime()?null:D}_calculatePreviousRun($,A){let F=new x4(void 0,this.options.timezone||this.options.utcOffset),D=$;if(this.options.startAt.getTime()<=F.getTime()){D=this.options.startAt;let B=D.getTime()+this.options.interval*1000;for(;B<=F.getTime();)D=new x4(D,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),B=D.getTime()+this.options.interval*1000;A=!0}return D===null&&(D=void 0),[D,A]}};var FU0=({pattern:$,run:A,maxRuns:F,enabledProtectedRuns:D})=>(B)=>new L41($,{maxRuns:F,protect:D},()=>A(B)),lr1;((V)=>{V.EVERY_SECOND="* * * * * *";V.EVERY_MINUTE="0 * * * * *";V.EVERY_HOUR="0 0 * * * *";V.EVERY_DAY_AT_MIDNIGHT="0 0 0 * * *";V.EVERY_WEEK="0 0 0 * * 0";V.EVERY_MONTH="0 0 0 1 * *";V.EVERY_YEAR="0 0 0 1 1 *";V.WEEKDAYS_MORNING="0 0 7 * * 1-5";V.WEEKENDS_EVENING="0 0 19 * * 6-7";V.FIRST_DAY_OF_MONTH="0 0 0 1 * *";V.LAST_DAY_OF_MONTH="0 0 0 L * *";V.EVERY_15_MINUTES="0 */15 * * * *";V.EVERY_30_MINUTES="0 */30 * * * *";V.EVERY_2_HOURS="0 0 */2 * * *";V.EVERY_6_HOURS="0 0 */6 * * *";V.EVERY_12_HOURS="0 0 */12 * * *"})(lr1||={});export{n3 as initializeHook,wc as getDefaultHooks,Vt as generateCodegen,FU0 as cron,R1 as contextWithRoot,i3 as buildMongoWhereQuery,_k1 as buildMongoOrderQuery,Ec as _findHooksByPriority,il as Wabe,Wq as SecondaryFactor,Yz as Schema,Zc as ProviderEnum,gk1 as PaymentReccuringInterval,pk1 as PaymentMode,pl as PaymentDevAdapter,yB as OperationType,fD as OAuth2Client,Jq as MongoAdapter,bD as Google,cl as FileDevAdapter,gl as EmailDevAdapter,_l as DatabaseEnum,Yq as DatabaseController,xl as Currency,lr1 as CronExpressions,O$ as AuthenticationProvider};
546
+ `)),clearInterval(Z),W.close()}catch(X){W.error(X)}},async cancel(W){clearInterval(Z),await w.return?.(W)}});return new F.Response(Y,E)}}var br1={mediaTypes:["multipart/mixed"],asyncIterables:!0,processResult:E41};function _r1(){return{mediaTypes:["text/event-stream"],asyncIterables:!0,processResult:Z41()}}var J41={mediaTypes:["application/graphql-response+json","application/json"],asyncIterables:!1,processResult:w41};function Y41(){let $=new WeakMap,A=_r1(),F=[A,br1,J41],D=[A,J41];return{onSubscribe({args:{contextValue:B}}){if(B.request)$.set(B.request,!0)},onResultProcess({request:B,result:E,acceptableMediaTypes:w,setResultProcessor:Z}){let Y=$.get(B)?D:F,W=A41(B),X=I6(E);for(let U of Y)for(let H of W){if(X&&!U.asyncIterables)continue;for(let Q of U.mediaTypes)if(w.push(Q),F41(Q,H))Z(U.processResult,Q)}}}}var W41="<!doctype html><html lang=en><head><meta charset=utf-8><title>Welcome to GraphQL Yoga</title><link rel=icon href=https://raw.githubusercontent.com/dotansimha/graphql-yoga/main/website/public/favicon.ico><style>body,html{padding:0;margin:0;height:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#fff;background-color:#000}main>section.hero{display:flex;height:90vh;justify-content:center;align-items:center;flex-direction:column}.logo{display:flex;align-items:center}.buttons{margin-top:24px}h1{font-size:80px}h2{color:#888;max-width:50%;margin-top:0;text-align:center}a{color:#fff;text-decoration:none;margin-left:10px;margin-right:10px;font-weight:700;transition:color .3s ease;padding:4px;overflow:visible}a.graphiql:hover{color:rgba(255,0,255,.7)}a.docs:hover{color:rgba(28,200,238,.7)}a.tutorial:hover{color:rgba(125,85,245,.7)}svg{margin-right:24px}.not-what-your-looking-for{margin-top:5vh}.not-what-your-looking-for>*{margin-left:auto;margin-right:auto}.not-what-your-looking-for>p{text-align:center}.not-what-your-looking-for>h2{color:#464646}.not-what-your-looking-for>p{max-width:600px;line-height:1.3em}.not-what-your-looking-for>pre{max-width:300px}</style></head><body id=body><main><section class=hero><div class=logo><div><svg xmlns=http://www.w3.org/2000/svg viewBox=\"-0.41 0.445 472.812 499.811\" height=150><defs><linearGradient id=paint0_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint1_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint2_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint3_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint4_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><linearGradient id=paint5_linear_1677_11483 x1=16 y1=14 x2=87.2132 y2=44.5982 gradientUnits=userSpaceOnUse><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><filter id=filter0_f_1677_11483 x=23 y=-25 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><filter id=filter1_f_1677_11483 x=-24 y=19 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><linearGradient id=paint6_linear_1677_11483 x1=30 y1=28 x2=66.1645 y2=44.4363 gradientUnits=userSpaceOnUse gradientTransform=\"matrix(8.139854, 0, 0, 8.139854, -130.346407, -113.25101)\"><stop stop-color=#7433FF /><stop offset=1 stop-color=#FFA3FD /></linearGradient><filter id=filter2_f_1677_11483 x=-12 y=-44 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter><filter id=filter3_f_1677_11483 x=13 y=19 width=100 height=100 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix /><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape /><feGaussianBlur stdDeviation=12 result=effect1_foregroundBlur_1677_11483 /></filter></defs><mask id=mask0_1677_11483 style=mask-type:alpha maskUnits=userSpaceOnUse x=16 y=14 width=58 height=62><path d=\"M21 25.3501C21.7279 25.3501 22.4195 25.5056 23.0433 25.7853L42.1439 14.8C43.0439 14.3 44.1439 14 45.1439 14C46.2439 14 47.2439 14.3 48.1439 14.8L64.5439 24.3C63.3439 25.1 62.4439 26.3 61.8439 27.7L45.9438 18.5C45.6439 18.3 45.344 18.3 45.0441 18.3C44.7441 18.3 44.4439 18.4 44.1439 18.5L25.8225 29.0251C25.9382 29.4471 26 29.8914 26 30.3501C26 33.1115 23.7614 35.3501 21 35.3501C18.2386 35.3501 16 33.1115 16 30.3501C16 27.5887 18.2386 25.3501 21 25.3501Z\" fill=url(#paint3_linear_1677_11483) /><path d=\"M67.2438 35.0329C65.3487 34.3219 64 32.4934 64 30.35C64 27.5886 66.2386 25.35 69 25.35C71.7614 25.35 74 27.5886 74 30.35C74 32.1825 73.0142 33.7848 71.5439 34.6554V55.2C71.5439 57.4 70.3439 59.4 68.5439 60.5L52.1439 69.9C52.1439 68.4 51.6438 66.9 50.7438 65.8L66.3439 56.8C66.9439 56.5 67.2438 55.9 67.2438 55.2V35.0329Z\" fill=url(#paint4_linear_1677_11483) /><path d=\"M49.8439 69.1055C49.9458 69.5034 50 69.9204 50 70.3501C50 73.1115 47.7614 75.3501 45 75.3501C42.5102 75.3501 40.4454 73.5302 40.0633 71.1481L21.8439 60.6C19.9439 59.5 18.8439 57.5 18.8439 55.3V36.8C19.5439 37 20.3439 37.2 21.0439 37.2C21.7439 37.2 22.4439 37.1 23.0439 36.9V55.3C23.0439 56 23.4438 56.6 23.9438 56.9L41.3263 66.9583C42.2398 65.9694 43.5476 65.3501 45 65.3501C47.3291 65.3501 49.2862 66.9426 49.8419 69.0981L49.8436 69.0997L49.8439 69.1055Z\" fill=url(#paint5_linear_1677_11483) /></mask><mask id=mask1_1677_11483 style=mask-type:alpha maskUnits=userSpaceOnUse x=30 y=28 width=30 height=30><path fill-rule=evenodd clip-rule=evenodd d=\"M49.3945 32.3945C49.3945 34.7088 47.5796 38.5469 45 38.5469C42.4271 38.5469 40.6055 34.7112 40.6055 32.3945C40.6055 29.9714 42.5769 28 45 28C47.4231 28 49.3945 29.9714 49.3945 32.3945ZM35.332 49.0433V48.2148C35.332 42.8117 37.8535 41.0004 39.8796 39.545L39.8801 39.5447C40.3928 39.1767 40.8604 38.8404 41.2488 38.4742C42.3293 39.6642 43.626 40.3047 45 40.3047C46.3752 40.3047 47.6725 39.6642 48.7529 38.4754C49.1408 38.841 49.6078 39.1773 50.1199 39.5447L50.1204 39.545C52.1465 41.0004 54.668 42.8117 54.668 48.2148V49.0433L53.8406 49.092C49.9848 49.3185 46.8646 46.9002 45 43.5777C43.1159 46.935 39.9847 49.318 36.1594 49.092L35.332 49.0433ZM58.1463 51.0747L58.1463 51.0746C57.0179 50.891 50.0128 49.7507 45.0007 55.693C40.0116 49.7553 33.1965 50.8592 31.9095 51.0677L31.9095 51.0677C31.7906 51.087 31.7189 51.0986 31.7002 51.0963C31.7005 51.0969 31.7011 51.1045 31.7023 51.1187C31.726 51.4003 31.9682 54.2745 34.0566 56.2422L30 58H60L55.8956 56.2422C57.8537 54.4764 58.1396 52.2685 58.2508 51.4092V51.4091C58.2697 51.2628 58.2836 51.1556 58.2998 51.0963C58.2881 51.0977 58.2356 51.0892 58.1463 51.0747ZM40.4836 50.104C42.3956 49.3212 43.6746 48.1737 45 46.61C46.332 48.1841 47.6159 49.3259 49.5164 50.104C49.5356 50.1425 49.5557 50.1805 49.5756 50.2182C49.5793 50.2253 49.583 50.2323 49.5867 50.2393C48.0911 50.8127 46.4264 51.825 45.0047 53.1444C43.5906 51.8221 41.9673 50.8196 40.4256 50.2153C40.4455 50.1784 40.4648 50.1415 40.4836 50.104Z\" fill=black /></mask><path d=\"M 40.59 93.095 C 46.517 93.095 52.14 94.365 57.22 96.635 L 212.7 7.22 C 220.025 3.149 228.978 0.706 237.12 0.706 C 246.073 0.706 254.213 3.149 261.54 7.22 L 395.032 84.547 C 385.264 91.059 377.939 100.827 373.055 112.224 L 243.631 37.338 C 241.19 35.71 238.747 35.71 236.305 35.71 C 233.863 35.71 231.42 36.523 228.978 37.338 L 79.84 123.009 C 80.786 126.443 81.29 130.058 81.29 133.793 C 81.29 156.269 63.065 174.493 40.59 174.493 C 18.116 174.493 -0.109 156.269 -0.109 133.793 C -0.109 111.32 18.116 93.095 40.59 93.095 Z\" fill=url(#paint0_linear_1677_11483) /><path d=\"M 417.01 171.913 C 401.585 166.126 390.603 151.238 390.603 133.793 C 390.603 111.32 408.83 93.095 431.303 93.095 C 453.777 93.095 472.001 111.32 472.001 133.793 C 472.001 148.706 463.976 161.755 452.011 168.835 L 452.011 336.07 C 452.011 353.977 442.243 370.258 427.591 379.21 L 294.098 455.726 C 294.098 443.516 290.029 431.306 282.703 422.353 L 409.683 349.093 C 414.568 346.651 417.01 341.767 417.01 336.07 L 417.01 171.913 Z\" fill=url(#paint1_linear_1677_11483) /><path d=\"M 275.376 449.253 C 276.206 452.495 276.646 455.889 276.646 459.389 C 276.646 481.863 258.422 500.087 235.947 500.087 C 215.679 500.087 198.87 485.272 195.761 465.883 L 47.46 380.025 C 31.995 371.071 23.041 354.792 23.041 336.884 L 23.041 186.296 C 28.738 187.923 35.25 189.553 40.948 189.553 C 46.646 189.553 52.345 188.738 57.228 187.111 L 57.228 336.884 C 57.228 342.582 60.485 347.465 64.554 349.908 L 206.042 431.777 C 213.481 423.728 224.127 418.689 235.947 418.689 C 254.905 418.689 270.833 431.656 275.36 449.196 L 275.376 449.214 L 275.376 449.253 Z\" fill=url(#paint2_linear_1677_11483) /><g mask=url(#mask0_1677_11483) transform=\"matrix(8.139854, 0, 0, 8.139854, -130.346375, -113.251038)\"><g filter=url(#filter0_f_1677_11483)><circle cx=73 cy=25 r=26 fill=#ED2E7E /></g><g filter=url(#filter1_f_1677_11483)><circle cx=26 cy=69 r=26 fill=#1CC8EE /></g></g><path fill-rule=evenodd clip-rule=evenodd d=\"M 271.713 150.431 C 271.713 169.275 256.948 200.517 235.947 200.517 C 215.003 200.517 200.172 169.292 200.172 150.431 C 200.172 130.708 216.225 114.666 235.947 114.666 C 255.67 114.666 271.713 130.708 271.713 150.431 Z M 157.251 285.952 L 157.251 279.212 C 157.251 235.233 177.771 220.485 194.27 208.641 C 198.447 205.644 202.247 202.901 205.414 199.923 C 214.204 209.608 224.763 214.826 235.947 214.826 C 247.138 214.826 257.697 209.608 266.496 199.931 C 269.653 202.911 273.456 205.644 277.622 208.641 C 294.114 220.485 314.642 235.233 314.642 279.212 L 314.642 285.952 L 307.912 286.351 C 276.525 288.191 251.128 268.509 235.947 241.468 C 220.611 268.795 195.126 288.191 163.981 286.351 L 157.251 285.952 Z M 342.953 302.492 C 333.771 300.994 276.751 291.715 235.955 340.082 C 195.345 291.749 139.865 300.734 129.389 302.436 C 128.428 302.59 127.841 302.688 127.687 302.665 C 127.687 302.673 127.695 302.729 127.702 302.85 C 127.897 305.138 129.867 328.532 146.872 344.55 L 113.849 358.862 L 358.044 358.862 L 324.639 344.55 C 340.576 330.177 342.905 312.202 343.807 305.212 C 343.962 304.022 344.077 303.153 344.206 302.665 C 344.108 302.68 343.686 302.606 342.953 302.492 Z M 199.188 294.59 C 214.751 288.215 225.161 278.879 235.947 266.15 C 246.788 278.96 257.241 288.255 272.707 294.59 C 272.869 294.898 273.031 295.207 273.196 295.518 C 273.219 295.574 273.252 295.631 273.285 295.688 C 261.107 300.361 247.555 308.598 235.989 319.334 C 224.477 308.573 211.258 300.417 198.715 295.493 C 198.87 295.191 199.033 294.891 199.188 294.59 Z\" fill=url(#paint6_linear_1677_11483) /><g mask=url(#mask1_1677_11483) transform=\"matrix(8.139854, 0, 0, 8.139854, -130.346375, -113.251038)\"><g filter=url(#filter2_f_1677_11483)><circle cx=38 cy=6 r=26 fill=#ED2E7E /></g><g filter=url(#filter3_f_1677_11483)><circle cx=63 cy=69 r=26 fill=#1CC8EE /></g></g></svg></div><h1>GraphQL Yoga</h1><p>Version: 5.11.0</p></div><h2>The batteries-included cross-platform GraphQL Server.</h2><div class=buttons><a href=https://www.the-guild.dev/graphql/yoga-server/docs class=docs>Read the Docs</a> <a href=https://www.the-guild.dev/graphql/yoga-server/tutorial/basic class=tutorial>Start the Tutorial </a><a href=__GRAPHIQL_LINK__ class=graphiql>Visit GraphiQL</a></div></section><section class=not-what-your-looking-for><h2>Not the page you are looking for? \uD83D\uDC40</h2><p>This page is shown be default whenever a 404 is hit.<br>You can disable this by behavior via the <code>landingPage</code> option.</p><pre>\n <code>\nimport { createYoga } from 'graphql-yoga';\n\nconst yoga = createYoga({\n landingPage: false\n})\n </code>\n </pre><p>If you expected this page to be the GraphQL route, you need to configure Yoga. Currently, the GraphQL route is configured to be on <code>__GRAPHIQL_LINK__</code>.</p><pre>\n <code>\nimport { createYoga } from 'graphql-yoga';\n\nconst yoga = createYoga({\n graphqlEndpoint: '__REQUEST_PATH__',\n})\n </code>\n </pre></section></main></body></html>";var pr1=function $(A){return new A.fetchAPI.Response(W41.replace(/__GRAPHIQL_LINK__/g,A.graphqlEndpoint).replace(/__REQUEST_PATH__/g,A.url.pathname),{status:200,statusText:"OK",headers:{"Content-Type":"text/html"}})};function X41($){let A;function F({URLPattern:B}){return A||=new B({pathname:$.graphqlEndpoint}),A}let D=$.landingPageRenderer||pr1;return{onRequest({request:B,fetchAPI:E,endResponse:w,url:Z}){if(!B.url.endsWith($.graphqlEndpoint)&&!B.url.endsWith(`${$.graphqlEndpoint}/`)&&Z.pathname!==$.graphqlEndpoint&&Z.pathname!==`${$.graphqlEndpoint}/`&&!F(E).test(Z)){if($.showLandingPage===!0&&B.method==="GET"&&!!B.headers?.get("accept")?.includes("text/html")){let J=D({request:B,fetchAPI:E,url:Z,graphqlEndpoint:$.graphqlEndpoint,get urlPattern(){return F(E)}});if(n1(J))return J.then(w);w(J);return}w(new E.Response("",{status:404,statusText:"Not Found"}))}}}}var U41=H1(K1(),1);async function Zu({request:$,result:A,fetchAPI:F,onResultProcessHooks:D,serverContext:B}){let E,w=[],Z="*/*";for(let J of D)await J({request:$,acceptableMediaTypes:w,result:A,setResult(Y){A=Y},resultProcessor:E,setResultProcessor(Y,W){E=Y,Z=W},serverContext:B});if(!E)return new F.Response(null,{status:406,statusText:"Not Acceptable",headers:{accept:w.join("; charset=utf-8, ")}});return E(A,F,Z)}async function H41({params:$,enveloped:A}){let F=A.parse($.query),D=A.validate(A.schema,F);if(D.length>0)return{errors:D};let B=await A.contextFactory(),E={schema:A.schema,document:F,contextValue:B,variableValues:$.variables,operationName:$.operationName};return(U41.getOperationAST(F,$.operationName)?.operation==="subscription"?A.subscribe:A.execute)(E)}var Q41=($,A,F=globalThis.process?.env?.NODE_ENV==="development")=>{if(f9($)){if($.originalError){if($.originalError.name==="GraphQLError")return $;let D={...$.extensions,unexpected:!0};if(F)D.originalError={message:$.originalError.message,stack:$.originalError.stack};return o(A,{nodes:$.nodes,source:$.source,positions:$.positions,path:$.path,extensions:D})}return $}return o(A,{extensions:{unexpected:!0,originalError:F?$ instanceof Error?{message:$.message,stack:$.stack}:$:void 0}})};class C41{getEnveloped;logger;graphqlEndpoint;fetchAPI;plugins;onRequestParseHooks;onParamsHooks;onExecutionResultHooks;onResultProcessHooks;maskedErrorsOpts;id;version="5.11.0";constructor($){if(this.id=$?.id??"yoga",this.fetchAPI={...OB},$?.fetchAPI){for(let Z in $.fetchAPI)if($.fetchAPI[Z])this.fetchAPI[Z]=$.fetchAPI[Z]}let A=$?.logging==null?!0:$.logging;this.logger=typeof A==="boolean"?A===!0?FY():FY("silent"):typeof A==="string"?FY(A):A;let F=typeof $?.maskedErrors==="object"&&$.maskedErrors.maskError||Q41,D=new WeakSet;this.maskedErrorsOpts=$?.maskedErrors===!1?null:{errorMessage:"Unexpected error.",...typeof $?.maskedErrors==="object"?$.maskedErrors:{},maskError:(Z,J)=>{if(D.has(Z))return Z;let Y=F(Z,J,this.maskedErrorsOpts?.isDev);if(Y!==Z)this.logger.error(Z);return D.add(Y),Y}};let B=this.maskedErrorsOpts==null?null:this.maskedErrorsOpts,E=0;if($?.batching)if(typeof $.batching==="boolean")E=10;else E=$.batching.limit??10;this.graphqlEndpoint=$?.graphqlEndpoint||"/graphql";let w=this.graphqlEndpoint;this.plugins=[Ae({parse:qA.parse,validate:qA.validate,execute:TY,subscribe:TY,specifiedRules:qA.specifiedRules}),!!$?.schema&&ht($.schema),$?.context!=null&&$e((Z)=>{if($?.context){if(typeof $.context==="function")return $.context(Z);return $.context}return{}}),n61({id:this.id,logger:this.logger,endpoint:$?.healthCheckEndpoint}),$?.cors!==!1&&L61($?.cors),$?.graphiql!==!1&&St({graphqlEndpoint:w,options:$?.graphiql,render:$?.renderGraphiQL,logger:this.logger}),GA({match:d61,parse:k61}),GA({match:_61,parse:p61}),$?.multipart!==!1&&GA({match:x61,parse:y61}),GA({match:f61,parse:b61}),GA({match:m61,parse:v61}),Y41(),S61((Z,J,Y)=>{let X={errors:hB(Z,this.maskedErrorsOpts,this.logger)};return Zu({request:J,result:X,fetchAPI:this.fetchAPI,onResultProcessHooks:this.onResultProcessHooks,serverContext:Y})}),...$?.plugins??[],{onPluginInit({addPlugin:Z}){if($?.parserAndValidationCache!==!1)Z($41(!$?.parserAndValidationCache||$?.parserAndValidationCache===!0?{}:$?.parserAndValidationCache));Z(i61(E)),Z(l61($?.extraParamNames));let J=!!($?.landingPage??!0);if(Z(X41({graphqlEndpoint:w,showLandingPage:J,landingPageRenderer:typeof $?.landingPage==="function"?$.landingPage:void 0})),Z(c61()),Z(s61()),B)Z({onSubscribe(){return{onSubscribeError({error:Y}){if(Bu(Y))throw Y}}}}),Z(eo(B));Z(a61())}}],this.getEnveloped=to({plugins:this.plugins}),this.plugins=this.getEnveloped._plugins,this.onRequestParseHooks=[],this.onParamsHooks=[],this.onExecutionResultHooks=[],this.onResultProcessHooks=[];for(let Z of this.plugins)if(Z){if(Z.onYogaInit)Z.onYogaInit({yoga:this});if(Z.onRequestParse)this.onRequestParseHooks.push(Z.onRequestParse);if(Z.onParams)this.onParamsHooks.push(Z.onParams);if(Z.onExecutionResult)this.onExecutionResultHooks.push(Z.onExecutionResult);if(Z.onResultProcess)this.onResultProcessHooks.push(Z.onResultProcess)}}handleParams=async({request:$,context:A,params:F})=>{let D;try{let B=A.request===$?{params:F}:{request:$,params:F};Object.assign(A,B);let E=this.getEnveloped(A);this.logger.debug("Processing GraphQL Parameters"),D=await H41({params:F,enveloped:E}),this.logger.debug("Processing GraphQL Parameters done.")}catch(B){D={errors:hB(B,this.maskedErrorsOpts,this.logger)}}if(I6(D))D=d9(D,(B)=>B,(B)=>{if(B.name==="AbortError")throw this.logger.debug("Request aborted"),B;return{errors:hB(B,this.maskedErrorsOpts,this.logger)}});return D};async getResultForParams({params:$,request:A},F){let D,B=this.handleParams;for(let E of this.onParamsHooks)await E({params:$,request:A,setParams(w){$=w},paramsHandler:B,setParamsHandler(w){B=w},setResult(w){D=w},fetchAPI:this.fetchAPI,context:F});D??=await B({request:A,params:$,context:F});for(let E of this.onExecutionResultHooks)await E({result:D,setResult(w){D=w},request:A,context:F});return D}handle=async($,A)=>{let F=new Proxy({},{get:(Z,J,Y)=>{return F=new this.fetchAPI.URL($.url,"http://localhost"),Reflect.get(F,J,F)}}),D,B=[];for(let Z of this.onRequestParseHooks){let J=await Z({request:$,url:F,requestParser:D,serverContext:A,setRequestParser(Y){D=Y}});if(J?.onRequestParseDone!=null)B.push(J.onRequestParseDone)}if(this.logger.debug("Parsing request to extract GraphQL parameters"),!D)return new this.fetchAPI.Response(null,{status:415,statusText:"Unsupported Media Type"});let E=await D($);for(let Z of B)await Z({requestParserResult:E,setRequestParserResult(J){E=J}});let w=await(Array.isArray(E)?Promise.all(E.map((Z)=>this.getResultForParams({params:Z,request:$},Object.create(A)))):this.getResultForParams({params:E,request:$},A));return Zu({request:$,result:w,fetchAPI:this.fetchAPI,onResultProcessHooks:this.onResultProcessHooks,serverContext:A})}}function G41($){let A=new C41($);return R61(A,{fetchAPI:A.fetchAPI,plugins:A.plugins})}var K41=({graphqlMiddleware:$,...A})=>{let F=G41({...A,schema:A.schema||co({typeDefs:A.typeDefs||"",resolvers:A.resolvers||{}})}),D=async(B)=>{let E=await(async()=>{if(!$)return F.handle(B.request,B);return $(async()=>F.handle(B.request,B),B.res)})();for(let[w,Z]of B.res.headers.entries()){if(w==="set-cookie"){E.headers.append("set-cookie",Z);continue}E.headers.set(w,Z)}return E};return(B)=>{B.get(A?.graphqlEndpoint||"/graphql",async(E)=>D(E)),B.post(A?.graphqlEndpoint||"/graphql",async(E)=>D(E))}};var q41=async($)=>{let A=$.config?.authentication?.roles||[];if(A.length===0)return;let D=(await $.controllers.database.getObjects({className:"Role",context:{isRoot:!0,wabe:$},select:{name:!0},where:{name:{in:A}}})).map((E)=>E?.name).filter(x2),B=A.filter((E)=>!D.includes(E)).map((E)=>({name:E}));if(B.length===0)return;await $.controllers.database.createObjects({className:"Role",context:{isRoot:!0,wabe:$},data:B,select:{}})};class Ju{adapter;constructor($){this.adapter=$}send($){return this.adapter.send($)}}class Yu{adapter;config;constructor($){this.adapter=$.adapter,this.config=$}deleteCoupon($){return this.adapter.deleteCoupon($)}updatePromotionCode($){return this.adapter.updatePromotionCode($)}createCoupon($){return this.adapter.createCoupon($)}createPromotionCode($){return this.adapter.createPromotionCode($)}getCustomerById($){return this.adapter.getCustomerById($)}validateWebhook($){return this.adapter.validateWebhook($)}createCustomer($){return this.adapter.createCustomer($)}createPayment($){return this.adapter.createPayment({...$,currency:this.config.currency,paymentMethod:this.config.supportedPaymentMethods})}cancelSubscription($){return this.adapter.cancelSubscription($)}getInvoices($){return this.adapter.getInvoices($)}getTotalRevenue($){return this.adapter.getTotalRevenue($)}getAllTransactions($){return this.adapter.getAllTransactions($)}getHypotheticalSubscriptionRevenue(){return this.adapter.getHypotheticalSubscriptionRevenue()}}var V41=H1(K1(),1),z41=new WeakMap,u41=($)=>{return{async onRequest({request:A}){let F=$?.isDisabled?await $.isDisabled(A):!0;z41.set(A,F)},onValidate({addValidationRule:A,context:F}){if(z41.get(F.request)??!0)A(V41.NoSchemaIntrospectionCustomRule)}}};class Wu{adapter;wabe;constructor($,A){this.adapter=$,this.wabe=A}uploadFile($){return this.adapter.uploadFile($)}readFile($,A){return this.adapter.readFile($,{...A,port:this.wabe.config.port})}deleteFile($){return this.adapter.deleteFile($)}}var P41=($)=>async(A)=>{let F=A.request.headers;if(F.get("Wabe-Root-Key")===$.config.rootKey){A.wabe={isRoot:!0,wabe:$,response:A.res};return}let D=()=>{if(F.get("Wabe-Access-Token"))return{accessToken:F.get("Wabe-Access-Token")};if(!!$.config.authentication?.session?.cookieSession)return{accessToken:Ru("accessToken",A.request.headers)};return{accessToken:null}},{accessToken:B}=D();if(!B){A.wabe={isRoot:!1,wabe:$,response:A.res};return}let E=new D4,{user:w,sessionId:Z,accessToken:J,refreshToken:Y}=await E.meFromAccessToken(B,{wabe:$,isRoot:!0});if(A.wabe={isRoot:!1,sessionId:Z,user:w,wabe:$,response:A.res},$.config.authentication?.session?.cookieSession&&J&&Y&&J!==B)A.res.setCookie("accessToken",J,{httpOnly:!0,path:"/",expires:E.getAccessTokenExpireAt($.config),sameSite:"None",secure:!0}),A.res.setCookie("refreshToken",Y,{httpOnly:!0,path:"/",expires:E.getAccessTokenExpireAt($.config),sameSite:"None",secure:!0})};var __dirname="/home/runner/work/wabe/wabe/packages/wabe/src/server";class il{server;config;controllers;constructor({isProduction:$,port:A,hostname:F,security:D,schema:B,database:E,authentication:w,rootKey:Z,codegen:J,hooks:Y,file:W,email:X,payment:U,routes:H,crons:Q}){this.config={isProduction:$,port:A,hostname:F,security:D,schema:B,database:E,codegen:J,authentication:w,rootKey:Z,hooks:Y,email:X,payment:U,routes:H,file:W,crons:Q},this.server=new az({hostname:F}).get("/health",(V)=>{V.res.status=200,V.res.send("OK")});let q=new Jq({databaseName:E.name,databaseUrl:E.url});this.controllers={database:new Yq(q),email:X?.adapter?new Ju(X.adapter):void 0,payment:U?.adapter?new Yu(U):void 0,file:W?.adapter?new Wu(W.adapter,this):void 0},this.loadCrons(),this.loadAuthenticationMethods(),this.loadRoleEnum(),this.loadRoutes(),this.loadHooks()}loadCrons(){if(!this.config.crons)return;let $=this.config.crons.map((A)=>({...A,job:A.cron(this)}));this.config.crons=$}loadRoleEnum(){let $=this.config.authentication?.roles||[];if($.length===0)return;let A={name:"RoleEnum",values:$.reduce((F,D)=>{return F[D]=D,F},{})};this.config.schema={...this.config.schema,enums:[...this.config.schema?.enums||[],A]}}loadAuthenticationMethods(){this.config.authentication={...this.config.authentication,customAuthenticationMethods:[...Mt(),...this.config.authentication?.customAuthenticationMethods||[]]}}loadHooks(){if(this.config.hooks?.find(($)=>$.priority<=0))throw new Error("Hook priority <= 0 is reserved for internal uses");this.config.hooks=[...wc(),...this.config.hooks||[]]}loadRoutes(){[...Ct(this.config.file?.devDirectory||`${__dirname}/../../bucket`),...this.config.routes||[]].map((A)=>{let{method:F}=A;switch(F){case"GET":this.server.get(A.path,A.handler);break;case"POST":this.server.post(A.path,A.handler);break;case"PUT":this.server.put(A.path,A.handler);break;case"DELETE":this.server.delete(A.path,A.handler);break;default:throw new Error("Invalid method for default route")}})}async start(){await this.controllers.database.connect();let $=new Yz(this.config);this.config.schema=$.schema;let F=new yz($).createSchema();if(this.config.graphqlSchema=new kB.GraphQLSchema({query:new kB.GraphQLObjectType({name:"Query",fields:F.queries}),mutation:new kB.GraphQLObjectType({name:"Mutation",fields:F.mutations}),types:[...F.scalars,...F.enums,...F.objects]}),!this.config.isProduction&&!0&&this.config.codegen&&this.config.codegen.enabled&&this.config.codegen.path.length>0){if(await Vt({path:this.config.codegen.path,schema:$.schema,graphqlSchema:this.config.graphqlSchema}),process.env.CODEGEN)process.exit(0)}this.server.options("/*",(B)=>{return B.res.send("OK")},iz(this.config.security?.corsOptions));let D=this.config.security?.rateLimit;if(D)this.server.beforeHandler(Xt(D));this.server.beforeHandler(iz(this.config.security?.corsOptions)),this.server.beforeHandler(this.config.authentication.sessionHandler||P41(this)),this.server.usePlugin(K41({schema:this.config.graphqlSchema,maskedErrors:this.config.security?.maskErrorMessage||this.config.isProduction,graphqlEndpoint:"/graphql",plugins:this.config.isProduction?[u41()]:[],context:async(B)=>B.wabe})),await Promise.all([q41(this)]),this.server.listen(this.config.port,({port:B})=>{if(!process.env.TEST)console.log(`Server is running on port ${B}`)})}async close(){await this.controllers.database.close(),this.server.stop()}}function J6($,A,F,D,B,E,w,Z){return J6.fromTZ(J6.tp($,A,F,D,B,E,w),Z)}J6.fromTZISO=($,A,F)=>J6.fromTZ(gr1($,A),F);J6.fromTZ=function($,A){let F=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),D=Xu($.tz,F),B=new Date(F.getTime()-D),E=Xu($.tz,B);if(E-D===0)return B;{let w=new Date(F.getTime()-E),Z=Xu($.tz,w);if(Z-E===0)return w;if(!A&&Z-E>0)return w;if(A)throw new Error("Invalid date passed to fromTZ()");return B}};J6.toTZ=function($,A){let F=$.toLocaleString("en-US",{timeZone:A}).replace(/[\u202f]/," "),D=new Date(F);return{y:D.getFullYear(),m:D.getMonth()+1,d:D.getDate(),h:D.getHours(),i:D.getMinutes(),s:D.getSeconds(),tz:A}};J6.tp=($,A,F,D,B,E,w)=>({y:$,m:A,d:F,h:D,i:B,s:E,tz:w});function Xu($,A=new Date){let F=A.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],D=A.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${D} GMT`)-Date.parse(`${D} ${F}`)}function gr1($,A){let F=new Date(Date.parse($));if(isNaN(F))throw new Error("minitz: Invalid ISO8601 passed to parser.");let D=$.substring(9);return $.includes("Z")||D.includes("-")||D.includes("+")?J6.tp(F.getUTCFullYear(),F.getUTCMonth()+1,F.getUTCDate(),F.getUTCHours(),F.getUTCMinutes(),F.getUTCSeconds(),"Etc/UTC"):J6.tp(F.getFullYear(),F.getMonth()+1,F.getDate(),F.getHours(),F.getMinutes(),F.getSeconds(),A)}J6.minitz=J6;var Uu=32,vB=31|Uu,R41=[1,2,4,8,16],M41=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,A){this.pattern=$,this.timezone=A,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw new TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw new TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let A=new x4(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",A.getSeconds().toString()),$[1]=$[1].replace("?",A.getMinutes().toString()),$[2]=$[2].replace("?",A.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",A.getDate().toString())),$[4]=$[4].replace("?",(A.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",A.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,vB),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,A,F,D){let B=this[$],E=$==="day"&&this.lastDayOfMonth;if(A===""&&!E)throw new TypeError("CronPattern: configuration entry "+$+" ("+A+") is empty, check for trailing spaces.");if(A==="*")return B.fill(D);let w=A.split(",");if(w.length>1)for(let Z=0;Z<w.length;Z++)this.partToArray($,w[Z],F,D);else A.indexOf("-")!==-1&&A.indexOf("/")!==-1?this.handleRangeWithStepping(A,$,F,D):A.indexOf("-")!==-1?this.handleRange(A,$,F,D):A.indexOf("/")!==-1?this.handleStepping(A,$,F,D):A!==""&&this.handleNumber(A,$,F,D)}throwAtIllegalCharacters($){for(let A=0;A<$.length;A++)if((A===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[A]))throw new TypeError("CronPattern: configuration entry "+A+" ("+$[A]+") contains illegal characters.")}handleNumber($,A,F,D){let B=this.extractNth($,A),E=parseInt(B[0],10)+F;if(isNaN(E))throw new TypeError("CronPattern: "+A+" is not a number: '"+$+"'");this.setPart(A,E,B[1]||D)}setPart($,A,F){if(!Object.prototype.hasOwnProperty.call(this,$))throw new TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(A===7&&(A=0),A<0||A>6)throw new RangeError("CronPattern: Invalid value for dayOfWeek: "+A);this.setNthWeekdayOfMonth(A,F);return}if($==="second"||$==="minute"){if(A<0||A>=60)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="hour"){if(A<0||A>=24)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="day"){if(A<0||A>=31)throw new RangeError("CronPattern: Invalid value for "+$+": "+A)}else if($==="month"&&(A<0||A>=12))throw new RangeError("CronPattern: Invalid value for "+$+": "+A);this[$][A]=F}handleRangeWithStepping($,A,F,D){let B=this.extractNth($,A),E=B[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(E===null)throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,w,Z,J]=E,Y=parseInt(w,10)+F,W=parseInt(Z,10)+F,X=parseInt(J,10);if(isNaN(Y))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(W))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(X))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(X===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(X>this[A].length)throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[A].length+")");if(Y>W)throw new TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let U=Y;U<=W;U+=X)this.setPart(A,U,B[1]||D)}extractNth($,A){let F=$,D;if(F.includes("#")){if(A!=="dayOfWeek")throw new Error("CronPattern: nth (#) only allowed in day-of-week field");D=F.split("#")[1],F=F.split("#")[0]}return[F,D]}handleRange($,A,F,D){let B=this.extractNth($,A),E=B[0].split("-");if(E.length!==2)throw new TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let w=parseInt(E[0],10)+F,Z=parseInt(E[1],10)+F;if(isNaN(w))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(w>Z)throw new TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let J=w;J<=Z;J++)this.setPart(A,J,B[1]||D)}handleStepping($,A,F,D){let B=this.extractNth($,A),E=B[0].split("/");if(E.length!==2)throw new TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");E[0]===""&&(E[0]="*");let w=0;E[0]!=="*"&&(w=parseInt(E[0],10)+F);let Z=parseInt(E[1],10);if(isNaN(Z))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[A].length)throw new TypeError("CronPattern: Syntax error, max steps for part is ("+this[A].length+")");for(let J=w;J<this[A].length;J+=Z)this.setPart(A,J,B[1]||D)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let A=$.trim().toLowerCase();return A==="@yearly"||A==="@annually"?"0 0 1 1 *":A==="@monthly"?"0 0 1 * *":A==="@weekly"?"0 0 * * 0":A==="@daily"?"0 0 * * *":A==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,A){if(typeof A!="number"&&A==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|Uu;else if(A===vB)this.dayOfWeek[$]=vB;else if(A<6&&A>0)this.dayOfWeek[$]=this.dayOfWeek[$]|R41[A-1];else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${A}, Type: ${typeof A}`)}},I41=[31,28,31,30,31,30,31,31,30,31,30,31],_9=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],x4=class ${tz;ms;second;minute;hour;day;month;year;constructor(A,F){if(this.tz=F,A&&A instanceof Date)if(!isNaN(A))this.fromDate(A);else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");else if(A===void 0)this.fromDate(new Date);else if(A&&typeof A=="string")this.fromString(A);else if(A instanceof $)this.fromCronDate(A);else throw new TypeError("CronDate: Invalid type ("+typeof A+") passed to CronDate constructor")}isNthWeekdayOfMonth(A,F,D,B){let E=new Date(Date.UTC(A,F,D)).getUTCDay(),w=0;for(let Z=1;Z<=D;Z++)new Date(Date.UTC(A,F,Z)).getUTCDay()===E&&w++;if(B&vB&&R41[w-1]&B)return!0;if(B&Uu){let Z=new Date(Date.UTC(A,F+1,0)).getUTCDate();for(let J=D+1;J<=Z;J++)if(new Date(Date.UTC(A,F,J)).getUTCDay()===E)return!1;return!0}return!1}fromDate(A){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=A.getUTCMilliseconds(),this.second=A.getUTCSeconds(),this.minute=A.getUTCMinutes()+this.tz,this.hour=A.getUTCHours(),this.day=A.getUTCDate(),this.month=A.getUTCMonth(),this.year=A.getUTCFullYear(),this.apply();else{let F=J6.toTZ(A,this.tz);this.ms=A.getMilliseconds(),this.second=F.s,this.minute=F.i,this.hour=F.h,this.day=F.d,this.month=F.m-1,this.year=F.y}else this.ms=A.getMilliseconds(),this.second=A.getSeconds(),this.minute=A.getMinutes(),this.hour=A.getHours(),this.day=A.getDate(),this.month=A.getMonth(),this.year=A.getFullYear()}fromCronDate(A){this.tz=A.tz,this.year=A.year,this.month=A.month,this.day=A.day,this.hour=A.hour,this.minute=A.minute,this.second=A.second,this.ms=A.ms}apply(){if(this.month>11||this.day>I41[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let A=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=A.getUTCMilliseconds(),this.second=A.getUTCSeconds(),this.minute=A.getUTCMinutes(),this.hour=A.getUTCHours(),this.day=A.getUTCDate(),this.month=A.getUTCMonth(),this.year=A.getUTCFullYear(),!0}else return!1}fromString(A){if(typeof this.tz=="number"){let F=J6.fromTZISO(A);this.ms=F.getUTCMilliseconds(),this.second=F.getUTCSeconds(),this.minute=F.getUTCMinutes(),this.hour=F.getUTCHours(),this.day=F.getUTCDate(),this.month=F.getUTCMonth(),this.year=F.getUTCFullYear(),this.apply()}else return this.fromDate(J6.fromTZISO(A,this.tz))}findNext(A,F,D,B){let E=this[F],w;D.lastDayOfMonth&&(this.month!==1?w=I41[this.month]:w=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!D.starDOW&&F=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let J=this[F]+B;J<D[F].length;J++){let Y=D[F][J];if(F==="day"&&D.lastDayOfMonth&&J-B==w&&(Y=1),F==="day"&&!D.starDOW){let W=D.dayOfWeek[(Z+(J-B-1))%7];if(W&&W&vB)W=this.isNthWeekdayOfMonth(this.year,this.month,J-B,W)?1:0;else if(W)throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${W}`);A.legacyMode&&!D.starDOM?Y=Y||W:Y=Y&&W}if(Y)return this[F]=J-B,E!==this[F]?2:1}return 3}recurse(A,F,D){let B=this.findNext(F,_9[D][0],A,_9[D][2]);if(B>1){let E=D+1;for(;E<_9.length;)this[_9[E][0]]=-_9[E][2],E++;if(B===3)return this[_9[D][1]]++,this[_9[D][0]]=-_9[D][2],this.apply(),this.recurse(A,F,0);if(this.apply())return this.recurse(A,F,D-1)}return D+=1,D>=_9.length?this:this.year>=3000?null:this.recurse(A,F,D)}increment(A,F,D){return this.second+=F.interval!==void 0&&F.interval>1&&D?F.interval:1,this.ms=0,this.apply(),this.recurse(A,F,0)}getDate(A){return A||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):J6.fromTZ(J6.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xr1($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new x4($.startAt,$.timezone)),$.stopAt&&($.stopAt=new x4($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw new Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw new Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw new Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw new Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function mB($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function yr1($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var j41=30000,FW=[],L41=class{name;options;_states;fn;constructor($,A,F){let D,B;if(mB(A))B=A;else if(typeof A=="object")D=A;else if(A!==void 0)throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(mB(F))B=F;else if(typeof F=="object")D=F;else if(F!==void 0)throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=D?.name,this.options=xr1(D),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:D?D.maxRuns:void 0,paused:D?D.paused:!1,pattern:new M41("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new x4($,this.options.timezone||this.options.utcOffset):this._states.pattern=new M41($,this.options.timezone),this.name){if(FW.find((E)=>E.name===this.name))throw new Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");FW.push(this)}return B!==void 0&&mB(B)&&(this.fn=B,this.schedule()),this}nextRun($){let A=this._next($);return A?A.getDate(!1):null}nextRuns($,A){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let F=[],D=A||this._states.currentRun||void 0;for(;$--&&(D=this.nextRun(D));)F.push(D);return F}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),A=!this._states.paused,F=this.fn!==void 0,D=!this._states.kill;return A&&F&&D&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){$=$||new Date;let A=this._next($);return A?$ instanceof x4||$ instanceof Date?A.getTime()-$.getTime():A.getTime()-new x4($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=FW.indexOf(this);$>=0&&FW.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let A=this.msToNext(),F=this.nextRun(this._states.currentRun);return A==null||isNaN(A)||F===null?this:(A>j41&&(A=j41),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(F),A),this._states.currentTimeout&&this.options.unref&&yr1(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new x4(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(A){mB(this.options.catch)&&this.options.catch(A,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new x4($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let A=new Date,F=!this._states.paused&&A.getTime()>=$.getTime(),D=this._states.blocking&&this.options.protect;F&&!D?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):F&&D&&mB(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let A=!!($||this._states.currentRun),F=!1;!$&&this.options.startAt&&this.options.interval&&([$,A]=this._calculatePreviousRun($,A),F=!$),$=new x4($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let D=this._states.once||new x4($,this.options.timezone||this.options.utcOffset);return!F&&D!==this._states.once&&(D=D.increment(this._states.pattern,this.options,A)),this._states.once&&this._states.once.getTime()<=$.getTime()||D===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&D.getTime()>=this.options.stopAt.getTime()?null:D}_calculatePreviousRun($,A){let F=new x4(void 0,this.options.timezone||this.options.utcOffset),D=$;if(this.options.startAt.getTime()<=F.getTime()){D=this.options.startAt;let B=D.getTime()+this.options.interval*1000;for(;B<=F.getTime();)D=new x4(D,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),B=D.getTime()+this.options.interval*1000;A=!0}return D===null&&(D=void 0),[D,A]}};var BU0=({pattern:$,run:A,maxRuns:F,enabledProtectedRuns:D})=>(B)=>new L41($,{maxRuns:F,protect:D},()=>A(B)),lr1;((V)=>{V.EVERY_SECOND="* * * * * *";V.EVERY_MINUTE="0 * * * * *";V.EVERY_HOUR="0 0 * * * *";V.EVERY_DAY_AT_MIDNIGHT="0 0 0 * * *";V.EVERY_WEEK="0 0 0 * * 0";V.EVERY_MONTH="0 0 0 1 * *";V.EVERY_YEAR="0 0 0 1 1 *";V.WEEKDAYS_MORNING="0 0 7 * * 1-5";V.WEEKENDS_EVENING="0 0 19 * * 6-7";V.FIRST_DAY_OF_MONTH="0 0 0 1 * *";V.LAST_DAY_OF_MONTH="0 0 0 L * *";V.EVERY_15_MINUTES="0 */15 * * * *";V.EVERY_30_MINUTES="0 */30 * * * *";V.EVERY_2_HOURS="0 0 */2 * * *";V.EVERY_6_HOURS="0 0 */6 * * *";V.EVERY_12_HOURS="0 0 */12 * * *"})(lr1||={});export{n3 as initializeHook,wc as getDefaultHooks,Vt as generateCodegen,Ct as defaultRoutes,BU0 as cron,R1 as contextWithRoot,i3 as buildMongoWhereQuery,_k1 as buildMongoOrderQuery,Ec as _findHooksByPriority,il as Wabe,Wq as SecondaryFactor,Yz as Schema,Zc as ProviderEnum,gk1 as PaymentReccuringInterval,pk1 as PaymentMode,pl as PaymentDevAdapter,yB as OperationType,fD as OAuth2Client,Jq as MongoAdapter,bD as Google,cl as FileDevAdapter,gl as EmailDevAdapter,_l as DatabaseEnum,Yq as DatabaseController,xl as Currency,lr1 as CronExpressions,O$ as AuthenticationProvider};
@@ -22,6 +22,8 @@ type SecurityConfig = {
22
22
  rateLimit?: RateLimitOptions
23
23
  maskErrorMessage?: boolean
24
24
  };
25
+ export * from "./interface";
26
+ export * from "./routes";
25
27
  export interface WabeConfig<T extends WabeTypes> {
26
28
  port: number;
27
29
  isProduction: boolean;
@@ -0,0 +1,9 @@
1
+ import type { WobeResponse } from "wobe";
2
+ import type { Wabe, WabeTypes } from ".";
3
+ export interface WabeContext<T extends WabeTypes> {
4
+ response?: WobeResponse;
5
+ user?: T["types"]["User"] | null;
6
+ sessionId?: string | null;
7
+ isRoot: boolean;
8
+ wabe: Wabe<T>;
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wabe",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
4
4
  "description": "Your backend in minutes not days",
5
5
  "homepage": "https://wabe.dev",
6
6
  "author": {