@asaidimu/utils-database 3.1.9 → 3.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.cts +11944 -0
- package/index.d.ts +11636 -819
- package/index.js +3 -1
- package/index.mjs +3 -1
- package/package.json +5 -3
- package/rolldown-runtime-QTnfLwEv.mjs +1 -0
- package/index.d.mts +0 -989
package/index.mjs
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{SystemError as e}from"@asaidimu/utils-error";import{Buffer as t}from"buffer";import{createEventBus as r}from"@asaidimu/utils-events";import{v7 as s}from"uuid";var n,i,a=Object.create,o=Object.defineProperty,c=Object.getOwnPropertyDescriptor,h=Object.getOwnPropertyNames,d=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[h(e)[0]])((t={exports:{}}).exports,t),t.exports},p=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of h(t))u.call(e,n)||n===r||o(e,n,{get:()=>t[n],enumerable:!(s=c(t,n))||s.enumerable});return e},m=(e,t,r)=>(r=null!=e?a(d(e)):{},p(e&&e.__esModule?r:o(r,"default",{value:e,enumerable:!0}),e)),f=e=>p(o({},"__esModule",{value:!0}),e),y=l({"node_modules/.bun/@asaidimu+events@1.1.2/node_modules/@asaidimu/events/index.js"(e,t){var r,s=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))a.call(e,c)||c===r||s(e,c,{get:()=>t[c],enumerable:!(o=n(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,n=0;const i=new Map,a=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,n+=t,i.set(e,(i.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach(({name:t,payload:r})=>{const s=performance.now();try{(a.get(t)||[]).forEach(e=>e(r))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)})},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),u=e=>{const r=t.get(e);r?a.set(e,Array.from(r)):a.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(a.get(t)||[]).forEach(e=>e(r))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),u(e),()=>{s.delete(r),0===s.size?(t.delete(e),a.delete(e)):u(e)}},emit:({name:t,payload:s})=>{if(e.async)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():d(),void(o&&o.postMessage({name:t,payload:s}));const n=performance.now();try{(a.get(t)||[]).forEach(e=>e(s)),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-n)},getMetrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:i,averageEmitDuration:s>0?n/s:0}),clear:()=>{t.clear(),a.clear(),r=[],s=0,n=0,i.clear(),o&&(o.close(),o=null)}}}}}),w=l({"node_modules/.bun/@asaidimu+query@1.1.2/node_modules/@asaidimu/query/index.js"(e,t){var r,s=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>d,createPaginator:()=>E,createProjector:()=>_,createSorter:()=>$}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))!a.call(e,c)&&c!==r&&s(e,c,{get:()=>t[c],enumerable:!(o=n(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:"offset",offset:e,limit:t},this}cursor(e,t,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"computed",expression:e,alias:t}),this}case(e,t,r){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"case",conditions:e,else:t,alias:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?s(t,e):function(e){return"computed"===e?.type}(t)?s(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(n(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every(t=>n(e,t))],["or",(e,t)=>t.some(t=>n(e,t))],["not",(e,t)=>!t.every(t=>n(e,t))],["nor",(e,t)=>!t.some(t=>n(e,t))],["xor",(e,t)=>1===t.filter(t=>n(e,t)).length]]);function s(r,s){let n=r.arguments.map(e=>t(s,e));if(e[r.function])return e[r.function](...n);throw new Error(`Function ${r.function} not found!`)}function n(s,n){if(function(e){return!!e&&void 0!==e.conditions}(n))return function(e,t){let{operator:s,conditions:n}=t,i=r.get(s);if(i)return i(e,n);throw new Error(`Unsupported logical operator: ${s}`)}(s,n);if(!n||!n.field)return!1;let{field:i,operator:a,value:o}=n,c=s[i],h=t(s,o),d=new Map([["eq",(e,t)=>e===t],["neq",(e,t)=>e!==t],["lt",(e,t)=>e<t],["lte",(e,t)=>e<=t],["gt",(e,t)=>e>t],["gte",(e,t)=>e>=t],["in",(e,t)=>Array.isArray(t)&&t.includes(e)],["nin",(e,t)=>Array.isArray(t)&&!t.includes(e)],["contains",(e,t)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),u=e[a]||d.get(a);if(u)return u(c,h);throw new Error(`Unsupported comparison operator: ${a}`)}return{resolve:t,evaluate:n}}function d(e){let{evaluate:t}=h(e),r=new WeakMap;function s(e,s){let n=r.get(e);n||(n=new Map,r.set(e,n));let i=JSON.stringify(s);if(n.has(i))return n.get(i);let a=t(e,s);return n.set(i,a),a}return{matcher:s,match:s}}var u=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},l=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(l(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce((e,t)=>e?.[t],e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map(e=>p(e,t))),r}return e}},m=async(e,t,r,s)=>{try{if(((e,t)=>{if(!e.relation)throw new u("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new u(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new u("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new u("Source data must be an array","INVALID_SOURCE_DATA");let n,i=e[r.relation];return r.query?.filters&&l(r.query.filters)&&(n=((e,t)=>{let r=new Map;return e.forEach(e=>{let s=e[t];r.has(s)||r.set(s,[]),r.get(s).push(e)}),r})(i,r.query.filters.field)),(await Promise.all(t.map(async e=>{let t,a=((e,t)=>{if(!e)return{};let r=p(e.filters,t);return{...e,filters:r}})(r.query,e);return t=a.filters&&l(a.filters)&&n?.has(a.filters.value)?n.get(a.filters.value)||[]:i.filter(e=>s.matcher(e,a.filters)),((e,t,r)=>{let s=r.alias||r.relation;return[{...e,[s]:t}]})(e,await[e=>a.sort?s.sorter(e,a.sort):e,e=>a.projection?s.projector(e,a.projection):e,async e=>a.pagination?await s.paginator(e,a.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(t)),r)}))).flat()}catch(e){throw e instanceof u?e:new u(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,r,s)=>r.reduce(async(t,r)=>m(e,await t,r,s),Promise.resolve(t));function y(){return{join:f}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},g=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new w(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort((e,r)=>{for(let s of t){let{field:t,direction:n}=s,i=e[t],a=r[t];try{if("asc"!==n&&"desc"!==n)throw new g(n);let e=b(i,a,n);if(0!==e)return e}catch(e){throw e instanceof w||e instanceof g?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function $(){return{sort:v}}function _(e){let{resolve:t}=h(e);function r(e,s){let n={};return s.include?.length&&function(e,t,s){for(let n of t){if("string"==typeof n){let t=n;s[t]=e[t];continue}for(let[t,i]of Object.entries(n))if(Object.prototype.hasOwnProperty.call(e,t)){let n=r(e[t],i);s[t]=n}}}(e,s.include,n),s.exclude?.length&&function(e,t,s){0===Object.keys(s).length&&Object.assign(s,e);for(let e of t)if("string"!=typeof e)for(let[t,n]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(s,t))continue;let e=s[t];e&&"object"==typeof e?s[t]=r(e,n):delete s[t]}else delete s[e]}(e,s.exclude,n),s.computed?.length&&function(e,r,s){for(let n of r)s[n.alias]=t(e,n)}(e,s.computed,n),n}return{project:r}}async function*k(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:s}=t,n=0,i=s,a=[];for await(let t of e)i<=0&&(yield a,a=[],i=s),n<r?n++:(a.push(t),i--);a.length>0&&(yield a)}(e,t):yield*async function*(e,t,r){let{cursor:s,limit:n,direction:i}=t,a=n,o=void 0===s,c=[];if("forward"===i)for await(let t of e)a<=0&&(yield c,c=[],a=n),o?(c.push(t),a--):o=r(t)===s;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let i=t[e];o?(c.push(i),a--,a<=0&&(yield c,c=[],a=n)):o=r(i)===s}}c.length>0&&(yield c)}(e,t,r)}function E(){return{paginate:k}}}}),g=l({"node_modules/.bun/just-once@1.1.0/node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,r;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?r:(t=!0,r=e.apply(this,arguments))}}}}),b=l({"node_modules/.bun/isomorphic-textencoder@1.0.1/node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),v=l({"node_modules/.bun/just-debounce-it@1.1.0/node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,r){var s;return function(){if(!t)return e.apply(this,arguments);var n=this,i=arguments,a=r&&!s;return clearTimeout(s),s=setTimeout(function(){if(s=null,!a)return e.apply(n,i)},t),a?e.apply(this,arguments):void 0}}}}),$=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function r(e){if(0===e.length)return".";let t=n(e);return t=t.reduce(i,[]),s(...t)}function s(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function n(e){if(0===e.length)return[];if("/"===e)return["/"];let t=e.split("/");return""===t[t.length-1]&&t.pop(),"/"===e[0]?t[0]="/":"."!==t[0]&&t.unshift("."),t}function i(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new Error("Unable to normalize path - traverses above root directory");if("."===e[0])return e.push(t),e}return".."===e[e.length-1]?(e.push(".."),e):(e.pop(),e)}return e.push(t),e}t.exports={join:s,normalize:r,split:n,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let n of e)t=n.startsWith("/")?n:r(s(t,n));return t}}}}),_=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function r(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var s=r("EEXIST"),n=r("ENOENT"),i=r("ENOTDIR"),a=r("ENOTEMPTY"),o=r("ETIMEDOUT"),c=r("EISDIR");t.exports={EEXIST:s,ENOENT:n,ENOTDIR:i,ENOTEMPTY:a,ETIMEDOUT:o,EISDIR:c}}}),k=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=$(),{EEXIST:s,ENOENT:n,ENOTDIR:i,ENOTEMPTY:a,EISDIR:o}=_();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:"dir",size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get("/"))-1}_countInodes(e){let t=1;for(let[r,s]of e)0!==r&&(t+=this._countInodes(s));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[r,s]of e)0!==r&&(t=Math.max(t,this._maxInode(s)));return t}print(e=this._root.get("/")){let t="";const r=(e,s)=>{for(let[n,i]of e){if(0===n)continue;let e=i.get(0),a=e.mode.toString(8);t+=`${"\t".repeat(s)}${n}\t${a}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",r(i,s+1))}};return r(e,0),t}parse(e){let t=0;function r(e){const r=++t,s=1===e.length?"dir":"file";let[n,i,a]=e;return n=parseInt(n,8),i=i?parseInt(i):0,a=a?parseInt(a):Date.now(),new Map([[0,{mode:n,type:s,size:i,mtimeMs:a,ino:r}]])}let s=e.trim().split("\n"),n=this._makeRoot(),i=[{indent:-1,node:n},{indent:0,node:null}];for(let e of s){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[s,...n]=e.split("\t"),a=r(n);if(t<=i[i.length-1].indent)for(;t<=i[i.length-1].indent;)i.pop();i.push({indent:t,node:a}),i[i.length-2].node.set(s,a)}return n}_lookup(e,t=!0){let s=this._root,i="/",a=r.split(e);for(let o=0;o<a.length;++o){let c=a[o];if(s=s.get(c),!s)throw new n(e);if(t||o<a.length-1){const e=s.get(0);if("symlink"===e.type){let t=r.resolve(i,e.target);s=this._lookup(t)}i=i?r.join(i,c):c}}return s}mkdir(e,{mode:t}){if("/"===e)throw new s;let n=this._lookup(r.dirname(e)),i=r.basename(e);if(n.has(i))throw new s;let a=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};a.set(0,o),n.set(i,a)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;if(t.size>1)throw new a;let s=this._lookup(r.dirname(e)),n=r.basename(e);s.delete(n)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;return[...t.keys()].filter(e=>"string"==typeof e)}writeStat(e,t,{mode:s}){let n,i;try{i=this.stat(e)}catch(e){}if(void 0!==i){if("dir"===i.type)throw new o;null==s&&(s=i.mode),n=i.ino}null==s&&(s=438),null==n&&(n=this.autoinc());let a=this._lookup(r.dirname(e)),c=r.basename(e),h={mode:s,type:"file",size:t,mtimeMs:Date.now(),ino:n},d=new Map;return d.set(0,h),a.set(c,d),h}unlink(e){let t=this._lookup(r.dirname(e)),s=r.basename(e);t.delete(s)}rename(e,t){let s=r.basename(t),n=this._lookup(e);this._lookup(r.dirname(t)).set(s,n),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let s,n;try{let e=this.stat(t);null===n&&(n=e.mode),s=e.ino}catch(e){}null==n&&(n=40960),null==s&&(s=this.autoinc());let i=this._lookup(r.dirname(t)),a=r.basename(t),o={mode:n,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:s},c=new Map;return c.set(0,o),i.set(a,c),o}_du(e){let t=0;for(const[r,s]of e.entries())t+=0===r?s.size:this._du(s);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),E={};function I(){return i||(i=new n),i}function A(e,t=I()){let r;return t._withIDBStore("readwrite",t=>{r=t.get(e)}).then(()=>r.result)}function S(e,t,r=I()){return r._withIDBStore("readwrite",r=>{r.put(t,e)})}function O(e,t,r=I()){return r._withIDBStore("readwrite",r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}})}function x(e,t=I()){return t._withIDBStore("readwrite",t=>{t.delete(e)})}function N(e=I()){return e._withIDBStore("readwrite",e=>{e.clear()})}function T(e=I()){const t=[];return e._withIDBStore("readwrite",e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function j(e=I()){return e._close()}((e,t)=>{for(var r in t)o(e,r,{get:t[r],enumerable:!0})})(E,{Store:()=>n,clear:()=>N,close:()=>j,del:()=>x,get:()=>A,keys:()=>T,set:()=>S,update:()=>O});var C,R,M=(C={"node_modules/.bun/@isomorphic-git+idb-keyval@3.3.2/node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){n=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise((e,t)=>{const r=indexedDB.open(this._dbName);r.onerror=()=>t(r.error),r.onsuccess=()=>e(r.result),r.onupgradeneeded=()=>{r.result.createObjectStore(this._storeName)}}))}_withIDBStore(e,t){return this._init(),this._dbp.then(r=>new Promise((s,n)=>{const i=r.transaction(this.storeName,e);i.oncomplete=()=>s(),i.onabort=i.onerror=()=>n(i.error),t(i.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}}}},function(){return C&&(R=(0,C[h(C)[0]])(C=0)),R}),D=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(M(),f(E));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename)}saveSuperblock(e){return r.set("!root",e,this._store)}loadSuperblock(){return r.get("!root",this._store)}readFile(e){return r.get(e,this._store)}writeFile(e,t){return r.set(e,t,this._store)}unlink(e){return r.del(e,this._store)}wipe(){return r.clear(this._store)}close(){return r.close(this._store)}}}}),P=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(e,t){t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+"/.superblock.txt").then(e=>e.ok?e.text():null)}async readFile(e){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),q=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(M(),f(E)),s=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await r.update("lock",r=>{const s=Date.now()+e;return t=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:s}:r,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,s,n;if(await r.update("lock",r=>{const i=Date.now(),a=i+e;return s=r&&r.expires<i,t=void 0===r||s,n=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:a}:r,this._lock},this._store),n)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:r}={}){for(;t--;){if(await this.acquire({ttl:r}))return!0;await s(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,s,n;if(await r.update("lock",r=>(t=e||r&&r.holder===this._id,s=void 0===r,n=r&&r.holder!==this._id,this._lock=t?void 0:r,this._lock),this._store),await r.close(this._store),!t&&!e){if(s)throw new Error("Mutex double-freed");if(n)throw new Error("Mutex lost ownership")}return t}}}}),F=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(e,t){t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+"_lock",{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,r)=>{const s=new AbortController;setTimeout(()=>{s.abort(),r(new Error("Mutex timeout"))},e),navigator.locks.request(this._database+"_lock",{signal:s.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+"_lock",{steal:!0},e=>!0)}}}}),L=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=b(),n=v(),i=k(),{ENOENT:a,ENOTEMPTY:o,ETIMEDOUT:c}=_(),h=D(),d=P(),u=q(),l=F(),p=$();t.exports=class{constructor(){this.saveSuperblock=n(()=>{this.flush()},500)}async init(e,{wipe:t,url:r,urlauto:s,fileDbName:n=e,db:a=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=a||new h(n,o),this._mutex=navigator.locks?new l(e):new u(c,p),this._cache=new i(e),this._opts={wipe:t,url:r},this._needsWipe=!!t,r&&(this._http=new d(r),this._urlauto=!!s)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,r){let s=p.split(p.dirname(e)),n=s.shift();for(let e of s){n=p.join(n,e);try{this._cache.mkdir(n,{mode:511})}catch(e){}}return this._cache.writeStat(e,t,r)}async readFile(e,t){const r="string"==typeof t?t:t&&t.encoding;if(r&&"utf8"!==r)throw new Error('Only "utf8" encoding is supported in readFile');let n=null,i=null;try{i=this._cache.stat(e),n=await this._idb.readFile(i.ino)}catch(e){if(!this._urlauto)throw e}if(!n&&this._http){let t=this._cache.lstat(e);for(;"symlink"===t.type;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);n=await this._http.readFile(e)}if(n&&(i&&i.size==n.byteLength||(i=await this._writeStat(e,n.byteLength,{mode:i?i.mode:438}),this.saveSuperblock()),"utf8"===r?n=s(n):n.toString=()=>s(n)),!i)throw new a(e);return n}async writeFile(e,t,s){const{mode:n,encoding:i="utf8"}=s;if("string"==typeof t){if("utf8"!==i)throw new Error('Only "utf8" encoding is supported in writeFile');t=r(t)}const a=await this._cache.writeStat(e,t.byteLength,{mode:n});await this._idb.writeFile(a.ino,t)}async unlink(e,t){const r=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==r.type&&await this._idb.unlink(r.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:r=511}=t;this._cache.mkdir(e,{mode:r})}rmdir(e,t){if("/"===e)throw new o;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let r=await this._http.sizeFile(e);await this._writeStat(e,r,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),U=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(e,t){t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),B=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=L(),s=U(),n=$();function i(e,t,...r){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=n.normalize(e),t,...r]}function a(e,t,r,...s){return void 0!==r&&"function"!=typeof r||(r={}),"string"==typeof r&&(r={encoding:r}),[e=n.normalize(e),t,r,...s]}function o(e,t,...r){return[n.normalize(e),n.normalize(t),...r]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,i,!1),this.writeFile=this._wrap(this.writeFile,a,!0),this.unlink=this._wrap(this.unlink,i,!0),this.readdir=this._wrap(this.readdir,i,!1),this.mkdir=this._wrap(this.mkdir,i,!0),this.rmdir=this._wrap(this.rmdir,i,!0),this.rename=this._wrap(this.rename,o,!0),this.stat=this._wrap(this.stat,i,!1),this.lstat=this._wrap(this.lstat,i,!1),this.readlink=this._wrap(this.readlink,i,!1),this.symlink=this._wrap(this.symlink,o,!0),this.backFile=this._wrap(this.backFile,i,!0),this.du=this._wrap(this.du,i,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new r,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(this._initPromiseResolve(),this._initPromiseResolve=null),t.defer||this.stat("/")}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,r){return async(...s)=>{s=t(...s);let n={name:e.name,args:s};this._operations.add(n);try{return await this._activate(),await e.apply(this,s)}finally{this._operations.delete(n),r&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(this._deactivationPromise=this._backend.deactivate?this._backend.deactivate():Promise.resolve()),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,r){return await this._backend.writeFile(e,t,r),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){const r=await this._backend.stat(e,t);return new s(r)}async lstat(e,t){const r=await this._backend.lstat(e,t);return new s(r)}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}}}),V=l({"node_modules/.bun/@isomorphic-git+lightning-fs@4.6.2/node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=g(),s=B();function n(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=r(t)]}t.exports=class{constructor(...e){this.promises=new s(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,r){const[s,i]=n(t,r);this.promises.readFile(e,t).then(s).catch(i)}writeFile(e,t,r,s){const[i,a]=n(r,s);this.promises.writeFile(e,t,r).then(i).catch(a)}unlink(e,t,r){const[s,i]=n(t,r);this.promises.unlink(e,t).then(s).catch(i)}readdir(e,t,r){const[s,i]=n(t,r);this.promises.readdir(e,t).then(s).catch(i)}mkdir(e,t,r){const[s,i]=n(t,r);this.promises.mkdir(e,t).then(s).catch(i)}rmdir(e,t,r){const[s,i]=n(t,r);this.promises.rmdir(e,t).then(s).catch(i)}rename(e,t,r){const[s,i]=n(r);this.promises.rename(e,t).then(s).catch(i)}stat(e,t,r){const[s,i]=n(t,r);this.promises.stat(e).then(s).catch(i)}lstat(e,t,r){const[s,i]=n(t,r);this.promises.lstat(e).then(s).catch(i)}readlink(e,t,r){const[s,i]=n(t,r);this.promises.readlink(e).then(s).catch(i)}symlink(e,t,r){const[s,i]=n(r);this.promises.symlink(e,t).then(s).catch(i)}backFile(e,t,r){const[s,i]=n(t,r);this.promises.backFile(e,t).then(s).catch(i)}du(e,t){const[r,s]=n(t);this.promises.du(e).then(r).catch(s)}flush(e){const[t,r]=n(e);this.promises.flush().then(t).catch(r)}}}}),z="$id",H=(e=>(e.SCHEMA_NOT_FOUND="SCHEMA_NOT_FOUND",e.SCHEMA_ALREADY_EXISTS="SCHEMA_ALREADY_EXISTS",e.INVALID_SCHEMA_NAME="INVALID_SCHEMA_NAME",e.INVALID_SCHEMA_DEFINITION="INVALID_SCHEMA_DEFINITION",e.SUBSCRIPTION_FAILED="SUBSCRIPTION_FAILED",e.INTERNAL_ERROR="INTERNAL_ERROR",e.INVALID_DATA="INVALID_DATA",e.CONFLICT="CONFLICT",e.TRANSIENT_ERROR="TRANSIENT_ERROR",e.TRANSACTION_FAILED="TRANSACTION_FAILED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.INVALID_OPERATION="INVALID_OPERATION",e))(H||{}),J=class extends Error{type;schema;issues;constructor(e,t,r,s,n){super(t,{cause:s}),this.name="DatabaseError",this.type=e,this.schema=r,this.issues=n}};function K(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce((e,[r,s])=>(r.startsWith("$")?t[r]=s:e[r]=s,e),{}),t]}function W(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new J("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function Y(e,t){const r=[];for(const s of t.fields){const t=e[s];if(null==t)return null;r.push(String(t))}return r.join("\0")}function G(e,t){if(!t.partial)return!0;const{field:r,value:s}=t.partial;return e[r]===s}var X=class{constructor(e,t="$id",r=[]){this.storeName=e,this.keyPath=t;for(const e of r)this.indexes.set(e.name,{definition:e,map:new Map})}data=new Map;indexes=new Map;nextId=1;name(){return this.storeName}async open(){}_snapshotMemory(){const e=new Map;for(const[t,r]of this.data)e.set(t,{...r});const t=new Map;for(const[e,r]of this.indexes){const s=new Map;for(const[e,t]of r.map)s.set(e,new Set(t));t.set(e,{definition:r.definition,map:s})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;const t={definition:e,map:new Map};this.indexes.set(e.name,t);for(const e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){const r=this.indexes.get(e);if(!r)throw new J("INTERNAL_ERROR",`Index '${e}' does not exist on this store`);const s=String(t),n=r.map.get(s);if(!n||0===n.size)return[];const i=[];for(const e of n){const t=this.data.get(e);t&&i.push(this.clone(t))}return i}async getByKeyRange(e,t){const r=this.indexes.get(e);if(!r)throw new J("INTERNAL_ERROR",`Index '${e}' does not exist on this store`);const s=[];for(const[e,n]of r.map.entries())if(this.isInKeyRange(e,t))for(const e of n){const t=this.data.get(e);t&&s.push(this.clone(t))}return s}async add(e){const t=Array.isArray(e)?e:[e],r=[];for(const e of t){let t=e[this.keyPath];if(void 0!==t&&""!==t||(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new J("CONFLICT",`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);const s=Object.freeze(this.clone(e));this.data.set(t,s),this.indexDocument(s),r.push(t)}return Array.isArray(e)?r:r[0]}async put(e){const t=this.getKey(e),r=this.data.get(t);W(r,e),this.enforceUniqueIndexes(e,r),r&&this.unindexDocument(r);const s=Object.freeze(this.clone(e));return this.data.set(t,s),this.indexDocument(s),t}async batch(e){const t=new Map,r=e=>t.has(e)?t.get(e):this.data.get(e);for(const s of e)if("add"===s.type||"put"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const n of e){let e;if("add"===s.type){e=n[this.keyPath],void 0!==e&&""!==e||(e=String(this.nextId++),n[this.keyPath]=e);const t=r(e);if(null!=t)throw new J("CONFLICT",`Duplicate key ${e}`)}else e=this.getKey(n);W(r(e)??void 0,n),t.set(e,Object.freeze(this.clone(n)))}}else{const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)t.set(r,null)}for(const[e,r]of t.entries()){const t=this.data.get(e);t&&this.unindexDocument(t),null===r?this.data.delete(e):(this.enforceUniqueIndexes(r,t),this.data.set(e,r),this.indexDocument(r))}}async delete(e){const t=Array.isArray(e)?e:[e];for(const e of t){const t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(const e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(null!==t)throw new J("INTERNAL_ERROR",`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(const t of e)if("add"===t.type)await this.add(t.data);else if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){const t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t="forward",r){let s=Array.from(this.data.entries());r&&(s=s.filter(([e])=>this.isInKeyRange(e,r)));const n=s.sort(([e],[t])=>e>t?1:e<t?-1:0);"backward"===t&&n.reverse();let i=null,a=0;for(;a<n.length;){const[t,r]=n[a],{value:s,done:o,offset:c}=await e(this.clone(r),t,null);if(i=s,o)break;a+=c&&c>0?c:1}return i}getKey(e){const t=e[this.keyPath];if(null==t)throw new J("INVALID_DATA",`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(const t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!G(t,e.definition))return;const r=Y(t,e.definition);if(null===r)return;const s=t[this.keyPath];if(void 0===s)return;let n=e.map.get(r);n||(n=new Set,e.map.set(r,n)),n.add(s)}unindexDocument(e){const t=e[this.keyPath];if(void 0!==t)for(const r of this.indexes.values()){const s=Y(e,r.definition);if(null===s)continue;const n=r.map.get(s);n&&(n.delete(t),0===n.size&&r.map.delete(s))}}enforceUniqueIndexes(e,t){const r=e[this.keyPath],s=t?t[this.keyPath]:void 0;for(const t of this.indexes.values()){if(!t.definition.unique)continue;if(!G(e,t.definition))continue;const n=Y(e,t.definition);if(null===n)continue;const i=t.map.get(n);if(i&&0!==i.size)for(const e of i)if(e!==r&&e!==s)throw new J("CONFLICT",`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(", ")}]`)}}isInKeyRange(e,t){if(!t)return!0;const{lower:r,upper:s,lowerOpen:n=!1,upperOpen:i=!1}=t;return(void 0===r||(n?e>r:e>=r))&&(void 0===s||(i?e<s:e<=s))}};function Q(e){return new X(e.database,e.keyPath)}var Z=class t extends e{constructor(e,r){super({code:"SYNC_ERROR",message:e,cause:r}),this.name="SyncError",Object.setPrototypeOf(this,t.prototype)}},ee=class e extends Z{constructor(t){super(`[ArtifactContainer] Operation timed out: ${t}`),this.name="TimeoutError",Object.setPrototypeOf(this,e.prototype)}},te=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise(e=>t=e);if(this.waiters.push(t),null==e)return void await r;let s;await Promise.race([r.then(()=>clearTimeout(s)),new Promise((r,n)=>{s=setTimeout(()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),n(new ee("Mutex lock timed out"))},e)})])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},re=class{mutex=new te({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}resolve(e){if(this._done)throw new Error("Cannot resolve: operation is already completed.");if(this.running())throw new Error("Cannot resolve: operation is currently running.");this._value=e,this._done=!0}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,r="Operation timed out"){if(null==t)return e;let s;return Promise.race([e.then(e=>(clearTimeout(s),e)),new Promise((e,n)=>{s=setTimeout(()=>n(new ee(r)),t)})])}},se=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new re({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise((e,t)=>{const r=indexedDB.open(this.config.database);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)})}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise((e,s)=>{const n=indexedDB.open(this.config.database,r);n.onerror=()=>s(new Error(`Failed to upgrade database: ${n.error?.message}`)),n.onupgradeneeded=e=>{const r=e.target.result,s=e.target.transaction;t(r,s)},n.onsuccess=()=>e(n.result)})}async ensureStore(e,t="$id",r=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(s=>{if(s.objectStoreNames.contains(this.schemasStoreName)||s.createObjectStore(this.schemasStoreName,{keyPath:"name"}),!s.objectStoreNames.contains(e)){const n=s.createObjectStore(e,{keyPath:t});for(const e of r){const t=1===e.fields.length?e.fields[0]:e.fields;n.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((r,s)=>{const n=s.objectStore(e);if(n.indexNames.contains(t.name))return;const i=1===t.fields.length?t.fields[0]:t.fields;n.createIndex(t.name,i,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((r,s)=>{const n=s.objectStore(e);n.indexNames.contains(t)&&n.deleteIndex(t)})}getConnection=async()=>{const e=await this.connectionInitializer.do(async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new J("CONNECTION_FAILED",`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t="readwrite"){return(await this.getConnection()).transaction(e,t)}async upgrade(e){const t=await this.getConnection();this.connectionInitializer.reset();const r=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(r.error)throw new J("INTERNAL_ERROR",`Database upgrade failed for ${this.config.database}`,void 0,r.error);return r.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function ne(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var ie=class{constructor(e,t,r="$id",s=[]){this.connectionManager=e,this.collection=t,this.keyPath=r,this.indexes=s}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx("readonly",async r=>{const s=r.index(e);return this.requestToPromise(s.get(t))})}async getByKeyRange(e,t){return this.withTx("readonly",async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(ne(t)))})}async findByIndex(e,t){return this.withTx("readonly",async r=>{const s=r.index(e),n=IDBKeyRange.only(t);return this.requestToPromise(s.getAll(n))})}async put(e){return this.withTx("readwrite",async t=>{const r=e[this.keyPath];if(void 0!==r){W(await this.requestToPromise(t.get(r)),e)}return this.requestToPromise(t.put(e))})}async add(e){return this.withTx("readwrite",async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]})}async batch(e){return this.withTx("readwrite",async t=>{for(const r of e)if("put"===r.type||"add"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const s of e)if("put"===r.type){const e=s[this.keyPath];if(void 0!==e){W(await this.requestToPromise(t.get(e)),s)}await this.requestToPromise(t.put(s))}else await this.requestToPromise(t.add(s))}else{const e=Array.isArray(r.data)?r.data:[r.data];for(const r of e)await this.requestToPromise(t.delete(r))}})}async delete(e){return this.withTx("readwrite",async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx("readwrite",async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new J("INTERNAL_ERROR",`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);const r=t.objectStore(this.collection);for(const t of e)if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e){const e=t[this.keyPath];if(void 0!==e){W(await this.requestToPromise(r.get(e)),t)}await this.requestToPromise(r.put(t))}}else if("add"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.add(t))}else{const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.delete(t))}}async getById(e){return this.withTx("readonly",async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx("readonly",async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx("readonly",async e=>this.requestToPromise(e.count()))}async cursor(e,t="forward",r){return this.withTx("readonly",async s=>{const n="forward"===t?"next":"prev",i=s.openCursor(ne(r),n);return new Promise((t,r)=>{let s=null;i.onsuccess=async n=>{const i=n.target.result;if(!i)return t(s);try{const{value:r,done:n,offset:a}=await e(i.value,i.key,i);s=r,n?t(s):a&&a>0?i.advance(a):i.continue()}catch(e){r(e)}},i.onerror=()=>r(this.mapError(i.error))})})}mapError(e){if(e instanceof J)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new J("INTERNAL_ERROR","Storage quota exceeded"):new J("VersionError"===r?"CONFLICT":"InvalidStateError"===r||"TransactionInactiveError"===r?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const r=await this.connectionManager.getConnection();return new Promise(async(s,n)=>{const i=r.transaction(this.collection,e),a=i.objectStore(this.collection);let o,c;i.oncomplete=()=>{c?n(c):s(o)},i.onerror=()=>n(this.mapError(i.error)),i.onabort=()=>n(this.mapError(i.error));try{const e=t(a,i);o=e instanceof Promise?await e:e}catch(e){c=e;try{i.abort()}catch(e){}}})}requestToPromise(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}},ae=new Map,oe=e=>{let t=ae.get(e.database);t||(t=new re({retry:!0,throws:!0}),ae.set(e.database,t));try{const{value:r,error:s}=t.doSync(()=>new se(e));if(s)throw new J("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,s);return new ie(r,e.collection,e.keyPath)}catch(e){if(e instanceof J)throw e;throw new J("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}};m(y()),m(y()),m(w()),m(V()),m(V());var ce=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function he(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(de).join("/"):"/"+e.split(".").map(de).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(ue)}function de(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ue(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var le=new Map;function pe(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new ce(`Invalid path - parent not found at ${e}`);if(Array.isArray(r)){let t="-"===e?r.length:parseInt(e);if(isNaN(t)||t<0||t>r.length)throw new ce(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new ce(`Property ${e} not found`);r=r[e]}}return r}function me(e,t){let r=le.get(t)||he(t);if(le.set(t,r),0===r.length)return e;let s=pe(e,r.slice(0,-1)),n=r[r.length-1];if(Array.isArray(s)){let e=parseInt(n);if(isNaN(e)||e<0||e>=s.length)throw new ce(`Invalid array index: ${n}`);return s[e]}return s[n]}function fe(e,t,r){let s=le.get(t)||he(t);le.set(t,s);let n=pe(e,s.slice(0,-1)),i=s[s.length-1];return Array.isArray(n)?n.splice(0,n.length,...n.filter(e=>e!==r)):n[i]===r&&delete n[i],e}function ye(e,t,r){let s=le.get(t)||he(t);if(le.set(t,s),0===s.length)return r;let n=s.slice(0,-1),i=s[s.length-1],a=pe(e,n);if(Array.isArray(a))if("-"===i)a.push(r);else{let e=parseInt(i);if(e<0||e>a.length)throw new ce(`Invalid array index: ${i}`);a.splice(e,0,r)}else a[i]=r;return e}function we(e,t){let r=le.get(t)||he(t);if(le.set(t,r),0===r.length)return;let s=pe(e,r.slice(0,-1)),n=r[r.length-1];if(Array.isArray(s)){let e=parseInt(n);s.splice(e,1)}else delete s[n];return e}function ge(e,t){let r=[];switch(e.type){case"addField":r.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":r.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,s])=>{"object"!=typeof s||null===s||Array.isArray(s),r.push({op:"replace",path:`${t}/${e}`,value:s})});break}case"deprecateField":r.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||r.push({op:"add",path:"/indexes",value:[]}),r.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let s=t.indexes?.findIndex(t=>t.name===e.name);void 0!==s&&s>=0&&r.push({op:"remove",path:`/indexes/${s}`});break}case"modifyIndex":{let s=t.indexes?.findIndex(t=>t.name===e.name);void 0!==s&&s>=0&&Object.entries(e.changes).forEach(([e,t])=>{r.push({op:"replace",path:`/indexes/${s}/${e}`,value:t})});break}case"addConstraint":t.constraints||r.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{r.push({op:"add",path:"/constraints/-",value:e})}):r.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let s=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);void 0!==s&&s>=0&&r.push({op:"remove",path:`/constraints/${s}`});break}case"modifyConstraint":{let s=function(e,t){if(!e.constraints)return null;for(let r=0;r<e.constraints.length;r++){let s=e.constraints[r];if(s.name===t)return`/constraints/${r}`;if(be(s)){let e=ve(s.rules,t);if(e)return`/constraints/${r}${e}`}}return null}(t,e.name);s&&Object.entries(e.changes).forEach(([e,t])=>{r.push({op:"replace",path:`${s}/${e}`,value:t})});break}}return r}function be(e){return e&&"operator"in e&&"rules"in e}function ve(e,t){for(let r=0;r<e.length;r++){let s=e[r];if("name"in s&&s.name===t)return`/rules/${r}`;if(be(s)){let e=ve(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var $e=new Map;function _e(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ke(e,t){let r=e=>({issues:e}),s=(e,t,r,s)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:r}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:r}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:r}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:r}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:r}];case"enum":return s?.values?s.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(s.values)}, got ${e}`,path:r}]:[{message:"Enum type requires 'values' definition",path:r}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:r}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:r}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];default:return[{message:`Unknown type '${t}'`,path:r}]}};function n(e,t,r,s,i){let a=[],o=e.rules.map((e,o)=>{let c=[...s,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(i.has(h))return!0;i.add(h);let s=n(e,t,r,c,i);return a.push(...s),i.delete(h),0===s.length}{let s=r[e.predicate];if(!s)return a.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let n=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if($e.has(n)){let t=$e.get(n);return t||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${_e(e.parameters)}`,path:c}),t}let i=s({data:t,field:e.field,arguments:e.parameters});return $e.set(n,i),i||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${_e(e.parameters)}`,path:c}),i}});return(()=>{switch(e.operator){case"and":return o.every(e=>e);case"or":return o.some(e=>e);case"not":return!o.every(e=>e);case"nor":return!o.some(e=>e);case"xor":return 1===o.filter(e=>e).length}})()||a.push({message:`Constraint group '${e.name}' failed`,path:s}),a}function i(e,t,r,a,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let i=a.length>0?e[a[a.length-1]]:e;return h.push(...s(i,t.type,a,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if("rules"in e)h.push(...n(e,{value:i},r,[...a,`constraints[${t}]`],c));else{let s=r[e.predicate];s?s({data:{value:i},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${_e(e.parameters)}`,path:[...a,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...a,`constraints[${t}]`]})}}),h}let d={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let r=t.fields,s=r.find(e=>!e.when);s&&Object.assign(d,s.fields);let n=r.find(t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value);if(n)Object.assign(d,n.fields);else if(!s)return h.push({message:"No matching field set found for discriminated schema",path:a}),h}else d=t.fields;else d=t.fields;let u=new Set(Object.values(d).map(e=>e.name));Object.entries(d).forEach(([t,d])=>{let u=[...a,d.name],l=Object.hasOwnProperty.call(e,d.name)?e[d.name]:void 0!==d.default?d.default:void 0;d.required&&null==l&&h.push({message:`Field '${d.name}' is required`,path:u});let p=d.schema||d.nestedSchema;if("object"===d.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:u});else{c.add(p.id);let t=l&&"object"==typeof l&&!Array.isArray(l)?l:{};h.push(...i(t,e,r,u,o,c)),p.constraints?.forEach((e,s)=>{if("rules"in e)h.push(...n(e,t,r,[...u,`constraints[${s}]`],c));else{let n=r[e.predicate];n?n({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${_e(e.parameters)}`,path:[...u,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...u,`constraints[${s}]`]})}}),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:u})}if("union"===d.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((s,a)=>{let h=o[s.id];if(h)if(c.has(s.id))t.push({message:`Circular reference detected at '${s.id}'`,path:[...u,a.toString()]});else{c.add(s.id);let a=l&&"object"==typeof l&&!Array.isArray(l)?l:{},d=i(a,h,r,u,o,new Set(c));0===d.length&&void 0!==l?(e=!0,s.constraints?.forEach((s,i)=>{if("rules"in s){let o=n(s,a,r,[...u,`constraints[${i}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let n=r[s.predicate];n&&!n({data:a,field:void 0,arguments:s.parameters})&&(e=!1,t.push({message:s.errorMessage||`Constraint '${s.name}' failed`,path:[...u,`constraints[${i}]`]}))}})):void 0===l&&t.push(...d.filter(e=>e.message.includes("is required"))),c.delete(s.id)}else t.push({message:`Nested schema '${s.id}' not found`,path:[...u,a.toString()]})}),e||void 0===l?void 0===l&&h.push(...t):(h.push({message:"Value does not match any union schema",path:u}),h.push(...t))}void 0!==l&&(h.push(...s(l,d.type,u,{values:d.values})),("array"===d.type||"set"===d.type)&&Array.isArray(l)&&(d.constraints?.forEach((e,t)=>{let s=r[e.predicate];s&&!s({data:{[d.name]:l},field:d.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${d.name}'`,path:[...u,`constraints[${t}]`]})}),d.itemsType&&l.forEach((e,t)=>h.push(...s(e,d.itemsType,[...u,t.toString()]))),p&&!Array.isArray(p)&&(o[p.id]?l.forEach((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...u,t.toString()]}):(c.add(p.id),h.push(...i(e,o[p.id],r,[...u,t.toString()],o,c)),c.delete(p.id)))}):h.push({message:`Nested schema '${p.id}' not found`,path:u}))),d.constraints?.forEach((t,s)=>{if("rules"in t)h.push(...n(t,e,r,[...u,`constraints[${s}]`],c));else{let n=r[t.predicate];n?n({data:e,field:d.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${d.name}' with params ${_e(t.parameters)}`,path:[...u,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...u,`constraints[${s}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!u.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...a,t]});return t.constraints?.forEach((t,s)=>{if("rules"in t)h.push(...n(t,e,r,[...a,`constraints[${s}]`],c));else{let n=r[t.predicate];n?n({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${_e(t.parameters)}`,path:[...a,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...a,`constraints[${s}]`]})}}),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if("object"!=typeof s||null===s)return r([{message:"Input must be an object",path:[]}]);let n=s,a=i(n,e,t,[],e.nestedSchemas||{});return a.length>0?r(a):(e=>({value:e}))(n)},types:{input:{},output:{}}}}}var Ee=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},Ie=e=>({value:e}),Ae=e=>({issues:e}),Se=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],Oe=(e,t)=>{let r=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&r.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},xe=(e,t)=>{let r=["and","or","not","nor","xor"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Ne=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Te=(e,t,r)=>{let s=[],n=["type","predicate","field","parameters","name","description","errorMessage"],i=e;return["predicate","name"].forEach(e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})}),s.push(...Se(e.name,`${r}.name`)),s.push(...Se(e.predicate,`${r}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&s.push({message:"Field must be a string",path:[`${r}.field`]}),void 0!==e.parameters&&s.push(...(e.parameters,[])),s.push(...Se(e.description,`${r}.description`,!1)),s.push(...Se(e.errorMessage,`${r}.errorMessage`,!1)),s},je=(e,t,r)=>{let s=[],n=["name","operator","rules"],i=n,a=e;return n.forEach(e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})}),s.push(...Se(e.name,`${r}.name`)),s.push(...xe(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach((e,n)=>{"rules"in e?s.push(...je(e,t,`${r}.rules[${n}]`)):s.push(...Te(e,0,`${r}.rules[${n}]`))}):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Ce=(e,t,r)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[r]}];let s=[];return e.forEach((e,n)=>{"rules"in e?s.push(...je(e,t,`${r}[${n}]`)):s.push(...Te(e,0,`${r}[${n}]`))}),s},Re=(e,t)=>{let r=[],s=["operator","field","value","conditions"],n=e;return["operator","field"].forEach(e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(n).forEach(e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...xe(e.operator,`${t}.operator`)),r.push(...Se(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach((e,s)=>r.push(...Re(e,`${t}.conditions[${s}]`))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},Me=(e,t)=>{let r=[],s=["fields","type","unique","partial","description","order","name"],n=e;return["fields","type","name"].forEach(e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(n).forEach(e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.name,`${t}.name`)),r.push(...((e,t)=>{let r=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every(e=>"string"==typeof e))&&r.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),r.push(...Ne(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...Re(e.partial,`${t}.partial`)),r.push(...Se(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&r.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),r},De=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let r=[];return e.forEach((e,s)=>r.push(...Me(e,`${t}[${s}]`))),r},Pe=(e,t,r,s,n)=>{let i=[];return void 0===e?[]:("union"===r&&Array.isArray(e)?(0===e.length&&i.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach((e,r)=>{let n=`${t}[${r}]`;i.push(...Se(e.id,`${n}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${n}.id`]}),e.constraints&&i.push(...Ce(e.constraints,"dynamic",`${n}.constraints`)),e.indexes&&i.push(...De(e.indexes,`${n}.indexes`))})):"object"!==r&&("array"!==r||"object"!==n)||Array.isArray(e)?i.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(i.push(...Se(e.id,`${t}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&i.push(...Ce(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&i.push(...De(e.indexes,`${t}.indexes`))),i)},qe=(e,t,r)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[r]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[r]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[r]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[r]}];break;case"enum":if(!Array.isArray(e)||!e.every(e=>"string"==typeof e||"number"==typeof e))return[{message:"Default must be an array of strings or numbers",path:[r]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[r]}];break;case"union":case"dynamic":return[]}return[]},Fe=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],Le=(e,t,r)=>{let s=[],n=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],i=e;if(["name","type"].forEach(e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),s.push(...Se(e.name,`${t}.name`)),s.push(...Oe(e.type,`${t}.type`)),s.push(...Ne(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Ce(e.constraints,e.type,`${t}.constraints`)),s.push(...qe(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every(e=>"string"==typeof e||"number"==typeof e))&&s.push({message:"Values must be a non-empty array of strings or numbers",path:[`${t}.values`]}):s.push({message:"Values is only valid for 'enum' type",path:[`${t}.values`]})),void 0!==e.schema&&s.push(...Pe(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Oe(e.itemsType,`${t}.itemsType`)),e.nestedSchema){s.push({message:"nestedSchema is deprecated; use schema instead",path:[`${t}.nestedSchema`]});let n=["id"],i=["id","constraints","indexes"],a=e.nestedSchema;n.forEach(e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),s.push(...Se(e.nestedSchema.id,`${t}.nestedSchema.id`)),r.includes(e.nestedSchema.id)||s.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&s.push(...Ce(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...De(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Ne(e.deprecated,`${t}.deprecated`,!1)),e.reference){s.push({message:"reference is deprecated",path:[`${t}.reference`]});let r=["schema","field"],n=["schema","field"],i=e.reference;r.forEach(e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),s.push(...Se(e.reference.schema,`${t}.reference.schema`)),s.push(...Se(e.reference.field,`${t}.reference.field`))}return s.push(...Se(e.description,`${t}.description`,!1)),s.push(...Ne(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Fe(e.hint,`${t}.hint`)),s},Ue=(e,t,r)=>{let s=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let n=["name","type","default","schema","itemsType","constraints","description","metadata"],i=e;["name","type"].forEach(e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),s.push(...Se(e.name,`${t}.name`)),s.push(...Oe(e.type,`${t}.type`)),s.push(...qe(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Pe(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Oe(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Ce(e.constraints,e.type,`${t}.constraints`)),s.push(...Se(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let n=["name","description","concrete","fields","indexes","constraints","metadata"],i=e;["name"].forEach(e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),s.push(...Se(e.name,`${t}.name`)),s.push(...Ne(i.concrete,`${t}.concrete`,!1)),i.concrete&&Array.isArray(i.fields)&&s.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(i.fields)?(0===i.fields.length&&s.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),i.fields.forEach((e,n)=>{let i=`${t}.fields[${n}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?s.push({message:"Fields must be a non-empty object",path:[`${i}.fields`]}):Object.entries(t).forEach(([e,t])=>{s.push(...Le(t,`${i}.fields.${e}`,r))}),void 0!==e.when&&("object"!=typeof e.when||null===e.when?s.push({message:"When must be an object",path:[`${i}.when`]}):s.push(...Se(e.when.field,`${i}.when.field`)))}else s.push({message:"Each variant must have a 'fields' property",path:[i]})})):void 0!==i.fields&&("object"!=typeof i.fields||null===i.fields?s.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(i.fields).forEach(([e,n])=>{s.push(...Le(n,`${t}.fields.${e}`,r))})),s.push(...Se(e.description,`${t}.description`,!1)),e.indexes&&s.push(...De(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Ce(i.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return s},Be=(e,t)=>{let r=[];switch(e.type||r.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let s=["type","id","changes"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addField":{let s=["type","id","definition"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),r.push(...Le(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let s=["type","id"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`));break}case"modifyField":{let s=["type","id","changes","nestedSchemaChanges"],n=e;if(["type","id","changes"].forEach(e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(n).forEach(e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]}),e.nestedSchemaChanges){let s=["id","constraints","indexes"],n=e.nestedSchemaChanges;Object.keys(n).forEach(e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),r.push(...Se(n.id,`${t}.nestedSchemaChanges.id`,!1)),n.constraints&&r.push(...Ce(n.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),n.indexes&&r.push(...De(n.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let s=["type","definition"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Me(e.definition,`${t}.definition`));break}case"removeIndex":{let s=["type","name"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.name,`${t}.name`));break}case"modifyIndex":{let s=["type","name","changes"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let s=["type","constraint"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),"rules"in e.constraint?r.push(...je(e.constraint,"dynamic",`${t}.constraint`)):r.push(...Te(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let s=["type","name"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.name,`${t}.name`));break}case"modifyConstraint":{let s=["type","name","changes"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addNestedSchema":{let s=["type","id","definition"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),r.push(...Ue(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let s=["type","id"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`));break}case"modifyNestedSchema":{let s=["type","id","changes"],n=s,i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:r.push({message:"Unknown schema change type",path:[`${t}.type`]})}return r},Ve=(e,t)=>{let r=[],s=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],n=[...s,"rollback","dependencies"],i=e;s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...Se(e.id,`${t}.id`)),r.push(...Se(e.schemaVersion,`${t}.schemaVersion`)),r.push(...Se(e.description,`${t}.description`));let a=["pending","applied","failed"];return a.includes(e.status)||r.push({message:`Status must be one of ${a.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach((e,s)=>{r.push(...Be(e,`${t}.changes[${s}]`))}):r.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach((e,s)=>r.push(...Be(e,`${t}.rollback[${s}]`))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(...Se(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?r.push(...((e,t)=>{let r=[],s=["forward","backward"],n=s,i=e;return s.forEach(e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(i).forEach(e=>{n.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),"function"!=typeof e.forward&&r.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&r.push({message:"Backward must be a function",path:[`${t}.backward`]}),r})(e.transform,`${t}.transform`)):r.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),r.push(...Se(e.createdAt,`${t}.createdAt`)),r.push(...Se(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>"string"==typeof e))&&r.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),r},ze={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return Ae([{message:"Schema must be an object",path:[]}]);let t=e,r=[],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],n=t;if(["name","version","fields"].forEach(e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[e]})}),Object.keys(n).forEach(e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[e]})}),r.push(...Se(t.name,"name")),r.push(...Se(t.version,"version")),"object"!=typeof t.fields||null===t.fields)r.push({message:"Fields must be a non-empty object",path:["fields"]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,s])=>{r.push(...Le(s,`fields.${t}`,e))})}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)r.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,s])=>r.push(...Ue(s,`nestedSchemas.${t}`,e)))}return r.push(...Se(t.description,"description",!1)),t.indexes&&r.push(...De(t.indexes,"indexes")),t.constraints&&r.push(...Ce(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&r.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>"string"==typeof e))&&r.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>r.push(...Ve(e,`migrations[${t}]`))):r.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&r.push({message:"Mock must be a function",path:["mock"]}),t.hint&&r.push(...Fe(t.hint,"hint")),r.length>0?Ae(r):Ie(t)},types:{input:{},output:{}}},He={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return Ae([{message:"Migration must be an object",path:[]}]);let t=e,r=Ve(t,"");return r.length>0?Ae(r):Ie(t)},types:{input:{},output:{}}},Je={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return Ae([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach((e,t)=>r.push(...Be(e,`[${t}]`))),r.length>0?Ae(r):Ie(t)},types:{input:[],output:[]}};function Ke(e){try{return!ze.validate(e).issues}catch(e){throw new Ee("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function We(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Ye(e,t,r){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,r=new Set,s=new Set,n=new Set;for(let i of e)switch(i.type){case"addField":if(r.has(i.id))throw new Error(`Cannot add previously removed field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot add already modified field: ${i.id}`);if(n.has(i.id))throw new Error(`Cannot add deprecated field: ${i.id}`);s.add(i.id);break;case"removeField":if(s.has(i.id))throw new Error(`Cannot remove newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot remove modified field: ${i.id}`);if(n.has(i.id))throw new Error(`Cannot remove field that is being deprecated: ${i.id}`);r.add(i.id);break;case"modifyField":if(r.has(i.id))throw new Error(`Cannot modify removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot modify newly added field: ${i.id}`);if(n.has(i.id))throw new Error(`Cannot modify field that is being deprecated: ${i.id}`);t.add(i.id);break;case"deprecateField":if(r.has(i.id))throw new Error(`Cannot deprecate removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot deprecate newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot deprecate modified field: ${i.id}`);n.add(i.id)}})(t),function(e){let t=new Set,r=new Set,s=new Set;for(let n of e)switch(n.type){case"addConstraint":let e=n.constraint.name;if(r.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);s.add(e);break;case"removeConstraint":if(s.has(n.name))throw new Error(`Cannot remove newly added constraint: ${n.name}`);if(t.has(n.name))throw new Error(`Cannot remove modified constraint: ${n.name}`);r.add(n.name);break;case"modifyConstraint":if(r.has(n.name))throw new Error(`Cannot modify removed constraint: ${n.name}`);if(s.has(n.name))throw new Error(`Cannot modify newly added constraint: ${n.name}`);t.add(n.name)}}(t);let s=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}(e),n="patch";for(let e of t){let t=We(e);if("major"===t){n="major";break}"minor"===t&&"patch"===n&&(n="minor")}switch(n){case"major":return`${s.major+1}.0.0`;case"minor":return`${s.major}.${s.minor+1}.0`;case"patch":return`${s.major}.${s.minor}.${s.patch+1}`}}function Ge(e,t){let r=e=>e.split(".").map(e=>parseInt(e,10)||0),[s,n,i]=r(e),[a,o,c]=r(t);return s-a||n-o||i-c}var Xe,Qe=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},Ze=((Xe=Ze||{}).INVALID_SCHEMA="INVALID_SCHEMA",Xe.INVALID_MIGRATION="INVALID_MIGRATION",Xe.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Xe.TIMEOUT="TIMEOUT",Xe.MEMORY_LIMIT="MEMORY_LIMIT",Xe.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Xe.TRANSFORM_ERROR="TRANSFORM_ERROR",Xe.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Xe.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Xe.STREAM_ERROR="STREAM_ERROR",Xe.ROLLBACK_ERROR="ROLLBACK_ERROR",Xe.MISSING_TRANSFORM="MISSING_TRANSFORM",Xe),et=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Ke(e))throw new Qe("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(e=>function(e){try{return!He.validate(e).issues}catch(e){throw new Ee("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e)))throw new Qe("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((e,t)=>Ge(e.schemaVersion,t.schemaVersion))}r&&(this.history=r.sort((e,t)=>Ge(e.version,t.version)))}catch(e){throw e instanceof Qe?e:new Qe("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new Qe("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new Qe("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new Qe("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(e=>function(e){try{return!Je.validate(e).issues}catch(e){throw new Ee("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e))}catch(e){throw new Qe("Invalid schema changes","INVALID_MIGRATION",void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:(new Date).toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,r,s){if(this.isProcessing)throw new Qe("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let n={...this.currentSchema},i=this.getRelevantMigrations(r,s);return{newSchema:i.reduce((e,t)=>{let s="forward"===r?t.changes:t.rollback||[];return this.applySchemaChanges(e,s,t.id)},n),dataPreview:await e.processMigrationList(t,r,i)}}catch(e){throw e instanceof Qe?e:new Qe("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(r=>{let s="forward"===e?"pending":"applied",n=!t||Ge(r.schemaVersion,t)>=0;return r.status===s&&n}).sort((t,r)=>"forward"===e?t.id.localeCompare(r.id):r.id.localeCompare(t.id))}applySchemaChanges(e,t,r){try{let s=Ye(e.version,t);return t.map(t=>{try{return ge(t,e)}catch(e){throw new Qe("Invalid schema change","INVALID_SCHEMA",r,e)}}).reduce((e,t)=>{try{return function(e,t){let r=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":r=ye(r,e.path,e.value);break;case"remove":r=we(r,e.path);break;case"removeValue":r=fe(r,e.path,e.value);break;case"replace":r=ye(we(r,e.path),e.path,e.value);break;case"copy":{let t=me(r,e.from);r=ye(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=me(r,e.from);r=ye(r,e.path,t),r=we(r,e.from);break}case"test":{let t=me(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ce("Test operation failed");break}default:throw new ce(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ce&&(t.operation=e),t}return r}(e,t)}catch(e){throw new Qe("Failed to apply patch","INVALID_SCHEMA",r,e)}},{...e,version:s})}catch(e){throw e instanceof Qe?e:new Qe("Schema update failed","INVALID_SCHEMA",r,e)}}async prepareMigration(){let e=this.migrations.filter(e=>"pending"===e.status);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Qe("Concurrent operation","CONCURRENT_OPERATION");let r=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let s=await e.processMigrationList(t,"forward",r);return this.markMigrationsApplied(r),s}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new Qe("Checksum mismatch","CHECKSUM_MISMATCH",e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new Qe("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(e=>"applied"===e.status).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,r){if(this.isProcessing)throw new Qe("Concurrent operation","CONCURRENT_OPERATION");try{let s=this.history.findIndex(e=>e.version===t);if(-1===s)throw new Error(`Version ${t} not found in history`);let n=this.migrations.filter(e=>e.schemaVersion===t&&"applied"===e.status).sort((e,t)=>t.id.localeCompare(e.id)),i=this.history.length-s;if(i<0)return r;for(let e=0;e<i;e++)this.transformSchema("backward");let a=await e.processMigrationList(r,"backward",n);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,r){return(await Promise.all(r.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Qe(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:r})=>e.pipeThrough(new TransformStream({async transform(e,s){try{let t=await r(e);s.enqueue(t)}catch(e){s.error(new Qe(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let r=await fetch(e);if(!r.ok)throw new Qe(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await r.text();if(typeof window<"u"){let e=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:r}=await import("vm"),n={module:{exports:{}},console:console};return r(s,n,e),n.module.exports[t]}}catch(t){throw new Qe(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new Qe(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter(e=>"pending"===e.status).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof Qe?e:new Qe("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=t);var tt=m(w()),rt=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let r=-1;const s=n=>{if(n<=r)throw new Error("next() called multiple times");r=n;const i=this.middlewares[n];if(n===this.middlewares.length)return t();try{return i(e,()=>s(n+1))}catch(e){return Promise.reject(e)}};return s(0)}wrap(e,t){const r=this;return new Proxy(e,{get(e,s,n){const i=Reflect.get(e,s,n);return"function"==typeof i?function(...n){const a={...t,operation:s.toString(),args:n};return r.execute(a,()=>i.apply(e,n))}:i}})}},st=async(e,t)=>{const r=Date.now();try{const s=await t();return nt(e,r,s,null),s}catch(t){throw nt(e,r,void 0,t),t}};function nt(e,t,r,s){if(!e.eventBus)return;const n=Date.now()-t;e.eventBus.emit({name:"telemetry",payload:{type:"telemetry",method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:n},source:{level:e.documentId?"document":e.collection?"collection":"database",collection:e.collection,document:e.documentId},result:s?void 0:{type:Array.isArray(r)?"array":typeof r,size:Array.isArray(r)?r.length:void 0},error:s?{message:s.message,name:s.name,stack:s.stack}:null}}})}var{match:it}=(0,tt.createMatcher)({});async function at(e){const{collection:t,initial:r,validator:n,store:i,bus:a,lockManager:o}=e,[c,h]=K(r),{value:d,issues:u}=n?await n["~standard"].validate(c):{value:r,issues:void 0};if(u)throw new J("INVALID_DATA",`Invalid data for ${t}`,e.schema,u,u);const l={current:Object.assign(d,h),deleted:!1};void 0===l.current.$id&&(l.current=Object.assign(l.current,{$id:s(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{await o.lock();try{const{$id:r,$version:s}=l.current;if(!r)throw new Error("Document ID missing.");const n=await i.getById(r);if(n&&n.$version!==s)throw new J("CONFLICT",`Version mismatch on ${t}/${r}`);return l.current.$version=(s||0)+1,l.current.$updated=(new Date).toJSON(),e?await e.addOp(i,"put",l.current):await i.put(l.current),a.emit({name:"document:write",payload:{type:"document:write",data:l.current,timestamp:Date.now()}}),!0}finally{o.unlock()}},update:async(r,s)=>{const[i,o]=K(Object.assign({},l.current,r)),{value:c,issues:h}=n?await n["~standard"].validate(i):{value:i,issues:void 0};if(h)throw new J("INVALID_DATA",`Invalid update for ${t}`,e.schema,h,h);l.current=Object.assign(c,o);const d=await p.save(s);return d&&a.emit({name:"document:update",payload:{type:"document:update",data:l.current,timestamp:Date.now()}}),d},delete:async e=>{await o.lock();try{const{$id:r,$version:s}=l.current;if(!r)throw new Error("Document ID missing.");const n=await i.getById(r);if(n&&n.$version!==s)throw new J("CONFLICT",`Version mismatch on delete ${t}/${r}`);return e?await e.addOp(i,"delete",r):await i.delete(r),a.emit({name:"document:delete",payload:{type:"document:delete",data:l.current,timestamp:Date.now()}}),l.deleted=!0,!0}finally{o.unlock()}},read:async()=>{const e=l.current.$id,t=await i.getById(e);if(!t)throw new Error("Document not found.");return l.current={...t},a.emit({name:"document:read",payload:{type:"document:read",data:l.current,timestamp:Date.now()}}),l.current},state:()=>(e=>{const[t]=K(e);return t})(l.current),$metadata:()=>K(l.current)[1],subscribe:a.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save","$metadata"].includes(t)){const e=p[t];return(...t)=>{if(l.deleted)throw new J("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(l.deleted)throw new J("INVALID_OPERATION","Document has been deleted");return Reflect.get(l.current,t)}})}function ot(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}async function ct({collection:e,validator:t,bus:r,store:n,pipeline:i,validate:a,schema:o}){const c=new te,h={collection:e,validator:a?t:void 0,schema:o,store:n,bus:r,pipeline:i,lockManager:c,valid:!0},d={async validate(e){const r=t["~standard"].validate(e);return r instanceof Promise?await r:r},create:async(i,c)=>{const[d,u]=K(i),{value:l,issues:p}=a?await t["~standard"].validate(d):{value:d,issues:void 0};if(p)throw new J("INVALID_DATA",`Invalid data for collection '${e}'`,o,p,p);const m=Object.assign(l,u,{$id:s(),$created:(new Date).toJSON(),$version:1});c?await c.addOp(n,"add",m):await n.add(m),r.emit({name:"document:create",payload:{type:"document:create",data:m,timestamp:Date.now()}});const f=await at({...h,initial:m});return r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),f},find:async t=>{let s;const i=ot(t);if(i)try{const e=t.value;s=(await n.findByIndex(i,e))[0]}catch{s=void 0}if(void 0===s&&(s=await n.cursor(async e=>e&&it(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!s)return null;const a=await at({...h,initial:s});return r.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),a},filter:async t=>{let s=[];const i=ot(t);if(i)try{const e=t.value;s=await n.findByIndex(i,e)}catch{s=[]}0===s.length&&await n.cursor(async e=>(e&&it(e,t)&&s.push(e),{value:null,done:!1}));const a=await Promise.all(s.map(e=>at({...h,initial:e})));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),a},update:async(s,i,h)=>{await c.lock();try{const c=await d.filter(s);if(0===c.length)return 0;const u=[];for(const r of c){const s=r.state(),n=Object.assign({},s,i);if(a){const r=await t["~standard"].validate(n);if(r.issues)throw new J("INVALID_DATA",`Bulk update failed validation for ${e}`,o,r.issues,r.issues)}const c=r.$metadata(),h=Object.assign(n,r.$metadata(),{$updated:(new Date).toJSON(),$version:(c.$version||0)+1});u.push(h)}return h?await h.addOp(n,"put",u):await n.batch(u.map(e=>({type:"put",data:e}))),u.forEach(e=>{r.emit({name:"document:update",payload:{type:"document:update",data:e,timestamp:Date.now()}})}),u.length}finally{c.unlock()}},delete:async(e,t)=>{await c.lock();try{const s=await d.filter(e),i=s.map(e=>e.$id);return 0===i.length?0:(t?await t.addOp(n,"delete",i):await n.delete(i),s.forEach(e=>{r.emit({name:"document:delete",payload:{type:"document:delete",data:e.state(),timestamp:Date.now()}})}),i.length)}finally{c.unlock()}},list:async t=>{const s={total:await n.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return 0===s.total?{next:async()=>({value:[],done:!0})}:{async next(){const i="offset"===t.type?await async function(e,t){const{offset:r,limit:s}=t,n=[];let i=0;return await e(async e=>i<r?(i++,{value:e,done:!1,offset:1}):(n.push(e),i++,n.length>=s?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),n}(n.cursor.bind(n),{...t,offset:s.offset}):await async function(e,t){const{limit:r,direction:s}=t,n=[];return await e(async e=>(n.push(e),n.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),s),n}(n.cursor.bind(n),{...t});s.offset+=s.limit,s.count+=i.length;const a=await Promise.all(i.map(e=>at({...h,initial:e})));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:a,done:s.count>=s.total}}}}},u={...i.wrap(d,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>h.valid=!1};return new Proxy(u,{get(t,r,s){const n=Reflect.get(t,r,s);return"function"==typeof n?(...s)=>{if(!h.valid&&"invalidate"!==r)throw new J("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return n.apply(t,s)}:n}})}function ht(e){return"function"==typeof e._getIDBConnection}var dt=class{id;staged=[];done=!1;constructor(){this.id=s()}async addOp(e,t,r){if(this.done)throw new J("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");this.staged.push({store:e,op:{type:t,data:r}})}async commit(){if(this.done)throw new J("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");if(this.done=!0,0===this.staged.length)return;const e=new Map,t=new Map;for(const{store:r,op:s}of this.staged)ht(r)?(e.has(r)||e.set(r,[]),e.get(r).push(s)):(t.has(r)||t.set(r,[]),t.get(r).push(s));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){const t=Array.from(e.keys()).map(e=>e.name()),r=e.keys().next().value,s=await r._getIDBConnection();await new Promise((r,n)=>{const i=s.transaction(t,"readwrite");i.oncomplete=()=>r(),i.onerror=()=>n(i.error??new Error("IDB transaction error")),i.onabort=()=>n(i.error??new Error("IDB transaction aborted")),(async()=>{try{for(const[t,r]of e)await t.executeInTransaction(r,i)}catch(e){try{i.abort()}catch(e){}n(e)}})()})}async commitMemory(e){const t=[];try{for(const[r,s]of e){const e=r._snapshotMemory();t.push({store:r,snapshot:e}),await r.executeInTransaction(s,null)}}catch(e){for(const{store:e,snapshot:r}of t)try{e._rollbackMemory(r)}catch(e){}throw e}}completed(){return this.done}};function ut(e,t){return e instanceof J?e:e instanceof Error?new J("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new J("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}async function lt(e,t){const s=r(),n=new Map,i=new rt;i.use(((e=3,t=100)=>async(r,s)=>{let n=0;for(;n<e;)try{return await s()}catch(r){if(!(r instanceof J&&"TRANSIENT_ERROR"===r.type))throw r;{if(n++,n>=e)throw r;const s=t*Math.pow(2,n)+50*Math.random();await new Promise(e=>setTimeout(e,s))}}})()),e.enableTelemetry&&i.use(st);const a=new Map,o=t({...e,collection:"schemas",keyPath:"name"},[]);async function c(r,s=[]){let n=a.get(r);return n||(n=t({...e,collection:r,keyPath:"$id"},s),a.set(r,n)),await n.open(),n}async function h(t){if(n.has(t))return n.get(t);const r=await o.getById(t);if(!r)throw new J("SCHEMA_NOT_FOUND",`Collection '${t}' does not exist`);const a=await c(t,r.indexes??[]),h=ke(r,e.predicates||{}),d=await ct({collection:t,bus:s,validator:h,validate:Boolean(e.validate),store:a,pipeline:i,schema:r});return s.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),n.set(t,d),n.get(t)}async function d(e){return await o.put(e),s.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await o.open();const u={collection:h,createCollection:async e=>{if(await o.getById(e.name))throw new J("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Ke(e))throw new J("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await o.put(e);const t=h(e.name);return s.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await o.getById(e);if(!t)throw new J("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const r=await c(e,t.indexes??[]);return await r.clear(),a.delete(e),await o.delete(e),n.delete(e),s.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,r=100)=>{const s=n.get(e);s&&(s.invalidate(),n.delete(e));const i=await o.getById(e);if(!i)throw new J("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const a=await c(e,i.indexes??[]),u=new et(i);await u.add(t);const l=(await u.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((i.indexes??[]).map(e=>e.name)),m=l.indexes??[],f=new Set(m.map(e=>e.name)),y=m.filter(e=>!p.has(e.name)),w=(i.indexes??[]).filter(e=>!f.has(e.name));await d(l);try{const t=function(e,t,r){let s,n=!1;return new ReadableStream({async pull(i){if(n)return void i.close();let a=0;const o=void 0!==s?{lower:s,lowerOpen:!0}:void 0;try{await t.cursor(async(e,t)=>(i.enqueue(e),s=t,a++,a>=r?{done:!0,value:e}:{done:!1,value:e}),"forward",o),a<r&&(n=!0)}catch(t){i.error(ut(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,a,r),s=await u.migrate(t);await async function(e,t,r,s){const n=t.getReader();let i=[];try{for(;;){const{value:e,done:t}=await n.read();if(t)break;if(!e)continue;const{$version:a}=e;e.$version=(a||0)+1,e.$updated=(new Date).toJSON(),i.push(e),i.length>=s&&(await r.batch([{type:"put",data:i}]),i=[])}i.length>0&&await r.batch([{type:"put",data:i}])}catch(t){throw ut(t,e)}finally{n.releaseLock()}}(e,s,a,r)}catch(t){throw ut(t,e)}for(const e of y)await a.createIndex(e);for(const e of w)await a.dropIndex(e.name);return await h(e)}},l=i.wrap(u,{eventBus:s}),p={...l,transaction:async e=>{const t=new dt;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:s.subscribe,close:()=>{a.clear(),s.clear()},clear:async()=>{await o.clear(),await Promise.all(a.values().map(e=>e.clear())),a.clear()},ensureCollection:async e=>{try{await l.createCollection(e)}catch(e){if(e instanceof J&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await p.ensureCollection(t)}};return p}export{se as ConnectionManager,z as DEFAULT_KEYPATH,lt as DatabaseConnection,J as DatabaseError,H as DatabaseErrorType,ie as IndexedDBStore,at as createDocument,Q as createEphemeralStore,oe as createIndexedDbStore,ct as openCollection};
|
|
1
|
+
import{t as e}from"./rolldown-runtime-QTnfLwEv.mjs";import{Mutex as t,Once as n}from"@asaidimu/utils-sync";import{Buffer as r}from"buffer";import{createEventBus as i}from"@asaidimu/utils-events";import{v7 as a}from"uuid";const o=`$id`;let s=function(e){return e.SCHEMA_NOT_FOUND=`SCHEMA_NOT_FOUND`,e.SCHEMA_ALREADY_EXISTS=`SCHEMA_ALREADY_EXISTS`,e.INVALID_SCHEMA_NAME=`INVALID_SCHEMA_NAME`,e.INVALID_SCHEMA_DEFINITION=`INVALID_SCHEMA_DEFINITION`,e.SUBSCRIPTION_FAILED=`SUBSCRIPTION_FAILED`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.INVALID_DATA=`INVALID_DATA`,e.CONFLICT=`CONFLICT`,e.TRANSIENT_ERROR=`TRANSIENT_ERROR`,e.TRANSACTION_FAILED=`TRANSACTION_FAILED`,e.CONNECTION_FAILED=`CONNECTION_FAILED`,e.INVALID_OPERATION=`INVALID_OPERATION`,e}({});var c=class extends Error{type;schema;issues;constructor(e,t,n,r,i){super(t,{cause:r}),this.name=`DatabaseError`,this.type=e,this.schema=n,this.issues=i}};function l(e){if(typeof e!=`object`||!e||Array.isArray(e))return[e,{}];let t={};return[Object.entries(e).reduce((e,[n,r])=>(n.startsWith(`$`)?t[n]=r:e[n]=r,e),{}),t]}function u(e,t){if(!(!e||e.$version===void 0||t.$version===void 0)&&t.$version<=e.$version)throw new c(`CONFLICT`,`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function d(e,t){let n=[];for(let r of t.fields){let t=e[r];if(t==null)return null;n.push(String(t))}return n.join(`\0`)}function f(e,t){if(!t.partial)return!0;let{field:n,value:r}=t.partial;return e[n]===r}var p=class{storeName;keyPath;data=new Map;indexes=new Map;nextId=1;constructor(e,t=`$id`,n=[]){this.storeName=e,this.keyPath=t;for(let e of n)this.indexes.set(e.name,{definition:e,map:new Map})}name(){return this.storeName}async open(){}_snapshotMemory(){let e=new Map;for(let[t,n]of this.data)e.set(t,{...n});let t=new Map;for(let[e,n]of this.indexes){let r=new Map;for(let[e,t]of n.map)r.set(e,new Set(t));t.set(e,{definition:n.definition,map:r})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;let t={definition:e,map:new Map};this.indexes.set(e.name,t);for(let e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){let n=this.indexes.get(e);if(!n)throw new c(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=String(t),i=n.map.get(r);if(!i||i.size===0)return[];let a=[];for(let e of i){let t=this.data.get(e);t&&a.push(this.clone(t))}return a}async getByKeyRange(e,t){let n=this.indexes.get(e);if(!n)throw new c(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=[];for(let[e,i]of n.map.entries())if(this.isInKeyRange(e,t))for(let e of i){let t=this.data.get(e);t&&r.push(this.clone(t))}return r}async add(e){let t=Array.isArray(e)?e:[e],n=[];for(let e of t){let t=e[this.keyPath];if((t===void 0||t===``)&&(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new c(`CONFLICT`,`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);let r=Object.freeze(this.clone(e));this.data.set(t,r),this.indexDocument(r),n.push(t)}return Array.isArray(e)?n:n[0]}async put(e){let t=this.getKey(e),n=this.data.get(t);u(n,e),this.enforceUniqueIndexes(e,n),n&&this.unindexDocument(n);let r=Object.freeze(this.clone(e));return this.data.set(t,r),this.indexDocument(r),t}async batch(e){let t=new Map,n=e=>t.has(e)?t.get(e):this.data.get(e);for(let r of e)if(r.type===`add`||r.type===`put`){let e=Array.isArray(r.data)?r.data:[r.data];for(let i of e){let e;if(r.type===`add`){if(e=i[this.keyPath],(e===void 0||e===``)&&(e=String(this.nextId++),i[this.keyPath]=e),n(e)!=null)throw new c(`CONFLICT`,`Duplicate key ${e}`)}else e=this.getKey(i);u(n(e)??void 0,i),t.set(e,Object.freeze(this.clone(i)))}}else{let e=Array.isArray(r.data)?r.data:[r.data];for(let n of e)t.set(n,null)}for(let[e,n]of t.entries()){let t=this.data.get(e);t&&this.unindexDocument(t),n===null?this.data.delete(e):(this.enforceUniqueIndexes(n,t),this.data.set(e,n),this.indexDocument(n))}}async delete(e){let t=Array.isArray(e)?e:[e];for(let e of t){let t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(let e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(t!==null)throw new c(`INTERNAL_ERROR`,`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(let t of e)if(t.type===`add`)await this.add(t.data);else if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){let t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t=`forward`,n){let r=Array.from(this.data.entries());n&&(r=r.filter(([e])=>this.isInKeyRange(e,n)));let i=r.sort(([e],[t])=>e>t?1:e<t?-1:0);t===`backward`&&i.reverse();let a=null,o=0;for(;o<i.length;){let[t,n]=i[o],{value:r,done:s,offset:c}=await e(this.clone(n),t,null);if(a=r,s)break;o+=c&&c>0?c:1}return a}getKey(e){let t=e[this.keyPath];if(t==null)throw new c(`INVALID_DATA`,`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(let t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!f(t,e.definition))return;let n=d(t,e.definition);if(n===null)return;let r=t[this.keyPath];if(r===void 0)return;let i=e.map.get(n);i||(i=new Set,e.map.set(n,i)),i.add(r)}unindexDocument(e){let t=e[this.keyPath];if(t!==void 0)for(let n of this.indexes.values()){let r=d(e,n.definition);if(r===null)continue;let i=n.map.get(r);i&&(i.delete(t),i.size===0&&n.map.delete(r))}}enforceUniqueIndexes(e,t){let n=e[this.keyPath],r=t?t[this.keyPath]:void 0;for(let t of this.indexes.values()){if(!t.definition.unique||!f(e,t.definition))continue;let i=d(e,t.definition);if(i===null)continue;let a=t.map.get(i);if(!(!a||a.size===0)){for(let e of a)if(!(e===n||e===r))throw new c(`CONFLICT`,`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(`, `)}]`)}}}isInKeyRange(e,t){if(!t)return!0;let{lower:n,upper:r,lowerOpen:i=!1,upperOpen:a=!1}=t;return(n===void 0||(i?e>n:e>=n))&&(r===void 0||(a?e<r:e<=r))}};function m(e){return new p(e.database,e.keyPath)}var h=class{config;connectionInitializer=new n({retry:!0,throws:!0});schemasStoreName;constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||`schemas`}async openDatabase(){return new Promise((e,t)=>{let n=indexedDB.open(this.config.database);n.onerror=()=>t(Error(`Failed to open database: ${n.error?.message}`)),n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:`name`})},n.onsuccess=()=>e(n.result)})}async upgradeDatabase(e,t){let n=e.version+1;return e.close(),new Promise((e,r)=>{let i=indexedDB.open(this.config.database,n);i.onerror=()=>r(Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{let n=e.target.result,r=e.target.transaction;t(n,r)},i.onsuccess=()=>e(i.result)})}async ensureStore(e,t=`$id`,n=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(r=>{if(r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:`name`}),!r.objectStoreNames.contains(e)){let i=r.createObjectStore(e,{keyPath:t});for(let e of n){let t=e.fields.length===1?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);if(i.indexNames.contains(t.name))return;let a=t.fields.length===1?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)})}getConnection=async()=>{let e=await this.connectionInitializer.do(async()=>{let e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new c(`CONNECTION_FAILED`,`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t=`readwrite`){return(await this.getConnection()).transaction(e,t)}async upgrade(e){let t=await this.getConnection();this.connectionInitializer.reset();let n=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(n.error)throw new c(`INTERNAL_ERROR`,`Database upgrade failed for ${this.config.database}`,void 0,n.error);return n.value}close(){let e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function g(e){if(e){if(e.lower!==void 0&&e.upper!==void 0)return IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen);if(e.lower!==void 0)return IDBKeyRange.lowerBound(e.lower,e.lowerOpen);if(e.upper!==void 0)return IDBKeyRange.upperBound(e.upper,e.upperOpen)}}var _=class{connectionManager;collection;keyPath;indexes;constructor(e,t,n=`$id`,r=[]){this.connectionManager=e,this.collection=t,this.keyPath=n,this.indexes=r}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.get(t))})}async getByKeyRange(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.getAll(g(t)))})}async findByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))})}async put(e){return this.withTx(`readwrite`,async t=>{let n=e[this.keyPath];return n!==void 0&&u(await this.requestToPromise(t.get(n)),e),this.requestToPromise(t.put(e))})}async add(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e],r=[];for(let e of n){let n=await this.requestToPromise(t.add(e));r.push(n)}return Array.isArray(e)?r:r[0]})}async batch(e){return this.withTx(`readwrite`,async t=>{for(let n of e)if(n.type===`put`||n.type===`add`){let e=Array.isArray(n.data)?n.data:[n.data];for(let r of e)if(n.type===`put`){let e=r[this.keyPath];e!==void 0&&u(await this.requestToPromise(t.get(e)),r),await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{let e=Array.isArray(n.data)?n.data:[n.data];for(let n of e)await this.requestToPromise(t.delete(n))}})}async delete(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e];for(let e of n)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx(`readwrite`,async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new c(`INTERNAL_ERROR`,`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);let n=t.objectStore(this.collection);for(let t of e)if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e){let e=t[this.keyPath];e!==void 0&&u(await this.requestToPromise(n.get(e)),t),await this.requestToPromise(n.put(t))}}else if(t.type===`add`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.add(t))}else{let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.delete(t))}}async getById(e){return this.withTx(`readonly`,async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.count()))}async cursor(e,t=`forward`,n){return this.withTx(`readonly`,async r=>{let i=t===`forward`?`next`:`prev`,a=r.openCursor(g(n),i);return new Promise((t,n)=>{let r=null;a.onsuccess=async i=>{let a=i.target.result;if(!a)return t(r);try{let{value:n,done:i,offset:o}=await e(a.value,a.key,a);r=n,i?t(r):o&&o>0?a.advance(o):a.continue()}catch(e){n(e)}},a.onerror=()=>n(this.mapError(a.error))})})}mapError(e){if(e instanceof c)return e;let t=e?.message||`Unknown IndexedDB Error`,n=e?.name||``;return n===`QuotaExceededError`?new c(`INTERNAL_ERROR`,`Storage quota exceeded`):n===`VersionError`?new c(`CONFLICT`,t):n===`InvalidStateError`||n===`TransactionInactiveError`?new c(`TRANSIENT_ERROR`,t):new c(`INTERNAL_ERROR`,t)}async withTx(e,t){let n=await this.connectionManager.getConnection();return new Promise(async(r,i)=>{let a=n.transaction(this.collection,e),o=a.objectStore(this.collection),s,c;a.oncomplete=()=>{c?i(c):r(s)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{let e=t(o,a);s=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch{}}})}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}};const v=new Map,y=e=>{let t=v.get(e.database);t||(t=new n({retry:!0,throws:!0}),v.set(e.database,t));try{let{value:n,error:r}=t.doSync(()=>new h(e));if(r)throw new c(`CONNECTION_FAILED`,`Failed to initialize connection for database: ${e.database}`,void 0,r);return new _(n,e.collection,e.keyPath)}catch(e){throw e instanceof c?e:new c(`CONNECTION_FAILED`,e instanceof Error?e.message:`An unexpected connection error occurred`,void 0,e)}};var b=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{createEventBus:()=>u}),t.exports=c(l);var u=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error(`EventBus Error:`,e),crossTab:!1,channelName:`event-bus-channel`})=>{let t=new Map,n=[],r=0,i=0,a=new Map,o=new Map,s=null;e.crossTab&&typeof BroadcastChannel<`u`?s=new BroadcastChannel(e.channelName):e.crossTab&&console.warn(`BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.`);let c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{let t=n;n=[],t.forEach(({name:t,payload:n})=>{let r=performance.now();try{(o.get(t)||[]).forEach(e=>e(n))}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-r)})},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{let n=t.get(e);n?o.set(e,Array.from(n)):o.delete(e)};return s&&(s.onmessage=e=>{let{name:t,payload:n}=e.data;(o.get(t)||[]).forEach(e=>e(n))}),{subscribe:(e,n)=>{t.has(e)||t.set(e,new Set);let r=t.get(e);return r.add(n),d(e),()=>{r.delete(n),r.size===0?(t.delete(e),o.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async){n.push({name:t,payload:r}),n.length>=e.batchSize?l():u(),s&&s.postMessage({name:t,payload:r});return}let i=performance.now();try{(o.get(t)||[]).forEach(e=>e(r)),s&&s.postMessage({name:t,payload:r})}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:a,averageEmitDuration:r>0?i/r:0}),clear:()=>{t.clear(),o.clear(),n=[],r=0,i=0,a.clear(),s&&=(s.close(),null)}}};0&&(t.exports={createEventBus:u})})),ee=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{QueryBuilder:()=>u,createJoiner:()=>se,createMatcher:()=>v,createPaginator:()=>O,createProjector:()=>ue,createSorter:()=>le}),t.exports=c(l);var u=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:`offset`,offset:e,limit:t},this}cursor(e,t,n){return this.query.pagination={type:`cursor`,cursor:e,limit:t,direction:n},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`computed`,expression:e,alias:t}),this}case(e,t,n){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`case`,conditions:e,else:t,alias:n}),this}join(e,t,n){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:n,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function d(e){function t(e,t){return f(t)?e[t.field]:p(t)?t.value:g(t)?i(t,e):m(t)?i(t.expression,e):h(t)?a(e,t):t}let n=new Map([[`and`,(e,t)=>t.every(t=>o(e,t))],[`or`,(e,t)=>t.some(t=>o(e,t))],[`not`,(e,t)=>!t.every(t=>o(e,t))],[`nor`,(e,t)=>!t.some(t=>o(e,t))],[`xor`,(e,t)=>t.filter(t=>o(e,t)).length===1]]);function r(e,t){let{operator:r,conditions:i}=t,a=n.get(r);if(a)return a(e,i);throw Error(`Unsupported logical operator: ${r}`)}function i(n,r){let i=n.arguments.map(e=>t(r,e));if(e[n.function])return e[n.function](...i);throw Error(`Function ${n.function} not found!`)}function a(e,t){for(let n of t.conditions)if(o(e,n.when))return n.then;return t.else}function o(n,i){if(_(i))return r(n,i);if(!i||!i.field)return!1;let{field:a,operator:o,value:s}=i,c=n[a],l=t(n,s),u=new Map([[`eq`,(e,t)=>e===t],[`neq`,(e,t)=>e!==t],[`lt`,(e,t)=>e<t],[`lte`,(e,t)=>e<=t],[`gt`,(e,t)=>e>t],[`gte`,(e,t)=>e>=t],[`in`,(e,t)=>Array.isArray(t)&&t.includes(e)],[`nin`,(e,t)=>Array.isArray(t)&&!t.includes(e)],[`contains`,(e,t)=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.includes(s):!1],[`ncontains`,(e,t)=>typeof e==`string`&&!e.includes(t)],[`startswith`,(e,t)=>typeof e==`string`&&e.startsWith(t)],[`endswith`,(e,t)=>typeof e==`string`&&e.endsWith(t)],[`exists`,e=>e!=null],[`nexists`,e=>e==null]]),d=e[o]||u.get(o);if(d)return d(c,l);throw Error(`Unsupported comparison operator: ${o}`)}return{resolve:t,evaluate:o}}function f(e){return e?.type===`field`}function p(e){return e?.type===`value`}function m(e){return e?.type===`computed`}function h(e){return e?.type===`case`}function g(e){return e?.type===`function`}function _(e){return e?e.conditions!==void 0:!1}function v(e){let{evaluate:t}=d(e),n=new WeakMap;function r(e,r){let i=n.get(e);i||(i=new Map,n.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let o=t(e,r);return i.set(a,o),o}return{matcher:r,match:r}}var y=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`JoinError`}},b=e=>e&&`field`in e&&`operator`in e&&`value`in e,ee=e=>`operator`in e&&`conditions`in e,te=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`field`,ne=(e,t)=>{if(!e.relation)throw new y(`Join configuration must specify a relation`,`INVALID_CONFIG`);if(!t[e.relation])throw new y(`Collection "${e.relation}" not found in database`,`COLLECTION_NOT_FOUND`);if(e.alias&&typeof e.alias!=`string`)throw new y(`Join alias must be a string`,`INVALID_ALIAS`)},re=(e,t)=>t.split(`.`).reduce((e,t)=>e?.[t],e),x=(e,t)=>{if(e){if(b(e)&&e){let n=te(e.value)?re(t,e.value.field):e.value;return{...e,value:n}}if(ee(e)){let n={...e};return e.conditions&&(n.conditions=e.conditions.map(e=>x(e,t))),n}return e}},S=(e,t)=>{if(!e)return{};let n=x(e.filters,t);return{...e,filters:n}},ie=(e,t,n)=>{let r=n.alias||n.relation;return[{...e,[r]:t}]},C=(e,t)=>{let n=new Map;return e.forEach(e=>{let r=e[t];n.has(r)||n.set(r,[]),n.get(r).push(e)}),n},ae=async(e,t,n,r)=>{try{if(ne(n,e),!Array.isArray(t))throw new y(`Source data must be an array`,`INVALID_SOURCE_DATA`);let i=e[n.relation],a;return n.query?.filters&&b(n.query.filters)&&(a=C(i,n.query.filters.field)),(await Promise.all(t.map(async e=>{let t=S(n.query,e),o;return o=t.filters&&b(t.filters)&&a?.has(t.filters.value)?a.get(t.filters.value)||[]:i.filter(e=>r.matcher(e,t.filters)),ie(e,await[e=>t.sort?r.sorter(e,t.sort):e,e=>t.projection?r.projector(e,t.projection):e,async e=>t.pagination?await r.paginator(e,t.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(o)),n)}))).flat()}catch(e){throw e instanceof y?e:new y(`Join operation failed: ${e.message}`,`JOIN_EXECUTION_ERROR`)}},oe=async(e,t,n,r)=>n.reduce(async(t,n)=>ae(e,await t,n,r),Promise.resolve(t));function se(){return{join:oe}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name=`UnsupportedComparisonError`}},T=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name=`InvalidSortDirectionError`}};function E(e,t,n){if(e===t)return 0;if(e==null||t==null)return e==null?n===`asc`?-1:1:n===`asc`?1:-1;if(typeof e==`string`&&typeof t==`string`)return n===`asc`?e.localeCompare(t):t.localeCompare(e);if(typeof e==`number`&&typeof t==`number`)return n===`asc`?e-t:t-e;throw new w(e,t)}function ce(e,t){let n=Array.from(e);return t.length===0?n:n.sort((e,n)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],o=n[t];try{if(i!==`asc`&&i!==`desc`)throw new T(i);let e=E(a,o,i);if(e!==0)return e}catch(e){throw e instanceof w||e instanceof T?e:Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function le(){return{sort:ce}}function ue(e){let{resolve:t}=d(e);function n(e,t,n){for(let r of t){if(typeof r==`string`){let t=r;n[t]=e[t];continue}for(let[t,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=a(e[t],i))}}function r(e,t,n){Object.keys(n).length===0&&Object.assign(n,e);for(let e of t){if(typeof e==`string`){let t=e;delete n[t];continue}for(let[t,r]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&typeof e==`object`?n[t]=a(e,r):delete n[t]}}}function i(e,n,r){for(let i of n)r[i.alias]=t(e,i)}function a(e,t){let a={};return t.include?.length&&n(e,t.include,a),t.exclude?.length&&r(e,t.exclude,a),t.computed?.length&&i(e,t.computed,a),a}return{project:a}}async function*D(e,t,n=e=>String(e)){t.type===`offset`?yield*de(e,t):yield*k(e,t,n)}function O(){return{paginate:D}}async function*de(e,t){let{offset:n,limit:r}=t,i=0,a=r,o=[];for await(let t of e){if(a<=0&&(yield o,o=[],a=r),i<n){i++;continue}o.push(t),a--}o.length>0&&(yield o)}async function*k(e,t,n){let{cursor:r,limit:i,direction:a}=t,o=i,s=r===void 0,c=[];if(a===`forward`)for await(let t of e){if(o<=0&&(yield c,c=[],o=i),!s){s=n(t)===r;continue}c.push(t),o--}else{let t=[];for await(let n of e)t.push(n);for(let e=t.length-1;e>=0;e--){let a=t[e];if(!s){s=n(a)===r;continue}c.push(a),o--,o<=0&&(yield c,c=[],o=i)}}c.length>0&&(yield c)}0&&(t.exports={QueryBuilder,createJoiner,createMatcher,createPaginator,createProjector,createSorter})})),te=e(((e,t)=>{t.exports=n;function n(e){var t,n;if(typeof e!=`function`)throw Error(`expected a function but got `+e);return function(){return t?n:(t=!0,n=e.apply(this,arguments),n)}}})),ne=e(((e,t)=>{t.exports={encode:e=>new Uint8Array(Buffer.from(e,`utf8`)),decode:e=>Buffer.from(e).toString(`utf8`)}})),re=e(((e,t)=>{t.exports=n;function n(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,o=n&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!o)return e.apply(i,a)},t),o)return e.apply(this,arguments)}}})),x=e(((e,t)=>{function n(e){if(e.length===0)return`.`;let t=a(e);return t=t.reduce(c,[]),i(...t)}function r(...e){let t=``;for(let r of e)t=r.startsWith(`/`)?r:n(i(t,r));return t}function i(...e){if(e.length===0)return``;let t=e.join(`/`);return t=t.replace(/\/{2,}/g,`/`),t}function a(e){if(e.length===0)return[];if(e===`/`)return[`/`];let t=e.split(`/`);return t[t.length-1]===``&&t.pop(),e[0]===`/`?t[0]=`/`:t[0]!==`.`&&t.unshift(`.`),t}function o(e){let t=e.lastIndexOf(`/`);if(t===-1)throw Error(`Cannot get dirname of "${e}"`);return t===0?`/`:e.slice(0,t)}function s(e){if(e===`/`)throw Error(`Cannot get basename of "${e}"`);let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function c(e,t){if(e.length===0)return e.push(t),e;if(t===`.`)return e;if(t===`..`){if(e.length===1){if(e[0]===`/`)throw Error(`Unable to normalize path - traverses above root directory`);if(e[0]===`.`)return e.push(t),e}return e[e.length-1]===`..`?(e.push(`..`),e):(e.pop(),e)}return e.push(t),e}t.exports={join:i,normalize:n,split:a,basename:s,dirname:o,resolve:r}})),S=e(((e,t)=>{function n(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+`: `+this.message:this.message=e}}}t.exports={EEXIST:n(`EEXIST`),ENOENT:n(`ENOENT`),ENOTDIR:n(`ENOTDIR`),ENOTEMPTY:n(`ENOTEMPTY`),ETIMEDOUT:n(`ETIMEDOUT`),EISDIR:n(`EISDIR`)}})),ie=e(((e,t)=>{let n=x(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:o,EISDIR:s}=S();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:`dir`,size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){e===null?this._root=new Map([[`/`,this._makeRoot()]]):typeof e==`string`?this._root=new Map([[`/`,this._makeRoot(this.parse(e))]]):this._root=e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get(`/`))-1}_countInodes(e){let t=1;for(let[n,r]of e)n!==0&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get(`/`))+1}_maxInode(e){let t=e.get(0).ino;for(let[n,r]of e)n!==0&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get(`/`)){let t=``,n=(e,r)=>{for(let[i,a]of e){if(i===0)continue;let e=a.get(0),o=e.mode.toString(8);t+=`${` `.repeat(r)}${i}\t${o}`,e.type===`file`?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+=`
|
|
2
|
+
`,n(a,r+1))}};return n(e,0),t}parse(e){let t=0;function n(e){let n=++t,r=e.length===1?`dir`:`file`,[i,a,o]=e;return i=parseInt(i,8),a=a?parseInt(a):0,o=o?parseInt(o):Date.now(),new Map([[0,{mode:i,type:r,size:a,mtimeMs:o,ino:n}]])}let r=e.trim().split(`
|
|
3
|
+
`),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of r){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[r,...i]=e.split(` `),o=n(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:o}),a[a.length-2].node.set(r,o)}return i}_lookup(e,t=!0){let r=this._root,a=`/`,o=n.split(e);for(let s=0;s<o.length;++s){let c=o[s];if(r=r.get(c),!r)throw new i(e);if(t||s<o.length-1){let e=r.get(0);if(e.type===`symlink`){let t=n.resolve(a,e.target);r=this._lookup(t)}a=a?n.join(a,c):c}}return r}mkdir(e,{mode:t}){if(e===`/`)throw new r;let i=this._lookup(n.dirname(e)),a=n.basename(e);if(i.has(a))throw new r;let o=new Map,s={mode:t,type:`dir`,size:0,mtimeMs:Date.now(),ino:this.autoinc()};o.set(0,s),i.set(a,o)}rmdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;if(t.size>1)throw new o;let r=this._lookup(n.dirname(e)),i=n.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;return[...t.keys()].filter(e=>typeof e==`string`)}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch{}if(a!==void 0){if(a.type===`dir`)throw new s;r??=a.mode,i=a.ino}r??=438,i??=this.autoinc();let o=this._lookup(n.dirname(e)),c=n.basename(e),l={mode:r,type:`file`,size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,l),o.set(c,u),l}unlink(e){let t=this._lookup(n.dirname(e)),r=n.basename(e);t.delete(r)}rename(e,t){let r=n.basename(t),i=this._lookup(e);this._lookup(n.dirname(t)).set(r,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let r,i;try{let e=this.stat(t);i===null&&(i=e.mode),r=e.ino}catch{}i??=40960,r??=this.autoinc();let a=this._lookup(n.dirname(t)),o=n.basename(t),s={mode:i,type:`symlink`,target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,s),a.set(o,c),s}_du(e){let t=0;for(let[n,r]of e.entries())n===0?t+=r.size:t+=this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}})),C=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(e=`keyval-store`,t=`keyval`){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||=new Promise((e,t)=>{let n=indexedDB.open(this._dbName);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{n.result.createObjectStore(this._storeName)}})}_withIDBStore(e,t){return this._init(),this._dbp.then(n=>new Promise((r,i)=>{let a=n.transaction(this.storeName,e);a.oncomplete=()=>r(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}};let n;function r(){return n||=new t,n}function i(e,t=r()){let n;return t._withIDBStore(`readwrite`,t=>{n=t.get(e)}).then(()=>n.result)}function a(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{n.put(t,e)})}function o(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{let r=n.get(e);r.onsuccess=()=>{n.put(t(r.result),e)}})}function s(e,t=r()){return t._withIDBStore(`readwrite`,t=>{t.delete(e)})}function c(e=r()){return e._withIDBStore(`readwrite`,e=>{e.clear()})}function l(e=r()){let t=[];return e._withIDBStore(`readwrite`,e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function u(e=r()){return e._close()}e.Store=t,e.get=i,e.set=a,e.update=o,e.del=s,e.clear=c,e.keys=l,e.close=u})),ae=e(((e,t)=>{let n=C();t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename)}saveSuperblock(e){return n.set(`!root`,e,this._store)}loadSuperblock(){return n.get(`!root`,this._store)}readFile(e){return n.get(e,this._store)}writeFile(e,t){return n.set(e,t,this._store)}unlink(e){return n.del(e,this._store)}wipe(){return n.clear(this._store)}close(){return n.close(this._store)}}})),oe=e(((e,t)=>{t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+`/.superblock.txt`).then(e=>e.ok?e.text():null)}async readFile(e){let t=await fetch(this._url+e);if(t.status===200)return t.arrayBuffer();throw Error(`ENOENT`)}async sizeFile(e){let t=await fetch(this._url+e,{method:`HEAD`});if(t.status===200)return t.headers.get(`content-length`);throw Error(`ENOENT`)}}})),se=e(((e,t)=>{let n=C(),r=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){let t=Date.now();return this._lock.expires>t+e?!0:await this.renew()}else return!1}async renew({ttl:e=5e3}={}){let t;return await n.update(`lock`,n=>{let r=Date.now()+e;return t=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:r}:n,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await n.update(`lock`,n=>{let a=Date.now(),o=a+e;return r=n&&n.expires<a,t=n===void 0||r,i=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:o}:n,this._lock},this._store),i)throw Error(`Mutex double-locked`);return t}async wait({interval:e=100,limit:t=6e3,ttl:n}={}){for(;t--;){if(await this.acquire({ttl:n}))return!0;await r(e)}throw Error(`Mutex timeout`)}async release({force:e=!1}={}){let t,r,i;if(await n.update(`lock`,n=>(t=e||n&&n.holder===this._id,r=n===void 0,i=n&&n.holder!==this._id,this._lock=t?void 0:n,this._lock),this._store),await n.close(this._store),!t&&!e){if(r)throw Error(`Mutex double-freed`);if(i)throw Error(`Mutex lost ownership`)}return t}}})),w=e(((e,t)=>{t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+`_lock`,{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,n)=>{let r=new AbortController;setTimeout(()=>{r.abort(),n(Error(`Mutex timeout`))},e),navigator.locks.request(this._database+`_lock`,{signal:r.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+`_lock`,{steal:!0},e=>!0)}}})),T=e(((e,t)=>{let{encode:n,decode:r}=ne(),i=re(),a=ie(),{ENOENT:o,ENOTEMPTY:s,ETIMEDOUT:c}=S(),l=ae(),u=oe(),d=se(),f=w(),p=x();t.exports=class{constructor(){this.saveSuperblock=i(()=>{this.flush()},500)}async init(e,{wipe:t,url:n,urlauto:r,fileDbName:i=e,db:o=null,fileStoreName:s=e+`_files`,lockDbName:c=e+`_lock`,lockStoreName:p=e+`_lock`}={}){this._name=e,this._idb=o||new l(i,s),this._mutex=navigator.locks?new f(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:n},this._needsWipe=!!t,n&&(this._http=new u(n),this._urlauto=!!r)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();let e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){let e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,n){let r=p.split(p.dirname(e)),i=r.shift();for(let e of r){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch{}}return this._cache.writeStat(e,t,n)}async readFile(e,t){let n=typeof t==`string`?t:t&&t.encoding;if(n&&n!==`utf8`)throw Error(`Only "utf8" encoding is supported in readFile`);let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;t.type===`symlink`;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&((!a||a.size!=i.byteLength)&&(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),n===`utf8`?i=r(i):i.toString=()=>r(i)),!a)throw new o(e);return i}async writeFile(e,t,r){let{mode:i,encoding:a=`utf8`}=r;if(typeof t==`string`){if(a!==`utf8`)throw Error(`Only "utf8" encoding is supported in writeFile`);t=n(t)}let o=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(o.ino,t)}async unlink(e,t){let n=this._cache.lstat(e);this._cache.unlink(e),n.type!==`symlink`&&await this._idb.unlink(n.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){let{mode:n=511}=t;this._cache.mkdir(e,{mode:n})}rmdir(e,t){if(e===`/`)throw new s;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let n=await this._http.sizeFile(e);await this._writeStat(e,n,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}})),E=e(((e,t)=>{t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type===`file`}isDirectory(){return this.type===`dir`}isSymbolicLink(){return this.type===`symlink`}}})),ce=e(((e,t)=>{let n=T(),r=E(),i=x();function a(e,t,...n){return e=i.normalize(e),(t===void 0||typeof t==`function`)&&(t={}),typeof t==`string`&&(t={encoding:t}),[e,t,...n]}function o(e,t,n,...r){return e=i.normalize(e),(n===void 0||typeof n==`function`)&&(n={}),typeof n==`string`&&(n={encoding:n}),[e,t,n,...r]}function s(e,t,...n){return[i.normalize(e),i.normalize(t),...n]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,o,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,s,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,s,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new n,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&=(this._initPromiseResolve(),null),t.defer||this.stat(`/`)}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,n){return async(...r)=>{r=t(...r);let i={name:e.name,args:r};this._operations.add(i);try{return await this._activate(),await e.apply(this,r)}finally{this._operations.delete(i),n&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&=(clearTimeout(this._deactivationTimeout),null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||=this._backend.activate?this._backend.activate():Promise.resolve(),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||=this._backend.deactivate?this._backend.deactivate():Promise.resolve(),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,n){return await this._backend.writeFile(e,t,n),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){return new r(await this._backend.stat(e,t))}async lstat(e,t){return new r(await this._backend.lstat(e,t))}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}})),le=e(((e,t)=>{let n=te(),r=ce();function i(e,t){return typeof e==`function`&&(t=e),t=n(t),[(...e)=>t(null,...e),t]}t.exports=class{constructor(...e){this.promises=new r(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,n){let[r,a]=i(t,n);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,n,r){let[a,o]=i(n,r);this.promises.writeFile(e,t,n).then(a).catch(o)}unlink(e,t,n){let[r,a]=i(t,n);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,n){let[r,a]=i(t,n);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,n){let[r,a]=i(t,n);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,n){let[r,a]=i(t,n);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,n){let[r,a]=i(n);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,n){let[r,a]=i(t,n);this.promises.stat(e).then(r).catch(a)}lstat(e,t,n){let[r,a]=i(t,n);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,n){let[r,a]=i(t,n);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,n){let[r,a]=i(n);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,n){let[r,a]=i(t,n);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){let[n,r]=i(t);this.promises.du(e).then(n).catch(r)}flush(e){let[t,n]=i(e);this.promises.flush().then(t).catch(n)}}}));b();var ue=ee();le();var D=class extends Error{constructor(e,t){super(e),this.operation=t,this.name=`JsonPatchError`}};function O(e){let t=de(e);return t===``?[]:t.substring(1).split(`/`).map(fe)}function de(e){return e===``||e===`/`?``:e.startsWith(`/`)?`/`+e.substring(1).split(`/`).map(k).join(`/`):`/`+e.split(`.`).map(k).join(`/`)}function k(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function fe(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}var A=new Map;function j(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)throw new D(`Invalid path - parent not found at ${e}`);if(Array.isArray(n)){let t=e===`-`?n.length:parseInt(e);if(isNaN(t)||t<0||t>n.length)throw new D(`Invalid array index: ${e}`);n=n[t]}else{if(!n.hasOwnProperty(e))throw new D(`Property ${e} not found`);n=n[e]}}return n}function M(e,t){let n=A.get(t)||O(t);if(A.set(t,n),n.length===0)return e;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new D(`Invalid array index: ${i}`);return r[e]}return r[i]}function pe(e,t,n){let r=A.get(t)||O(t);A.set(t,r);let i=j(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter(e=>e!==n)):i[a]===n&&delete i[a],e}function N(e,t,n){let r=A.get(t)||O(t);if(A.set(t,r),r.length===0)return n;let i=r.slice(0,-1),a=r[r.length-1],o=j(e,i);if(Array.isArray(o))if(a===`-`)o.push(n);else{let e=parseInt(a);if(e<0||e>o.length)throw new D(`Invalid array index: ${a}`);o.splice(e,0,n)}else o[a]=n;return e}function P(e,t){let n=A.get(t)||O(t);if(A.set(t,n),n.length===0)return;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function me(e,t){let n=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case`add`:n=N(n,e.path,e.value);break;case`remove`:n=P(n,e.path);break;case`removeValue`:n=pe(n,e.path,e.value);break;case`replace`:n=N(P(n,e.path),e.path,e.value);break;case`copy`:{let t=M(n,e.from);n=N(n,e.path,JSON.parse(JSON.stringify(t)));break}case`move`:{let t=M(n,e.from);n=N(n,e.path,t),n=P(n,e.from);break}case`test`:{let t=M(n,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new D(`Test operation failed`);break}default:throw new D(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof D&&(t.operation=e),t}return n}function he(e,t){let n=[];switch(e.type){case`addField`:n.push({op:`add`,path:`/fields/${e.id}`,value:e.definition});break;case`removeField`:n.push({op:`remove`,path:`/fields/${e.id}`});break;case`modifyField`:{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,r])=>{n.push({op:`replace`,path:`${t}/${e}`,value:r})});break}case`deprecateField`:n.push({op:`add`,path:`/fields/${e.id}/deprecated`,value:!0});break;case`addIndex`:t.indexes||n.push({op:`add`,path:`/indexes`,value:[]}),n.push({op:`add`,path:`/indexes/-`,value:e.definition});break;case`removeIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/indexes/${r}`});break}case`modifyIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`/indexes/${r}/${e}`,value:t})});break}case`addConstraint`:t.constraints||n.push({op:`add`,path:`/constraints`,value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{n.push({op:`add`,path:`/constraints/-`,value:e})}):n.push({op:`add`,path:`/constraints/-`,value:e.constraint});break;case`removeConstraint`:{let r=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/constraints/${r}`});break}case`modifyConstraint`:{let r=ge(t,e.name);r&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`${r}/${e}`,value:t})});break}}return n}function ge(e,t){if(!e.constraints)return null;for(let n=0;n<e.constraints.length;n++){let r=e.constraints[n];if(r.name===t)return`/constraints/${n}`;if(_e(r)){let e=ve(r.rules,t);if(e)return`/constraints/${n}${e}`}}return null}function _e(e){return e&&`operator`in e&&`rules`in e}function ve(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(`name`in r&&r.name===t)return`/rules/${n}`;if(_e(r)){let e=ve(r.rules,t);if(e)return`/rules/${n}${e}`}}return null}var F=new Map;function I(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ye(e,t){let n=e=>({value:e}),r=e=>({issues:e}),i=(e,t,n,r)=>{switch(t){case`string`:return typeof e==`string`?[]:[{message:`Expected string, got ${typeof e}`,path:n}];case`number`:return typeof e!=`number`||isNaN(e)?[{message:`Expected number, got ${typeof e}`,path:n}]:[];case`boolean`:return typeof e==`boolean`?[]:[{message:`Expected boolean, got ${typeof e}`,path:n}];case`array`:return Array.isArray(e)?[]:[{message:`Expected array, got ${typeof e}`,path:n}];case`set`:return!Array.isArray(e)||new Set(e).size!==e.length?[{message:`Expected unique array, got ${typeof e}`,path:n}]:[];case`enum`:return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:n}]:[{message:`Enum type requires 'values' definition`,path:n}];case`object`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected object, got ${typeof e}`,path:n}]:[];case`record`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];case`union`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected union (object), got ${typeof e}`,path:n}]:[];case`dynamic`:return console.warn(`Deprecated: 'dynamic' type used. Use 'record' instead.`),typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];default:return[{message:`Unknown type '${t}'`,path:n}]}};function a(e,t,n,r,i){let o=[],s=e.rules.map((e,s)=>{let c=[...r,`rules[${s}]`],l=`${e.name}@${c.join(`.`)}`;if(`rules`in e){if(i.has(l))return!0;i.add(l);let r=a(e,t,n,c,i);return o.push(...r),i.delete(l),r.length===0}else{let r=n[e.predicate];if(!r)return o.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(F.has(i)){let t=F.get(i);return t||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return F.set(i,a),a||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),a}});return(()=>{switch(e.operator){case`and`:return s.every(e=>e);case`or`:return s.some(e=>e);case`not`:return!s.every(e=>e);case`nor`:return!s.some(e=>e);case`xor`:return s.filter(e=>e).length===1}})()||o.push({message:`Constraint group '${e.name}' failed`,path:r}),o}function o(e,t,n,r,s,c=new Set){let l=[];if(`type`in t&&!(`fields`in t)){let o=r.length>0?e[r[r.length-1]]:e;return l.push(...i(o,t.type,r,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if(`rules`in e)l.push(...a(e,{value:o},n,[...r,`constraints[${t}]`],c));else{let i=n[e.predicate];i?i({data:{value:o},field:`value`,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...r,`constraints[${t}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...r,`constraints[${t}]`]})}}),l}let u={};if(`concrete`in t)if(t.concrete===!0||!Array.isArray(t.fields))u=t.fields;else{let n=t.fields,i=n.find(e=>!e.when);i&&Object.assign(u,i.fields);let a=n.find(t=>t.when&&e[t.when.field]!==void 0&&e[t.when.field]===t.when.value);if(a)Object.assign(u,a.fields);else if(!i)return l.push({message:`No matching field set found for discriminated schema`,path:r}),l}else u=t.fields;let d=new Set(Object.values(u).map(e=>e.name));Object.entries(u).forEach(([t,u])=>{let d=[...r,u.name],f=Object.hasOwnProperty.call(e,u.name)?e[u.name]:u.default===void 0?void 0:u.default;u.required&&f==null&&l.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if(u.type===`object`&&p&&!Array.isArray(p)){let e=s[p.id];if(e)if(c.has(p.id))l.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=f&&typeof f==`object`&&!Array.isArray(f)?f:{};l.push(...o(t,e,n,d,s,c)),p.constraints?.forEach((e,r)=>{if(`rules`in e)l.push(...a(e,t,n,[...d,`constraints[${r}]`],c));else{let i=n[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}),c.delete(p.id)}else l.push({message:`Nested schema '${p.id}' not found`,path:d})}if(u.type===`union`&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((r,i)=>{let l=s[r.id];if(l)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,i.toString()]});else{c.add(r.id);let i=f&&typeof f==`object`&&!Array.isArray(f)?f:{},u=o(i,l,n,d,s,new Set(c));u.length===0&&f!==void 0?(e=!0,r.constraints?.forEach((r,o)=>{if(`rules`in r){let s=a(r,i,n,[...d,`constraints[${o}]`],c);s.length>0&&(e=!1,t.push(...s))}else{let a=n[r.predicate];a&&!a({data:i,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${o}]`]}))}})):f===void 0&&t.push(...u.filter(e=>e.message.includes(`is required`))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,i.toString()]})}),!e&&f!==void 0?(l.push({message:`Value does not match any union schema`,path:d}),l.push(...t)):f===void 0&&l.push(...t)}f!==void 0&&(l.push(...i(f,u.type,d,{values:u.values})),(u.type===`array`||u.type===`set`)&&Array.isArray(f)&&(u.constraints?.forEach((e,t)=>{let r=n[e.predicate];r&&!r({data:{[u.name]:f},field:u.name,arguments:e.parameters})&&l.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})}),u.itemsType&&f.forEach((e,t)=>l.push(...i(e,u.itemsType,[...d,t.toString()]))),p&&!Array.isArray(p)&&(s[p.id]?f.forEach((e,t)=>{typeof e==`object`&&e&&(c.has(p.id)?l.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),l.push(...o(e,s[p.id],n,[...d,t.toString()],s,c)),c.delete(p.id)))}):l.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach((t,r)=>{if(`rules`in t)l.push(...a(t,e,n,[...d,`constraints[${r}]`],c));else{let i=n[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${I(t.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&l.push({message:`Unexpected field '${t}'`,path:[...r,t]});return t.constraints?.forEach((t,i)=>{if(`rules`in t)l.push(...a(t,e,n,[...r,`constraints[${i}]`],c));else{let a=n[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${I(t.parameters)}`,path:[...r,`constraints[${i}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...r,`constraints[${i}]`]})}}),l}return e.version!==`1.0.0`&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:i=>{if(typeof i!=`object`||!i)return r([{message:`Input must be an object`,path:[]}]);let a=i,s=o(a,e,t,[],e.nestedSchemas||{});return s.length>0?r(s):n(a)},types:{input:{},output:{}}}}}var L=class extends Error{constructor(e,t){super(e),this.errors=t,this.name=`SchemaValidationError`}},R=e=>({value:e}),z=e=>({issues:e}),B=(e,t,n=!0)=>e===void 0&&!n?[]:typeof e!=`string`||e.trim()===``?[{message:`Must be a non-empty string`,path:[t]}]:[],V=(e,t)=>{let n=[`string`,`number`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`dynamic`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:e===`dynamic`?[{message:`Field type 'dynamic' is deprecated; use 'record' instead`,path:[t]}]:[]},be=(e,t)=>{let n=[`normal`,`unique`,`btree`,`hash`,`spatial`,`fulltext`,`gi`,`expression`,`composite`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},xe=(e,t)=>{let n=[`and`,`or`,`not`,`nor`,`xor`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},H=(e,t,n=!1)=>e===void 0&&!n||typeof e==`boolean`?[]:[{message:`Must be a boolean`,path:[t]}],Se=(e,t,n)=>[],U=(e,t,n)=>{let r=[],i=[`predicate`,`name`],a=[`type`,`predicate`,`field`,`parameters`,`name`,`description`,`errorMessage`],o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...B(e.predicate,`${n}.predicate`)),e.field!==void 0&&typeof e.field!=`string`&&r.push({message:`Field must be a string`,path:[`${n}.field`]}),e.parameters!==void 0&&r.push(...Se(e.parameters,t,`${n}.parameters`)),r.push(...B(e.description,`${n}.description`,!1)),r.push(...B(e.errorMessage,`${n}.errorMessage`,!1)),r},W=(e,t,n)=>{let r=[],i=[`name`,`operator`,`rules`],a=i,o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...xe(e.operator,`${n}.operator`)),!Array.isArray(e.rules)||e.rules.length===0?r.push({message:`Rules must be a non-empty array`,path:[`${n}.rules`]}):e.rules.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}.rules[${i}]`)):r.push(...U(e,t,`${n}.rules[${i}]`))}),r},G=(e,t,n)=>{if(!Array.isArray(e))return[{message:`Must be an array`,path:[n]}];let r=[];return e.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}[${i}]`)):r.push(...U(e,t,`${n}[${i}]`))}),r},Ce=(e,t)=>{let n=[],r=[`operator`,`field`],i=[`operator`,`field`,`value`,`conditions`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...xe(e.operator,`${t}.operator`)),n.push(...B(e.field,`${t}.field`)),e.conditions!==void 0&&(Array.isArray(e.conditions)?e.conditions.forEach((e,r)=>n.push(...Ce(e,`${t}.conditions[${r}]`))):n.push({message:`Conditions must be an array`,path:[`${t}.conditions`]})),n},we=(e,t)=>{let n=[],r=[`fields`,`type`,`name`],i=[`fields`,`type`,`unique`,`partial`,`description`,`order`,`name`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),n.push(...be(e.type,`${t}.type`)),(!Array.isArray(e.fields)||e.fields.length===0||!e.fields.every(e=>typeof e==`string`))&&n.push({message:`Fields must be a non-empty array of strings`,path:[`${t}.fields`]}),n.push(...H(e.unique,`${t}.unique`,!1)),e.partial&&n.push(...Ce(e.partial,`${t}.partial`)),n.push(...B(e.description,`${t}.description`,!1)),e.order!==void 0&&![`asc`,`desc`].includes(e.order)&&n.push({message:`Order must be 'asc' or 'desc'`,path:[`${t}.order`]}),n},K=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))return[{message:`Must be an array`,path:[t]}];let n=[];return e.forEach((e,r)=>n.push(...we(e,`${t}[${r}]`))),n},Te=(e,t,n,r,i)=>{let a=[];return e===void 0?[]:(n===`union`&&Array.isArray(e)?(e.length===0&&a.push({message:`Schema array must not be empty for union type`,path:[t]}),e.forEach((e,n)=>{let i=`${t}[${n}]`;a.push(...B(e.id,`${i}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${i}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${i}.indexes`))})):(n===`object`||n===`array`&&i===`object`)&&!Array.isArray(e)?(a.push(...B(e.id,`${t}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${t}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${t}.indexes`))):a.push({message:`Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'`,path:[t]}),a)},Ee=(e,t,n)=>{if(e===void 0)return[];switch(t){case`string`:if(typeof e!=`string`)return[{message:`Default must be a string`,path:[n]}];break;case`number`:if(typeof e!=`number`)return[{message:`Default must be a number`,path:[n]}];break;case`boolean`:if(typeof e!=`boolean`)return[{message:`Default must be a boolean`,path:[n]}];break;case`array`:case`set`:if(!Array.isArray(e))return[{message:`Default must be an array`,path:[n]}];break;case`enum`:if(!Array.isArray(e)||!e.every(e=>typeof e==`string`||typeof e==`number`))return[{message:`Default must be an array of strings or numbers`,path:[n]}];break;case`object`:case`record`:if(typeof e!=`object`||!e)return[{message:`Default must be an object`,path:[n]}];break;case`union`:case`dynamic`:return[]}return[]},De=(e,t)=>e===void 0?[]:typeof e!=`object`||!e?[{message:`Hint must be an object`,path:[t]}]:`input`in e&&typeof e.input!=`object`?[{message:`Hint.input must be an object`,path:[`${t}.input`]}]:[],q=(e,t,n)=>{let r=[],i=[`name`,`type`],a=[`name`,`type`,`required`,`constraints`,`default`,`values`,`schema`,`itemsType`,`nestedSchema`,`deprecated`,`reference`,`description`,`unique`,`hint`],o=e;if(i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...H(e.required,`${t}.required`,!1)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...Ee(e.default,e.type,`${t}.default`)),e.values!==void 0&&(e.type===`enum`?(!Array.isArray(e.values)||e.values.length===0||!e.values.every(e=>typeof e==`string`||typeof e==`number`))&&r.push({message:`Values must be a non-empty array of strings or numbers`,path:[`${t}.values`]}):r.push({message:`Values is only valid for 'enum' type`,path:[`${t}.values`]})),e.schema!==void 0&&r.push(...Te(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.nestedSchema){r.push({message:`nestedSchema is deprecated; use schema instead`,path:[`${t}.nestedSchema`]});let i=[`id`],a=[`id`,`constraints`,`indexes`],o=e.nestedSchema;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),r.push(...B(e.nestedSchema.id,`${t}.nestedSchema.id`)),n.includes(e.nestedSchema.id)||r.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&r.push(...G(e.nestedSchema.constraints,`dynamic`,`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...K(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...H(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:`reference is deprecated`,path:[`${t}.reference`]});let n=[`schema`,`field`],i=[`schema`,`field`],a=e.reference;n.forEach(e=>{a[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),r.push(...B(e.reference.schema,`${t}.reference.schema`)),r.push(...B(e.reference.field,`${t}.reference.field`))}return r.push(...B(e.description,`${t}.description`,!1)),r.push(...H(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...De(e.hint,`${t}.hint`)),r},Oe=(e,t,n)=>{let r=[];if(`type`in e&&[`string`,`number`,`boolean`,`array`,`set`,`enum`,`record`].includes(e.type)){let i=[`name`,`type`],a=[`name`,`type`,`default`,`schema`,`itemsType`,`constraints`,`description`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...Ee(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Te(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...B(e.description,`${t}.description`,!1)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}else{let i=[`name`],a=[`name`,`description`,`concrete`,`fields`,`indexes`,`constraints`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...H(o.concrete,`${t}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&r.push({message:`Fields must be an object when concrete is true`,path:[`${t}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&r.push({message:`Fields array must not be empty`,path:[`${t}.fields`]}),o.fields.forEach((e,i)=>{let a=`${t}.fields[${i}]`;if(typeof e!=`object`||!e||!(`fields`in e))r.push({message:`Each variant must have a 'fields' property`,path:[a]});else{let t=e.fields;typeof t!=`object`||!t?r.push({message:`Fields must be a non-empty object`,path:[`${a}.fields`]}):Object.entries(t).forEach(([e,t])=>{r.push(...q(t,`${a}.fields.${e}`,n))}),e.when!==void 0&&(typeof e.when!=`object`||e.when===null?r.push({message:`When must be an object`,path:[`${a}.when`]}):r.push(...B(e.when.field,`${a}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!=`object`||o.fields===null?r.push({message:`Fields must be a non-empty object`,path:[`${t}.fields`]}):Object.entries(o.fields).forEach(([e,i])=>{r.push(...q(i,`${t}.fields.${e}`,n))})),r.push(...B(e.description,`${t}.description`,!1)),e.indexes&&r.push(...K(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...G(o.constraints,`dynamic`,`${t}.constraints`)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}return r},ke=e=>{if(typeof e!=`object`||!e)return z([{message:`Schema must be an object`,path:[]}]);let t=e,n=[],r=[`name`,`version`,`fields`],i=[`name`,`version`,`description`,`fields`,`nestedSchemas`,`indexes`,`constraints`,`metadata`,`dependencies`,`migrations`,`mock`,`hint`],a=t;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[e]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[e]})}),n.push(...B(t.name,`name`)),n.push(...B(t.version,`version`)),typeof t.fields!=`object`||t.fields===null)n.push({message:`Fields must be a non-empty object`,path:[`fields`]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,r])=>{n.push(...q(r,`fields.${t}`,e))})}if(t.nestedSchemas!==void 0)if(typeof t.nestedSchemas!=`object`||t.nestedSchemas===null)n.push({message:`NestedSchemas must be an object`,path:[`nestedSchemas`]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,r])=>n.push(...Oe(r,`nestedSchemas.${t}`,e)))}return n.push(...B(t.description,`description`,!1)),t.indexes&&n.push(...K(t.indexes,`indexes`)),t.constraints&&n.push(...G(t.constraints,`dynamic`,`constraints`)),t.metadata!==void 0&&(typeof t.metadata!=`object`||t.metadata===null)&&n.push({message:`Metadata must be an object`,path:[`metadata`]}),t.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`dependencies`]})),t.migrations!==void 0&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>n.push(...je(e,`migrations[${t}]`))):n.push({message:`Migrations must be an array`,path:[`migrations`]})),t.mock!==void 0&&typeof t.mock!=`function`&&n.push({message:`Mock must be a function`,path:[`mock`]}),t.hint&&n.push(...De(t.hint,`hint`)),n.length>0?z(n):R(t)},J=(e,t)=>{let n=[];switch(e.type||n.push({message:`type is required`,path:[`${t}.type`]}),e.type){case`modifyProperty`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),(e.changes===void 0||typeof e.changes!=`object`)&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addField`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...q(e.definition,`${t}.definition`,[]));break}case`removeField`:case`deprecateField`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyField`:{let r=[`type`,`id`,`changes`],i=[`type`,`id`,`changes`,`nestedSchemaChanges`],a=e;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]}),e.nestedSchemaChanges){let r=[`id`,`constraints`,`indexes`],i=e.nestedSchemaChanges;Object.keys(i).forEach(e=>{r.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),n.push(...B(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&n.push(...G(i.constraints,`dynamic`,`${t}.nestedSchemaChanges.constraints`)),i.indexes&&n.push(...K(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case`addIndex`:{let r=[`type`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...we(e.definition,`${t}.definition`));break}case`removeIndex`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyIndex`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addConstraint`:{let r=[`type`,`constraint`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),`rules`in e.constraint?n.push(...W(e.constraint,`dynamic`,`${t}.constraint`)):n.push(...U(e.constraint,`dynamic`,`${t}.constraint`));break}case`removeConstraint`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyConstraint`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addNestedSchema`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...Oe(e.definition,`${t}.definition`,[]));break}case`removeNestedSchema`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyNestedSchema`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}default:n.push({message:`Unknown schema change type`,path:[`${t}.type`]})}return n},Ae=(e,t)=>{let n=[],r=[`forward`,`backward`],i=r,a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),typeof e.forward!=`function`&&n.push({message:`Forward must be a function`,path:[`${t}.forward`]}),typeof e.backward!=`function`&&n.push({message:`Backward must be a function`,path:[`${t}.backward`]}),n},je=(e,t)=>{let n=[],r=[`id`,`schemaVersion`,`changes`,`description`,`status`,`transform`,`createdAt`,`checksum`],i=[...r,`rollback`,`dependencies`],a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...B(e.schemaVersion,`${t}.schemaVersion`)),n.push(...B(e.description,`${t}.description`));let o=[`pending`,`applied`,`failed`];return o.includes(e.status)||n.push({message:`Status must be one of ${o.join(`, `)}`,path:[`${t}.status`]}),!Array.isArray(e.changes)||e.changes.length===0?n.push({message:`Changes must be a non-empty array`,path:[`${t}.changes`]}):e.changes.forEach((e,r)=>{n.push(...J(e,`${t}.changes[${r}]`))}),e.rollback!==void 0&&(Array.isArray(e.rollback)?e.rollback.forEach((e,r)=>n.push(...J(e,`${t}.rollback[${r}]`))):n.push({message:`Rollback must be an array`,path:[`${t}.rollback`]})),typeof e.transform==`string`?n.push(...B(e.transform,`${t}.transform`)):typeof e.transform==`object`&&e.transform!==null?n.push(...Ae(e.transform,`${t}.transform`)):n.push({message:`Transform must be a string or object`,path:[`${t}.transform`]}),n.push(...B(e.createdAt,`${t}.createdAt`)),n.push(...B(e.checksum,`${t}.checksum`)),e.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`${t}.dependencies`]})),n},Me={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:ke,types:{input:{},output:{}}}},Ne={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(typeof e!=`object`||!e)return z([{message:`Migration must be an object`,path:[]}]);let t=e,n=je(t,``);return n.length>0?z(n):R(t)},types:{input:{},output:{}}}},Pe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(!Array.isArray(e))return z([{message:`SchemaChanges must be an array`,path:[]}]);let t=e,n=[];return t.forEach((e,t)=>n.push(...J(e,`[${t}]`))),n.length>0?z(n):R(t)},types:{input:[],output:[]}}};function Fe(e){try{return!Ne[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid migration definition`,e instanceof Error?e:Error(String(e)))}}function Ie(e){try{return!Pe[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema change definition`,e instanceof Error?e:Error(String(e)))}}function Le(e){try{return!Me[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema definition`,e instanceof Error?e:Error(String(e)))}}var Re=async e=>{if(typeof window<`u`&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}else{let{createHash:t}=await import(`crypto`);return t(`sha256`).update(e).digest(`hex`)}};function ze(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function Be(e,t){if(t&&`field`in e&&e.field){let n=t.fields[e.field];if(n)return n.type}if(`parameters`in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]==`string`)return`string`;if(typeof t==`number`||Array.isArray(t)&&typeof t[0]==`number`)return`number`;if(typeof t==`boolean`)return`boolean`;if(typeof t==`object`&&t){if(`minItems`in t||`maxItems`in t)return`array`;if(`schema`in t)return`object`}}}function Ve(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function He(e,t,n){switch(n){case`string`:if(e instanceof RegExp&&t instanceof RegExp)return e.source!==t.source;if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`number`:if(typeof e==`object`&&typeof t==`object`&&`precision`in e&&`precision`in t)return t.precision<e.precision||(t.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`array`:if(typeof e==`object`&&typeof t==`object`&&`minItems`in e&&`maxItems`in e&&`minItems`in t&&`maxItems`in t)return t.minItems>e.minItems||t.maxItems<e.maxItems;break;case`object`:if(typeof e==`object`&&typeof t==`object`&&`schema`in e&&`schema`in t)return Object.keys(t.schema).length>Object.keys(e.schema).length;break}return!1}function Ue(e,t){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&n[t.operator]>n[e.operator]||t.rules&&t.rules.length>e.rules.length)}function We(e,t,n){if(!t)return!0;if(`rules`in t&&`rules`in e)return Ue(t,e);if(`predicate`in e&&e.predicate!==void 0)return!0;if(`parameters`in e&&e.parameters!==void 0){let r=Be(t,n);return r?He(t.parameters,e.parameters,r):!0}return!1}function Ge(e,t){switch(e.type){case`removeField`:case`removeIndex`:return`major`;case`modifyField`:return Ve(e.changes)?`major`:e.changes.deprecated?`minor`:`patch`;case`modifyIndex`:return e.changes.unique!==void 0||e.changes.fields!==void 0?`major`:`minor`;case`addConstraint`:return`major`;case`removeConstraint`:return`minor`;case`modifyConstraint`:let n=t?.constraints?.find(t=>`name`in t&&t.name===e.name);return We(e.changes,n,t)?`major`:`minor`;case`addField`:case`addIndex`:case`deprecateField`:return`minor`;default:throw Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Ke(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case`addField`:if(n.has(a.id))throw Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case`removeField`:if(r.has(a.id))throw Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case`modifyField`:if(n.has(a.id))throw Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case`deprecateField`:if(n.has(a.id))throw Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id);break}}function qe(e){let t=new Set,n=new Set,r=new Set;for(let i of e)switch(i.type){case`addConstraint`:let e=i.constraint,a=(`name`in e,e.name);if(n.has(a))throw Error(`Cannot add previously removed constraint: ${a}`);if(t.has(a))throw Error(`Cannot add already modified constraint: ${a}`);r.add(a);break;case`removeConstraint`:if(r.has(i.name))throw Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw Error(`Cannot remove modified constraint: ${i.name}`);n.add(i.name);break;case`modifyConstraint`:if(n.has(i.name))throw Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name);break}}function Je(e,t,n){if(t.length===0)throw Error(`No changes provided`);Ke(t),qe(t);let r=ze(e),i=`patch`;for(let e of t){let t=Ge(e,n);if(t===`major`){i=`major`;break}else t===`minor`&&i===`patch`&&(i=`minor`)}switch(i){case`major`:return`${r.major+1}.0.0`;case`minor`:return`${r.major}.${r.minor+1}.0`;case`patch`:return`${r.major}.${r.minor}.${r.patch+1}`}}function Y(e,t){let n=e=>e.split(`.`).map(e=>parseInt(e,10)||0),[r,i,a]=n(e),[o,s,c]=n(t);return r-o||i-s||a-c}var X=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.migrationId=n,this.cause=r,this.name=`MigrationError`}},Ye=(e=>(e.INVALID_SCHEMA=`INVALID_SCHEMA`,e.INVALID_MIGRATION=`INVALID_MIGRATION`,e.CHECKSUM_MISMATCH=`CHECKSUM_MISMATCH`,e.TIMEOUT=`TIMEOUT`,e.MEMORY_LIMIT=`MEMORY_LIMIT`,e.CONCURRENT_OPERATION=`CONCURRENT_OPERATION`,e.TRANSFORM_ERROR=`TRANSFORM_ERROR`,e.VERSION_NOT_FOUND=`VERSION_NOT_FOUND`,e.CIRCULAR_DEPENDENCY=`CIRCULAR_DEPENDENCY`,e.STREAM_ERROR=`STREAM_ERROR`,e.ROLLBACK_ERROR=`ROLLBACK_ERROR`,e.MISSING_TRANSFORM=`MISSING_TRANSFORM`,e))(Ye||{}),Xe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,n){try{if(!Le(e))throw new X(`Invalid initial schema`,`INVALID_SCHEMA`);if(this.currentSchema=e,t){if(!t.every(e=>Fe(e)))throw new X(`Invalid migration configuration`,`INVALID_MIGRATION`);this.migrations=t.sort((e,t)=>Y(e.schemaVersion,t.schemaVersion))}n&&(this.history=n.sort((e,t)=>Y(e.version,t.version)))}catch(e){throw e instanceof X?e:new X(`Failed to initialize MigrationEngine`,`INVALID_SCHEMA`,void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{return await Re(JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt}))}catch(t){throw new X(`Checksum generation failed`,`CHECKSUM_MISMATCH`,e.id,t)}}async add(e){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);if(!e.changes?.length)throw new X(`Migration must include changes`,`INVALID_MIGRATION`);try{e.changes.forEach(e=>Ie(e))}catch(e){throw new X(`Invalid schema changes`,`INVALID_MIGRATION`,void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:`pending`,rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:``};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,n,r){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(n,r);return{newSchema:a.reduce((e,t)=>{let r=n===`forward`?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)},i),dataPreview:await e.processMigrationList(t,n,a)}}catch(e){throw e instanceof X?e:new X(`Dry run failed`,`INVALID_SCHEMA`,void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(n=>{let r=e===`forward`?`pending`:`applied`,i=t?Y(n.schemaVersion,t)>=0:!0;return n.status===r&&i}).sort((t,n)=>e===`forward`?t.id.localeCompare(n.id):n.id.localeCompare(t.id))}applySchemaChanges(e,t,n){try{let r=Je(e.version,t);return t.map(t=>{try{return he(t,e)}catch(e){throw new X(`Invalid schema change`,`INVALID_SCHEMA`,n,e)}}).reduce((e,t)=>{try{return me(e,t)}catch(e){throw new X(`Failed to apply patch`,`INVALID_SCHEMA`,n,e)}},{...e,version:r})}catch(e){throw e instanceof X?e:new X(`Schema update failed`,`INVALID_SCHEMA`,n,e)}}async prepareMigration(){let e=this.migrations.filter(e=>e.status===`pending`);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema(`forward`);let r=await e.processMigrationList(t,`forward`,n);return this.markMigrationsApplied(n),r}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new X(`Checksum mismatch`,`CHECKSUM_MISMATCH`,e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:`applied`}:t)}async rollback(e){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);return this.migrations.filter(e=>e.status===`applied`).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,n){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);try{let r=this.history.findIndex(e=>e.version===t);if(r===-1)throw Error(`Version ${t} not found in history`);let i=this.migrations.filter(e=>e.schemaVersion===t&&e.status===`applied`).sort((e,t)=>t.id.localeCompare(e.id)),a=this.history.length-r;if(a<0)return n;for(let e=0;e<a;e++)this.transformSchema(`backward`);let o=await e.processMigrationList(n,`backward`,i);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&e.status===`applied`?{...e,status:`pending`}:e),o}finally{this.isProcessing=!1}}static async processMigrationList(e,t,n){return(await Promise.all(n.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new X(`Failed to resolve transform for migration ${e.id}`,`TRANSFORM_ERROR`,e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:n})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await n(e);r.enqueue(t)}catch(e){r.error(new X(`Data transformation failed for migration ${t.id}`,`TRANSFORM_ERROR`,t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform==`string`?e.transform.startsWith(`http://`)||e.transform.startsWith(`https://`)?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let n=await fetch(e);if(!n.ok)throw new X(`Failed to fetch transform module: ${e}`,`TRANSFORM_ERROR`,void 0);let r=await n.text();if(typeof window<`u`){let e=new Blob([r],{type:`application/javascript`});return(await import(URL.createObjectURL(e))).default[t]}else{let{runInNewContext:n}=await import(`vm`),i={module:{exports:{}},console};return n(r,i,e),i.module.exports[t]}}catch(t){throw new X(`Failed to load remote transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new X(`Failed to import local transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}transformSchema(e){try{if(e===`backward`){let e=this.history.pop();if(!e)throw Error(`No previous version`);this.currentSchema=e;return}let t=this.migrations.filter(e=>e.status===`pending`).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof X?e:new X(`Schema transformation failed`,`INVALID_SCHEMA`,void 0,e)}}};typeof window<`u`&&(window.Buffer=r);var Ze=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let n=-1,r=i=>{if(i<=n)throw Error(`next() called multiple times`);n=i;let a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,()=>r(i+1))}catch(e){return Promise.reject(e)}};return r(0)}wrap(e,t){let n=this;return new Proxy(e,{get(e,r,i){let a=Reflect.get(e,r,i);return typeof a==`function`?function(...i){let o={...t,operation:r.toString(),args:i};return n.execute(o,()=>a.apply(e,i))}:a}})}};const Qe=(e=3,t=100)=>async(n,r)=>{let i=0;for(;i<e;)try{return await r()}catch(n){if(n instanceof c&&n.type===`TRANSIENT_ERROR`){if(i++,i>=e)throw n;let r=t*2**i+Math.random()*50;await new Promise(e=>setTimeout(e,r))}else throw n}},$e=async(e,t)=>{let n=Date.now();try{let r=await t();return Z(e,n,r,null),r}catch(t){throw Z(e,n,void 0,t),t}};function Z(e,t,n,r){if(!e.eventBus)return;let i=Date.now()-t;e.eventBus.emit({name:`telemetry`,payload:{type:`telemetry`,method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?`document`:e.collection?`collection`:`database`,collection:e.collection,document:e.documentId},result:r?void 0:{type:Array.isArray(n)?`array`:typeof n,size:Array.isArray(n)?n.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}async function et(e,t){let{offset:n,limit:r}=t,i=[],a=0;return await e(async e=>a<n?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,i.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),i}async function tt(e,t){let{limit:n,direction:r}=t,i=[];return await e(async e=>(i.push(e),i.length>=n?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),r),i}const{match:nt}=(0,ue.createMatcher)({});async function Q(e){let{collection:t,initial:n,validator:r,store:i,bus:o,lockManager:s}=e,[u,d]=l(n),{value:f,issues:p}=r?await r[`~standard`].validate(u):{value:n,issues:void 0};if(p)throw new c(`INVALID_DATA`,`Invalid data for ${t}`,e.schema,p,p);let m={current:Object.assign(f,d),deleted:!1};m.current.$id===void 0&&(m.current=Object.assign(m.current,{$id:a(),$created:new Date().toJSON(),$version:1}));let h=e=>{let[t]=l(e);return t},g={save:async e=>{await s.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let a=await i.getById(n);if(a&&a.$version!==r)throw new c(`CONFLICT`,`Version mismatch on ${t}/${n}`);return m.current.$version=(r||0)+1,m.current.$updated=new Date().toJSON(),e?await e.addOp(i,`put`,m.current):await i.put(m.current),o.emit({name:`document:write`,payload:{type:`document:write`,data:m.current,timestamp:Date.now()}}),!0}finally{s.unlock()}},update:async(n,i)=>{let[a,s]=l(Object.assign({},m.current,n)),{value:u,issues:d}=r?await r[`~standard`].validate(a):{value:a,issues:void 0};if(d)throw new c(`INVALID_DATA`,`Invalid update for ${t}`,e.schema,d,d);m.current=Object.assign(u,s);let f=await g.save(i);return f&&o.emit({name:`document:update`,payload:{type:`document:update`,data:m.current,timestamp:Date.now()}}),f},delete:async e=>{await s.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let a=await i.getById(n);if(a&&a.$version!==r)throw new c(`CONFLICT`,`Version mismatch on delete ${t}/${n}`);return e?await e.addOp(i,`delete`,n):await i.delete(n),o.emit({name:`document:delete`,payload:{type:`document:delete`,data:m.current,timestamp:Date.now()}}),m.deleted=!0,!0}finally{s.unlock()}},read:async()=>{let e=m.current.$id,t=await i.getById(e);if(!t)throw Error(`Document not found.`);return m.current={...t},o.emit({name:`document:read`,payload:{type:`document:read`,data:m.current,timestamp:Date.now()}}),m.current},state:()=>h(m.current),$metadata:()=>l(m.current)[1],subscribe:o.subscribe};return new Proxy({},{get(e,t){if([`update`,`delete`,`subscribe`,`read`,`state`,`save`,`$metadata`].includes(t)){let e=g[t];return(...t)=>{if(m.deleted)throw new c(`INVALID_OPERATION`,`Document has been deleted`);return e(...t)}}if(m.deleted)throw new c(`INVALID_OPERATION`,`Document has been deleted`);return Reflect.get(m.current,t)}})}function rt(e,t){return`field`in e&&`operator`in e&&e.operator===`eq`&&`value`in e?e.field:null}async function it({collection:e,validator:n,bus:r,store:i,pipeline:o,validate:s,schema:u}){let d=new t,f={collection:e,validator:s?n:void 0,schema:u,store:i,bus:r,pipeline:o,lockManager:d,valid:!0},p={async validate(e){let t=n[`~standard`].validate(e);return t instanceof Promise?await t:t},create:async(t,o)=>{let[d,p]=l(t),{value:m,issues:h}=s?await n[`~standard`].validate(d):{value:d,issues:void 0};if(h)throw new c(`INVALID_DATA`,`Invalid data for collection '${e}'`,u,h,h);let g=Object.assign(m,p,{$id:a(),$created:new Date().toJSON(),$version:1});o?await o.addOp(i,`add`,g):await i.add(g),r.emit({name:`document:create`,payload:{type:`document:create`,data:g,timestamp:Date.now()}});let _=await Q({...f,initial:g});return r.emit({name:`collection:read`,payload:{type:`collection:read`,model:e,timestamp:Date.now()}}),_},find:async t=>{let n,a=rt(t,i);if(a)try{let e=t.value;n=(await i.findByIndex(a,e))[0]}catch{n=void 0}if(n===void 0&&(n=await i.cursor(async e=>e&&nt(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!n)return null;let o=await Q({...f,initial:n});return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`find`,model:e,timestamp:Date.now()}}),o},filter:async t=>{let n=[],a=rt(t,i);if(a)try{let e=t.value;n=await i.findByIndex(a,e)}catch{n=[]}n.length===0&&await i.cursor(async e=>(e&&nt(e,t)&&n.push(e),{value:null,done:!1}));let o=await Promise.all(n.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`filter`,model:e,timestamp:Date.now()}}),o},update:async(t,a,o)=>{await d.lock();try{let l=await p.filter(t);if(l.length===0)return 0;let d=[];for(let t of l){let r=t.state(),i=Object.assign({},r,a);if(s){let t=await n[`~standard`].validate(i);if(t.issues)throw new c(`INVALID_DATA`,`Bulk update failed validation for ${e}`,u,t.issues,t.issues)}let o=t.$metadata(),l=Object.assign(i,t.$metadata(),{$updated:new Date().toJSON(),$version:(o.$version||0)+1});d.push(l)}return o?await o.addOp(i,`put`,d):await i.batch(d.map(e=>({type:`put`,data:e}))),d.forEach(e=>{r.emit({name:`document:update`,payload:{type:`document:update`,data:e,timestamp:Date.now()}})}),d.length}finally{d.unlock()}},delete:async(e,t)=>{await d.lock();try{let n=await p.filter(e),a=n.map(e=>e.$id);return a.length===0?0:(t?await t.addOp(i,`delete`,a):await i.delete(a),n.forEach(e=>{r.emit({name:`document:delete`,payload:{type:`document:delete`,data:e.state(),timestamp:Date.now()}})}),a.length)}finally{d.unlock()}},list:async t=>{let n={total:await i.count(),offset:t.type===`offset`?t.offset:0,limit:t.limit,cursor:t.type===`cursor`?t.cursor:void 0,count:0};return n.total===0?{async next(){return{value:[],done:!0}}}:{async next(){let a=t.type===`offset`?await et(i.cursor.bind(i),{...t,offset:n.offset}):await tt(i.cursor.bind(i),{...t,cursor:n.cursor});n.offset+=n.limit,n.count+=a.length;let o=await Promise.all(a.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`list`,model:e,timestamp:Date.now()}}),{value:o,done:n.count>=n.total}}}}},m={...o.wrap(p,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>f.valid=!1};return new Proxy(m,{get(t,n,r){let i=Reflect.get(t,n,r);return typeof i==`function`?(...r)=>{if(!f.valid&&n!==`invalidate`)throw new c(`INVALID_OPERATION`,`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}function at(e){return typeof e._getIDBConnection==`function`}var ot=class{id;staged=[];done=!1;constructor(){this.id=a()}async addOp(e,t,n){if(this.done)throw new c(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);this.staged.push({store:e,op:{type:t,data:n}})}async commit(){if(this.done)throw new c(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);if(this.done=!0,this.staged.length===0)return;let e=new Map,t=new Map;for(let{store:n,op:r}of this.staged)at(n)?(e.has(n)||e.set(n,[]),e.get(n).push(r)):(t.has(n)||t.set(n,[]),t.get(n).push(r));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){let t=Array.from(e.keys()).map(e=>e.name()),n=await e.keys().next().value._getIDBConnection();await new Promise((r,i)=>{let a=n.transaction(t,`readwrite`);a.oncomplete=()=>r(),a.onerror=()=>i(a.error??Error(`IDB transaction error`)),a.onabort=()=>i(a.error??Error(`IDB transaction aborted`)),(async()=>{try{for(let[t,n]of e)await t.executeInTransaction(n,a)}catch(e){try{a.abort()}catch{}i(e)}})()})}async commitMemory(e){let t=[];try{for(let[n,r]of e){let e=n._snapshotMemory();t.push({store:n,snapshot:e}),await n.executeInTransaction(r,null)}}catch(e){for(let{store:e,snapshot:n}of t)try{e._rollbackMemory(n)}catch{}throw e}}completed(){return this.done}};function st(e,t,n){let r,i=!1;return new ReadableStream({async pull(a){if(i){a.close();return}let o=0,s=r===void 0?void 0:{lower:r,lowerOpen:!0};try{await t.cursor(async(e,t)=>(a.enqueue(e),r=t,o++,o>=n?{done:!0,value:e}:{done:!1,value:e}),`forward`,s),o<n&&(i=!0)}catch(t){a.error($(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}async function ct(e,t,n,r){let i=t.getReader(),a=[];try{for(;;){let{value:e,done:t}=await i.read();if(t)break;if(!e)continue;let{$version:o}=e;e.$version=(o||0)+1,e.$updated=new Date().toJSON(),a.push(e),a.length>=r&&(await n.batch([{type:`put`,data:a}]),a=[])}a.length>0&&await n.batch([{type:`put`,data:a}])}catch(t){throw $(t,e)}finally{i.releaseLock()}}function $(e,t){return e instanceof c?e:e instanceof Error?new c(`INTERNAL_ERROR`,`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new c(`INTERNAL_ERROR`,`An unexpected error occurred during migration of collection '${t}'`)}async function lt(e,t){let n=i(),r=new Map,a=new Ze;a.use(Qe()),e.enableTelemetry&&a.use($e);let o=new Map,s=t({...e,collection:`schemas`,keyPath:`name`},[]);await s.open();async function l(n,r=[]){let i=o.get(n);return i||(i=t({...e,collection:n,keyPath:`$id`},r),o.set(n,i)),await i.open(),i}async function u(t){if(r.has(t))return r.get(t);let i=await s.getById(t);if(!i)throw new c(`SCHEMA_NOT_FOUND`,`Collection '${t}' does not exist`);let o=await l(t,i.indexes??[]),u=await it({collection:t,bus:n,validator:ye(i,e.predicates||{}),validate:!!e.validate,store:o,pipeline:a,schema:i});return n.emit({name:`collection:read`,payload:{type:`collection:read`,schema:{name:t},timestamp:Date.now()}}),r.set(t,u),r.get(t)}async function d(e){return await s.put(e),n.emit({name:`collection:update`,payload:{type:`collection:update`,schema:e,timestamp:Date.now()}}),!0}let f={collection:u,createCollection:async e=>{if(await s.getById(e.name))throw new c(`SCHEMA_ALREADY_EXISTS`,`Collection '${e.name}' already exists`);if(!Le(e))throw new c(`INVALID_SCHEMA_DEFINITION`,`Invalid schema definition`);await s.put(e);let t=u(e.name);return n.emit({name:`collection:create`,payload:{type:`collection:create`,schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{let t=await s.getById(e);if(!t)throw new c(`SCHEMA_NOT_FOUND`,`Collection '${e}' does not exist`);return await(await l(e,t.indexes??[])).clear(),o.delete(e),await s.delete(e),r.delete(e),n.emit({name:`collection:delete`,payload:{type:`collection:delete`,schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,n=100)=>{let i=r.get(e);i&&(i.invalidate(),r.delete(e));let a=await s.getById(e);if(!a)throw new c(`SCHEMA_NOT_FOUND`,`Schema for '${e}' not found`);let o=await l(e,a.indexes??[]),f=new Xe(a);await f.add(t);let p=(await f.dryRun(new ReadableStream({start(e){e.close()}}),`forward`)).newSchema,m=new Set((a.indexes??[]).map(e=>e.name)),h=p.indexes??[],g=new Set(h.map(e=>e.name)),_=h.filter(e=>!m.has(e.name)),v=(a.indexes??[]).filter(e=>!g.has(e.name));await d(p);try{let t=st(e,o,n);await ct(e,await f.migrate(t),o,n)}catch(t){throw $(t,e)}for(let e of _)await o.createIndex(e);for(let e of v)await o.dropIndex(e.name);return await u(e)}},p=a.wrap(f,{eventBus:n}),m={...p,transaction:async e=>{let t=new ot;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:n.subscribe,close:()=>{o.clear(),n.clear()},clear:async()=>{await s.clear(),await Promise.all(o.values().map(e=>e.clear())),o.clear()},ensureCollection:async e=>{try{await p.createCollection(e)}catch(e){if(e instanceof c&&e.type===`SCHEMA_ALREADY_EXISTS`)return;throw e}},setupCollections:async e=>{for(let t of e)await m.ensureCollection(t)}};return m}export{h as ConnectionManager,o as DEFAULT_KEYPATH,lt as DatabaseConnection,c as DatabaseError,s as DatabaseErrorType,_ as IndexedDBStore,Q as createDocument,m as createEphemeralStore,y as createIndexedDbStore,it as openCollection};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asaidimu/utils-database",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.11",
|
|
4
4
|
"description": "A collection of database utilities.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"module": "index.mjs",
|
|
@@ -38,7 +38,8 @@
|
|
|
38
38
|
"@asaidimu/anansi": "4.0.2",
|
|
39
39
|
"@asaidimu/query": "^1.1.2",
|
|
40
40
|
"@asaidimu/utils-events": "^1.0.0",
|
|
41
|
-
"uuid": "^14.0.0"
|
|
41
|
+
"uuid": "^14.0.0",
|
|
42
|
+
"@asaidimu/utils-sync": "^1.0.0"
|
|
42
43
|
},
|
|
43
44
|
"publishConfig": {
|
|
44
45
|
"registry": "https://registry.npmjs.org/",
|
|
@@ -64,5 +65,6 @@
|
|
|
64
65
|
}
|
|
65
66
|
]
|
|
66
67
|
]
|
|
67
|
-
}
|
|
68
|
+
},
|
|
69
|
+
"peerDependencies": {}
|
|
68
70
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));export{s as n,l as r,o as t};
|