@asaidimu/utils-database 2.0.0 → 3.0.0
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.mts +92 -13
- package/index.d.ts +92 -13
- package/index.js +1 -1
- package/index.mjs +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t,r=require("buffer"),s=require("uuid"),n=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,d=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},l=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of o(t))h.call(e,n)||n===r||i(e,n,{get:()=>t[n],enumerable:!(s=a(t,n))||s.enumerable});return e},u=(e,t,r)=>(r=null!=e?n(c(e)):{},l(e&&e.__esModule?r:i(r,"default",{value:e,enumerable:!0}),e)),p=e=>l(i({},"__esModule",{value:!0}),e),m=d({"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)}})(),l=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),l(e),()=>{s.delete(r),0===s.size?(t.delete(e),a.delete(e)):l(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)}}}}}),f=d({"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:()=>k,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]]),l=e[a]||d.get(a);if(l)return l(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 l=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},u=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(u(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 l("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new l(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new l("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new l("Source data must be an array","INVALID_SOURCE_DATA");let n,i=e[r.relation];return r.query?.filters&&u(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&&u(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 l?e:new l(`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 v(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 b(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=v(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:b}}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){for(let[t,i]of Object.entries(n))if(Object.prototype.hasOwnProperty.call(e,t)){let n=r(e[t],i);s[t]=n}}else{let t=n;s[t]=e[t]}}(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*E(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 k(){return{paginate:E}}}}),y=d({"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))}}}}),w=d({"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")}}}),g=d({"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}}}}),v=d({"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}}}}),b=d({"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}}}),_=d({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=v(),{EEXIST:s,ENOENT:n,ENOTDIR:i,ENOTEMPTY:a,EISDIR:o}=b();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)}}}}),$={};function E(){return t||(t=new e),t}function k(e,t=E()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function I(e,t,r=E()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function S(e,t,r=E()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function A(e,t=E()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function x(e=E()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function O(e=E()){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 N(e=E()){return e._close()}((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})($,{Store:()=>e,clear:()=>x,close:()=>N,del:()=>A,get:()=>k,keys:()=>O,set:()=>I,update:()=>S});var T,j,C=(T={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){e=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 T&&(j=(0,T[o(T)[0]])(T=0)),j}),R=d({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(C(),p($));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)}}}}),M=d({"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")}}}}),D=d({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(C(),p($)),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}}}}),P=d({"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))}}}}),q=d({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=w(),n=g(),i=_(),{ENOENT:a,ENOTEMPTY:o,ETIMEDOUT:c}=b(),h=R(),d=M(),l=D(),u=P(),p=v();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 u(e):new l(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()}}}}),F=d({"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}}}}),L=d({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=q(),s=F(),n=v();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()}}}}),B=d({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=L();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)}}}}),U=(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))(U||{}),V=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}},z=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function H(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 J(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new V("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function K(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 W(e,t){if(!t.partial)return!0;const{field:r,value:s}=t.partial;return e[r]===s}var Y=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 V("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 V("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 V("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);J(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 V("CONFLICT",`Duplicate key ${e}`)}else e=this.getKey(n);J(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 V("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 V("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(!W(t,e.definition))return;const r=K(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=K(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(!W(e,t.definition))continue;const n=K(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 V("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))}};var G=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},X=class extends G{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},Q=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 X("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}},Z=class{mutex=new Q({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{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()}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this.isReady()}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}currentExecution(){return this.promise}done(){return this._done}_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 X(r))),t)}))])}},ee=class{_delay;_leading;_timer;_pendingFn;_pendingResolvers=[];_leadingFired=!1;constructor(e){this._delay=e?.delay??300,this._leading=e?.leading??!1}do(e){return new Promise((t=>{this._enqueue(e,t)}))}fire(e){this._enqueue(e,void 0)}_enqueue(e,t){if(this._pendingFn=e,t&&this._pendingResolvers.push(t),this._leading&&!this._leadingFired)return this._leadingFired=!0,this._fire(),clearTimeout(this._timer),void(this._timer=setTimeout((()=>{this._leadingFired=!1,void 0!==this._pendingFn&&this._fire()}),this._delay));clearTimeout(this._timer),this._timer=setTimeout((()=>{this._leadingFired=!1,this._fire()}),this._delay)}cancel(){clearTimeout(this._timer),this._timer=void 0,this._pendingFn=void 0,this._leadingFired=!1;const e=this._pendingResolvers.splice(0);for(const t of e)t({status:"cancelled"})}async flush(){return this._pendingFn?(clearTimeout(this._timer),this._timer=void 0,this._leadingFired=!1,this._fire()):null}pending(){return void 0!==this._pendingFn}async _fire(){const e=this._pendingFn,t=this._pendingResolvers.splice(0);let r;this._pendingFn=void 0;try{r={status:"ok",value:await e()}}catch(e){r={status:"error",error:e}}for(const e of t)e(r);return r}},te=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new Z({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 V("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 V("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 re(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 se=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(re(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){J(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){J(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 V("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){J(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(re(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 V)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new V("INTERNAL_ERROR","Storage quota exceeded"):new V("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)}))}},ne=new Map;u(m()),u(m()),u(f()),u(B()),u(B());var ie=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ae(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(oe).join("/"):"/"+e.split(".").map(oe).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(ce)}function oe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ce(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var he=new Map;function de(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new ie(`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 ie(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new ie(`Property ${e} not found`);r=r[e]}}return r}function le(e,t){let r=he.get(t)||ae(t);if(he.set(t,r),0===r.length)return e;let s=de(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 ie(`Invalid array index: ${n}`);return s[e]}return s[n]}function ue(e,t,r){let s=he.get(t)||ae(t);he.set(t,s);let n=de(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 pe(e,t,r){let s=he.get(t)||ae(t);if(he.set(t,s),0===s.length)return r;let n=s.slice(0,-1),i=s[s.length-1],a=de(e,n);if(Array.isArray(a))if("-"===i)a.push(r);else{let e=parseInt(i);if(e<0||e>a.length)throw new ie(`Invalid array index: ${i}`);a.splice(e,0,r)}else a[i]=r;return e}function me(e,t){let r=he.get(t)||ae(t);if(he.set(t,r),0===r.length)return;let s=de(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 fe(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(ye(s)){let e=we(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 ye(e){return e&&"operator"in e&&"rules"in e}function we(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(ye(s)){let e=we(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var ge=new Map;function ve(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function be(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(ge.has(n)){let t=ge.get(n);return t||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ve(e.parameters)}`,path:c}),t}let i=s({data:t,field:e.field,arguments:e.parameters});return ge.set(n,i),i||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ve(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 ${ve(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 l=new Set(Object.values(d).map((e=>e.name)));Object.entries(d).forEach((([t,d])=>{let l=[...a,d.name],u=Object.hasOwnProperty.call(e,d.name)?e[d.name]:void 0!==d.default?d.default:void 0;d.required&&null==u&&h.push({message:`Field '${d.name}' is required`,path:l});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:l});else{c.add(p.id);let t=u&&"object"==typeof u&&!Array.isArray(u)?u:{};h.push(...i(t,e,r,l,o,c)),p.constraints?.forEach(((e,s)=>{if("rules"in e)h.push(...n(e,t,r,[...l,`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 ${ve(e.parameters)}`,path:[...l,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...l,`constraints[${s}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:l})}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:[...l,a.toString()]});else{c.add(s.id);let a=u&&"object"==typeof u&&!Array.isArray(u)?u:{},d=i(a,h,r,l,o,new Set(c));0===d.length&&void 0!==u?(e=!0,s.constraints?.forEach(((s,i)=>{if("rules"in s){let o=n(s,a,r,[...l,`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:[...l,`constraints[${i}]`]}))}}))):void 0===u&&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:[...l,a.toString()]})})),e||void 0===u?void 0===u&&h.push(...t):(h.push({message:"Value does not match any union schema",path:l}),h.push(...t))}void 0!==u&&(h.push(...s(u,d.type,l,{values:d.values})),("array"===d.type||"set"===d.type)&&Array.isArray(u)&&(d.constraints?.forEach(((e,t)=>{let s=r[e.predicate];s&&!s({data:{[d.name]:u},field:d.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${d.name}'`,path:[...l,`constraints[${t}]`]})})),d.itemsType&&u.forEach(((e,t)=>h.push(...s(e,d.itemsType,[...l,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?u.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...l,t.toString()]}):(c.add(p.id),h.push(...i(e,o[p.id],r,[...l,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:l}))),d.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...n(t,e,r,[...l,`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 ${ve(t.parameters)}`,path:[...l,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...l,`constraints[${s}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!l.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 ${ve(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 _e=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},$e=e=>({value:e}),Ee=e=>({issues:e}),ke=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],Ie=(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]}]},Se=(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]}]},Ae=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],xe=(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(...ke(e.name,`${r}.name`)),s.push(...ke(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(...ke(e.description,`${r}.description`,!1)),s.push(...ke(e.errorMessage,`${r}.errorMessage`,!1)),s},Oe=(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(...ke(e.name,`${r}.name`)),s.push(...Se(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,n)=>{"rules"in e?s.push(...Oe(e,t,`${r}.rules[${n}]`)):s.push(...xe(e,0,`${r}.rules[${n}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Ne=(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(...Oe(e,t,`${r}[${n}]`)):s.push(...xe(e,0,`${r}[${n}]`))})),s},Te=(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(...Se(e.operator,`${t}.operator`)),r.push(...ke(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...Te(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},je=(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(...ke(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(...Ae(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...Te(e.partial,`${t}.partial`)),r.push(...ke(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},Ce=(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(...je(e,`${t}[${s}]`)))),r},Re=(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(...ke(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(...Ne(e.constraints,"dynamic",`${n}.constraints`)),e.indexes&&i.push(...Ce(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(...ke(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(...Ne(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&i.push(...Ce(e.indexes,`${t}.indexes`))),i)},Me=(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[]},De=(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`]}]:[],Pe=(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(...ke(e.name,`${t}.name`)),s.push(...Ie(e.type,`${t}.type`)),s.push(...Ae(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Ne(e.constraints,e.type,`${t}.constraints`)),s.push(...Me(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(...Re(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Ie(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(...ke(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(...Ne(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...Ce(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Ae(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(...ke(e.reference.schema,`${t}.reference.schema`)),s.push(...ke(e.reference.field,`${t}.reference.field`))}return s.push(...ke(e.description,`${t}.description`,!1)),s.push(...Ae(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...De(e.hint,`${t}.hint`)),s},qe=(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(...ke(e.name,`${t}.name`)),s.push(...Ie(e.type,`${t}.type`)),s.push(...Me(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Re(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Ie(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Ne(e.constraints,e.type,`${t}.constraints`)),s.push(...ke(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(...ke(e.name,`${t}.name`)),s.push(...Ae(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(...Pe(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(...ke(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(...Pe(n,`${t}.fields.${e}`,r))}))),s.push(...ke(e.description,`${t}.description`,!1)),e.indexes&&s.push(...Ce(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Ne(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},Fe=(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(...ke(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(...ke(e.id,`${t}.id`)),r.push(...Pe(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(...ke(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(...ke(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(...ke(n.id,`${t}.nestedSchemaChanges.id`,!1)),n.constraints&&r.push(...Ne(n.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),n.indexes&&r.push(...Ce(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(...je(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(...ke(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(...ke(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(...Oe(e.constraint,"dynamic",`${t}.constraint`)):r.push(...xe(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(...ke(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(...ke(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(...ke(e.id,`${t}.id`)),r.push(...qe(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(...ke(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(...ke(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},Le=(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(...ke(e.id,`${t}.id`)),r.push(...ke(e.schemaVersion,`${t}.schemaVersion`)),r.push(...ke(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(...Fe(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(...Fe(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(...ke(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(...ke(e.createdAt,`${t}.createdAt`)),r.push(...ke(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},Be={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return Ee([{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(...ke(t.name,"name")),r.push(...ke(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(...Pe(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(...qe(s,`nestedSchemas.${t}`,e))))}return r.push(...ke(t.description,"description",!1)),t.indexes&&r.push(...Ce(t.indexes,"indexes")),t.constraints&&r.push(...Ne(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(...Le(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(...De(t.hint,"hint")),r.length>0?Ee(r):$e(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return Ee([{message:"Migration must be an object",path:[]}]);let t=e,r=Le(t,"");return r.length>0?Ee(r):$e(t)},types:{input:{},output:{}}},Ve={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return Ee([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...Fe(e,`[${t}]`)))),r.length>0?Ee(r):$e(t)},types:{input:[],output:[]}};function ze(e){try{return!Be.validate(e).issues}catch(e){throw new _e("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function He(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 Je(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=He(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 Ke(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 We,Ye=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},Ge=((We=Ge||{}).INVALID_SCHEMA="INVALID_SCHEMA",We.INVALID_MIGRATION="INVALID_MIGRATION",We.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",We.TIMEOUT="TIMEOUT",We.MEMORY_LIMIT="MEMORY_LIMIT",We.CONCURRENT_OPERATION="CONCURRENT_OPERATION",We.TRANSFORM_ERROR="TRANSFORM_ERROR",We.VERSION_NOT_FOUND="VERSION_NOT_FOUND",We.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",We.STREAM_ERROR="STREAM_ERROR",We.ROLLBACK_ERROR="ROLLBACK_ERROR",We.MISSING_TRANSFORM="MISSING_TRANSFORM",We),Xe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!ze(e))throw new Ye("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new _e("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new Ye("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Ke(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>Ke(e.version,t.version))))}catch(e){throw e instanceof Ye?e:new Ye("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 Ye("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new Ye("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new Ye("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Ve.validate(e).issues}catch(e){throw new _e("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new Ye("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 Ye("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 Ye?e:new Ye("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||Ke(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=Je(e.version,t);return t.map((t=>{try{return fe(t,e)}catch(e){throw new Ye("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=pe(r,e.path,e.value);break;case"remove":r=me(r,e.path);break;case"removeValue":r=ue(r,e.path,e.value);break;case"replace":r=pe(me(r,e.path),e.path,e.value);break;case"copy":{let t=le(r,e.from);r=pe(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=le(r,e.from);r=pe(r,e.path,t),r=me(r,e.from);break}case"test":{let t=le(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ie("Test operation failed");break}default:throw new ie(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ie&&(t.operation=e),t}return r}(e,t)}catch(e){throw new Ye("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof Ye?e:new Ye("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 Ye("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 Ye("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 Ye("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 Ye("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 Ye(`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 Ye(`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 Ye(`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 Ye(`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 Ye(`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 Ye?e:new Ye("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=r.Buffer);var Qe=u(f()),Ze=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}})}},et=async(e,t)=>{const r=Date.now();try{const s=await t();return tt(e,r,s,null),s}catch(t){throw tt(e,r,void 0,t),t}};function tt(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:rt}=(0,Qe.createMatcher)({});async function st(e){const{collection:t,initial:r,validator:n,store:i,bus:a,lockManager:o}=e,[c,h]=H(r),{value:d,issues:l}=n?await n["~standard"].validate(c):{value:r,issues:void 0};if(l)throw console.warn({issues:l}),new V("INVALID_DATA",`Invalid data for ${t}`);const u={current:Object.assign(d,h),deleted:!1};void 0===u.current.$id&&(u.current=Object.assign(u.current,{$id:s.v7(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=u.current;if(!r)throw new Error("Document ID missing.");const n=await i.getById(r);if(n&&n.$version!==s)throw new V("CONFLICT",`Version mismatch on ${t}/${r}`);return u.current.$version=(s||0)+1,u.current.$updated=(new Date).toJSON(),e?await e.addOp(i,"put",u.current):await i.put(u.current),a.emit({name:"document:write",payload:{type:"document:write",data:u.current,timestamp:Date.now()}}),!0}finally{r()}},update:async(e,r)=>{const[s,i]=H(Object.assign({},u.current,e)),{value:o,issues:c}=n?await n["~standard"].validate(s):{value:s,issues:void 0};if(c)throw new V("INVALID_DATA",`Invalid update for ${t}`);u.current=Object.assign(o,i);const h=await p.save(r);return h&&a.emit({name:"document:update",payload:{type:"document:update",data:u.current,timestamp:Date.now()}}),h},delete:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=u.current;if(!r)throw new Error("Document ID missing.");const n=await i.getById(r);if(n&&n.$version!==s)throw new V("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:u.current,timestamp:Date.now()}}),u.deleted=!0,!0}finally{r()}},read:async()=>{const e=u.current.$id,t=await i.getById(e);if(!t)throw new Error("Document not found.");return u.current={...t},a.emit({name:"document:read",payload:{type:"document:read",data:u.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=H(e);return t})(u.current),subscribe:a.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save"].includes(t)){const e=p[t];return(...t)=>{if(u.deleted)throw new V("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(u.deleted)throw new V("INVALID_OPERATION","Document has been deleted");return Reflect.get(u.current,t)}})}function nt(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}async function it({collection:e,validator:t,bus:r,store:n,pipeline:i,validate:a}){const o=new z,c={collection:e,validator:a?t:void 0,store:n,bus:r,pipeline:i,lockManager:o,valid:!0},h={async validate(e){const r=t["~standard"].validate(e);return r instanceof Promise?await r:r},create:async(i,o)=>{const[h,d]=H(i),{value:l,issues:u}=a?await t["~standard"].validate(h):{value:h,issues:void 0};if(u)throw new V("INVALID_DATA",`Invalid data for collection '${e}'`);const p=Object.assign(l,d,{$id:s.v7(),$created:(new Date).toJSON(),$version:1});o?await o.addOp(n,"add",p):await n.add(p),r.emit({name:"document:create",payload:{type:"document:create",data:p,timestamp:Date.now()}});const m=await st({...c,initial:p});return r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),m},find:async t=>{let s;const i=nt(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&&rt(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!s)return null;const a=await st({...c,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=nt(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&&rt(e,t)&&s.push(e),{value:null,done:!1})));const a=await Promise.all(s.map((e=>st({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),a},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,a=!1;for(;!(a||(await e((async e=>i<r?(i++,{value:e,done:!1,offset:1}):(n.push(e),i++,i>=r+s?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),n.length>=s)););return n}(n.cursor.bind(n),{...t,offset:s.offset}):await async function(e,t){const{limit:r,direction:s}=t,n=[];let i=!1;for(;!i;)await e((async e=>(n.push(e),n.length>=r?(i=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),s);return n}(n.cursor.bind(n),{...t});s.offset+=s.limit,s.count+=i.length;const a=await Promise.all(i.map((e=>st({...c,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}}}}},d={...i.wrap(h,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>c.valid=!1};return new Proxy(d,{get(t,r,s){const n=Reflect.get(t,r,s);return"function"==typeof n?(...s)=>{if(!c.valid&&"invalidate"!==r)throw new V("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return n.apply(t,s)}:n}})}function at(e){return"function"==typeof e._getIDBConnection}var ot=class{id;staged=[];done=!1;constructor(){this.id=s.v7()}async addOp(e,t,r){if(this.done)throw new V("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 V("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)at(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 ct(e,t){return e instanceof V?e:e instanceof Error?new V("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new V("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}exports.ConnectionManager=te,exports.DEFAULT_KEYPATH="$id",exports.DatabaseConnection=async function(e,t){const r=function(){const e={},{deferred:t,batchSize:r,batchDelay:s,errorHandler:n,broadcast:i,channel:a}={deferred:null!=e.batch?.size,batchSize:e.batch?.size,batchDelay:e.batch?.delay||16,errorHandler:e.errorHandler||(e=>console.error("EventBus Error:",e)),broadcast:null!=e.broadcast?.channel&&e.broadcast.channel.length>0,channel:null!=e.broadcast?.channel&&e.broadcast.channel.length>0?e.broadcast?.channel:"event-bus-channel"},o=new Map;let c=[],h=0,d=0;const l=new Map,u=()=>{if(!i)return null;if("undefined"==typeof BroadcastChannel)return console.warn("EventBus: BroadcastChannel is not supported in this environment. Cross-tab notifications are disabled."),null;const e=new BroadcastChannel(a);return e.onmessage=e=>{const{name:t,payload:r}=e.data;f(t,r)},e};let p=u();const m=(e,t)=>{h++,d+=t,l.set(e,(l.get(e)??0)+1)},f=(e,t)=>{const r=o.get(e);if(r&&0!==r.size)for(const s of Array.from(r))try{s(t)}catch(r){const s=r instanceof Error?r:Object.assign(new Error(String(r)),{cause:r}),i=Object.assign(s,{eventName:e,payload:t});n(i)}},y=()=>{const e=c;c=[];for(const{name:t,payload:r}of e){const e=performance.now();f(t,r),m(t,performance.now()-e)}},w=new ee({delay:s});return{subscribe:(e,t)=>{o.has(e)||o.set(e,new Set);const r=o.get(e);return r.add(t),()=>{r.delete(t),0===r.size&&o.delete(e)}},once:(e,t)=>{let r;const s=e=>{r(),t(e)};return r=(()=>{o.has(e)||o.set(e,new Set);const t=o.get(e);return t.add(s),()=>{t.delete(s),0===t.size&&o.delete(e)}})(),r},emit:({name:e,payload:s})=>{if(t)return c.push({name:e,payload:s}),c.length>=r?(w.cancel(),void y()):(w.fire((()=>y())),void p?.postMessage({name:e,payload:s}));const n=performance.now();f(e,s),m(e,performance.now()-n),p?.postMessage({name:e,payload:s})},metrics:()=>({totalEvents:h,activeSubscriptions:Array.from(o.values()).reduce(((e,t)=>e+t.size),0),eventCounts:l,averageEmitDuration:h>0?d/h:0}),clear:()=>{o.clear(),c=[],w.cancel(),h=0,d=0,l.clear(),p?.close(),p=u()}}}(),s=new Map,n=new Ze;n.use(((e=3,t=100)=>async(r,s)=>{let n=0;for(;n<e;)try{return await s()}catch(r){if(!(r instanceof V&&"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&&n.use(et);const i=new Map,a=t({...e,collection:"schemas",keyPath:"name"},[]);async function o(r,s=[]){let n=i.get(r);return n||(n=t({...e,collection:r,keyPath:"$id"},s),i.set(r,n)),await n.open(),n}async function c(t){if(s.has(t))return s.get(t);const i=await a.getById(t);if(!i)throw new V("SCHEMA_NOT_FOUND",`Collection '${t}' does not exist`);const c=await o(t,i.indexes??[]),h=be(i,e.predicates||{}),d=await it({collection:t,bus:r,validator:h,validate:Boolean(e.validate),store:c,pipeline:n});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),s.set(t,d),s.get(t)}async function h(e){return await a.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await a.open();const d={collection:c,createCollection:async e=>{if(await a.getById(e.name))throw new V("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!ze(e))throw new V("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await a.put(e);const t=c(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await a.getById(e);if(!t)throw new V("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const n=await o(e,t.indexes??[]);return await n.clear(),i.delete(e),await a.delete(e),s.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:h,migrateCollection:async(e,t,r=100)=>{const n=s.get(e);n&&(n.invalidate(),s.delete(e));const i=await a.getById(e);if(!i)throw new V("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const d=await o(e,i.indexes??[]),l=new Xe(i);await l.add(t);const u=(await l.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((i.indexes??[]).map((e=>e.name))),m=u.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 h(u);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(ct(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,d,r),s=await l.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 ct(t,e)}finally{n.releaseLock()}}(e,s,d,r)}catch(t){throw ct(t,e)}for(const e of y)await d.createIndex(e);for(const e of w)await d.dropIndex(e.name);return await c(e)}},l=n.wrap(d,{eventBus:r}),u={...l,transaction:async e=>{const t=new ot;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:r.subscribe,close:()=>{i.clear(),r.clear()},clear:async()=>{await a.clear(),await Promise.all(i.values().map((e=>e.clear())))},ensureCollection:async e=>{try{await l.createCollection(e)}catch(e){if(e instanceof V&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await u.ensureCollection(t)}};return u},exports.DatabaseError=V,exports.DatabaseErrorType=U,exports.IndexedDBStore=se,exports.createDocument=st,exports.createEphemeralStore=function(e){return new Y(e.database,e.keyPath)},exports.createIndexedDbStore=e=>{let t=ne.get(e.database);t||(t=new Z({retry:!0,throws:!0}),ne.set(e.database,t));try{const{value:r,error:s}=t.doSync((()=>new te(e)));if(s)throw new V("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,s);return new se(r,e.collection,e.keyPath)}catch(e){if(e instanceof V)throw e;throw new V("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}},exports.openCollection=it;
|
|
1
|
+
"use strict";var e,t,r=require("buffer"),s=require("uuid"),n=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,d=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},u=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of o(t))h.call(e,n)||n===r||i(e,n,{get:()=>t[n],enumerable:!(s=a(t,n))||s.enumerable});return e},l=(e,t,r)=>(r=null!=e?n(c(e)):{},u(e&&e.__esModule?r:i(r,"default",{value:e,enumerable:!0}),e)),p=e=>u(i({},"__esModule",{value:!0}),e),m=d({"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)}}}}}),f=d({"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:()=>k,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 v(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 b(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=v(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:b}}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){for(let[t,i]of Object.entries(n))if(Object.prototype.hasOwnProperty.call(e,t)){let n=r(e[t],i);s[t]=n}}else{let t=n;s[t]=e[t]}}(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*E(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 k(){return{paginate:E}}}}),y=d({"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))}}}}),w=d({"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")}}}),g=d({"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}}}}),v=d({"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}}}}),b=d({"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}}}),_=d({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=v(),{EEXIST:s,ENOENT:n,ENOTDIR:i,ENOTEMPTY:a,EISDIR:o}=b();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)}}}}),$={};function E(){return t||(t=new e),t}function k(e,t=E()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function I(e,t,r=E()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function A(e,t,r=E()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function S(e,t=E()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function O(e=E()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function x(e=E()){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 N(e=E()){return e._close()}((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})($,{Store:()=>e,clear:()=>O,close:()=>N,del:()=>S,get:()=>k,keys:()=>x,set:()=>I,update:()=>A});var T,j,C=(T={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){e=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 T&&(j=(0,T[o(T)[0]])(T=0)),j}),R=d({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(C(),p($));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)}}}}),M=d({"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")}}}}),D=d({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(C(),p($)),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}}}}),P=d({"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))}}}}),F=d({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=w(),n=g(),i=_(),{ENOENT:a,ENOTEMPTY:o,ETIMEDOUT:c}=b(),h=R(),d=M(),u=D(),l=P(),p=v();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()}}}}),q=d({"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}}}}),L=d({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=F(),s=q(),n=v();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()}}}}),B=d({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=L();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)}}}}),U=(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))(U||{}),V=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 z(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 H(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new V("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function J(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 K(e,t){if(!t.partial)return!0;const{field:r,value:s}=t.partial;return e[r]===s}var W=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 V("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 V("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 V("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);H(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 V("CONFLICT",`Duplicate key ${e}`)}else e=this.getKey(n);H(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 V("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 V("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(!K(t,e.definition))return;const r=J(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=J(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(!K(e,t.definition))continue;const n=J(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 V("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))}};var Y=class{_delay;_leading;_timer;_pendingFn;_pendingResolvers=[];_leadingFired=!1;constructor(e){this._delay=e?.delay??300,this._leading=e?.leading??!1}do(e){return new Promise((t=>{this._enqueue(e,t)}))}fire(e){this._enqueue(e,void 0)}_enqueue(e,t){if(this._pendingFn=e,t&&this._pendingResolvers.push(t),this._leading&&!this._leadingFired)return this._leadingFired=!0,this._fire(),clearTimeout(this._timer),void(this._timer=setTimeout((()=>{this._leadingFired=!1,void 0!==this._pendingFn&&this._fire()}),this._delay));clearTimeout(this._timer),this._timer=setTimeout((()=>{this._leadingFired=!1,this._fire()}),this._delay)}cancel(){clearTimeout(this._timer),this._timer=void 0,this._pendingFn=void 0,this._leadingFired=!1;const e=this._pendingResolvers.splice(0);for(const t of e)t({status:"cancelled"})}async flush(){return this._pendingFn?(clearTimeout(this._timer),this._timer=void 0,this._leadingFired=!1,this._fire()):null}pending(){return void 0!==this._pendingFn}async _fire(){const e=this._pendingFn,t=this._pendingResolvers.splice(0);let r;this._pendingFn=void 0;try{r={status:"ok",value:await e()}}catch(e){r={status:"error",error:e}}for(const e of t)e(r);return r}},G=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},X=class extends G{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},Q=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 X("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}},Z=class{mutex=new Q({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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 X(r))),t)}))])}},ee=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new Z({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 V("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 V("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 te(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 re=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(te(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){H(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){H(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 V("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){H(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(te(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 V)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new V("INTERNAL_ERROR","Storage quota exceeded"):new V("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)}))}},se=new Map;l(m()),l(m()),l(f()),l(B()),l(B());var ne=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ie(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(ae).join("/"):"/"+e.split(".").map(ae).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(oe)}function ae(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function oe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var ce=new Map;function he(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new ne(`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 ne(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new ne(`Property ${e} not found`);r=r[e]}}return r}function de(e,t){let r=ce.get(t)||ie(t);if(ce.set(t,r),0===r.length)return e;let s=he(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 ne(`Invalid array index: ${n}`);return s[e]}return s[n]}function ue(e,t,r){let s=ce.get(t)||ie(t);ce.set(t,s);let n=he(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 le(e,t,r){let s=ce.get(t)||ie(t);if(ce.set(t,s),0===s.length)return r;let n=s.slice(0,-1),i=s[s.length-1],a=he(e,n);if(Array.isArray(a))if("-"===i)a.push(r);else{let e=parseInt(i);if(e<0||e>a.length)throw new ne(`Invalid array index: ${i}`);a.splice(e,0,r)}else a[i]=r;return e}function pe(e,t){let r=ce.get(t)||ie(t);if(ce.set(t,r),0===r.length)return;let s=he(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 me(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(fe(s)){let e=ye(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 fe(e){return e&&"operator"in e&&"rules"in e}function ye(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(fe(s)){let e=ye(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var we=new Map;function ge(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ve(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(we.has(n)){let t=we.get(n);return t||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(e.parameters)}`,path:c}),t}let i=s({data:t,field:e.field,arguments:e.parameters});return we.set(n,i),i||a.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(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 ${ge(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 ${ge(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 ${ge(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 ${ge(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 be=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},_e=e=>({value:e}),$e=e=>({issues:e}),Ee=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],ke=(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]}]},Ie=(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]}]},Ae=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Se=(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(...Ee(e.name,`${r}.name`)),s.push(...Ee(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(...Ee(e.description,`${r}.description`,!1)),s.push(...Ee(e.errorMessage,`${r}.errorMessage`,!1)),s},Oe=(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(...Ee(e.name,`${r}.name`)),s.push(...Ie(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,n)=>{"rules"in e?s.push(...Oe(e,t,`${r}.rules[${n}]`)):s.push(...Se(e,0,`${r}.rules[${n}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},xe=(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(...Oe(e,t,`${r}[${n}]`)):s.push(...Se(e,0,`${r}[${n}]`))})),s},Ne=(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(...Ie(e.operator,`${t}.operator`)),r.push(...Ee(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...Ne(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},Te=(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(...Ee(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(...Ae(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...Ne(e.partial,`${t}.partial`)),r.push(...Ee(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},je=(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(...Te(e,`${t}[${s}]`)))),r},Ce=(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(...Ee(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(...xe(e.constraints,"dynamic",`${n}.constraints`)),e.indexes&&i.push(...je(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(...Ee(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(...xe(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&i.push(...je(e.indexes,`${t}.indexes`))),i)},Re=(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[]},Me=(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`]}]:[],De=(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(...Ee(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Ae(e.required,`${t}.required`,!1)),e.constraints&&s.push(...xe(e.constraints,e.type,`${t}.constraints`)),s.push(...Re(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(...Ce(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(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(...Ee(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(...xe(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...je(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Ae(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(...Ee(e.reference.schema,`${t}.reference.schema`)),s.push(...Ee(e.reference.field,`${t}.reference.field`))}return s.push(...Ee(e.description,`${t}.description`,!1)),s.push(...Ae(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Me(e.hint,`${t}.hint`)),s},Pe=(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(...Ee(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Re(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Ce(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...xe(e.constraints,e.type,`${t}.constraints`)),s.push(...Ee(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(...Ee(e.name,`${t}.name`)),s.push(...Ae(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(...De(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(...Ee(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(...De(n,`${t}.fields.${e}`,r))}))),s.push(...Ee(e.description,`${t}.description`,!1)),e.indexes&&s.push(...je(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...xe(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},Fe=(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(...Ee(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(...Ee(e.id,`${t}.id`)),r.push(...De(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(...Ee(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(...Ee(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(...Ee(n.id,`${t}.nestedSchemaChanges.id`,!1)),n.constraints&&r.push(...xe(n.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),n.indexes&&r.push(...je(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(...Te(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(...Ee(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(...Ee(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(...Oe(e.constraint,"dynamic",`${t}.constraint`)):r.push(...Se(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(...Ee(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(...Ee(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(...Ee(e.id,`${t}.id`)),r.push(...Pe(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(...Ee(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(...Ee(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},qe=(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(...Ee(e.id,`${t}.id`)),r.push(...Ee(e.schemaVersion,`${t}.schemaVersion`)),r.push(...Ee(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(...Fe(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(...Fe(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(...Ee(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(...Ee(e.createdAt,`${t}.createdAt`)),r.push(...Ee(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},Le={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{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(...Ee(t.name,"name")),r.push(...Ee(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(...De(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(...Pe(s,`nestedSchemas.${t}`,e))))}return r.push(...Ee(t.description,"description",!1)),t.indexes&&r.push(...je(t.indexes,"indexes")),t.constraints&&r.push(...xe(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(...qe(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(...Me(t.hint,"hint")),r.length>0?$e(r):_e(t)},types:{input:{},output:{}}},Be={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Migration must be an object",path:[]}]);let t=e,r=qe(t,"");return r.length>0?$e(r):_e(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return $e([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...Fe(e,`[${t}]`)))),r.length>0?$e(r):_e(t)},types:{input:[],output:[]}};function Ve(e){try{return!Le.validate(e).issues}catch(e){throw new be("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function ze(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 He(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=ze(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 Je(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 Ke,We=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},Ye=((Ke=Ye||{}).INVALID_SCHEMA="INVALID_SCHEMA",Ke.INVALID_MIGRATION="INVALID_MIGRATION",Ke.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Ke.TIMEOUT="TIMEOUT",Ke.MEMORY_LIMIT="MEMORY_LIMIT",Ke.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Ke.TRANSFORM_ERROR="TRANSFORM_ERROR",Ke.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Ke.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Ke.STREAM_ERROR="STREAM_ERROR",Ke.ROLLBACK_ERROR="ROLLBACK_ERROR",Ke.MISSING_TRANSFORM="MISSING_TRANSFORM",Ke),Ge=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Ve(e))throw new We("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Be.validate(e).issues}catch(e){throw new be("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new We("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Je(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>Je(e.version,t.version))))}catch(e){throw e instanceof We?e:new We("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 We("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new We("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new be("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new We("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 We("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 We?e:new We("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||Je(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=He(e.version,t);return t.map((t=>{try{return me(t,e)}catch(e){throw new We("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=le(r,e.path,e.value);break;case"remove":r=pe(r,e.path);break;case"removeValue":r=ue(r,e.path,e.value);break;case"replace":r=le(pe(r,e.path),e.path,e.value);break;case"copy":{let t=de(r,e.from);r=le(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=de(r,e.from);r=le(r,e.path,t),r=pe(r,e.from);break}case"test":{let t=de(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ne("Test operation failed");break}default:throw new ne(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ne&&(t.operation=e),t}return r}(e,t)}catch(e){throw new We("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof We?e:new We("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 We("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 We("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 We("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 We("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 We(`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 We(`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 We(`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 We(`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 We(`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 We?e:new We("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=r.Buffer);var Xe=l(f()),Qe=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}})}},Ze=async(e,t)=>{const r=Date.now();try{const s=await t();return et(e,r,s,null),s}catch(t){throw et(e,r,void 0,t),t}};function et(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:tt}=(0,Xe.createMatcher)({});async function rt(e){const{collection:t,initial:r,validator:n,store:i,bus:a,lockManager:o}=e,[c,h]=z(r),{value:d,issues:u}=n?await n["~standard"].validate(c):{value:r,issues:void 0};if(u)throw new V("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.v7(),$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 V("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]=z(Object.assign({},l.current,r)),{value:c,issues:h}=n?await n["~standard"].validate(i):{value:i,issues:void 0};if(h)throw new V("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 V("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()}}),!0},state:()=>(e=>{const[t]=z(e);return t})(l.current),$metadata:()=>z(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 V("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(l.deleted)throw new V("INVALID_OPERATION","Document has been deleted");return Reflect.get(l.current,t)}})}function st(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}async function nt({collection:e,validator:t,bus:r,store:n,pipeline:i,validate:a,schema:o}){const c=new Q,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]=z(i),{value:l,issues:p}=a?await t["~standard"].validate(d):{value:d,issues:void 0};if(p)throw new V("INVALID_DATA",`Invalid data for collection '${e}'`,o,p,p);const m=Object.assign(l,u,{$id:s.v7(),$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 rt({...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=st(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&&tt(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!s)return null;const a=await rt({...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=st(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&&tt(e,t)&&s.push(e),{value:null,done:!1})));const a=await Promise.all(s.map((e=>rt({...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 V("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=>rt({...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 V("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return n.apply(t,s)}:n}})}function it(e){return"function"==typeof e._getIDBConnection}var at=class{id;staged=[];done=!1;constructor(){this.id=s.v7()}async addOp(e,t,r){if(this.done)throw new V("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 V("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)it(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 ot(e,t){return e instanceof V?e:e instanceof Error?new V("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new V("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}exports.ConnectionManager=ee,exports.DEFAULT_KEYPATH="$id",exports.DatabaseConnection=async function(e,t){const r=function(){const e={},t=e.errorHandler??(e=>console.error("EventBus Error:",e)),r=null!=e.batch?.size,s=e.batch?.size,n=e.batch?.delay??16;if(r&&(s<=0||!Number.isFinite(s)))throw new Error(`EventBus: batch.size must be a positive finite number, got ${s}.`);if(r&&(n<0||!Number.isFinite(n)))throw new Error(`EventBus: batch.delay must be a non-negative finite number, got ${n}.`);const i=e.broadcast?.channel,a=null!=i&&i.length>0,o=new Map;let c=[];const h=r?new Y({delay:n}):null;let d=0,u=0;const l=new Map,p=()=>{if(!a)return null;if("undefined"==typeof BroadcastChannel)return console.warn("EventBus: BroadcastChannel is not supported in this environment. Cross-tab notifications are disabled."),null;const e=new BroadcastChannel(i);return e.onmessage=e=>{const{name:t,payload:r}=e.data;y(t,r)},e};let m=p();const f=(e,t)=>{d++,u+=t,l.set(e,(l.get(e)??0)+1)},y=(e,r)=>{const s=o.get(e);if(s&&0!==s.size)for(const n of Array.from(s))try{n(r)}catch(s){const n=s instanceof Error?s:Object.assign(new Error(String(s)),{cause:s}),i=Object.assign(n,{eventName:e,payload:r});t(i)}},w=(e,t)=>{o.has(e)||o.set(e,new Set);const r=o.get(e);return r.add(t),()=>{r.delete(t),0===r.size&&o.delete(e)}},g=()=>{const e=c;c=[];for(const{name:t,payload:r}of e){const e=performance.now();y(t,r),f(t,performance.now()-e)}};return{subscribe:(e,t)=>w(e,t),once:(e,t)=>{let r;return r=w(e,(e=>{r(),t(e)})),r},emit:({name:e,payload:t})=>{if(r)return c.push({name:e,payload:t}),c.length>=s?(h.cancel(),void g()):(h.fire((()=>g())),void m?.postMessage({name:e,payload:t}));const n=performance.now();y(e,t),f(e,performance.now()-n),m?.postMessage({name:e,payload:t})},metrics:()=>({totalEvents:d,activeSubscriptions:Array.from(o.values()).reduce(((e,t)=>e+t.size),0),eventCounts:new Map(l),averageEmitDuration:d>0?u/d:0}),clear:()=>{h?.cancel(),c=[],o.clear(),d=0,u=0,l.clear(),m?.close(),m=p()}}}(),s=new Map,n=new Qe;n.use(((e=3,t=100)=>async(r,s)=>{let n=0;for(;n<e;)try{return await s()}catch(r){if(!(r instanceof V&&"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&&n.use(Ze);const i=new Map,a=t({...e,collection:"schemas",keyPath:"name"},[]);async function o(r,s=[]){let n=i.get(r);return n||(n=t({...e,collection:r,keyPath:"$id"},s),i.set(r,n)),await n.open(),n}async function c(t){if(s.has(t))return s.get(t);const i=await a.getById(t);if(!i)throw new V("SCHEMA_NOT_FOUND",`Collection '${t}' does not exist`);const c=await o(t,i.indexes??[]),h=ve(i,e.predicates||{}),d=await nt({collection:t,bus:r,validator:h,validate:Boolean(e.validate),store:c,pipeline:n,schema:i});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),s.set(t,d),s.get(t)}async function h(e){return await a.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await a.open();const d={collection:c,createCollection:async e=>{if(await a.getById(e.name))throw new V("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Ve(e))throw new V("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await a.put(e);const t=c(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await a.getById(e);if(!t)throw new V("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const n=await o(e,t.indexes??[]);return await n.clear(),i.delete(e),await a.delete(e),s.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:h,migrateCollection:async(e,t,r=100)=>{const n=s.get(e);n&&(n.invalidate(),s.delete(e));const i=await a.getById(e);if(!i)throw new V("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const d=await o(e,i.indexes??[]),u=new Ge(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 h(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(ot(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,d,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 ot(t,e)}finally{n.releaseLock()}}(e,s,d,r)}catch(t){throw ot(t,e)}for(const e of y)await d.createIndex(e);for(const e of w)await d.dropIndex(e.name);return await c(e)}},u=n.wrap(d,{eventBus:r}),l={...u,transaction:async e=>{const t=new at;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:r.subscribe,close:()=>{i.clear(),r.clear()},clear:async()=>{await a.clear(),await Promise.all(i.values().map((e=>e.clear()))),i.clear()},ensureCollection:async e=>{try{await u.createCollection(e)}catch(e){if(e instanceof V&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await l.ensureCollection(t)}};return l},exports.DatabaseError=V,exports.DatabaseErrorType=U,exports.IndexedDBStore=re,exports.createDocument=rt,exports.createEphemeralStore=function(e){return new W(e.database,e.keyPath)},exports.createIndexedDbStore=e=>{let t=se.get(e.database);t||(t=new Z({retry:!0,throws:!0}),se.set(e.database,t));try{const{value:r,error:s}=t.doSync((()=>new ee(e)));if(s)throw new V("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,s);return new re(r,e.collection,e.keyPath)}catch(e){if(e instanceof V)throw e;throw new V("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}},exports.openCollection=nt;
|