better-auth-instantdb 1.3.2 → 1.3.3
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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InstantAdminDatabase } from '@instantdb/admin';
|
|
2
|
-
import { DBAdapterDebugLogOption, Where } from 'better-auth/adapters';
|
|
2
|
+
import { createAdapterFactory, DBAdapterDebugLogOption, Where } from 'better-auth/adapters';
|
|
3
3
|
/**
|
|
4
4
|
* The InstantDB adapter config options.
|
|
5
5
|
*/
|
|
@@ -20,6 +20,6 @@ interface InstantAdapterConfig {
|
|
|
20
20
|
/**
|
|
21
21
|
* The InstantDB adapter.
|
|
22
22
|
*/
|
|
23
|
-
export declare const instantAdapter: ({ db, usePlural, debugLogs }: InstantAdapterConfig) =>
|
|
23
|
+
export declare const instantAdapter: ({ db, usePlural, debugLogs }: InstantAdapterConfig) => ReturnType<typeof createAdapterFactory>;
|
|
24
24
|
export declare function parseWhere(where?: Where[]): Record<string, unknown>;
|
|
25
25
|
export {};
|
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k={Remove:"remove",Replace:"replace",Add:"add"},Pe=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),de=Symbol.iterator,K={mutable:"mutable",immutable:"immutable"},Ae={};function ae(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Me(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,t);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function ze(e){return Object.getPrototypeOf(e)===Set.prototype}function qe(e){return Object.getPrototypeOf(e)===Map.prototype}function F(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function ye(e){return!!v(e)}function v(e){return typeof e!="object"?null:e?.[Pe]}function Ie(e){var t;const n=v(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function Q(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!t?.mark&&((n=t.mark(e,K))===K.immutable||typeof n=="function")}function Ve(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,r=v(J(n,e.key));if(r!==null&&r?.original!==e.original)return null;const i=e.parent.type===3,o=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>o||ae(n,o)))return null;t.push(o)}if(e.parent)return Ve(e.parent,t);t.reverse();try{Qe(e.copy,t)}catch{return null}return t}function le(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function J(e,t){return le(e)===2?e.get(t):e[t]}function Te(e,t,n){le(e)===2?e.set(t,n):e[t]=n}function we(e,t){const n=v(e);return(n?F(n):e)[t]}function Z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function X(e,t){return t?e:[""].concat(e).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Qe(e,t){for(let n=0;n<t.length-1;n+=1){const r=t[n];if(e=J(le(e)===3?Array.from(e):e,r),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function et(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(e,n);if(r.enumerable&&r.configurable&&r.writable){t[n]=e[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:e[n]}),Reflect.defineProperty(t,n,r)}),t}const tt=Object.prototype.propertyIsEnumerable;function nt(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!ze(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!qe(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e)}return new Map(e)}else if(t?.mark&&(n=t.mark(e,K),n!==void 0)&&n!==K.mutable){if(n===K.immutable)return et(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const r={};return Object.keys(e).forEach(i=>{r[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{tt.call(e,i)&&(r[i]=e[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function q(e){e.copy||(e.copy=nt(e.original,e.options))}function oe(e){if(!Q(e))return Ie(e);if(Array.isArray(e))return e.map(oe);if(e instanceof Map){const n=Array.from(e.entries()).map(([r,i])=>[r,oe(i)]);if(!qe(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(oe);if(!ze(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=oe(e[n]);return t}function pe(e){return ye(e)?oe(e):e}function W(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&W(e.parent))}function rt(e,t){const n=le(e);if(n===0)Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)});else if(n===1){let r=0;for(const i of e)t(r,i,e),r+=1}else e.forEach((r,i)=>t(i,r,e))}function Fe(e,t,n){if(ye(e)||!Q(e,n)||t.has(e)||Object.isFrozen(e))return;const r=e instanceof Set,i=r?new Map:void 0;if(t.add(e),rt(e,(o,f)=>{var s;if(ye(f)){const a=v(f);q(a);const c=!((s=a.assignedMap)===null||s===void 0)&&s.size||a.operated?a.copy:a.original;Te(r?i:e,o,c)}else Fe(f,t,n)}),i){const o=e,f=Array.from(o);o.clear(),f.forEach(s=>{o.add(i.has(s)?i.get(s):s)})}}function it(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Fe(J(n,t),e.finalities.handledSet,e.options)}function _e(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(Ie(t))}))}function Oe(e,t,n,r){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&r){const o=Ve(e);o&&t(e,o,n,r)}e.finalized=!0}}function Re(e,t,n,r){const i=v(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((o,f)=>{var s;const a=e.type===3?e.setMap:e.copy;if(Z(J(a,t),n)){let c=i.original;i.copy&&(c=i.copy),_e(e),Oe(e,r,o,f),e.options.enableAutoFreeze&&(e.options.updatedValues=(s=e.options.updatedValues)!==null&&s!==void 0?s:new WeakMap,e.options.updatedValues.set(c,i.original)),Te(a,t,c)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),Q(n,e.options)&&e.finalities.draft.push(()=>{const o=e.type===3?e.setMap:e.copy;Z(J(o,t),n)&&it(e,t)})}function ot(e,t,n,r,i){let{original:o,assignedMap:f,options:s}=e,a=e.copy;a.length<o.length&&([o,a]=[a,o],[n,r]=[r,n]);for(let c=0;c<o.length;c+=1)if(f.get(c.toString())&&a[c]!==o[c]){const l=t.concat([c]),y=X(l,i);n.push({op:k.Replace,path:y,value:pe(a[c])}),r.push({op:k.Replace,path:y,value:pe(o[c])})}for(let c=o.length;c<a.length;c+=1){const l=t.concat([c]),y=X(l,i);n.push({op:k.Add,path:y,value:pe(a[c])})}if(o.length<a.length){const{arrayLengthAssignment:c=!0}=s.enablePatches;if(c){const l=t.concat(["length"]),y=X(l,i);r.push({op:k.Replace,path:y,value:o.length})}else for(let l=a.length;o.length<l;l-=1){const y=t.concat([l-1]),w=X(y,i);r.push({op:k.Remove,path:w})}}}function st({original:e,copy:t,assignedMap:n},r,i,o,f){n.forEach((s,a)=>{const c=J(e,a),l=pe(J(t,a)),y=s?ae(e,a)?k.Replace:k.Add:k.Remove;if(Z(c,l)&&y===k.Replace)return;const w=r.concat(a),S=X(w,f);i.push(y===k.Remove?{op:y,path:S}:{op:y,path:S,value:l}),o.push(y===k.Add?{op:k.Remove,path:S}:y===k.Remove?{op:k.Add,path:S,value:c}:{op:k.Replace,path:S,value:c})})}function at({original:e,copy:t},n,r,i,o){let f=0;e.forEach(s=>{if(!t.has(s)){const a=n.concat([f]),c=X(a,o);r.push({op:k.Remove,path:c,value:s}),i.unshift({op:k.Add,path:c,value:s})}f+=1}),f=0,t.forEach(s=>{if(!e.has(s)){const a=n.concat([f]),c=X(a,o);r.push({op:k.Add,path:c,value:s}),i.unshift({op:k.Remove,path:c,value:s})}f+=1})}function ce(e,t,n,r){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return st(e,t,n,r,i);case 1:return ot(e,t,n,r,i);case 3:return at(e,t,n,r,i)}}const he=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!Q(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},$e={get size(){return F(v(this)).size},has(e){return F(v(this)).has(e)},set(e,t){const n=v(this),r=F(n);return(!r.has(e)||!Z(r.get(e),t))&&(q(n),W(n),n.assignedMap.set(e,!0),n.copy.set(e,t),Re(n,e,t,ce)),this},delete(e){if(!this.has(e))return!1;const t=v(this);return q(t),W(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=v(this);if(this.size){q(e),W(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=v(this);F(n).forEach((r,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const r=v(this),i=F(r).get(e),o=((n=(t=r.options).mark)===null||n===void 0?void 0:n.call(t,i,K))===K.mutable;if(r.options.strict&&he(i,r.options,o),o||r.finalized||!Q(i,r.options)||i!==r.original.get(e))return i;const f=Ae.createDraft({original:i,parentDraft:r,key:e,finalities:r.finalities,options:r.options});return q(r),r.copy.set(e,f),f},keys(){return F(v(this)).keys()},values(){const e=this.keys();return{[de]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[de]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[de](){return this.entries()}},ut=Reflect.ownKeys($e),xe=(e,t,{isValuesIterator:n})=>()=>{var r,i;const o=t.next();if(o.done)return o;const f=o.value;let s=e.setMap.get(f);const a=v(s),c=((i=(r=e.options).mark)===null||i===void 0?void 0:i.call(r,s,K))===K.mutable;if(e.options.strict&&he(f,e.options,c),!c&&!a&&Q(f,e.options)&&!e.finalized&&e.original.has(f)){const l=Ae.createDraft({original:f,parentDraft:e,key:f,finalities:e.finalities,options:e.options});e.setMap.set(f,l),s=l}else a&&(s=a.proxy);return{done:!1,value:n?s:[s,s]}},be={get size(){return v(this).setMap.size},has(e){const t=v(this);if(t.setMap.has(e))return!0;q(t);const n=v(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=v(this);return this.has(e)||(q(t),W(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),Re(t,e,e,ce)),this},delete(e){if(!this.has(e))return!1;const t=v(this);q(t),W(t);const n=v(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=v(this);q(e),W(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=v(this);q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:xe(e,t,{isValuesIterator:!0})}},entries(){const e=v(this);q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:xe(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[de](){return this.values()},forEach(e,t){const n=this.values();let r=n.next();for(;!r.done;)e.call(t,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(be,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const ct=Reflect.ownKeys(be),Ue={get(e,t,n){var r,i;const o=(r=e.copy)===null||r===void 0?void 0:r[t];if(o&&e.finalities.draftsCache.has(o))return o;if(t===Pe)return e;let f;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(f=e.options.mark(c,K),f===K.mutable)return e.options.strict&&he(c,e.options,!0),c}const s=F(e);if(s instanceof Map&&ut.includes(t))return t==="size"?Object.getOwnPropertyDescriptor($e,"size").get.call(e.proxy):$e[t].bind(e.proxy);if(s instanceof Set&&ct.includes(t))return t==="size"?Object.getOwnPropertyDescriptor(be,"size").get.call(e.proxy):be[t].bind(e.proxy);if(!ae(s,t)){const c=Me(s,t);return c?"value"in c?c.value:(i=c.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const a=s[t];if(e.options.strict&&he(a,e.options),e.finalized||!Q(a,e.options))return a;if(a===we(e.original,t)){if(q(e),e.copy[t]=Be({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof f=="function"){const c=v(e.copy[t]);return q(c),W(c),c.copy}return e.copy[t]}return ye(a)&&e.finalities.draftsCache.add(a),a},set(e,t,n){var r;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const o=Me(F(e),t);if(o?.set)return o.set.call(e.proxy,n),!0;const f=we(F(e),t),s=v(f);return s&&Z(s.original,n)?(e.copy[t]=n,e.assignedMap=(r=e.assignedMap)!==null&&r!==void 0?r:new Map,e.assignedMap.set(t,!1),!0):(Z(n,f)&&(n!==void 0||ae(e.original,t))||(q(e),W(e),ae(e.original,t)&&Z(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,Re(e,t,n,ce)),!0)},has(e,t){return t in F(e)},ownKeys(e){return Reflect.ownKeys(F(e))},getOwnPropertyDescriptor(e,t){const n=F(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?Ue.set.call(this,e,t,void 0,e.proxy):(we(e.original,t)!==void 0||t in e.original?(q(e),W(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function Be(e){const{original:t,parentDraft:n,key:r,finalities:i,options:o}=e,f=le(t),s={type:f,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:o,setMap:f===3?new Map(t.entries()):void 0};(r||"key"in e)&&(s.key=r);const{proxy:a,revoke:c}=Proxy.revocable(f===1?Object.assign([],s):s,Ue);if(i.revoke.push(c),s.proxy=a,n){const l=n;l.finalities.draft.push((y,w)=>{var S,C;const x=v(a);let E=l.type===3?l.setMap:l.copy;const B=J(E,r),V=v(B);if(V){let u=V.original;V.operated&&(u=Ie(B)),_e(V),Oe(V,ce,y,w),l.options.enableAutoFreeze&&(l.options.updatedValues=(S=l.options.updatedValues)!==null&&S!==void 0?S:new WeakMap,l.options.updatedValues.set(u,V.original)),Te(E,r,u)}(C=x.callbacks)===null||C===void 0||C.forEach(u=>{u(y,w)})})}else{const l=v(a);l.finalities.draft.push((y,w)=>{_e(l),Oe(l,ce,y,w)})}return a}Ae.createDraft=Be;Object.prototype.constructor.toString();const P=[];for(let e=0;e<256;++e)P.push((e+256).toString(16).slice(1));function lt(e,t=0){return(P[e[t+0]]+P[e[t+1]]+P[e[t+2]]+P[e[t+3]]+"-"+P[e[t+4]]+P[e[t+5]]+"-"+P[e[t+6]]+P[e[t+7]]+"-"+P[e[t+8]]+P[e[t+9]]+"-"+P[e[t+10]]+P[e[t+11]]+P[e[t+12]]+P[e[t+13]]+P[e[t+14]]+P[e[t+15]]).toLowerCase()}let ge;const ft=new Uint8Array(16);function dt(){if(!ge){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ge=crypto.getRandomValues.bind(crypto)}return ge(ft)}const pt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),je={randomUUID:pt};function mt(e,t,n){if(je.randomUUID&&!e)return je.randomUUID();e=e||{};const r=e.random??e.rng?.()??dt();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,lt(r)}function yt(){return mt()}function ht(e,t){return e.localeCompare(t)}function bt(){let e=ht;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}bt();function wt(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const gt=wt();function ve(e,t,n){const r={__etype:e,__ops:n};return new Proxy(r,{get:(i,o)=>{if(o==="__ops")return n;if(o==="__etype")return e;if(gt.has(o))return(f,s)=>ve(e,t,[...n,s?[o,e,t,f,s]:[o,e,t,f]])}})}function _t(e){return e.startsWith("lookup__")}function Ot(e){const[t,n,...r]=e.split("__");return[n,JSON.parse(r.join("__"))]}function $t(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const r=n;return _t(r)?ve(e,Ot(r),[]):ve(e,r,[])}})}function vt(){return new Proxy({},{get(e,t){return $t(t)}})}vt();const Nt={"unique?":!0,"index?":!0};Object.assign(Object.assign({},Nt),{cardinality:"one"});typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));function St(){var e;return globalThis.__instantDbSchemaHashStore=(e=globalThis.__instantDbSchemaHashStore)!==null&&e!==void 0?e:new WeakMap,globalThis.__instantDbSchemaHashStore}function At(){var e;return globalThis.__instantDbStore=(e=globalThis.__instantDbStore)!==null&&e!==void 0?e:{},globalThis.__instantDbStore}At();St();const me=Object.create(null),ne=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?me:globalThis),re=new Proxy(me,{get(e,t){return ne()[t]??me[t]},has(e,t){const n=ne();return t in n||t in me},set(e,t,n){const r=ne(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;const n=ne(!0);return delete n[t],!0},ownKeys(){const e=ne(!0);return Object.keys(e)}});typeof process<"u"&&process.env&&process.env.NODE_ENV;function M(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}const ie=1,L=4,G=8,U=24,ke={eterm:L,cons25:L,console:L,cygwin:L,dtterm:L,gnome:L,hurd:L,jfbterm:L,konsole:L,kterm:L,mlterm:L,mosh:U,putty:L,st:L,"rxvt-unicode-24bit":U,terminator:U,"xterm-kitty":U},It=new Map(Object.entries({APPVEYOR:G,BUILDKITE:G,CIRCLECI:U,DRONE:G,GITEA_ACTIONS:U,GITHUB_ACTIONS:U,GITLAB_CI:G,TRAVIS:G})),Tt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Ke(){if(M("FORCE_COLOR")!==void 0)switch(M("FORCE_COLOR")){case"":case"1":case"true":return L;case"2":return G;case"3":return U;default:return ie}if(M("NODE_DISABLE_COLORS")!==void 0&&M("NODE_DISABLE_COLORS")!==""||M("NO_COLOR")!==void 0&&M("NO_COLOR")!==""||M("TERM")==="dumb")return ie;if(M("TMUX"))return U;if("TF_BUILD"in re&&"AGENT_NAME"in re)return L;if("CI"in re){for(const{0:e,1:t}of It)if(e in re)return t;return M("CI_NAME")==="codeship"?G:ie}if("TEAMCITY_VERSION"in re)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(M("TEAMCITY_VERSION"))!==null?L:ie;switch(M("TERM_PROGRAM")){case"iTerm.app":return!M("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(M("TERM_PROGRAM_VERSION"))!==null?G:U;case"HyperTerm":case"MacTerm":return U;case"Apple_Terminal":return G}if(M("COLORTERM")==="truecolor"||M("COLORTERM")==="24bit")return U;if(M("TERM")){if(/truecolor/.exec(M("TERM"))!==null)return U;if(/^xterm-256/.exec(M("TERM"))!==null)return G;const e=M("TERM").toLowerCase();if(ke[e])return ke[e];if(Tt.some(t=>t.exec(e)!==null))return L}return M("COLORTERM")?L:ie}const D={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",fg:{red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m"},bg:{black:"\x1B[40m"}},Ne=["info","success","warn","error","debug"];function Rt(e,t){return Ne.indexOf(t)<=Ne.indexOf(e)}const Et={info:D.fg.blue,success:D.fg.green,warn:D.fg.yellow,error:D.fg.red,debug:D.fg.magenta},Mt=(e,t,n)=>{const r=new Date().toISOString();return n?`${D.dim}${r}${D.reset} ${Et[e]}${e.toUpperCase()}${D.reset} ${D.bright}[Better Auth]:${D.reset} ${t}`:`${r} ${e.toUpperCase()} [Better Auth]: ${t}`},xt=e=>{const t="error",n=Ke()!==1,r=(o,f,s=[])=>{if(!Rt(t,o))return;const a=Mt(o,f,n);{o==="error"?console.error(a,...s):o==="warn"?console.warn(a,...s):console.log(a,...s);return}};return{...Object.fromEntries(Ne.map(o=>[o,(...[f,...s])=>r(o,f,s)])),get level(){return t}}},Y=xt();function jt(e){function t(n,r){if(typeof r=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(r)){const o=new Date(r);if(!isNaN(o.getTime()))return o}return r}try{return typeof e!="string"?e:JSON.parse(e,t)}catch(n){return Y.error("Error parsing JSON",{error:n}),null}}const De=e=>{const t=(e.plugins??[]).reduce((c,l)=>{const y=l.schema;if(!y)return c;for(const[w,S]of Object.entries(y))c[w]={fields:{...c[w]?.fields,...S.fields},modelName:S.modelName||w};return c},{}),n=e.rateLimit?.storage==="database",r={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:i,session:o,account:f,...s}=t,a={session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...o?.fields,...e.session?.additionalFields},order:2}};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...e.user?.additionalFields},order:1},...!e.secondaryStorage||e.session?.storeSessionInDatabase?a:{},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...f?.fields,...e.account?.additionalFields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...s,...n?r:{}}};function Le(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${e}`)}}function Ge(...e){const t=e.map(Le).join("");if(t.length===0)throw new Error("No valid characters provided for random string generation.");const n=t.length;return(r,...i)=>{if(r<=0)throw new Error("Length must be a positive integer.");let o=t,f=n;i.length>0&&(o=i.map(Le).join(""),f=o.length);const s=Math.floor(256/f)*f,a=new Uint8Array(r*2),c=a.length;let l="",y=c,w;for(;l.length<r;)y>=c&&(crypto.getRandomValues(a),y=0),w=a[y++],w<s&&(l+=o[w%f]);return l}}const kt=e=>Ge("a-z","A-Z","0-9")(32);var Dt=Object.defineProperty,Lt=(e,t)=>{for(var n in t)Dt(e,n,{get:t[n],enumerable:!0})},Ct={};Lt(Ct,{BIGINT_FORMAT_RANGES:()=>dn,Class:()=>An,NUMBER_FORMAT_RANGES:()=>fn,aborted:()=>gn,allowsEval:()=>tn,assert:()=>Ft,assertEqual:()=>Pt,assertIs:()=>qt,assertNever:()=>Vt,assertNotEqual:()=>zt,assignProp:()=>Ee,cached:()=>We,captureStackTrace:()=>en,cleanEnum:()=>Sn,cleanRegex:()=>Wt,clone:()=>ee,createTransparentProxy:()=>cn,defineLazy:()=>Ht,esc:()=>Qt,escapeRegex:()=>an,extend:()=>yn,finalizeIssue:()=>On,floatSafeRemainder:()=>Jt,getElementAtPath:()=>Yt,getEnumValues:()=>Ut,getLengthableOrigin:()=>vn,getParsedType:()=>rn,getSizableOrigin:()=>$n,isObject:()=>Se,isPlainObject:()=>Je,issue:()=>Nn,joinValues:()=>Bt,jsonStringifyReplacer:()=>Kt,merge:()=>hn,normalizeParams:()=>un,nullish:()=>Gt,numKeys:()=>nn,omit:()=>mn,optionalKeys:()=>ln,partial:()=>bn,pick:()=>pn,prefixIssues:()=>_n,primitiveTypes:()=>sn,promiseAllObject:()=>Xt,propertyKeyTypes:()=>on,randomString:()=>Zt,required:()=>wn,stringifyPrimitive:()=>He,unwrapMessage:()=>se});function Pt(e){return e}function zt(e){return e}function qt(e){}function Vt(e){throw new Error}function Ft(e){}function Ut(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Bt(e,t="|"){return e.map(n=>He(n)).join(t)}function Kt(e,t){return typeof t=="bigint"?t.toString():t}function We(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Gt(e){return e==null}function Wt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Jt(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),f=Number.parseInt(t.toFixed(i).replace(".",""));return o%f/10**i}function Ht(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Ee(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Yt(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function Xt(e){const t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{const i={};for(let o=0;o<t.length;o++)i[t[o]]=r[o];return i})}function Zt(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function Qt(e){return JSON.stringify(e)}var en=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tn=We(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Je(e){if(Se(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Se(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function nn(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var rn=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},on=new Set(["string","number","symbol"]),sn=new Set(["string","number","bigint","boolean","symbol","undefined"]);function an(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ee(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function un(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cn(e){let t;return new Proxy({},{get(n,r,i){return t??(t=e()),Reflect.get(t,r,i)},set(n,r,i,o){return t??(t=e()),Reflect.set(t,r,i,o)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??(t=e()),Reflect.defineProperty(t,r,i)}})}function He(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ln(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var fn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},dn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pn(e,t){const n={},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(n[i]=r.shape[i])}return ee(e,{...e._zod.def,shape:n,checks:[]})}function mn(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete n[i]}return ee(e,{...e._zod.def,shape:n,checks:[]})}function yn(e,t){if(!Je(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Ee(this,"shape",r),r},checks:[]};return ee(e,n)}function hn(e,t){return ee(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ee(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function bn(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=e?new e({type:"optional",innerType:r[o]}):r[o])}else for(const o in r)i[o]=e?new e({type:"optional",innerType:r[o]}):r[o];return ee(t,{...t._zod.def,shape:i,checks:[]})}function wn(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=new e({type:"nonoptional",innerType:r[o]}))}else for(const o in r)i[o]=new e({type:"nonoptional",innerType:r[o]});return ee(t,{...t._zod.def,shape:i,checks:[]})}function gn(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function _n(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function se(e){return typeof e=="string"?e:e?.message}function On(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const i=se(e.inst?._zod.def?.error?.(e))??se(t?.error?.(e))??se(n.customError?.(e))??se(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function $n(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function vn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Nn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function Sn(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var An=class{constructor(...e){}};Ge("a-z","0-9","A-Z","-_");function In(e,t,n){return n==="update"?e===void 0&&t.onUpdate!==void 0?typeof t.onUpdate=="function"?t.onUpdate():t.onUpdate:e:e==null&&t.defaultValue!==void 0?typeof t.defaultValue=="function"?t.defaultValue():t.defaultValue:e}let fe=[],z=-1;const Tn=e=>t=>t(e),Rn=({adapter:e,config:t})=>n=>{const r=Math.random().toString(36).substring(2,15),i={...t,supportsBooleans:t.supportsBooleans??!0,supportsDates:t.supportsDates??!0,supportsJSON:t.supportsJSON??!1,adapterName:t.adapterName??t.adapterId,supportsNumericIds:t.supportsNumericIds??!0,transaction:t.transaction??!1,disableTransformInput:t.disableTransformInput??!1,disableTransformOutput:t.disableTransformOutput??!1};if(n.advanced?.database?.useNumberId===!0&&i.supportsNumericIds===!1)throw new Error(`[${i.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);const o=De(n),f=({field:u,model:m})=>{if(u==="id"||u==="_id")return"id";const p=s(m);let d=o[p]?.fields[u];if(!d){const h=Object.entries(o[p].fields).find(([b,O])=>O.fieldName===u);h&&(d=h[1],u=h[0])}if(!d)throw l(`Field ${u} not found in model ${p}`),l("Schema:",o),new Error(`Field ${u} not found in model ${p}`);return u},s=u=>{if(i.usePlural&&u.charAt(u.length-1)==="s"){let p=u.slice(0,-1),d=o[p]?p:void 0;if(d||(d=Object.entries(o).find(([h,b])=>b.modelName===p)?.[0]),d)return d}let m=o[u]?u:void 0;if(m||(m=Object.entries(o).find(([p,d])=>d.modelName===u)?.[0]),!m)throw l(`Model "${u}" not found in schema`),l("Schema:",o),new Error(`Model "${u}" not found in schema`);return m},a=u=>{const m=s(u),p=i&&i.usePlural;return o&&o[m]&&o[m].modelName!==u?p?`${o[m].modelName}s`:o[m].modelName:p?`${u}s`:u};function c({model:u,field:m}){const p=s(u),d=f({model:p,field:m});return o[p]?.fields[d]?.fieldName||d}const l=(...u)=>{if(i.debugLogs===!0||typeof i.debugLogs=="object"){if(typeof i.debugLogs=="object"&&"isRunningAdapterTests"in i.debugLogs){i.debugLogs.isRunningAdapterTests&&(u.shift(),fe.push({instance:r,args:u}));return}if(typeof i.debugLogs=="object"&&i.debugLogs.logCondition&&!i.debugLogs.logCondition?.())return;if(typeof u[0]=="object"&&"method"in u[0]){const m=u.shift().method;if(typeof i.debugLogs=="object"){if(m==="create"&&!i.debugLogs.create)return;if(m==="update"&&!i.debugLogs.update)return;if(m==="updateMany"&&!i.debugLogs.updateMany)return;if(m==="findOne"&&!i.debugLogs.findOne)return;if(m==="findMany"&&!i.debugLogs.findMany)return;if(m==="delete"&&!i.debugLogs.delete)return;if(m==="deleteMany"&&!i.debugLogs.deleteMany)return;if(m==="count"&&!i.debugLogs.count)return}Y.info(`[${i.adapterName}]`,...u)}else Y.info(`[${i.adapterName}]`,...u)}},y=({customModelName:u,forceAllowId:m})=>{const p=!i.disableIdGeneration&&!n.advanced?.database?.useNumberId&&!m,d=s(u??"id");return{type:n.advanced?.database?.useNumberId?"number":"string",required:!!p,...p?{defaultValue(){if(i.disableIdGeneration)return;const h=n.advanced?.database?.useNumberId;let b=n.advanced?.database?.generateId;if(n.advanced?.generateId!==void 0&&(Y.warn("Your Better Auth config includes advanced.generateId which is deprecated. Please use advanced.database.generateId instead. This will be removed in future releases."),b=n.advanced?.generateId),!(b===!1||h))return b?b({model:d}):i.customIdGenerator?i.customIdGenerator({model:d}):kt()}}:{}}},w=({model:u,field:m})=>{const p=s(u),d=f({field:m,model:p}),h=o[p].fields;return h.id=y({customModelName:p}),h[d]},S=async(u,m,p,d)=>{const h={},b=o[m].fields,O=i.mapKeysTransformInput??{};!i.disableIdGeneration&&!n.advanced?.database?.useNumberId&&(b.id=y({customModelName:m,forceAllowId:d&&"id"in u}));for(const g in b){const N=u[g],A=b[g];let _=O[g]||b[g].fieldName||g;if(N===void 0&&(A.defaultValue===void 0&&!A.transform?.input&&!(p==="update"&&A.onUpdate)||p==="update"&&!A.onUpdate))continue;let $=In(N,A,p);A.transform?.input&&($=await A.transform.input($)),A.references?.field==="id"&&n.advanced?.database?.useNumberId?Array.isArray($)?$=$.map(te=>te!==null?Number(te):null):$=$!==null?Number($):null:i.supportsJSON===!1&&typeof $=="object"&&A.type==="json"?$=JSON.stringify($):i.supportsDates===!1&&$ instanceof Date&&A.type==="date"?$=$.toISOString():i.supportsBooleans===!1&&typeof $=="boolean"&&($=$?1:0),i.customTransformInput&&($=i.customTransformInput({data:$,action:p,field:_,fieldAttributes:A,model:m,schema:o,options:n})),$!==void 0&&(h[_]=$)}return h},C=async(u,m,p=[])=>{if(!u)return null;const d=i.mapKeysTransformOutput??{},h={},b=o[m].fields,O=Object.entries(d).find(([g,N])=>N==="id")?.[0];b[O??"id"]={type:n.advanced?.database?.useNumberId?"number":"string"};for(const g in b){if(p.length&&!p.includes(g))continue;const N=b[g];if(N){const A=N.fieldName||g;let _=u[Object.entries(d).find(([te,Ze])=>Ze===A)?.[0]||A];N.transform?.output&&(_=await N.transform.output(_));let $=d[g]||g;A==="id"||N.references?.field==="id"?typeof _<"u"&&_!==null&&(_=String(_)):i.supportsJSON===!1&&typeof _=="string"&&N.type==="json"?_=jt(_):i.supportsDates===!1&&typeof _=="string"&&N.type==="date"?_=new Date(_):i.supportsBooleans===!1&&typeof _=="number"&&N.type==="boolean"&&(_=_===1),i.customTransformOutput&&(_=i.customTransformOutput({data:_,field:$,fieldAttributes:N,select:p,model:m,schema:o,options:n})),h[$]=_}}return h},x=({model:u,where:m})=>{if(!m)return;const p=i.mapKeysTransformInput??{};return m.map(d=>{const{field:h,value:b,operator:O="eq",connector:g="AND"}=d;if(O==="in"&&!Array.isArray(b))throw new Error("Value must be an array");const N=s(u),A=f({field:h,model:u}),_=p[A]||c({field:A,model:N}),$=w({field:A,model:N});return(A==="id"||$.references?.field==="id")&&n.advanced?.database?.useNumberId?Array.isArray(b)?{operator:O,connector:g,field:_,value:b.map(Number)}:{operator:O,connector:g,field:_,value:Number(b)}:{operator:O,connector:g,field:_,value:b}})},E=e({options:n,schema:o,debugLog:l,getFieldName:c,getModelName:a,getDefaultModelName:s,getDefaultFieldName:f,getFieldAttributes:w,transformInput:S,transformOutput:C,transformWhereClause:x});let B=null;const V={transaction:async u=>(B||(i.transaction?(Y.debug(`[${i.adapterName}] - Using provided transaction implementation.`),B=i.transaction):(typeof i.debugLogs=="object"&&"isRunningAdapterTests"in i.debugLogs&&i.debugLogs.isRunningAdapterTests||Y.warn(`[${i.adapterName}] - Transactions are not supported. Executing operations sequentially.`),B=Tn(V))),B(u)),create:async({data:u,model:m,select:p,forceAllowId:d=!1})=>{z++;let h=z;const b=a(m);if(m=s(m),"id"in u&&!d){Y.warn(`[${i.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`);const _=new Error().stack?.split(`
|
|
2
|
-
`).filter((
|
|
3
|
-
`).replace("Error:","Create method with `id` being called at:");console.log(_),u.id=void 0}l({method:"create"},`${I(h)} ${T(1,4)}`,`${R("create")} ${j("Unsafe Input")}:`,{model:b,data:u});let O=u;i.disableTransformInput||(O=await S(u,m,"create",d)),l({method:"create"},`${I(h)} ${T(2,4)}`,`${R("create")} ${j("Parsed Input")}:`,{model:b,data:O});const g=await E.create({data:O,model:b});l({method:"create"},`${I(h)} ${T(3,4)}`,`${R("create")} ${j("DB Result")}:`,{model:b,res:g});let N=g;return i.disableTransformOutput||(N=await C(g,m,p)),l({method:"create"},`${I(h)} ${T(4,4)}`,`${R("create")} ${j("Parsed Result")}:`,{model:b,data:N}),N},update:async({model:u,where:m,update:p})=>{z++;let d=z;u=s(u);const h=a(u),b=x({model:u,where:m});l({method:"update"},`${I(d)} ${T(1,4)}`,`${R("update")} ${j("Unsafe Input")}:`,{model:h,data:p});let O=p;i.disableTransformInput||(O=await S(p,u,"update")),l({method:"update"},`${I(d)} ${T(2,4)}`,`${R("update")} ${j("Parsed Input")}:`,{model:h,data:O});const g=await E.update({model:h,where:b,update:O});l({method:"update"},`${I(d)} ${T(3,4)}`,`${R("update")} ${j("DB Result")}:`,{model:h,data:g});let N=g;return i.disableTransformOutput||(N=await C(g,u)),l({method:"update"},`${I(d)} ${T(4,4)}`,`${R("update")} ${j("Parsed Result")}:`,{model:h,data:N}),N},updateMany:async({model:u,where:m,update:p})=>{z++;let d=z;const h=a(u),b=x({model:u,where:m});u=s(u),l({method:"updateMany"},`${I(d)} ${T(1,4)}`,`${R("updateMany")} ${j("Unsafe Input")}:`,{model:h,data:p});let O=p;i.disableTransformInput||(O=await S(p,u,"update")),l({method:"updateMany"},`${I(d)} ${T(2,4)}`,`${R("updateMany")} ${j("Parsed Input")}:`,{model:h,data:O});const g=await E.updateMany({model:h,where:b,update:O});return l({method:"updateMany"},`${I(d)} ${T(3,4)}`,`${R("updateMany")} ${j("DB Result")}:`,{model:h,data:g}),l({method:"updateMany"},`${I(d)} ${T(4,4)}`,`${R("updateMany")} ${j("Parsed Result")}:`,{model:h,data:g}),g},findOne:async({model:u,where:m,select:p})=>{z++;let d=z;const h=a(u),b=x({model:u,where:m});u=s(u),l({method:"findOne"},`${I(d)} ${T(1,3)}`,`${R("findOne")}:`,{model:h,where:b,select:p});const O=await E.findOne({model:h,where:b,select:p});l({method:"findOne"},`${I(d)} ${T(2,3)}`,`${R("findOne")} ${j("DB Result")}:`,{model:h,data:O});let g=O;return i.disableTransformOutput||(g=await C(O,u,p)),l({method:"findOne"},`${I(d)} ${T(3,3)}`,`${R("findOne")} ${j("Parsed Result")}:`,{model:h,data:g}),g},findMany:async({model:u,where:m,limit:p,sortBy:d,offset:h})=>{z++;let b=z;const O=p??n.advanced?.database?.defaultFindManyLimit??100,g=a(u),N=x({model:u,where:m});u=s(u),l({method:"findMany"},`${I(b)} ${T(1,3)}`,`${R("findMany")}:`,{model:g,where:N,limit:O,sortBy:d,offset:h});const A=await E.findMany({model:g,where:N,limit:O,sortBy:d,offset:h});l({method:"findMany"},`${I(b)} ${T(2,3)}`,`${R("findMany")} ${j("DB Result")}:`,{model:g,data:A});let _=A;return i.disableTransformOutput||(_=await Promise.all(A.map(async $=>await C($,u)))),l({method:"findMany"},`${I(b)} ${T(3,3)}`,`${R("findMany")} ${j("Parsed Result")}:`,{model:g,data:_}),_},delete:async({model:u,where:m})=>{z++;let p=z;const d=a(u),h=x({model:u,where:m});u=s(u),l({method:"delete"},`${I(p)} ${T(1,2)}`,`${R("delete")}:`,{model:d,where:h}),await E.delete({model:d,where:h}),l({method:"delete"},`${I(p)} ${T(2,2)}`,`${R("delete")} ${j("DB Result")}:`,{model:d})},deleteMany:async({model:u,where:m})=>{z++;let p=z;const d=a(u),h=x({model:u,where:m});u=s(u),l({method:"deleteMany"},`${I(p)} ${T(1,2)}`,`${R("deleteMany")} ${j("DeleteMany")}:`,{model:d,where:h});const b=await E.deleteMany({model:d,where:h});return l({method:"deleteMany"},`${I(p)} ${T(2,2)}`,`${R("deleteMany")} ${j("DB Result")}:`,{model:d,data:b}),b},count:async({model:u,where:m})=>{z++;let p=z;const d=a(u),h=x({model:u,where:m});u=s(u),l({method:"count"},`${I(p)} ${T(1,2)}`,`${R("count")}:`,{model:d,where:h});const b=await E.count({model:d,where:h});return l({method:"count"},`${I(p)} ${T(2,2)}`,`${R("count")}:`,{model:d,data:b}),b},createSchema:E.createSchema?async(u,m)=>{const p=De(n);return n.secondaryStorage&&!n.session?.storeSessionInDatabase&&delete p.session,n.rateLimit&&n.rateLimit.storage==="database"&&(typeof n.rateLimit.enabled>"u"||n.rateLimit.enabled===!0)&&(p.ratelimit={modelName:n.rateLimit.modelName??"ratelimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:n.rateLimit.fields?.key??"key"},count:{type:"number",required:!0,fieldName:n.rateLimit.fields?.count??"count"},lastRequest:{type:"number",required:!0,bigint:!0,defaultValue:()=>Date.now(),fieldName:n.rateLimit.fields?.lastRequest??"lastRequest"}}}),E.createSchema({file:m,tables:p})}:void 0,options:{adapterConfig:i,...E.options??{}},id:i.adapterId,...i.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){fe=fe.filter(u=>u.instance!==r)},printDebugLogs(){const u="─".repeat(80),m=fe.filter(d=>d.instance===r);if(m.length===0)return;let p=m.reverse().map(d=>(d.args[0]=`
|
|
4
|
-
|
|
5
|
-
`
|
|
6
|
-
${
|
|
7
|
-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V={Remove:"remove",Replace:"replace",Add:"add"},Xe=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),$e=Symbol.iterator,Z={mutable:"mutable",immutable:"immutable"},ke={};function ye(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Pe(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Ze(e){return Object.getPrototypeOf(e)===Set.prototype}function Qe(e){return Object.getPrototypeOf(e)===Map.prototype}function W(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function ve(e){return!!T(e)}function T(e){return typeof e!="object"?null:e?.[Xe]}function Ce(e){var t;const n=T(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ce(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!t?.mark&&((n=t.mark(e,Z))===Z.immutable||typeof n=="function")}function et(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=T(ie(n,e.key));if(i!==null&&i?.original!==e.original)return null;const r=e.parent.type===3,s=r?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(r&&n.size>s||ye(n,s)))return null;t.push(s)}if(e.parent)return et(e.parent,t);t.reverse();try{lt(e.copy,t)}catch{return null}return t}function we(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function ie(e,t){return we(e)===2?e.get(t):e[t]}function Le(e,t,n){we(e)===2?e.set(t,n):e[t]=n}function Se(e,t){const n=T(e);return(n?W(n):e)[t]}function ae(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function se(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function lt(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=ie(we(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function ft(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const pt=Object.prototype.propertyIsEnumerable;function mt(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Ze(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Qe(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t?.mark&&(n=t.mark(e,Z),n!==void 0)&&n!==Z.mutable){if(n===Z.immutable)return ft(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const i={};return Object.keys(e).forEach(r=>{i[r]=e[r]}),Object.getOwnPropertySymbols(e).forEach(r=>{pt.call(e,r)&&(i[r]=e[r])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function J(e){e.copy||(e.copy=mt(e.original,e.options))}function me(e){if(!ce(e))return Ce(e);if(Array.isArray(e))return e.map(me);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,r])=>[i,me(r)]);if(!Qe(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(me);if(!Ze(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=me(e[n]);return t}function Oe(e){return ve(e)?me(e):e}function te(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&te(e.parent))}function yt(e,t){const n=we(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const r of e)t(i,r,e),i+=1}else e.forEach((i,r)=>t(r,i,e))}function tt(e,t,n){if(ve(e)||!ce(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,r=i?new Map:void 0;if(t.add(e),yt(e,(s,a)=>{var u;if(ve(a)){const o=T(a);J(o);const c=!((u=o.assignedMap)===null||u===void 0)&&u.size||o.operated?o.copy:o.original;Le(i?r:e,s,c)}else tt(a,t,n)}),r){const s=e,a=Array.from(s);s.clear(),a.forEach(u=>{s.add(r.has(u)?r.get(u):u)})}}function ht(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&tt(ie(n,t),e.finalities.handledSet,e.options)}function Me(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(Ce(t))}))}function Te(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const s=et(e);s&&t(e,s,n,i)}e.finalized=!0}}function Fe(e,t,n,i){const r=T(n);r&&(r.callbacks||(r.callbacks=[]),r.callbacks.push((s,a)=>{var u;const o=e.type===3?e.setMap:e.copy;if(ae(ie(o,t),n)){let c=r.original;r.copy&&(c=r.copy),Me(e),Te(e,i,s,a),e.options.enableAutoFreeze&&(e.options.updatedValues=(u=e.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,e.options.updatedValues.set(c,r.original)),Le(o,t,c)}}),e.options.enableAutoFreeze&&r.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ce(n,e.options)&&e.finalities.draft.push(()=>{const s=e.type===3?e.setMap:e.copy;ae(ie(s,t),n)&&ht(e,t)})}function bt(e,t,n,i,r){let{original:s,assignedMap:a,options:u}=e,o=e.copy;o.length<s.length&&([s,o]=[o,s],[n,i]=[i,n]);for(let c=0;c<s.length;c+=1)if(a.get(c.toString())&&o[c]!==s[c]){const d=t.concat([c]),f=se(d,r);n.push({op:V.Replace,path:f,value:Oe(o[c])}),i.push({op:V.Replace,path:f,value:Oe(s[c])})}for(let c=s.length;c<o.length;c+=1){const d=t.concat([c]),f=se(d,r);n.push({op:V.Add,path:f,value:Oe(o[c])})}if(s.length<o.length){const{arrayLengthAssignment:c=!0}=u.enablePatches;if(c){const d=t.concat(["length"]),f=se(d,r);i.push({op:V.Replace,path:f,value:s.length})}else for(let d=o.length;s.length<d;d-=1){const f=t.concat([d-1]),g=se(f,r);i.push({op:V.Remove,path:g})}}}function wt({original:e,copy:t,assignedMap:n},i,r,s,a){n.forEach((u,o)=>{const c=ie(e,o),d=Oe(ie(t,o)),f=u?ye(e,o)?V.Replace:V.Add:V.Remove;if(ae(c,d)&&f===V.Replace)return;const g=i.concat(o),$=se(g,a);r.push(f===V.Remove?{op:f,path:$}:{op:f,path:$,value:d}),s.push(f===V.Add?{op:V.Remove,path:$}:f===V.Remove?{op:V.Add,path:$,value:c}:{op:V.Replace,path:$,value:c})})}function gt({original:e,copy:t},n,i,r,s){let a=0;e.forEach(u=>{if(!t.has(u)){const o=n.concat([a]),c=se(o,s);i.push({op:V.Remove,path:c,value:u}),r.unshift({op:V.Add,path:c,value:u})}a+=1}),a=0,t.forEach(u=>{if(!e.has(u)){const o=n.concat([a]),c=se(o,s);i.push({op:V.Add,path:c,value:u}),r.unshift({op:V.Remove,path:c,value:u})}a+=1})}function be(e,t,n,i){const{pathAsArray:r=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return wt(e,t,n,i,r);case 1:return bt(e,t,n,i,r);case 3:return gt(e,t,n,i,r)}}const _e=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ce(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},je={get size(){return W(T(this)).size},has(e){return W(T(this)).has(e)},set(e,t){const n=T(this),i=W(n);return(!i.has(e)||!ae(i.get(e),t))&&(J(n),te(n),n.assignedMap.set(e,!0),n.copy.set(e,t),Fe(n,e,t,be)),this},delete(e){if(!this.has(e))return!1;const t=T(this);return J(t),te(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=T(this);if(this.size){J(e),te(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=T(this);W(n).forEach((i,r)=>{e.call(t,this.get(r),r,this)})},get(e){var t,n;const i=T(this),r=W(i).get(e),s=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,r,Z))===Z.mutable;if(i.options.strict&&_e(r,i.options,s),s||i.finalized||!ce(r,i.options)||r!==i.original.get(e))return r;const a=ke.createDraft({original:r,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return J(i),i.copy.set(e,a),a},keys(){return W(T(this)).keys()},values(){const e=this.keys();return{[$e]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[$e]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[$e](){return this.entries()}},$t=Reflect.ownKeys(je),Ue=(e,t,{isValuesIterator:n})=>()=>{var i,r;const s=t.next();if(s.done)return s;const a=s.value;let u=e.setMap.get(a);const o=T(u),c=((r=(i=e.options).mark)===null||r===void 0?void 0:r.call(i,u,Z))===Z.mutable;if(e.options.strict&&_e(a,e.options,c),!c&&!o&&ce(a,e.options)&&!e.finalized&&e.original.has(a)){const d=ke.createDraft({original:a,parentDraft:e,key:a,finalities:e.finalities,options:e.options});e.setMap.set(a,d),u=d}else o&&(u=o.proxy);return{done:!1,value:n?u:[u,u]}},Ae={get size(){return T(this).setMap.size},has(e){const t=T(this);if(t.setMap.has(e))return!0;J(t);const n=T(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=T(this);return this.has(e)||(J(t),te(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),Fe(t,e,e,be)),this},delete(e){if(!this.has(e))return!1;const t=T(this);J(t),te(t);const n=T(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=T(this);J(e),te(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=T(this);J(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Ue(e,t,{isValuesIterator:!0})}},entries(){const e=T(this);J(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Ue(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[$e](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Ae,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const Ot=Reflect.ownKeys(Ae),nt={get(e,t,n){var i,r;const s=(i=e.copy)===null||i===void 0?void 0:i[t];if(s&&e.finalities.draftsCache.has(s))return s;if(t===Xe)return e;let a;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(a=e.options.mark(c,Z),a===Z.mutable)return e.options.strict&&_e(c,e.options,!0),c}const u=W(e);if(u instanceof Map&&$t.includes(t))return t==="size"?Object.getOwnPropertyDescriptor(je,"size").get.call(e.proxy):je[t].bind(e.proxy);if(u instanceof Set&&Ot.includes(t))return t==="size"?Object.getOwnPropertyDescriptor(Ae,"size").get.call(e.proxy):Ae[t].bind(e.proxy);if(!ye(u,t)){const c=Pe(u,t);return c?"value"in c?c.value:(r=c.get)===null||r===void 0?void 0:r.call(e.proxy):void 0}const o=u[t];if(e.options.strict&&_e(o,e.options),e.finalized||!ce(o,e.options))return o;if(o===Se(e.original,t)){if(J(e),e.copy[t]=rt({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof a=="function"){const c=T(e.copy[t]);return J(c),te(c),c.copy}return e.copy[t]}return ve(o)&&e.finalities.draftsCache.add(o),o},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let r;if(e.type===1&&t!=="length"&&!(Number.isInteger(r=Number(t))&&r>=0&&(t===0||r===0||String(r)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const s=Pe(W(e),t);if(s?.set)return s.set.call(e.proxy,n),!0;const a=Se(W(e),t),u=T(a);return u&&ae(u.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(ae(n,a)&&(n!==void 0||ye(e.original,t))||(J(e),te(e),ye(e.original,t)&&ae(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,Fe(e,t,n,be)),!0)},has(e,t){return t in W(e)},ownKeys(e){return Reflect.ownKeys(W(e))},getOwnPropertyDescriptor(e,t){const n=W(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?nt.set.call(this,e,t,void 0,e.proxy):(Se(e.original,t)!==void 0||t in e.original?(J(e),te(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function rt(e){const{original:t,parentDraft:n,key:i,finalities:r,options:s}=e,a=we(t),u={type:a,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:r,options:s,setMap:a===3?new Map(t.entries()):void 0};(i||"key"in e)&&(u.key=i);const{proxy:o,revoke:c}=Proxy.revocable(a===1?Object.assign([],u):u,nt);if(r.revoke.push(c),u.proxy=o,n){const d=n;d.finalities.draft.push((f,g)=>{var $,v;const j=T(o);let U=d.type===3?d.setMap:d.copy;const X=ie(U,i),H=T(X);if(H){let C=H.original;H.operated&&(C=Ce(X)),Me(H),Te(H,be,f,g),d.options.enableAutoFreeze&&(d.options.updatedValues=($=d.options.updatedValues)!==null&&$!==void 0?$:new WeakMap,d.options.updatedValues.set(C,H.original)),Le(U,i,C)}(v=j.callbacks)===null||v===void 0||v.forEach(C=>{C(f,g)})})}else{const d=T(o);d.finalities.draft.push((f,g)=>{Me(d),Te(d,be,f,g)})}return o}ke.createDraft=rt;Object.prototype.constructor.toString();const z=[];for(let e=0;e<256;++e)z.push((e+256).toString(16).slice(1));function Nt(e,t=0){return(z[e[t+0]]+z[e[t+1]]+z[e[t+2]]+z[e[t+3]]+"-"+z[e[t+4]]+z[e[t+5]]+"-"+z[e[t+6]]+z[e[t+7]]+"-"+z[e[t+8]]+z[e[t+9]]+"-"+z[e[t+10]]+z[e[t+11]]+z[e[t+12]]+z[e[t+13]]+z[e[t+14]]+z[e[t+15]]).toLowerCase()}let Ie;const vt=new Uint8Array(16);function _t(){if(!Ie){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ie=crypto.getRandomValues.bind(crypto)}return Ie(vt)}const At=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Be={randomUUID:At};function St(e,t,n){if(Be.randomUUID&&!e)return Be.randomUUID();e=e||{};const i=e.random??e.rng?.()??_t();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Nt(i)}function It(){return St()}function Mt(e,t){return e.localeCompare(t)}function Tt(){let e=Mt;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Tt();function jt(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Rt=jt();function Re(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(r,s)=>{if(s==="__ops")return n;if(s==="__etype")return e;if(Rt.has(s))return(a,u)=>Re(e,t,[...n,u?[s,e,t,a,u]:[s,e,t,a]])}})}function xt(e){return e.startsWith("lookup__")}function Dt(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Et(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const i=n;return xt(i)?Re(e,Dt(i),[]):Re(e,i,[])}})}function kt(){return new Proxy({},{get(e,t){return Et(t)}})}kt();const Ct={"unique?":!0,"index?":!0};Object.assign(Object.assign({},Ct),{cardinality:"one"});typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));function Lt(){var e;return globalThis.__instantDbSchemaHashStore=(e=globalThis.__instantDbSchemaHashStore)!==null&&e!==void 0?e:new WeakMap,globalThis.__instantDbSchemaHashStore}function Ft(){var e;return globalThis.__instantDbStore=(e=globalThis.__instantDbStore)!==null&&e!==void 0?e:{},globalThis.__instantDbStore}Ft();Lt();var re=class extends Error{constructor(e,t){super(e,t),this.name="BetterAuthError",this.message=e,this.stack=""}};const de=({usePlural:e,schema:t})=>i=>{if(e&&i.charAt(i.length-1)==="s"){const s=i.slice(0,-1);let a=t[s]?s:void 0;if(a||(a=Object.entries(t).find(([u,o])=>o.modelName===s)?.[0]),a)return a}let r=t[i]?i:void 0;if(r||(r=Object.entries(t).find(([s,a])=>a.modelName===i)?.[0]),!r)throw new re(`Model "${i}" not found in schema`);return r},qe=({schema:e,usePlural:t})=>{const n=de({schema:e,usePlural:t});return({field:r,model:s})=>{if(r==="id"||r==="_id")return"id";const a=n(s);let u=e[a]?.fields[r];if(!u){const o=Object.entries(e[a].fields).find(([c,d])=>d.fieldName===r);o&&(u=o[1],r=o[0])}if(!u)throw new re(`Field ${r} not found in model ${a}`);return r}},Ne=Object.create(null),le=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ne:globalThis),fe=new Proxy(Ne,{get(e,t){return le()[t]??Ne[t]},has(e,t){return t in le()||t in Ne},set(e,t,n){const i=le(!0);return i[t]=n,!0},deleteProperty(e,t){if(!t)return!1;const n=le(!0);return delete n[t],!0},ownKeys(){const e=le(!0);return Object.keys(e)}});typeof process<"u"&&process.env&&process.env.NODE_ENV;function L(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}const pe=1,B=4,ee=8,Y=24,ze={eterm:B,cons25:B,console:B,cygwin:B,dtterm:B,gnome:B,hurd:B,jfbterm:B,konsole:B,kterm:B,mlterm:B,mosh:Y,putty:B,st:B,"rxvt-unicode-24bit":Y,terminator:Y,"xterm-kitty":Y},qt=new Map(Object.entries({APPVEYOR:ee,BUILDKITE:ee,CIRCLECI:Y,DRONE:ee,GITEA_ACTIONS:Y,GITHUB_ACTIONS:Y,GITLAB_CI:ee,TRAVIS:ee})),Vt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function it(){if(L("FORCE_COLOR")!==void 0)switch(L("FORCE_COLOR")){case"":case"1":case"true":return B;case"2":return ee;case"3":return Y;default:return pe}if(L("NODE_DISABLE_COLORS")!==void 0&&L("NODE_DISABLE_COLORS")!==""||L("NO_COLOR")!==void 0&&L("NO_COLOR")!==""||L("TERM")==="dumb")return pe;if(L("TMUX"))return Y;if("TF_BUILD"in fe&&"AGENT_NAME"in fe)return B;if("CI"in fe){for(const{0:e,1:t}of qt)if(e in fe)return t;return L("CI_NAME")==="codeship"?ee:pe}if("TEAMCITY_VERSION"in fe)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(L("TEAMCITY_VERSION"))!==null?B:pe;switch(L("TERM_PROGRAM")){case"iTerm.app":return!L("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(L("TERM_PROGRAM_VERSION"))!==null?ee:Y;case"HyperTerm":case"MacTerm":return Y;case"Apple_Terminal":return ee}if(L("COLORTERM")==="truecolor"||L("COLORTERM")==="24bit")return Y;if(L("TERM")){if(/truecolor/.exec(L("TERM"))!==null)return Y;if(/^xterm-256/.exec(L("TERM"))!==null)return ee;const e=L("TERM").toLowerCase();if(ze[e])return ze[e];if(Vt.some(t=>t.exec(e)!==null))return B}return L("COLORTERM")?B:pe}const P={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",fg:{red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m"},bg:{black:"\x1B[40m"}},xe=["debug","info","success","warn","error"];function Pt(e,t){return xe.indexOf(t)>=xe.indexOf(e)}const Ut={info:P.fg.blue,success:P.fg.green,warn:P.fg.yellow,error:P.fg.red,debug:P.fg.magenta},Bt=(e,t,n)=>{const i=new Date().toISOString();return n?`${P.dim}${i}${P.reset} ${Ut[e]}${e.toUpperCase()}${P.reset} ${P.bright}[Better Auth]:${P.reset} ${t}`:`${i} ${e.toUpperCase()} [Better Auth]: ${t}`},De=e=>{const t=e?.disabled!==!0,n=e?.level??"warn",i=e?.disableColors!==void 0?!e.disableColors:it()!==1,r=(s,a,u=[])=>{if(!t||!Pt(n,s))return;const o=Bt(s,a,i);if(!e||typeof e.log!="function"){s==="error"?console.error(o,...u):s==="warn"?console.warn(o,...u):console.log(o,...u);return}e.log(s==="success"?"info":s,a,...u)};return{...Object.fromEntries(xe.map(s=>[s,(...[a,...u])=>r(s,a,u)])),get level(){return n}}},ot=De();function Ke(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${e}`)}}function zt(...e){const t=e.map(Ke).join("");if(t.length===0)throw new Error("No valid characters provided for random string generation.");const n=t.length;return(i,...r)=>{if(i<=0)throw new Error("Length must be a positive integer.");let s=t,a=n;r.length>0&&(s=r.map(Ke).join(""),a=s.length);const u=Math.floor(256/a)*a,o=new Uint8Array(i*2),c=o.length;let d="",f=c,g;for(;d.length<i;)f>=c&&(crypto.getRandomValues(o),f=0),g=o[f++],g<u&&(d+=s[g%a]);return d}}const Kt=e=>zt("a-z","A-Z","0-9")(32),st=({usePlural:e,schema:t,disableIdGeneration:n,options:i,customIdGenerator:r,supportsUUIDs:s})=>{const a=de({usePlural:e,schema:t});return({customModelName:o,forceAllowId:c})=>{const d=i.advanced?.database?.generateId==="serial",f=i.advanced?.database?.generateId==="uuid",g=n||d&&!c?!1:f?!s:!0,$=a(o??"id");return{type:d?"number":"string",required:!!g,...g?{defaultValue(){if(n)return;const v=i.advanced?.database?.generateId;if(!(v===!1||v==="serial"))return typeof v=="function"?v({model:$}):v==="uuid"?crypto.randomUUID():r?r({model:$}):Kt()}}:{},transform:{input:v=>{if(v){if(d){const j=Number(v);return isNaN(j)?void 0:j}if(f){if(g&&!c)return v;if(n)return;if(c&&typeof v=="string"){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v))return v;{const j=new Error().stack?.split(`
|
|
2
|
+
`).filter((U,X)=>X!==1).join(`
|
|
3
|
+
`).replace("Error:","");ot.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.",j)}}return s?void 0:typeof v!="string"&&!s?crypto.randomUUID():void 0}return v}},output:v=>{if(v)return String(v)}}}}},Gt=({usePlural:e,schema:t,options:n,customIdGenerator:i,disableIdGeneration:r})=>{const s=de({usePlural:e,schema:t}),a=qe({usePlural:e,schema:t}),u=st({usePlural:e,schema:t,options:n,customIdGenerator:i,disableIdGeneration:r});return({model:c,field:d})=>{const f=s(c),g=a({field:d,model:f}),$=t[f].fields;$.id=u({customModelName:f});const v=$[g];if(!v)throw new re(`Field ${d} not found in model ${c}`);return v}},Jt=({schema:e,usePlural:t})=>{const n=de({schema:e,usePlural:t}),i=qe({schema:e,usePlural:t});function r({model:s,field:a}){const u=n(s),o=i({model:u,field:a});return e[u]?.fields[o]?.fieldName||o}return r},Ht=({usePlural:e,schema:t})=>{const n=de({schema:t,usePlural:e});return r=>{const s=n(r);return t&&t[s]&&t[s].modelName!==r?e?`${t[s].modelName}s`:t[s].modelName:e?`${r}s`:r}};function Wt(e,t,n){return n==="update"?e===void 0&&t.onUpdate!==void 0?typeof t.onUpdate=="function"?t.onUpdate():t.onUpdate:e:n==="create"&&(e===void 0||t.required===!0&&e===null)&&t.defaultValue!==void 0?typeof t.defaultValue=="function"?t.defaultValue():t.defaultValue:e}const Ge=e=>{const t=(e.plugins??[]).reduce((f,g)=>{const $=g.schema;if(!$)return f;for(const[v,j]of Object.entries($))f[v]={fields:{...f[v]?.fields,...j.fields},modelName:j.modelName||v};return f},{}),n=e.rateLimit?.storage==="database",i={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:r,session:s,account:a,verification:u,...o}=t,c={verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"},...u?.fields,...e.verification?.additionalFields},order:4}},d={session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...e.session?.additionalFields},order:2}};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...e.user?.additionalFields},order:1},...!e.secondaryStorage||e.session?.storeSessionInDatabase?d:{},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:e.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...a?.fields,...e.account?.additionalFields},order:3},...!e.secondaryStorage||e.verification?.storeInDatabase?c:{},...o,...n?i:{}}},Yt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function at(e){if(typeof e=="string"&&Yt.test(e)){const t=new Date(e);if(!isNaN(t.getTime()))return t}return e}function Ee(e){if(e==null)return e;if(typeof e=="string")return at(e);if(e instanceof Date)return e;if(Array.isArray(e))return e.map(Ee);if(typeof e=="object"){const t={};for(const n of Object.keys(e))t[n]=Ee(e[n]);return t}return e}function Je(e){try{return typeof e!="string"?e==null?null:Ee(e):JSON.parse(e,(t,n)=>at(n))}catch(t){return ot.error("Error parsing JSON",{error:t}),null}}const He="db.collection.name",We="db.operation.name";function Q(e,t,n){return n()}let ge=[],K=-1;const Xt=e=>t=>t(e),Zt=({adapter:e,config:t})=>n=>{const i=Math.random().toString(36).substring(2,15),r={...t,supportsBooleans:t.supportsBooleans??!0,supportsDates:t.supportsDates??!0,supportsJSON:t.supportsJSON??!1,adapterName:t.adapterName??t.adapterId,supportsNumericIds:t.supportsNumericIds??!0,supportsUUIDs:t.supportsUUIDs??!1,supportsArrays:t.supportsArrays??!1,transaction:t.transaction??!1,disableTransformInput:t.disableTransformInput??!1,disableTransformOutput:t.disableTransformOutput??!1,disableTransformJoin:t.disableTransformJoin??!1};if(n.advanced?.database?.generateId==="serial"&&r.supportsNumericIds===!1)throw new re(`[${r.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);const s=Ge(n),a=(...l)=>{if(r.debugLogs===!0||typeof r.debugLogs=="object"){const b=De({level:"info"});if(typeof r.debugLogs=="object"&&"isRunningAdapterTests"in r.debugLogs){r.debugLogs.isRunningAdapterTests&&(l.shift(),ge.push({instance:i,args:l}));return}if(typeof r.debugLogs=="object"&&r.debugLogs.logCondition&&!r.debugLogs.logCondition?.())return;if(typeof l[0]=="object"&&"method"in l[0]){const h=l.shift().method;if(typeof r.debugLogs=="object"){if(h==="create"&&!r.debugLogs.create)return;if(h==="update"&&!r.debugLogs.update)return;if(h==="updateMany"&&!r.debugLogs.updateMany)return;if(h==="findOne"&&!r.debugLogs.findOne)return;if(h==="findMany"&&!r.debugLogs.findMany)return;if(h==="delete"&&!r.debugLogs.delete)return;if(h==="deleteMany"&&!r.debugLogs.deleteMany)return;if(h==="count"&&!r.debugLogs.count)return}b.info(`[${r.adapterName}]`,...l)}else b.info(`[${r.adapterName}]`,...l)}},u=De(n.logger),o=de({usePlural:r.usePlural,schema:s}),c=qe({usePlural:r.usePlural,schema:s}),d=Ht({usePlural:r.usePlural,schema:s}),f=Jt({schema:s,usePlural:r.usePlural}),g=st({schema:s,options:n,usePlural:r.usePlural,disableIdGeneration:r.disableIdGeneration,customIdGenerator:r.customIdGenerator,supportsUUIDs:r.supportsUUIDs}),$=Gt({schema:s,options:n,usePlural:r.usePlural,disableIdGeneration:r.disableIdGeneration,customIdGenerator:r.customIdGenerator}),v=async(l,b,h,y)=>{const p={},N=s[b].fields,A=r.mapKeysTransformInput??{},w=n.advanced?.database?.generateId==="serial";N.id=g({customModelName:b,forceAllowId:y&&"id"in l});for(const _ in N){let S=l[_];const m=N[_],I=A[_]||N[_].fieldName||_;if(S===void 0&&(m.defaultValue===void 0&&!m.transform?.input&&!(h==="update"&&m.onUpdate)||h==="update"&&!m.onUpdate))continue;if(m&&m.type==="date"&&!(S instanceof Date)&&typeof S=="string")try{S=new Date(S)}catch{u.error("[Adapter Factory] Failed to convert string to date",{value:S,field:_})}let O=Wt(S,m,h);m.transform?.input&&(O=await m.transform.input(O)),m.references?.field==="id"&&w?Array.isArray(O)?O=O.map(F=>F!==null?Number(F):null):O=O!==null?Number(O):null:r.supportsJSON===!1&&typeof O=="object"&&m.type==="json"||r.supportsArrays===!1&&Array.isArray(O)&&(m.type==="string[]"||m.type==="number[]")?O=JSON.stringify(O):r.supportsDates===!1&&O instanceof Date&&m.type==="date"?O=O.toISOString():r.supportsBooleans===!1&&typeof O=="boolean"&&(O=O?1:0),r.customTransformInput&&(O=r.customTransformInput({data:O,action:h,field:I,fieldAttributes:m,model:d(b),schema:s,options:n})),O!==void 0&&(p[I]=O)}return p},j=async(l,b,h=[],y)=>{const p=async(w,_,S=[])=>{if(!w)return null;const m=r.mapKeysTransformOutput??{},I={},O=s[o(_)].fields,F=Object.entries(m).find(([R,x])=>x==="id")?.[0];O[F??"id"]={type:n.advanced?.database?.generateId==="serial"?"number":"string"};for(const R in O){if(S.length&&!S.includes(R))continue;const x=O[R];if(x){const G=x.fieldName||R;let M=w[Object.entries(m).find(([un,dt])=>dt===G)?.[0]||G];x.transform?.output&&(M=await x.transform.output(M));const ne=m[R]||R;G==="id"||x.references?.field==="id"?typeof M<"u"&&M!==null&&(M=String(M)):r.supportsJSON===!1&&typeof M=="string"&&x.type==="json"||r.supportsArrays===!1&&typeof M=="string"&&(x.type==="string[]"||x.type==="number[]")?M=Je(M):r.supportsDates===!1&&typeof M=="string"&&x.type==="date"?M=new Date(M):r.supportsBooleans===!1&&typeof M=="number"&&x.type==="boolean"&&(M=M===1),r.customTransformOutput&&(M=r.customTransformOutput({data:M,field:ne,fieldAttributes:x,select:S,model:d(_),schema:s,options:n})),I[ne]=M}}return I};if(!y||Object.keys(y).length===0)return await p(l,b,h);b=o(b);const N=await p(l,b,h),A=Object.entries(y).map(([w,_])=>({modelName:d(w),defaultModelName:o(w),joinConfig:_}));if(!l)return null;for(const{modelName:w,defaultModelName:_,joinConfig:S}of A){let m=await(async()=>n.experimental?.joins?l[w]:await H({baseModel:b,baseData:N,joinModel:w,specificJoinConfig:S}))();m==null&&(m=S.relation==="one-to-one"?null:[]),S.relation==="one-to-many"&&!Array.isArray(m)&&(m=[m]);const I=[];if(Array.isArray(m))for(const O of m){const F=await p(O,w,[]);I.push(F)}else{const O=await p(m,w,[]);I.push(O)}N[_]=(S.relation==="one-to-one"?I[0]:I)??null}return N},U=({model:l,where:b,action:h})=>{if(!b)return;const y=r.mapKeysTransformInput??{};return b.map(p=>{const{field:N,value:A,operator:w="eq",connector:_="AND",mode:S="sensitive"}=p;if(w==="in"&&!Array.isArray(A))throw new re("Value must be an array");let m=A;const I=o(l),O=c({field:N,model:l}),F=y[O]||f({field:O,model:I}),R=$({field:O,model:I}),x=n.advanced?.database?.generateId==="serial";if((O==="id"||R.references?.field==="id")&&x&&(Array.isArray(A)?m=A.map(Number):m=Number(A)),R.type==="date"&&A instanceof Date&&!r.supportsDates&&(m=A.toISOString()),R.type==="boolean"&&typeof m=="string"&&(m=m==="true"),R.type==="number"){if(typeof m=="string"&&m.trim()!==""){const G=Number(m);Number.isNaN(G)||(m=G)}else if(Array.isArray(m)){const G=m.map(M=>typeof M=="string"&&M.trim()!==""?Number(M):NaN);G.every(M=>!Number.isNaN(M))&&(m=G)}}if(R.type==="boolean"&&typeof m=="boolean"&&!r.supportsBooleans&&(m=m?1:0),R.type==="json"&&typeof A=="object"&&!r.supportsJSON)try{m=JSON.stringify(A)}catch(G){throw new Error(`Failed to stringify JSON value for field ${F}`,{cause:G})}return r.customTransformInput&&(m=r.customTransformInput({data:m,fieldAttributes:R,field:F,model:d(l),schema:s,options:n,action:h})),{operator:w,connector:_,field:F,value:m,mode:S}})},X=(l,b,h)=>{if(!b||Object.keys(b).length===0)return;const y={};for(const[p,N]of Object.entries(b)){if(!N)continue;const A=o(p),w=o(l);let _=Object.entries(s[A].fields).filter(([M,ne])=>ne.references&&o(ne.references.model)===w),S=!0;if(_.length||(_=Object.entries(s[w].fields).filter(([M,ne])=>ne.references&&o(ne.references.model)===A),S=!1),_.length){if(_.length>1)throw new re(`Multiple foreign keys found for model ${p} and base model ${l} while performing join operation. Only one foreign key is supported.`)}else throw new re(`No foreign key found for model ${p} and base model ${l} while performing join operation.`);const[m,I]=_[0];if(!I.references)throw new re(`No references found for foreign key ${m} on model ${p} while performing join operation.`);let O,F,R;S?(R=I.references.field,O=f({model:l,field:R}),F=f({model:p,field:m})):(R=m,O=f({model:l,field:R}),F=f({model:p,field:I.references.field})),h&&!h.includes(R)&&h.push(R);const x=F==="id"?!0:I.unique??!1;let G=n.advanced?.database?.defaultFindManyLimit??100;x?G=1:typeof N=="object"&&typeof N.limit=="number"&&(G=N.limit),y[d(p)]={on:{from:O,to:F},limit:G,relation:x?"one-to-one":"one-to-many"}}return{join:y,select:h}},H=async({baseModel:l,baseData:b,joinModel:h,specificJoinConfig:y})=>{if(!b)return b;const p=d(h),N=y.on.to,A=b[c({field:y.on.from,model:l})];if(A==null)return y.relation==="one-to-one"?null:[];let w;const _=U({model:p,where:[{field:N,value:A,operator:"eq",connector:"AND"}],action:"findOne"});try{if(y.relation==="one-to-one")w=await Q(`db findOne ${p}`,{[We]:"findOne",[He]:p},()=>C.findOne({model:p,where:_}));else{const S=y.limit??n.advanced?.database?.defaultFindManyLimit??100;w=await Q(`db findMany ${p}`,{[We]:"findMany",[He]:p},()=>C.findMany({model:p,where:_,limit:S}))}}catch(S){throw u.error(`Failed to query fallback join for model ${p}:`,{where:_,limit:y.limit}),console.error(S),S}return w},C=e({options:n,schema:s,debugLog:a,getFieldName:f,getModelName:d,getDefaultModelName:o,getDefaultFieldName:c,getFieldAttributes:$,transformInput:v,transformOutput:j,transformWhereClause:U});let ue=null;const Ve={transaction:async l=>(ue||(r.transaction?(u.debug(`[${r.adapterName}] - Using provided transaction implementation.`),ue=r.transaction):ue=Xt(Ve)),ue(l)),create:async({data:l,model:b,select:h,forceAllowId:y=!1})=>{K++;const p=K,N=d(b);if(b=o(b),"id"in l&&typeof l.id<"u"&&!y){u.warn(`[${r.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`);const S=new Error().stack?.split(`
|
|
4
|
+
`).filter((m,I)=>I!==1).join(`
|
|
5
|
+
`).replace("Error:","Create method with `id` being called at:");console.log(S),l.id=void 0}a({method:"create"},`${D(p)} ${E(1,4)}`,`${k("create")} ${q("Unsafe Input")}:`,{model:N,data:l});let A=l;r.disableTransformInput||(A=await v(l,b,"create",y)),a({method:"create"},`${D(p)} ${E(2,4)}`,`${k("create")} ${q("Parsed Input")}:`,{model:N,data:A});const w=await Q(`db create ${N}`,{},()=>C.create({data:A,model:N}));a({method:"create"},`${D(p)} ${E(3,4)}`,`${k("create")} ${q("DB Result")}:`,{model:N,res:w});let _=w;return r.disableTransformOutput||(_=await j(w,b,h,void 0)),a({method:"create"},`${D(p)} ${E(4,4)}`,`${k("create")} ${q("Parsed Result")}:`,{model:N,data:_}),_},update:async({model:l,where:b,update:h})=>{K++;const y=K;l=o(l);const p=d(l),N=U({model:l,where:b,action:"update"});a({method:"update"},`${D(y)} ${E(1,4)}`,`${k("update")} ${q("Unsafe Input")}:`,{model:p,data:h});let A=h;r.disableTransformInput||(A=await v(h,l,"update")),a({method:"update"},`${D(y)} ${E(2,4)}`,`${k("update")} ${q("Parsed Input")}:`,{model:p,data:A});const w=await Q(`db update ${p}`,{},()=>C.update({model:p,where:N,update:A}));a({method:"update"},`${D(y)} ${E(3,4)}`,`${k("update")} ${q("DB Result")}:`,{model:p,data:w});let _=w;return r.disableTransformOutput||(_=await j(w,l,void 0,void 0)),a({method:"update"},`${D(y)} ${E(4,4)}`,`${k("update")} ${q("Parsed Result")}:`,{model:p,data:_}),_},updateMany:async({model:l,where:b,update:h})=>{K++;const y=K,p=d(l),N=U({model:l,where:b,action:"updateMany"});l=o(l),a({method:"updateMany"},`${D(y)} ${E(1,4)}`,`${k("updateMany")} ${q("Unsafe Input")}:`,{model:p,data:h});let A=h;r.disableTransformInput||(A=await v(h,l,"update")),a({method:"updateMany"},`${D(y)} ${E(2,4)}`,`${k("updateMany")} ${q("Parsed Input")}:`,{model:p,data:A});const w=await Q(`db updateMany ${p}`,{},()=>C.updateMany({model:p,where:N,update:A}));return a({method:"updateMany"},`${D(y)} ${E(3,4)}`,`${k("updateMany")} ${q("DB Result")}:`,{model:p,data:w}),a({method:"updateMany"},`${D(y)} ${E(4,4)}`,`${k("updateMany")} ${q("Parsed Result")}:`,{model:p,data:w}),w},findOne:async({model:l,where:b,select:h,join:y})=>{K++;const p=K,N=d(l),A=U({model:l,where:b,action:"findOne"});l=o(l);let w,_=!0;if(r.disableTransformJoin)w=y;else{const I=X(l,y,h);I&&(w=I.join,h=I.select),!n.experimental?.joins&&w&&Object.keys(w).length>0&&(_=!1)}a({method:"findOne"},`${D(p)} ${E(1,3)}`,`${k("findOne")}:`,{model:N,where:A,select:h,join:w});const S=await Q(`db findOne ${N}`,{},()=>C.findOne({model:N,where:A,select:h,join:_?w:void 0}));a({method:"findOne"},`${D(p)} ${E(2,3)}`,`${k("findOne")} ${q("DB Result")}:`,{model:N,data:S});let m=S;return r.disableTransformOutput||(m=await j(S,l,h,w)),a({method:"findOne"},`${D(p)} ${E(3,3)}`,`${k("findOne")} ${q("Parsed Result")}:`,{model:N,data:m}),m},findMany:async({model:l,where:b,limit:h,select:y,sortBy:p,offset:N,join:A})=>{K++;const w=K,_=h??n.advanced?.database?.defaultFindManyLimit??100,S=d(l),m=U({model:l,where:b,action:"findMany"});l=o(l);let I,O=!0;if(r.disableTransformJoin)I=A;else{const x=X(l,A,y);x&&(I=x.join,y=x.select),!n.experimental?.joins&&I&&Object.keys(I).length>0&&(O=!1)}a({method:"findMany"},`${D(w)} ${E(1,3)}`,`${k("findMany")}:`,{model:S,where:m,limit:_,sortBy:p,offset:N,join:I});const F=await Q(`db findMany ${S}`,{},()=>C.findMany({model:S,where:m,limit:_,select:y,sortBy:p,offset:N,join:O?I:void 0}));a({method:"findMany"},`${D(w)} ${E(2,3)}`,`${k("findMany")} ${q("DB Result")}:`,{model:S,data:F});let R=F;return r.disableTransformOutput||(R=await Promise.all(F.map(async x=>await j(x,l,void 0,I)))),a({method:"findMany"},`${D(w)} ${E(3,3)}`,`${k("findMany")} ${q("Parsed Result")}:`,{model:S,data:R}),R},delete:async({model:l,where:b})=>{K++;const h=K,y=d(l),p=U({model:l,where:b,action:"delete"});l=o(l),a({method:"delete"},`${D(h)} ${E(1,2)}`,`${k("delete")}:`,{model:y,where:p}),await Q(`db delete ${y}`,{},()=>C.delete({model:y,where:p})),a({method:"delete"},`${D(h)} ${E(2,2)}`,`${k("delete")} ${q("DB Result")}:`,{model:y})},deleteMany:async({model:l,where:b})=>{K++;const h=K,y=d(l),p=U({model:l,where:b,action:"deleteMany"});l=o(l),a({method:"deleteMany"},`${D(h)} ${E(1,2)}`,`${k("deleteMany")} ${q("DeleteMany")}:`,{model:y,where:p});const N=await Q(`db deleteMany ${y}`,{},()=>C.deleteMany({model:y,where:p}));return a({method:"deleteMany"},`${D(h)} ${E(2,2)}`,`${k("deleteMany")} ${q("DB Result")}:`,{model:y,data:N}),N},count:async({model:l,where:b})=>{K++;const h=K,y=d(l),p=U({model:l,where:b,action:"count"});l=o(l),a({method:"count"},`${D(h)} ${E(1,2)}`,`${k("count")}:`,{model:y,where:p});const N=await Q(`db count ${y}`,{},()=>C.count({model:y,where:p}));return a({method:"count"},`${D(h)} ${E(2,2)}`,`${k("count")}:`,{model:y,data:N}),N},createSchema:C.createSchema?async(l,b)=>{const h=Ge(n);return n.secondaryStorage&&!n.session?.storeSessionInDatabase&&delete h.session,C.createSchema({file:b,tables:h})}:void 0,options:{adapterConfig:r,...C.options??{}},id:r.adapterId,...r.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){ge=ge.filter(l=>l.instance!==i)},printDebugLogs(){const l="─".repeat(80),b=ge.filter(y=>y.instance===i);if(b.length===0)return;const h=b.reverse().map(y=>(y.args[0]=`
|
|
6
|
+
${y.args[0]}`,[...y.args,`
|
|
7
|
+
`])).reduce((y,p)=>[...p,...y],[`
|
|
8
|
+
${l}`]);console.log(...h)}}}:{}};return Ve};function D(e){return it()<8?`#${e}`:`${P.fg.magenta}#${e}${P.reset}`}function E(e,t){return`${P.bg.black}${P.fg.yellow}[${e}/${t}]${P.reset}`}function k(e){return`${P.bright}${e}${P.reset}`}function q(e){return`${P.dim}(${e})${P.reset}`}function he(e){if(typeof process<"u"&&process.versions?.node&&typeof require<"u")try{const{inspect:t}=require("node:util");return t(e,{colors:!0,depth:null})}catch{}return JSON.stringify(e,null,2)}function ct(e,t){return e.toLowerCase().endsWith("id")?e.slice(0,-2):t}function Qt(e,t,n){const{type:i,required:r,unique:s,sortable:a}=e,u=Array.isArray(i)?i[0]:i;let o;switch(u){case"string":o="i.string()";break;case"boolean":o="i.boolean()";break;case"date":o="i.date()";break;case"number":o="i.number()";break;case"json":o="i.json()";break;case"number[]":o="i.json()";break;case"string[]":o="i.json()";break;default:o="i.string()"}return s&&(o+=".unique()"),r===!1&&(o+=".optional()"),a&&(o+=".indexed()"),t==="user"&&n!=="email"&&!o.endsWith(".optional()")&&(o+=".optional()"),o}function Ye(e,t,n){return e==="user"?"$users":n?`${t}s`:t}function en(e){return e.charAt(0).toLowerCase()+e.slice(1)}function tn(e,t){const n={},i={};for(const[r,s]of Object.entries(e)){const{modelName:a}=s;i[a]=Ye(a,r,t)}for(const[r,s]of Object.entries(e)){const{modelName:a,fields:u}=s,o=Ye(a,r,t);for(const[c,d]of Object.entries(u)){const{references:f}=d;if(f){const{model:g,onDelete:$}=f,v=i[g];if(!v){console.warn(`Warning: Could not find entity name for model "${g}" referenced by ${a}.${c}`);continue}const j=ct(c,g),U=o.replace("$",""),X=j.charAt(0).toUpperCase()+en(j.slice(1)),H=`${U}${X}`,C=o.replace("$","");n[H]={forward:{on:o,has:"one",label:j,onDelete:$||"cascade"},reverse:{on:v,has:"many",label:C}}}}}return n}function nn(e,t){const n={};for(const[u,o]of Object.entries(e)){const{modelName:c,fields:d}=o,f=[];for(const[$,v]of Object.entries(d)){const j=Qt(v,c,$);f.push(`${$}: ${j}`)}const g=c==="user"?"$users":t?`${u}s`:u;n[g]=`i.entity({
|
|
9
|
+
${f.join(`,
|
|
8
10
|
`)}
|
|
9
|
-
})`}const
|
|
10
|
-
`),
|
|
11
|
+
})`}const i=tn(e,t),r=Object.entries(n).map(([u,o])=>` ${u}: ${o}`).join(`,
|
|
12
|
+
`),s=Object.entries(i).map(([u,o])=>{const c=o.forward,d=o.reverse;return` ${u}: {
|
|
11
13
|
forward: {
|
|
12
14
|
on: "${c.on}",
|
|
13
15
|
has: "${c.has}",
|
|
@@ -15,21 +17,21 @@ ${u}`]);console.log(...p)}}}:{}};return V};function I(e){return Ke()<8?`#${e}`:`
|
|
|
15
17
|
onDelete: "${c.onDelete}"`:""}
|
|
16
18
|
},
|
|
17
19
|
reverse: {
|
|
18
|
-
on: "${
|
|
19
|
-
has: "${
|
|
20
|
-
label: "${
|
|
20
|
+
on: "${d.on}",
|
|
21
|
+
has: "${d.has}",
|
|
22
|
+
label: "${d.label}"
|
|
21
23
|
}
|
|
22
24
|
}`}).join(`,
|
|
23
|
-
`),
|
|
25
|
+
`),a=s?`,
|
|
24
26
|
links: {
|
|
25
|
-
${
|
|
27
|
+
${s}
|
|
26
28
|
}`:"";return`// Docs: https://www.instantdb.com/docs/modeling-data
|
|
27
29
|
|
|
28
30
|
import { i } from "@instantdb/react"
|
|
29
31
|
|
|
30
32
|
export const authSchema = i.schema({
|
|
31
33
|
entities: {
|
|
32
|
-
${
|
|
33
|
-
}${
|
|
34
|
+
${r}
|
|
35
|
+
}${a}
|
|
34
36
|
})
|
|
35
|
-
`}function
|
|
37
|
+
`}function rn(e,t,n){return e==="user"?"$users":n?`${t}s`:t}function on(e,t){const n={};for(const[i,r]of Object.entries(e)){const{modelName:s}=r;n[s]=rn(s,i,t)}return n}function sn({db:e,model:t,modelSchema:n,data:i,entityNameMap:r}){const s=[],{fields:a,modelName:u}=n;for(const[o,c]of Object.entries(a)){const{references:d}=c;if(d){const{model:f}=d;if(!r[f]){console.warn(`Warning: Could not find entity name for model "${f}" referenced by ${u}.${o}`);continue}const $=i[o];if($!=null){const j={[ct(o,f)]:$},U=e.tx[t][i.id].link(j);s.push(U)}}}return s}const an=({db:e,usePlural:t=!0,debugLogs:n=!1})=>{const i=Zt({config:{customIdGenerator:It,adapterId:"instantdb-adapter",adapterName:"InstantDB Adapter",usePlural:t,debugLogs:n,supportsJSON:!0,supportsDates:!1,supportsBooleans:!0,supportsNumericIds:!1},adapter:({debugLog:r,getDefaultModelName:s,getFieldName:a,schema:u})=>({create:async({data:o,model:c})=>{const d=s(c),f=u[d];if(d==="session"){const X=(await e.query({$users:{$:{where:{id:o.userId}}}})).$users;if(!X.length)throw new Error(`$users entity not found: ${o.userId}`);const H=X[0];r("Create Token",H.email);const C=await e.auth.createToken(H.email),ue=a({model:c,field:"token"});Object.assign(o,{[ue]:C})}d==="user"&&(c="$users"),r("Create",c,he(o));const g=on(u,t),$=e.tx[c][o.id].create(o),v=sn({db:e,model:c,modelSchema:f,data:o,entityNameMap:g}),j=[$,...v];return await e.transact(j),o},update:async({update:o,model:c,where:d})=>{s(c)==="user"&&(c="$users");const f=await oe({db:e,model:c,where:d,debugLog:r});if(!f.length)return null;r("Update:",f.map($=>$.id),he(o));const g=f.map($=>e.tx[c][$.id].update(o));return await e.transact(g),{...f[0],...o}},updateMany:async({update:o,model:c,where:d})=>{s(c)==="user"&&(c="$users");const f=await oe({db:e,model:c,where:d,debugLog:r});if(!f.length)return 0;r("Update:",f.map($=>$.id),he(o));const g=f.map($=>e.tx[c][$.id].update(o));return await e.transact(g),f.length},delete:async({model:o,where:c})=>{s(o)==="user"&&(o="$users");const d=await oe({db:e,model:o,where:c,debugLog:r});if(!d.length)return;const f=d.map(g=>e.tx[o][g.id].delete());await e.transact(f),s(o)==="session"&&Promise.all(d.map(async g=>{try{const $=a({model:o,field:"token"});await e.auth.signOut({refresh_token:g[$]})}catch{}}))},deleteMany:async({model:o,where:c})=>{s(o)==="user"&&(o="$users");const d=await oe({db:e,model:o,where:c,debugLog:r});if(!d.length)return 0;const f=d.map(g=>e.tx[o][g.id].delete());return await e.transact(f),s(o)==="session"&&Promise.all(d.map(async g=>{try{const $=a({model:o,field:"token"});await e.auth.signOut({refresh_token:g[$]})}catch{}})),d.length},findOne:async({model:o,where:c})=>{s(o)==="user"&&(o="$users");const d=await oe({db:e,model:o,where:c,debugLog:r});return d.length?d[0]:null},findMany:async({model:o,where:c,limit:d,sortBy:f,offset:g})=>(s(o)==="user"&&(o="$users"),await oe({db:e,model:o,where:c,limit:d,sortBy:f,offset:g,debugLog:r})),count:async({model:o,where:c})=>(s(o)==="user"&&(o="$users"),(await oe({db:e,model:o,where:c,debugLog:r})).length),createSchema:async({file:o="./auth.schema.ts",tables:c})=>({code:nn(c,t),path:o})})});return(r=>{const s=i(r),a=s.findOne.bind(s);return{...s,findOne:async u=>{const o=await a(u);if(u.model==="session"&&u.join?.user&&o&&!o.user&&o.userId){const c=await a({model:"user",where:[{field:"id",value:o.userId}]});return{...o,user:c}}return o}}})};async function oe({db:e,debugLog:t,model:n,where:i,limit:r,offset:s,sortBy:a}){let u;a&&(u={[a.field]:a.direction});const o={[n]:{$:{where:ut(i),limit:r,offset:s,order:u}}};t("Query",he(o));const c=await e.query(o);return t("Result",he(c)),c[n]}function ut(e){const t={};return e?.forEach(n=>{switch(n.operator){case"eq":t[n.field]=n.value;break;case"in":t[n.field]={$in:n.value};break;case"contains":t[n.field]={$like:`%${n.value}%`};break;case"starts_with":t[n.field]={$like:`${n.value}%`};break;case"ends_with":t[n.field]={$like:`%${n.value}`};break;case"ne":t[n.field]={$not:n.value};break;case"gt":t[n.field]={$gt:n.value};break;case"gte":t[n.field]={$gte:n.value};break;case"lt":t[n.field]={$lt:n.value};break;case"lte":t[n.field]={$lte:n.value};break}}),t}async function cn(e,t){const n=await e.getAuth();t&&n?.id!==t?.userId&&e.auth.signInWithToken(t.token),!t&&n&&e.auth.signOut()}exports.instantAdapter=an;exports.instantAuth=cn;exports.parseWhere=ut;
|